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/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Raku | Raku | my @random_distances = ([+] rand**2 xx 2) xx *;
sub approximate_pi(Int $n) {
4 * @random_distances[^$n].grep(* < 1) / $n
}
say "Monte-Carlo π approximation:";
say "$_ iterations: ", approximate_pi $_
for 100, 1_000, 10_000;
|
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Pascal | Pascal |
{$mode delphi}
PROGRAM cw;
// Output a string as Morse code and CW.
// Cross-platform PCM audio uses OpenAL
USES OpenAL, HRTimer;
// Intl. Morse codes in ASCII order
CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-');
// lengthen dah by this fraction of dit:
// best = 0.4; also lengthens pauses
doh = 0.4;
// an 0.05 sec dit is around 26 wpm
dit = 0.05;
dah = 3 * dit + doh * dit;
VAR // OpenAL variables
buffer : TALuint;
source : TALuint;
sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 );
sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 );
argv: ARRAY OF PalByte;
format: TALEnum;
size: TALSizei;
freq: TALSizei;
loop: TALInt;
data: TALVoid;
// rewinding has an effect on the output:
// <with> and <without> sound rather different
rewind : BOOLEAN = FALSE;
// the high-res timer is from Wolfgang Ehrhardt
// http://www.wolfgang-ehrhardt.de/misc_en.html
t : THRTimer;
msg : STRING = 'the quick brown fox jumps over the lazy dog.';
PROCEDURE PlayS(s: Extended);
BEGIN
StartTimer(t);
AlSourcePlay(source);
WHILE readseconds(t) < s DO BEGIN END;
IF rewind THEN AlSourceRewind(source);
AlSourceStop(source);
END;
PROCEDURE Pause(s: Extended);
BEGIN
StartTimer(t);
WHILE readseconds(t) < s DO BEGIN END;
END;
PROCEDURE doDit;
BEGIN
PlayS(dit);
Pause(dit);
END;
PROCEDURE doDah;
BEGIN
PlayS(dah);
Pause(dit);
END;
// ASCII char to Morse CW
FUNCTION AtoM(ch: CHAR): STRING;
VAR i: Integer;
u: CHAR;
BEGIN
u := ch;
IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F);
result := Morse[ord(u)];
FOR i := 1 TO Length(result) DO
CASE result[i] OF
'.': BEGIN doDit; Write('. ') END;
'-': BEGIN doDah; Write('_ ') END;
END;
Pause(dah);
Write(' ');
IF u = ' ' THEN Write(' ');
END;
// ASCII string to Morse CW
PROCEDURE StoM(s: STRING);
VAR i: Integer;
BEGIN
FOR i := 1 TO Length(s) DO AtoM(s[i]);
END;
BEGIN
// OpenAL preparation
InitOpenAL;
AlutInit(nil,argv);
AlGenBuffers(1, @buffer);
// load the 500 Hz 1 sec sine-wave file
// get it from http://audiocheck.net
AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop);
AlBufferData(buffer, format, data, size, freq);
AlutUnloadWav(format, data, size, freq);
AlGenSources(1, @source);
AlSourcei ( source, AL_BUFFER, buffer);
AlSourcef ( source, AL_PITCH, 1.0 );
AlSourcef ( source, AL_GAIN, 1.0 );
AlSourcefv ( source, AL_POSITION, @sourcepos);
AlSourcefv ( source, AL_VELOCITY, @sourcevel);
AlSourcei ( source, AL_LOOPING, AL_TRUE);
// Sound and print the Morse
StoM(msg);
Pause(1.0);
AlSourceRewind(source);
AlSourceStop(source);
// Clean up
AlDeleteBuffers(1, @buffer);
AlDeleteSources(1, @source);
AlutExit();
END.
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #MATLAB | MATLAB | function montyHall(numDoors,numSimulations)
assert(numDoors > 2);
function num = randInt(n)
num = floor( n*rand()+1 );
end
%The first column will tallie wins, the second losses
switchedDoors = [0 0];
stayed = [0 0];
for i = (1:numSimulations)
availableDoors = (1:numDoors); %Preallocate the available doors
winningDoor = randInt(numDoors); %Define the winning door
playersOriginalChoice = randInt(numDoors); %The player picks his initial choice
availableDoors(playersOriginalChoice) = []; %Remove the players choice from the available doors
%Pick the door to open from the available doors
openDoor = availableDoors(randperm(numel(availableDoors))); %Sort the available doors randomly
openDoor(openDoor == winningDoor) = []; %Make sure Monty doesn't open the winning door
openDoor = openDoor(randInt(numel(openDoor))); %Choose a random door to open
availableDoors(availableDoors==openDoor) = []; %Remove the open door from the available doors
availableDoors(end+1) = playersOriginalChoice; %Put the player's original choice back into the pool of available doors
availableDoors = sort(availableDoors);
playersNewChoice = availableDoors(randInt(numel(availableDoors))); %Pick one of the available doors
if playersNewChoice == playersOriginalChoice
switch playersNewChoice == winningDoor
case true
stayed(1) = stayed(1) + 1;
case false
stayed(2) = stayed(2) + 1;
otherwise
error 'ERROR'
end
else
switch playersNewChoice == winningDoor
case true
switchedDoors(1) = switchedDoors(1) + 1;
case false
switchedDoors(2) = switchedDoors(2) + 1;
otherwise
error 'ERROR'
end
end
end
disp(sprintf('Switch win percentage: %f%%\nStay win percentage: %f%%\n', [switchedDoors(1)/sum(switchedDoors),stayed(1)/sum(stayed)] * 100));
end |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Swift | Swift | extension BinaryInteger {
@inlinable
public func modInv(_ mod: Self) -> Self {
var (m, n) = (mod, self)
var (x, y) = (Self(0), Self(1))
while n != 0 {
(x, y) = (y, x - (m / n) * y)
(m, n) = (n, m % n)
}
while x < 0 {
x += mod
}
return x
}
}
print(42.modInv(2017)) |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Tcl | Tcl | proc gcdExt {a b} {
if {$b == 0} {
return [list 1 0 $a]
}
set q [expr {$a / $b}]
set r [expr {$a % $b}]
lassign [gcdExt $b $r] s t g
return [list $t [expr {$s - $q*$t}] $g]
}
proc modInv {a m} {
lassign [gcdExt $a $m] i -> g
if {$g != 1} {
return -code error "no inverse exists of $a %! $m"
}
while {$i < 0} {incr i $m}
return $i
} |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Forth | Forth |
: multiplication-table
cr 2 spaces 13 2 do i 4 u.r loop
cr
13 2 do
cr i 2 u.r
13 2 do
i j < if 4 spaces else i j * 4 u.r then
loop
loop ;
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Prolog | Prolog | solution([]).
solution([X/Y|Others]) :-
solution(Others),
member(Y, [1,2,3,4,5,6,7,8]),
noattack(X/Y, Others).
noattack(_,[]).
noattack(X/Y,[X1/Y1|Others]) :-
Y =\= Y1,
Y1 - Y =\= X1 - X,
Y1 - Y =\= X - X1,
noattack(X/Y,Others).
member(Item,[Item|Rest]).
member(Item,[First|Rest]) :-
member(Item,Rest).
template([1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8]). |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR n=0 TO 25
20 GO SUB 140
30 PRINT n$;" ";
40 NEXT n
50 FOR n=250 TO 265
60 GO SUB 140
70 PRINT n$;" ";
80 NEXT n
90 FOR n=1000 TO 1025
100 GO SUB 140
110 PRINT n$;" ";
120 NEXT n
130 STOP
140 LET s$="th"
150 LET n$=STR$ n
160 IF LEN n$=1 THEN GO TO 180
170 IF n$(LEN n$-1)="1" THEN GO TO 210
180 IF n$(LEN n$)="1" THEN LET s$="st"
190 IF n$(LEN n$)="2" THEN LET s$="nd"
200 IF n$(LEN n$)="3" THEN LET s$="rd"
210 LET n$=n$+s$
220 RETURN |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #PicoLisp | PicoLisp | (de f (N)
(if (=0 N)
1
(- N (m (f (dec N)))) ) )
(de m (N)
(if (=0 N)
0
(- N (f (m (dec N)))) ) ) |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #REXX | REXX | /*REXX program computes and displays the value of pi÷4 using the Monte Carlo algorithm*/
numeric digits 20 /*use 20 decimal digits to handle args.*/
parse arg times chunk digs r? . /*does user want a specific number? */
if times=='' | times=="," then times= 5e12 /*five trillion should do it, hopefully*/
if chunk=='' | chunk=="," then chunk= 100000 /*perform Monte Carlo in 100k chunks.*/
if digs =='' | digs=="," then digs= 99 /*indicates to use length of PI - 1. */
if datatype(r?, 'W') then call random ,,r? /*Is there a random seed? Then use it.*/
/* [↓] pi meant to line─up with a SAY.*/
pi= 3.141592653589793238462643383279502884197169399375105820974944592307816406
pi= strip( left(pi, digs + length(.) ) ) /*obtain length of pi to what's wanted.*/
numeric digits length(pi) - 1 /*define decimal digits as length PI -1*/
say ' 1 2 3 4 5 6 7 '
say 'scale: 1·234567890123456789012345678901234567890123456789012345678901234567890123'
say /* [↑] a two─line scale for showing pi*/
say 'true pi= ' pi"+" /*we might as well brag about true pi.*/
say /*display a blank line for separation. */
limit = 10000 - 1 /*REXX random generates only integers. */
limitSq = limit **2 /*··· so, instead of one, use limit**2.*/
accuracy= 0 /*accuracy of Monte Carlo pi (so far).*/
@reps= 'repetitions: Monte Carlo pi is' /*a handy─dandy short literal for a SAY*/
!= 0 /*!: is the accuracy of pi (so far). */
do j=1 for times % chunk
do chunk /*do Monte Carlo, one chunk at─a─time. */
if random(, limit)**2 + random(, limit)**2 <= limitSq then != ! + 1
end /*chunk*/
reps= chunk * j /*calculate the number of repetitions. */
_= compare(4*! / reps, pi) /*compare apples and ··· crabapples. */
if _<=accuracy then iterate /*Not better accuracy? Keep truckin'. */
say right(commas(reps), 20) @reps 'accurate to' _-1 "places." /*─1≡dec. point*/
accuracy= _ /*use this accuracy for next baseline. */
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _ |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Perl | Perl | use Acme::AGMorse qw(SetMorseVals SendMorseMsg);
SetMorseVals(20,30,400);
SendMorseMsg('Hello World! abcdefg @\;'); # note, caps are ingnored in Morse Code
exit; |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #MAXScript | MAXScript | fn montyHall choice switch =
(
doors = #(false, false, false)
doors[random 1 3] = true
chosen = doors[choice]
if switch then chosen = not chosen
chosen
)
fn iterate iterations switched =
(
wins = 0
for i in 1 to iterations do
(
if (montyHall (random 1 3) switched) then
(
wins += 1
)
)
wins * 100 / iterations as float
)
iterations = 10000
format ("Stay strategy:%\%\n") (iterate iterations false)
format ("Switch strategy:%\%\n") (iterate iterations true) |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #NetRexx | NetRexx | /* NetRexx ************************************************************
* 30.08.2013 Walter Pachl translated from Java/REXX/PL/I
**********************************************************************/
options replace format comments java crossref savelog symbols nobinary
doors = create_doors
switchWins = 0
stayWins = 0
shown=0
Loop plays=1 To 1000000
doors=0
r=r3()
doors[r]=1
choice = r3()
loop Until shown<>choice & doors[shown]=0
shown = r3()
End
If doors[choice]=1 Then
stayWins=stayWins+1
Else
switchWins=switchWins+1
End
Say "Switching wins " switchWins " times."
Say "Staying wins " stayWins " times."
method create_doors static returns Rexx
doors = ''
doors[0] = 0
doors[1] = 0
doors[2] = 0
return doors
method r3 static
rand=random()
return rand.nextInt(3) + 1 |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Tiny_BASIC | Tiny BASIC |
PRINT "Modular inverse."
PRINT "What is the modulus?"
INPUT M
PRINT "What number is to be inverted?"
INPUT X
PRINT "Solution is:"
10 LET A = A + 1
GOTO 20
15 IF B = 1 THEN PRINT A
IF B = 1 THEN END
IF A = M-1 THEN PRINT "nonexistent"
IF A = M-1 THEN END
GOTO 10
20 LET B = A*X
30 IF B < M THEN GOTO 15
LET B = B - M
GOTO 30
|
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #tsql | tsql | ;WITH Iterate(N,A,B,X0,X1)
AS (
SELECT
1
,CASE WHEN @a < 0 THEN @b-(-@a % @b) ELSE @a END
,CASE WHEN @b < 0 THEN -@b ELSE @b END
,0
,1
UNION ALL
SELECT
N+1
,B
,A%B
,X1-((A/B)*X0)
,X0
FROM Iterate
WHERE A != 1 AND B != 0
),
ModularInverse(Result)
AS (
SELECT
-1
FROM Iterate
WHERE A != 1 AND B = 0
UNION ALL
SELECT
TOP(1)
CASE WHEN X1 < 0 THEN X1+@b ELSE X1 END AS Result
FROM Iterate
WHERE (SELECT COUNT(*) FROM Iterate WHERE A != 1 AND B = 0) = 0
ORDER BY N DESC
)
SELECT *
FROM ModularInverse |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Fortran | Fortran | program multtable
implicit none
integer :: i, j, k
write(*, "(a)") " x| 1 2 3 4 5 6 7 8 9 10 11 12"
write(*, "(a)") "--+------------------------------------------------"
do i = 1, 12
write(*, "(i2, a)", advance="no") i, "|"
do k = 2, i
write(*, "(a4)", advance="no") ""
end do
do j = i, 12
write(*, "(i4)", advance="no") i*j
end do
write(*, *)
end do
end program multtable |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Pure | Pure | /*
n-queens.pure
Tectonics:
pure -c queens.pure -o queens
or
pure -q -i queens.pure
*/
using system;
queens n = search n 1 [] with
search n i p = [reverse p] if i>n;
= cat [search n (i+1) ((i,j):p) | j = 1..n; safe (i,j) p];
safe (i,j) p = ~any (check (i,j)) p;
check (i1,j1) (i2,j2)
= i1==i2 || j1==j2 || i1+j1==i2+j2 || i1-j1==i2-j2;
end;
compiling || (puts("queens 4: " + str(queens 4)) $$
puts("Solutions to queens 7: " + str(#queens 7))); |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #PL.2FI | PL/I | test: procedure options (main);
M: procedure (n) returns (fixed) recursive; /* 8/1/2010 */
declare n fixed;
if n <= 0 then return (0);
else return ( n - F(M(n-1)) );
end M;
F: procedure (n) returns (fixed) recursive;
declare n fixed;
if n <= 0 then return (1);
else return ( n - M(F(n-1)) );
end F;
declare i fixed;
do i = 1 to 15;
put skip list ( F(i), M(i) );
end;
end test; |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Ring | Ring |
decimals(8)
see "monteCarlo(1000) = " + monteCarlo(1000) + nl
see "monteCarlo(10000) = " + monteCarlo(10000) + nl
see "monteCarlo(100000) = " + monteCarlo(100000) + nl
func monteCarlo t
n=0
for i = 1 to t
if sqrt(pow(random(1),2) + pow(random(1),2)) <= 1 n += 1 ok
next
t = (4 * n) / t
return t
|
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Ruby | Ruby | def approx_pi(throws)
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
end
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Phix | Phix | --
-- demo\rosetta\Morse_code.exw
-- ===========================
--
with javascript_semantics
include pGUI.e
include builtins\beep.e
Ihandle input, canvas, output, vbox, dlg
cdCanvas cddbuffer, cdcanvas
constant title = "Morse code",
help_text = """
Enter a message to convert to morse code.
Press Return to listen to the result.
Characters A-Z are shown with Baden-Powell menemonics.
(Note said are a memory aid, not perfectly readable.)
Obviously deliberately looking away and listening
would be the best way to use this as a learning aid.
"""
function show_help()
IupMessage(title,help_text,bWrap:=false)
IupSetFocus(input)
return IUP_IGNORE -- (don't open the browser help!)
end function
constant morse_data = """
!-.-.--#".-..-.#$...-..-#&.-...#'.----.#(-.--.#)-.--.-#+.-.-.#,--..--#--....-#..-.-.-#/-..-.#=-...-#
0-----#1.----#2..---#3...--#4....-#5.....#6-....#7--...#8---..#9----.#:---...#;-.-.-.#?..--..#@.--.-.#
A.-51517525#B-...7177414144444747#C-.-.7121121277271616#D-..717741414747#E.7474#F..-.7171111174247777#
G--.712177271818#H....2121717127277777#I..51515757#J.---2121222558269668#K-.-742184854428#(-.--.#
L.-..7171727677771717#M--45118155#N-.71362727#O---712182861216#P.--.8181612164247777#)-.--.-#
Q--.-8286121677775818#R.-.717144261717#S...515154545757#T-7121#U..-818111117727#V...-8181111156567727#
W.--818187534317#X-..-8154333365654518#Y-.--8163545433115558#Z--..7121762277771717#_..--.-# #"""
sequence morse = repeat(``,255), -- the eg "..."'s
bdnpwl = repeat({},255) -- Baden-Powell mnemonics
procedure setMorse()
-- I trust the characters and morse codes are all pretty evident in morse_data.
-- Baden-Powell mnemonics are encoded as 4 points on a 9wx7h grid per dot/dash,
-- counting (it just turned out that way) right to left and top to bottom, such
-- that "9711" (=1197) is(/looks like) a forwardslash and "9117" a backslash.
-- Each quite fiddly to set up - rather relieved there were only 26 of them!
sequence data = split(substitute(morse_data,"\n",""),'#')
for di in data do
integer key = di[1]
string bpm = trim_head(di[2..$],".- "),
code = di[2..-length(bpm)-1]
assert(length(bpm)=0 or length(bpm)=4*length(code))
morse[key] = code -- eg morse['S'] = "..."
bdnpwl[key] = sq_sub('5',bpm)
end for
morse['['] = morse['(']
morse[']'] = morse[')']
end procedure
setMorse()
function redraw_cb(Ihandle /*ih*/)
string text = upper(IupGetAttribute(input,"VALUE")),
outstr = ""
integer {dw,dh} = IupGetIntInt(canvas, "DRAWSIZE"),
{tw,th} = cdCanvasGetTextSize(cddbuffer,text)
while tw>dw do
if length(outstr) then outstr &= " " end if
outstr &= morse[text[1]]
text = text[2..$]
{tw,th} = cdCanvasGetTextSize(cddbuffer,text)
end while
atom cw = tw/max(length(text),1),
cx = dw/2,
cy = dh/2
cdCanvasActivate(cddbuffer)
cdCanvasSetBackground(cddbuffer, CD_LIGHT_PARCHMENT)
cdCanvasClear(cddbuffer)
cdCanvasSetForeground(cddbuffer, #BBADA0)
cdCanvasText(cddbuffer, cx, cy, text)
cx -= cw*(length(text)/2-0.5)
cdCanvasSetForeground(cddbuffer, CD_BLUE)
cdCanvasSetLineWidth(cddbuffer,3)
{} = cdCanvasMarkSize(cddbuffer,3)
atom gw = cw*0.75, gh = th*0.285
for ch in text do
sequence bpm = bdnpwl[ch]
if length(bpm) then
for k=1 to length(bpm) by 4 do
atom x1 = cx+gw*bpm[k+0]/8-1,
y1 = cy+gh*bpm[k+1]/4-3,
x2 = cx+gw*bpm[k+2]/8-1,
y2 = cy+gh*bpm[k+3]/4-3
if x1=x2 and y1=y2 then
cdCanvasMark(cddbuffer, x1, y1)
else
cdCanvasLine(cddbuffer, x1, y1, x2, y2)
end if
end for
end if
cx += cw
if length(outstr) then outstr &= " " end if
outstr &= morse[ch]
end for
cdCanvasFlush(cddbuffer)
IupSetStrAttribute(output,"TITLE",outstr)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
-- cdCanvasFont(cddbuffer,"Courier",CD_PLAIN,24)
cdCanvasFont(cddbuffer,"Courier",CD_PLAIN,48)
cdCanvasSetTextAlignment(cddbuffer, CD_CENTER)
return IUP_DEFAULT
end function
constant frequency = 1280, -- in Hz, 37..32767
wpm = 15, -- words per minute
dit = 1200/wpm, -- in milliseconds
dah = 3*dit,
lettergap = 3*dit,
wordgap = 7*dit
function key_cb(Ihandle /*dlg*/, atom c)
if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me)
if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work)
if c=K_F1 then return show_help() end if
if c=K_CR then
string text = trim(upper(IupGetAttribute(input,"VALUE")))
sequence durations = {}
for ch in text do
if ch=' ' then
durations &= wordgap
else
if length(durations) then
durations &= lettergap
end if
string m = morse[ch]
for i=1 to length(m) do
if i>1 then durations &= dit end if
durations &= iff(m[i]='.'?dit:dah)
end for
end if
end for
beep(frequency,durations,0.5)
IupSetAttribute(input,"SELECTION","ALL")
elsif find(c,"#") then
beep()
return IUP_IGNORE
else
IupUpdate(canvas)
end if
return IUP_CONTINUE
end function
IupOpen()
input = IupText("EXPAND=HORIZONTAL")
canvas = IupCanvas("RASTERSIZE=520x40")
output = IupLabel("","EXPAND=HORIZONTAL")
vbox = IupVbox({input,canvas,output}, "MARGIN=10x5, GAP=5")
dlg = IupDialog(vbox,`TITLE="%s",MINSIZE=440x140`,{title})
IupSetCallback(dlg,"KEY_CB",Icallback("key_cb"))
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
IupSetAttributeHandle(NULL,"PARENTDIALOG",dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Nim | Nim | import random
randomize()
proc shuffle[T](x: var seq[T]) =
for i in countdown(x.high, 0):
let j = rand(i)
swap(x[i], x[j])
# 1 represents a car
# 0 represent a goat
var
stay = 0 # amount won if stay in the same position
switch = 0 # amount won if you switch
for i in 1..1000:
var lst = @[1,0,0] # one car and two goats
shuffle(lst) # shuffles the list randomly
let ran = rand(2 ) # gets a random number for the random guess
let user = lst[ran] # storing the random guess
del lst, ran # deleting the random guess
var huh = 0
for i in lst: # getting a value 0 and deleting it
if i == 0:
del lst, huh # deletes a goat when it finds it
break
inc huh
if user == 1: # if the original choice is 1 then stay adds 1
inc stay
if lst[0] == 1: # if the switched value is 1 then switch adds 1
inc switch
echo "Stay = ",stay
echo "Switch = ",switch |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #OCaml | OCaml | let trials = 10000
type door = Car | Goat
let play switch =
let n = Random.int 3 in
let d1 = [|Car; Goat; Goat|].(n) in
if not switch then d1
else match d1 with
Car -> Goat
| Goat -> Car
let cars n switch =
let total = ref 0 in
for i = 1 to n do
let prize = play switch in
if prize = Car then
incr total
done;
!total
let () =
let switch = cars trials true
and stay = cars trials false in
let msg strat n =
Printf.printf "The %s strategy succeeds %f%% of the time.\n"
strat (100. *. (float n /. float trials)) in
msg "switch" switch;
msg "stay" stay |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #TypeScript | TypeScript |
// Modular inverse
function modInv(e: number, t: number): number {
var d = 0;
if (e < t) {
var count = 1;
var bal = e;
do {
var step = Math.floor((t - bal) / e) + 1;
bal += step * e;
count += step;
bal -= t;
} while (bal != 1);
d = count;
}
return d;
}
console.log(`${modInv(42, 2017)}`); // 1969
|
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #uBasic.2F4tH | uBasic/4tH | Print FUNC(_MulInv(42, 2017))
End
_MulInv Param(2)
Local(5)
c@ = b@
f@ = 0
g@ = 1
If b@ = 1 Then Return
Do While a@ > 1
e@ = a@ / b@
d@ = b@
b@ = a@ % b@
a@ = d@
d@ = f@
f@ = g@ - e@ * f@
g@ = d@
Loop
If g@ < 0 Then g@ = g@ + c@
Return (g@) |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64
Print " X|";
For i As Integer = 1 To 12
Print Using "####"; i;
Next
Print
Print "---+"; String(48, "-")
For i As Integer = 1 To 12
Print Using "###"; i;
Print"|"; Spc(4 * (i - 1));
For j As Integer = i To 12
Print Using "####"; i * j;
Next j
Print
Next i
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #PureBasic | PureBasic | Global solutions
Procedure showBoard(Array queenCol(1))
Protected row, column, n = ArraySize(queenCol())
PrintN(" Solution " + Str(solutions))
For row = 0 To n
For column = 0 To n
If queenCol(row) = column
Print("|Q")
Else
Print("| ")
EndIf
Next
PrintN("|")
Next
EndProcedure
Macro advanceIfPossible()
x + 1
While x <= n And columns(x): x + 1: Wend
If x > n
ProcedureReturn #False ;backtrack
EndIf
EndMacro
Procedure placeQueens(Array queenCol(1), Array columns(1), row = 0)
Protected n = ArraySize(queenCol())
If row > n
solutions + 1
showBoard(queenCol())
ProcedureReturn #False ;backtrack
EndIf
Protected x, queen, passed
While columns(x): x + 1: Wend
;place a new queen in one of the available columns
Repeat
passed = #True
For queen = 0 To row - 1
If ((queenCol(queen) - x) = (queen - row)) Or ((queenCol(queen) - x) = -(queen - row))
advanceIfPossible()
passed = #False
Break ;ForNext loop
EndIf
Next
If passed
queenCol(row) = x: columns(x) = 1
If Not placeQueens(queenCol(), columns(), row + 1)
columns(x) = 0
advanceIfPossible()
EndIf
EndIf
ForEver
EndProcedure
Procedure queens(n)
If n > 0
Dim queenCol(n - 1)
Dim columns(n - 1)
placeQueens(queenCol(), columns())
EndIf
EndProcedure
If OpenConsole()
Define i
For i = 1 To 12
solutions = 0
queens(i)
PrintN(#CRLF$ + Str(solutions) + " solutions found for " + Str(i) + "-queens.")
Input()
Next
Print(#CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #PostScript | PostScript |
/female{
/n exch def
n 0 eq
{1}
{
n n 1 sub female male sub
}ifelse
}def
/male{
/n exch def
n 0 eq
{0}
{
n n 1 sub male female sub
}ifelse
}def
|
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Rust | Rust | extern crate rand;
use rand::Rng;
use std::f64::consts::PI;
// `(f32, f32)` would be faster for some RNGs (including `rand::thread_rng` on 32-bit platforms
// and `rand::weak_rng` as of rand v0.4) as `next_u64` combines two `next_u32`s if not natively
// supported by the RNG. It would less accurate however.
fn is_inside_circle((x, y): (f64, f64)) -> bool {
x * x + y * y <= 1.0
}
fn simulate<R: Rng>(rng: &mut R, samples: usize) -> f64 {
let mut count = 0;
for _ in 0..samples {
if is_inside_circle(rng.gen()) {
count += 1;
}
}
(count as f64) / (samples as f64)
}
fn main() {
let mut rng = rand::weak_rng();
println!("Real pi: {}", PI);
for samples in (3..9).map(|e| 10_usize.pow(e)) {
let estimate = 4.0 * simulate(&mut rng, samples);
let deviation = 100.0 * (1.0 - estimate / PI).abs();
println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation);
}
} |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Scala | Scala | object MonteCarlo {
private val random = new scala.util.Random
/** Returns a random number between -1 and 1 */
def nextThrow: Double = (random.nextDouble * 2.0) - 1.0
/** Returns true if the argument point would be 'inside' the unit circle with
* center at the origin, and bounded by a square with side lengths of 2
* units. */
def insideCircle(pt: (Double, Double)): Boolean = pt match {
case (x, y) => (x * x) + (y * y) <= 1.0
}
/** Runs the simulation the specified number of times. Uses the result to
* estimate a value of pi */
def simulate(times: Int): Double = {
val inside = Iterator.tabulate (times) (_ => (nextThrow, nextThrow)) count insideCircle
inside.toDouble / times.toDouble * 4.0
}
def main(args: Array[String]): Unit = {
val sims = Seq(10000, 100000, 1000000, 10000000, 100000000)
sims.foreach { n =>
println(n+" simulations; pi estimation: "+ simulate(n))
}
}
} |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #PicoLisp | PicoLisp | # *Morse *Dit *Dah
(balance '*Morse
(mapcar
'((L)
(def (car L)
(mapcar = (chop (cadr L)) '("." .)) ) )
(quote
("!" "---.") ("\"" ".-..-.") ("$" "...-..-") ("'" ".----.")
("(" "-.--.") (")" "-.--.-") ("+" ".-.-.") ("," "--..--")
("-" "-....-") ("." ".-.-.-") ("/" "-..-.")
("0" "-----") ("1" ".----") ("2" "..---") ("3" "...--")
("4" "....-") ("5" ".....") ("6" "-....") ("7" "--...")
("8" "---..") ("9" "----.")
(":" "---...") (";" "-.-.-.") ("=" "-...-") ("?" "..--..")
("@" ".--.-.")
("A" ".-") ("B" "-...") ("C" "-.-.") ("D" "-..")
("E" ".") ("F" "..-.") ("G" "--.") ("H" "....")
("I" "..") ("J" ".---") ("K" "-.-") ("L" ".-..")
("M" "--") ("N" "-.") ("O" "---") ("P" ".--.")
("Q" "--.-") ("R" ".-.") ("S" "...") ("T" "-")
("U" "..-") ("V" "...-") ("W" ".--") ("X" "-..-")
("Y" "-.--") ("Z" "--..")
("[" "-.--.") ("]" "-.--.-") ("_" "..--.-") ) ) )
# Words per minute
(de wpm (N)
(setq *Dit (*/ 1200 N) *Dah (* 3 *Dit)) )
(wpm 20)
# Morse a string
(de morse (Str)
(for C (chop Str)
(cond
((sp? C) (wait (+ *Dah *Dit))) # White space: Pause
((idx '*Morse (uppc C)) # Known character
(for Flg (val (car @))
(call "/usr/bin/beep" "-D" *Dit "-l" (if Flg *Dit *Dah)) ) )
(T (call "/usr/bin/beep" "-f" 370)) ) # Unkown character
(wait (- *Dah *Dit)) ) )
(morse "Hello world!") |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PARI.2FGP | PARI/GP | test(trials)={
my(stay=0,change=0);
for(i=1,trials,
my(prize=random(3),initial=random(3),opened);
while((opened=random(3))==prize | opened==initial,);
if(prize == initial, stay++, change++)
);
print("Wins when staying: "stay);
print("Wins when changing: "change);
[stay, change]
};
test(1e4) |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #UNIX_Shell | UNIX Shell | function invmod {
typeset -i a=$1 n=$2
if (( n < 0 )); then (( n = -n )); fi
if (( a < 0 )); then (( a = n - (-a) % n )); fi
typeset -i t=0 nt=1 r=n nr q tmp
(( nr = a % n ))
while (( nr )); do
(( q = r/nr ))
(( tmp = nt ))
(( nt = t - q*nt ))
(( t = tmp ))
(( tmp = nr ))
(( nr = r - q*nr ))
(( r = tmp ))
done
if (( r > 1 )); then
return 1
fi
while (( t < 0 )); do (( t += n )); done
printf '%s\n' "$t"
}
invmod 42 2017 |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #VBA | VBA |
Private Function mul_inv(a As Long, n As Long) As Variant
If n < 0 Then n = -n
If a < 0 Then a = n - ((-a) Mod n)
Dim t As Long: t = 0
Dim nt As Long: nt = 1
Dim r As Long: r = n
Dim nr As Long: nr = a
Dim q As Long
Do While nr <> 0
q = r \ nr
tmp = t
t = nt
nt = tmp - q * nt
tmp = r
r = nr
nr = tmp - q * nr
Loop
If r > 1 Then
mul_inv = "a is not invertible"
Else
If t < 0 Then t = t + n
mul_inv = t
End If
End Function
Public Sub mi()
Debug.Print mul_inv(42, 2017)
Debug.Print mul_inv(40, 1)
Debug.Print mul_inv(52, -217) '/* Pari semantics for negative modulus */
Debug.Print mul_inv(-486, 217)
Debug.Print mul_inv(40, 2018)
End Sub |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Frink | Frink | a = makeArray[[13,13], {|a,b| a==0 ? b : (b==0 ? a : (a<=b ? a*b : ""))}]
formatTable[a,"right"] |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Python | Python | from itertools import permutations
n = 8
cols = range(n)
for vec in permutations(cols):
if n == len(set(vec[i]+i for i in cols)) \
== len(set(vec[i]-i for i in cols)):
print ( vec ) |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #PowerShell | PowerShell | function F($n) {
if ($n -eq 0) { return 1 }
return $n - (M (F ($n - 1)))
}
function M($n) {
if ($n -eq 0) { return 0 }
return $n - (F (M ($n - 1)))
} |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: pi (in integer: throws) is func
result
var float: pi is 0.0;
local
var integer: throw is 0;
var integer: inside is 0;
begin
for throw range 1 to throws do
if rand(0.0, 1.0) ** 2 + rand(0.0, 1.0) ** 2 <= 1.0 then
incr(inside);
end if;
end for;
pi := flt(4 * inside) / flt(throws);
end func;
const proc: main is func
begin
writeln(" 10000: " <& pi( 10000) digits 5);
writeln(" 100000: " <& pi( 100000) digits 5);
writeln(" 1000000: " <& pi( 1000000) digits 5);
writeln(" 10000000: " <& pi( 10000000) digits 5);
writeln("100000000: " <& pi(100000000) digits 5);
end func; |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #SequenceL | SequenceL |
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
main(args(2)) := monteCarlo(stringToInt(args[1]), stringToInt(args[2]));
monteCarlo(n, seed) :=
let
totalHits := monteCarloHelper(n, seedRandom(seed), 0);
in
(totalHits / intToFloat(n))*4.0;
monteCarloHelper(n, generator, result) :=
let
xRand := getRandom(generator);
x := xRand.Value/(generator.RandomMax + 1.0);
yRand := getRandom(xRand.Generator);
y := yRand.Value/(generator.RandomMax + 1.0);
newResult := result + 1 when x^2 + y^2 < 1.0 else
result;
in
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
|
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #PL.2FI | PL/I |
/* Sound Morse code via the PC buzzer. June 2011 */
MORSE: procedure options (main);
declare (i, j) fixed binary;
declare buzz character (1) static initial ('07'x);
declare text character (100) varying,
c character (1);
declare alphabet character (36) static initial (
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
declare morse_character character(5) varying;
declare morse_codes(36) character(5) varying static initial (
/* Letters A-Z */
'.-', '-...', '-.-.', '-..', '.',
'..-.', '--.', '....', '..', '.---',
'-.-', '.-..', '--', '-.', '---',
'--.-', '--.-', '.-.', '...', '-',
'..-', '...-', '.--', '-..-', '-.--',
'--..',
/* Digits 0-9 */
'-----', '.----', '..---', '...--', '....-',
'.....', '-....', '--...', '---..', '----.' );
put skip list ('Please type the text to be transmitted:');
get edit (text) (L);
do i = 1 to length (text);
c = substr(text, i, 1);
j = index(alphabet, uppercase(c));
if j > 0 then
do;
morse_character = morse_codes(j);
put skip list (morse_character); /* Display the Morse. */
call send_morse (morse_character);
end;
end;
send_morse: procedure (morse_character);
declare morse_character character(*) varying;
declare i fixed binary;
do i = 1 to length(morse_character);
if substr(morse_character, 1, 1) = '-' then
put skip edit (buzz, ' ', buzz) (a(1), A, skip, a(1));
else
put skip edit (buzz, ' ') (a(1));
delay (1000); /* Delay one period. */
end;
delay (1000);
/* Making a delay of 2 periods after each English letter. */
end send_morse;
END MORSE; |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Pascal | Pascal | program MontyHall;
uses
sysutils;
const
NumGames = 1000;
{Randomly pick a door(a number between 0 and 2}
function PickDoor(): Integer;
begin
Exit(Trunc(Random * 3));
end;
var
i: Integer;
PrizeDoor: Integer;
ChosenDoor: Integer;
WinsChangingDoors: Integer = 0;
WinsNotChangingDoors: Integer = 0;
begin
Randomize;
for i := 0 to NumGames - 1 do
begin
//randomly picks the prize door
PrizeDoor := PickDoor;
//randomly chooses a door
ChosenDoor := PickDoor;
//if the strategy is not changing doors the only way to win is if the chosen
//door is the one with the prize
if ChosenDoor = PrizeDoor then
Inc(WinsNotChangingDoors);
//if the strategy is changing doors the only way to win is if we choose one
//of the two doors that hasn't the prize, because when we change we change to the prize door.
//The opened door doesn't have a prize
if ChosenDoor <> PrizeDoor then
Inc(WinsChangingDoors);
end;
Writeln('Num of games:' + IntToStr(NumGames));
Writeln('Wins not changing doors:' + IntToStr(WinsNotChangingDoors) + ', ' +
FloatToStr((WinsNotChangingDoors / NumGames) * 100) + '% of total.');
Writeln('Wins changing doors:' + IntToStr(WinsChangingDoors) + ', ' +
FloatToStr((WinsChangingDoors / NumGames) * 100) + '% of total.');
end.
|
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Wren | Wren | import "/big" for BigInt
var a = BigInt.new(42)
var b = BigInt.new(2017)
System.print(a.modInv(b)) |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #XPL0 | XPL0 | code IntOut=11, Text=12;
int X;
def A=42, M=2017;
[for X:= 2 to M-1 do
if rem(A*X/M) = 1 then [IntOut(0, X); exit];
Text(0, "Does not exist");
] |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Gambas | Gambas | 'Code 'stolen' from Free Basic and altered to work in Gambas
Public Sub Main()
Dim i, j As Integer
Print " X|";
For i = 1 To 12
Print Format(i, "####");
Next
Print
Print "---+"; String(48, "-")
For i = 1 To 12
Print Format(i, "###");
Print "|"; Space(4 * (i - 1));
For j = i To 12
Print Format(i * j, "####");
Next
Print
Next
End |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #QBasic | QBasic | DIM SHARED queens AS INTEGER
CLS
COLOR 15
INPUT "Numero de reinas"; queens
IF queens <= 0 THEN END
CLS
PRINT "queens: Calcula el problema de las"; queens; " reinas."
DIM SHARED arrayqcol(queens) AS LONG ' columnas de reinas
DIM SHARED nsoluciones AS LONG
dofila (1)' comenzar en la fila 1
COLOR 14: LOCATE 6 + (2 * queens), 1: PRINT "Hay " + STR$(nsoluciones) + " soluciones"
END
SUB dofila (ifila) ' comienza con la fila de abajo
FOR icol = 1 TO queens
FOR iqueen = 1 TO ifila - 1 ' Comprueba conflictos con las reinas anteriores
IF arrayqcol(iqueen) = icol THEN GOTO continue1 ' misma columna?
' iqueen también es fila de la reina
IF iqueen + arrayqcol(iqueen) = ifila + icol THEN GOTO continue1 ' diagonal derecha?
IF iqueen - arrayqcol(iqueen) = ifila - icol THEN GOTO continue1 ' diagonal izquierda?
NEXT iqueen
' En este punto podemos añadir una reina
arrayqcol(ifila) = icol ' añadir al array
COLOR 8
LOCATE ifila + 2, icol: PRINT "x"; ' mostrar progreso
COLOR 15
IF ifila = queens THEN ' solucion?
nsoluciones = nsoluciones + 1
LOCATE 4 + queens, 1: PRINT "Solucion #" + STR$(nsoluciones)
FOR i1 = 1 TO queens ' filas
s1$ = STRING$(queens, ".") ' columnas
MID$(s1$, arrayqcol(i1), 1) = "Q" ' Q en la columna reina
PRINT s1$
NEXT i1
PRINT ""
ELSE
dofila (ifila + 1)' llamada recursiva a la siguiente fila
END IF
COLOR 7: LOCATE ifila + 2, icol: PRINT "."; ' quitar reina
continue1:
NEXT icol
END SUB |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Prolog | Prolog | female(0,1).
female(N,F) :- N>0,
N1 is N-1,
female(N1,R),
male(R, R1),
F is N-R1.
male(0,0).
male(N,F) :- N>0,
N1 is N-1,
male(N1,R),
female(R, R1),
F is N-R1. |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Sidef | Sidef | func monteCarloPi(nthrows) {
4 * (^nthrows -> count_by {
hypot(1.rand(2) - 1, 1.rand(2) - 1) < 1
}) / nthrows
}
for n in [1e2, 1e3, 1e4, 1e5, 1e6] {
printf("%9d: %07f\n", n, monteCarloPi(n))
} |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Stata | Stata | program define mcdisk
clear all
quietly set obs `1'
gen x=2*runiform()
gen y=2*runiform()
quietly count if (x-1)^2+(y-1)^2<1
display 4*r(N)/_N
end
. mcdisk 10000
3.1424
. mcdisk 1000000
3.141904
. mcdisk 100000000
3.1416253 |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #PowerShell | PowerShell |
function Send-MorseCode
{
[CmdletBinding()]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[string]
$Message,
[switch]
$ShowCode
)
Begin
{
$morseCode = @{
a = ".-" ; b = "-..." ; c = "-.-." ; d = "-.."
e = "." ; f = "..-." ; g = "--." ; h = "...."
i = ".." ; j = ".---" ; k = "-.-" ; l = ".-.."
m = "--" ; n = "-." ; o = "---" ; p = ".--."
q = "--.-" ; r = ".-." ; s = "..." ; t = "-"
u = "..-" ; v = "...-" ; w = ".--" ; x = "-..-"
y = "-.--" ; z = "--.." ; 0 = "-----"; 1 = ".----"
2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....."
6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----."
}
}
Process
{
foreach ($word in $Message)
{
$word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object {
foreach ($char in $_.ToCharArray())
{
if ($char -in $morseCode.Keys)
{
foreach ($code in ($morseCode."$char").ToCharArray())
{
if ($code -eq ".") {$duration = 250} else {$duration = 750}
[System.Console]::Beep(1000, $duration)
Start-Sleep -Milliseconds 50
}
if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine}
}
}
if ($ShowCode) {Write-Host}
}
if ($ShowCode) {Write-Host}
}
}
}
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Perl | Perl | #! /usr/bin/perl
use strict;
my $trials = 10000;
my $stay = 0;
my $switch = 0;
foreach (1 .. $trials)
{
my $prize = int(rand 3);
# let monty randomly choose a door where he puts the prize
my $chosen = int(rand 3);
# let us randomly choose a door...
my $show;
do { $show = int(rand 3) } while $show == $chosen || $show == $prize;
# ^ monty opens a door which is not the one with the
# prize, that he knows it is the one the player chosen
$stay++ if $prize == $chosen;
# ^ if player chose the correct door, player wins only if he stays
$switch++ if $prize == 3 - $chosen - $show;
# ^ if player switches, the door he picks is (3 - $chosen - $show),
# because 0+1+2=3, and he picks the only remaining door that is
# neither $chosen nor $show
}
print "Stay win ratio " . (100.0 * $stay/$trials) . "\n";
print "Switch win ratio " . (100.0 * $switch/$trials) . "\n"; |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #zkl | zkl | fcn gcdExt(a,b){
if(b==0) return(1,0,a);
q,r:=a.divr(b); s,t,g:=gcdExt(b,r); return(t,s-q*t,g);
}
fcn modInv(a,m){i,_,g:=gcdExt(a,m); if(g==1) {if(i<0)i+m} else Void} |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Go | Go |
package main
import (
"fmt"
)
func main() {
fmt.Print(" x |")
for i := 1; i <= 12; i++ {
fmt.Printf("%4d", i)
}
fmt.Print("\n---+")
for i := 1; i <= 12; i++ {
fmt.Print("----")
}
for j := 1; j <= 12; j++ {
fmt.Printf("\n%2d |", j)
for i := 1; i <= 12; i++ {
if i >= j {
fmt.Printf("%4d", i*j)
} else {
fmt.Print(" ")
}
}
}
fmt.Println("")
}
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #QB64 | QB64 |
DIM SHARED QUEENS AS INTEGER
PRINT "# of queens:";: INPUT QUEENS
IF QUEENS = 0 THEN END
OPEN LTRIM$(STR$(QUEENS)) + "queens.dat" FOR OUTPUT AS #1
PRINT "Queens: Calculates"; QUEENS; " queens problem."
DIM SHARED arrayqcol(QUEENS) AS LONG ' columns of queens
DIM SHARED nsolutions AS LONG
CALL dorow(1) ' start with row 1
LOCATE 22, 1
PRINT STR$(nsolutions) + " solutions"
END
SUB dorow (irow) ' starts with row irow
FOR icol = 1 TO QUEENS
FOR iqueen = 1 TO irow - 1 ' check for conflict with previous queens
IF arrayqcol(iqueen) = icol THEN GOTO continue1 ' same column?
' iqueen is also row of queen
IF iqueen + arrayqcol(iqueen) = irow + icol THEN GOTO continue1 ' right diagonal?
IF iqueen - arrayqcol(iqueen) = irow - icol THEN GOTO continue1 ' left diagonal?
NEXT iqueen
' at this point we can add a queen
arrayqcol(irow) = icol ' add to array
LOCATE irow + 2, icol: PRINT "x"; ' show progress
_DELAY (.001) ' slows processing
IF irow = QUEENS THEN ' solution?
nsolutions = nsolutions + 1
PRINT #1, "Solution #" + MID$(STR$(nsolutions), 2) + "."
FOR i1 = 1 TO QUEENS ' rows
s1$ = STRING$(QUEENS, ".") ' columns
MID$(s1$, arrayqcol(i1), 1) = "x" ' x in queen column
PRINT #1, s1$
NEXT i1
PRINT #1, ""
ELSE
CALL dorow(irow + 1) ' recursive call to next row
END IF
LOCATE irow + 2, icol: PRINT "."; ' remove queen
continue1:
NEXT icol
END SUB
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Pure | Pure | F 0 = 1;
M 0 = 0;
F n = n - M(F(n-1)) if n>0;
M n = n - F(M(n-1)) if n>0; |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Swift | Swift | import Foundation
func mcpi(sampleSize size:Int) -> Double {
var x = 0 as Double
var y = 0 as Double
var m = 0 as Double
for i in 0..<size {
x = Double(arc4random()) / Double(UINT32_MAX)
y = Double(arc4random()) / Double(UINT32_MAX)
if ((x * x) + (y * y) < 1) {
m += 1
}
}
return (4.0 * m) / Double(size)
}
println(mcpi(sampleSize: 100))
println(mcpi(sampleSize: 1000))
println(mcpi(sampleSize: 10000))
println(mcpi(sampleSize: 100000))
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 100000000)) |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Tcl | Tcl | proc pi {samples} {
set i 0
set inside 0
while {[incr i] <= $samples} {
if {sqrt(rand()**2 + rand()**2) <= 1.0} {
incr inside
}
}
return [expr {4.0 * $inside / $samples}]
}
puts "PI is approx [expr {atan(1)*4}]\n"
foreach runs {1e2 1e4 1e6 1e8} {
puts "$runs => [pi $runs]"
} |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Prolog | Prolog |
% convert text to morse
% query text2morse(Text, Morse)
% where
% Text is string to convert
% Morse is Morse representation
% There is a space between chars and double space between words
%
text2morse(Text, Morse) :-
string_lower(Text, TextLower), % rules are in lower case
string_chars(TextLower, Chars), % convert string into list of chars
chars2morse(Chars, MorseChars), % convert each char into morse
string_chars(MorsePlusSpace, MorseChars), % append returned string list into single string
string_concat(Morse, ' ', MorsePlusSpace). % Remove trailing space
chars2morse([], "").
chars2morse([H|CharTail], Morse) :-
morse(H, M),
chars2morse(CharTail, MorseTail),
string_concat(M,' ', MorseSpace),
string_concat(MorseSpace, MorseTail, Morse).
% space
morse(' ', " ").
% letters
morse('a', ".-").
morse('b', "-...").
morse('c', "-.-.").
morse('d', "-..").
morse('e', ".").
morse('f', "..-.").
morse('g', "--.").
morse('h', "....").
morse('i', "..").
morse('j', ".---").
morse('k', "-.-").
morse('l', ".-..").
morse('m', "--").
morse('n', "-.").
morse('o', "---").
morse('p', ".--.").
morse('q', "--.-").
morse('r', ".-.").
morse('s', "...").
morse('t', "-").
morse('u', "..-").
morse('v', "...-").
morse('w', ".--").
morse('x', "-..-").
morse('y', "-.--").
morse('z', "--..").
% numbers
morse('1', ".----").
morse('2', "..---").
morse('3', "...--").
morse('4', "....-").
morse('5', ".....").
morse('6', "-....").
morse('7', "--...").
morse('8', "---..").
morse('9', "----.").
morse('0', "-----").
% common punctuation
morse('.', ".-.-.-").
morse(',', "--..--").
morse('/', "-..-.").
morse('?', "..--..").
morse('=', "-...-").
morse('+', ".-.-.").
morse('-', "-....-").
morse('@', ".--.-.").
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Phix | Phix | with javascript_semantics
integer swapWins = 0, stayWins = 0, winner, choice, reveal, other
atom t0 = time()
for game=1 to 1_000_000 do
winner = rand(3)
choice = rand(3)
while 1 do
reveal = rand(3)
if reveal!=winner and reveal!=choice then exit end if
end while
stayWins += (choice==winner)
other = 6-choice-reveal -- (as 1+2+3=6, and reveal!=choice)
swapWins += (other==winner)
end for
printf(1, "Stay: %,d\nSwap: %,d\nTime: %s\n",{stayWins,swapWins,elapsed(time()-t0)})
|
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Groovy | Groovy | def printMultTable = { size = 12 ->
assert size > 1
// factor1 line
print ' |'; (1..size).each { f1 -> printf('%4d', f1) }; println ''
// dividing line
print '--+'; (1..size).each { printf('----', it) }; println ''
// factor2 result lines
(1..size).each { f2 ->
printf('%2d|', f2)
(1..<f2).each{ print ' ' }
(f2..size).each{ f1 -> printf('%4d', f1*f2) }
println ''
}
}
printMultTable() |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #R | R | queens <- function(n) {
a <- seq(n)
u <- rep(T, 2 * n - 1)
v <- rep(T, 2 * n - 1)
m <- NULL
aux <- function(i) {
if (i > n) {
m <<- cbind(m, a)
} else {
for (j in seq(i, n)) {
k <- a[[j]]
p <- i - k + n
q <- i + k - 1
if (u[[p]] && v[[q]]) {
u[[p]] <<- v[[q]] <<- F
a[[j]] <<- a[[i]]
a[[i]] <<- k
aux(i + 1)
u[[p]] <<- v[[q]] <<- T
a[[i]] <<- a[[j]]
a[[j]] <<- k
}
}
}
}
aux(1)
m
} |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #PureBasic | PureBasic | Declare M(n)
Procedure F(n)
If n = 0
ProcedureReturn 1
ElseIf n > 0
ProcedureReturn n - M(F(n - 1))
EndIf
EndProcedure
Procedure M(n)
If n = 0
ProcedureReturn 0
ElseIf n > 0
ProcedureReturn n - F(M(n - 1))
EndIf
EndProcedure
Define i
If OpenConsole()
For i = 0 To 19
Print(Str(F(i)))
If i = 19
Continue
EndIf
Print(", ")
Next
PrintN("")
For i = 0 To 19
Print(Str(M(i)))
If i = 19
Continue
EndIf
Print(", ")
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Ursala | Ursala | #import std
#import flo
mcp "n" = times/4. div\float"n" (rep"n" (fleq/.5+ sqrt+ plus+ ~~ sqr+ minus/.5+ rand)?/~& plus/1.) 0. |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var mcPi = Fn.new { |n|
var inside = 0
for (i in 1..n) {
var x = rand.float()
var y = rand.float()
if (x*x + y*y <= 1) inside = inside + 1
}
return 4 * inside / n
}
System.print("Iterations -> Approx Pi -> Error\%")
System.print("---------- ---------- ------")
var n = 1000
while (n <= 1e8) {
var pi = mcPi.call(n)
var err = (Num.pi - pi).abs / Num.pi * 100.0
Fmt.print("$9d -> $10.8f -> $6.4f", n, pi, err)
n = n * 10
} |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #PureBasic | PureBasic | #BaseTime =50
#Frequence=1250
#Short = #BaseTime
#Long =3* #BaseTime
#Intergap = #BaseTime
#LetterGap=3* #BaseTime
#WordGap =7* #BaseTime
Declare.s TextToMorse(Text$)
Declare.i PlayMorse(Text$)
Text$ =InputRequester("Morse coder","Enter text to send","Hello RosettaWorld!")
Text$ =TextToMorse(Text$)
If Not (InitSound() And PlayMorse(Text$))
Text$=ReplaceString(Text$, ",","")
MessageRequester("Morse EnCoded",Text$)
EndIf
;-
Procedure PlayMorse(Code$) ;- Beep() is normally only Ok on Windows_x86
CompilerIf #PB_Compiler_Processor=#PB_Processor_x86 And #PB_Compiler_OS=#PB_OS_Windows
Protected i, sign
For i=1 To Len(Code$)
sign=Asc(Mid(Code$,i,1))
Select sign
Case '.': Beep_(#Frequence,#Short): Delay(#Intergap)
Case '-': Beep_(#Frequence,#Long) : Delay(#Intergap)
Case ',': Delay(#LetterGap)
Case ' ': Delay(#WordGap)
EndSelect
Next
ProcedureReturn 1
CompilerElse
ProcedureReturn 0
CompilerEndIf
EndProcedure
Procedure.s TextToMorse(InString$)
Protected *p.Character=@InString$, CurrStr$, i=1
Protected.s s1, s2, result
Repeat
If Not *p\c: Break: EndIf
CurrStr$=UCase(PeekS(*p,1))
*p+StringByteLength(">")
Restore MorseCode
Repeat
Read.s s1
If s1="Done"
s2+s1+" " ; failed to find this coding
Break
ElseIf Not s1=CurrStr$
Continue
EndIf
Read.s s2
result+s2
If s2<>" "
result+","
EndIf
ForEver
ForEver
ProcedureReturn result
EndProcedure
DataSection
MorseCode:
Data.s "A", ".-"
Data.s "B", "-..."
Data.s "C", "-.-."
Data.s "D", "-.."
Data.s "E", "."
Data.s "F", "..-."
Data.s "G", "--."
Data.s "H", "...."
Data.s "I", ".."
Data.s "J", ".---"
Data.s "K", "-.-"
Data.s "L", ".-.."
Data.s "M", "--"
Data.s "N", "-."
Data.s "O", "---"
Data.s "P", ".--."
Data.s "Q", "--.-"
Data.s "R", ".-."
Data.s "S", "..."
Data.s "T", "-"
Data.s "U", "..-"
Data.s "V", "...-"
Data.s "W", ".--"
Data.s "X", "-..-"
Data.s "Y", "-.--"
Data.s "Z", "--.."
Data.s "Á", "--.-"
Data.s "Ä", ".-.-"
Data.s "É", "..-.."
Data.s "Ñ", "--.--"
Data.s "Ö", "---."
Data.s "Ü", "..--"
Data.s "1", ".----"
Data.s "2", "..---"
Data.s "3", "...--"
Data.s "4", "....-"
Data.s "5", "....."
Data.s "6", "-...."
Data.s "7", "--..."
Data.s "8", "---.."
Data.s "9", "----."
Data.s "0", "-----"
Data.s ",", "--..--"
Data.s ".", ".-.-.-"
Data.s "?", "..--.."
Data.s ";", "-.-.-"
Data.s ":", "---..."
Data.s "/", "-..-."
Data.s "-", "-....-"
Data.s "'", ".----."
Data.s "+", ".-.-."
Data.s "-", "-....-"
Data.s #DOUBLEQUOTE$, ".-..-."
Data.s "@", ".--.-."
Data.s "(", "-.--."
Data.s ")", "-.--.-"
Data.s "_", "..--.-"
Data.s "$", "...-..-"
Data.s "&", ".-..."
Data.s "=", "---..."
Data.s " ", " "
Data.s "Done",""
EndOfMorseCode:
EndDataSection |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PHP | PHP | <?php
function montyhall($iterations){
$switch_win = 0;
$stay_win = 0;
foreach (range(1, $iterations) as $i){
$doors = array(0, 0, 0);
$doors[array_rand($doors)] = 1;
$choice = array_rand($doors);
do {
$shown = array_rand($doors);
} while($shown == $choice || $doors[$shown] == 1);
$stay_win += $doors[$choice];
$switch_win += $doors[3 - $choice - $shown];
}
$stay_percentages = ($stay_win/$iterations)*100;
$switch_percentages = ($switch_win/$iterations)*100;
echo "Iterations: {$iterations} - ";
echo "Stayed wins: {$stay_win} ({$stay_percentages}%) - ";
echo "Switched wins: {$switch_win} ({$switch_percentages}%)";
}
montyhall(10000);
?> |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #GW-BASIC | GW-BASIC |
10 ' Multiplication Tables
20 LET N% = 12
30 FOR J% = 1 TO N% - 1
40 PRINT USING "###"; J%;
50 PRINT " ";
60 NEXT J%
70 PRINT USING "###"; N%
80 FOR J% = 0 TO N% - 1
90 PRINT "----";
100 NEXT J%
110 PRINT "+"
120 FOR I% = 1 TO N%
130 FOR J% = 1 TO N%
140 IF J% < I% THEN PRINT " "; ELSE PRINT USING "###"; I% * J%;: PRINT " ";
150 NEXT J%
160 PRINT "| "; USING "##"; I%
170 NEXT I%
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Racket | Racket |
#lang racket
(struct Q (x y) #:transparent)
;; returns true if given q1 and q2 do not conflict
(define (safe? q1 q2)
(match* (q1 q2)
[((Q x1 y1) (Q x2 y2))
(not (or (= x1 x2) (= y1 y2)
(= (abs (- x1 x2)) (abs (- y1 y2)))))]))
;; returns true if given q doesn't conflict with anything in given list of qs
(define (safe-lst? q qs) (for/and ([q2 qs]) (safe? q q2)))
(define (nqueens n)
;; qs is partial solution; x y is current position to try
(let loop ([qs null] [x 0] [y 0])
(cond [(= (length qs) n) qs] ; found a solution
[(>= x n) (loop qs 0 (add1 y))] ; go to next row
[(>= y n) #f] ; current solution is invalid
[else
(define q (Q x y))
(if (safe-lst? q qs) ; is current position safe?
(or (loop (cons q qs) 0 (add1 y)) ; optimistically place a queen
; (and move pos to next row)
(loop qs (add1 x) y)) ; backtrack if it fails
(loop qs (add1 x) y))])))
(nqueens 8)
; => (list (Q 3 7) (Q 1 6) (Q 6 5) (Q 2 4) (Q 5 3) (Q 7 2) (Q 4 1) (Q 0 0))
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Python | Python | def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))
print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ]) |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #XPL0 | XPL0 | code Ran=1, CrLf=9;
code real RlOut=48;
func real MontePi(N); \Calculate pi using Monte Carlo method
int N; \number of randomly selected points
int I, X, Y, C;
def R = 10000; \radius of circle
[C:= 0; \initialize count of points in circle
for I:= 0 to N-1 do
[X:= Ran(R);
Y:= Ran(R);
if X*X + Y*Y <= R*R then C:= C+1;
];
return float(C)*4.0 / float(N); \Acir/Asqr = pi*R^2/4*R^2 = pi/4
];
[RlOut(0, MontePi( 100)); CrLf(0);
RlOut(0, MontePi( 10_000)); CrLf(0);
RlOut(0, MontePi( 1_000_000)); CrLf(0);
RlOut(0, MontePi(100_000_000)); CrLf(0);
] |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #zkl | zkl | fcn monty(n){
inCircle:=0;
do(n){
x:=(0.0).random(1); y:=(0.0).random(1);
if(x*x + y*y < 1.0) inCircle+=1;
}
4.0*inCircle/n
} |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Python | Python | import time, winsound #, sys
char2morse = {
"!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.",
"(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--",
"-": "-....-", ".": ".-.-.-", "/": "-..-.",
"0": "-----", "1": ".----", "2": "..---", "3": "...--",
"4": "....-", "5": ".....", "6": "-....", "7": "--...",
"8": "---..", "9": "----.",
":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..",
"@": ".--.-.",
"A": ".-", "B": "-...", "C": "-.-.", "D": "-..",
"E": ".", "F": "..-.", "G": "--.", "H": "....",
"I": "..", "J": ".---", "K": "-.-", "L": ".-..",
"M": "--", "N": "-.", "O": "---", "P": ".--.",
"Q": "--.-", "R": ".-.", "S": "...", "T": "-",
"U": "..-", "V": "...-", "W": ".--", "X": "-..-",
"Y": "-.--", "Z": "--..",
"[": "-.--.", "]": "-.--.-", "_": "..--.-",
}
e = 50 # Element time in ms. one dit is on for e then off for e
f = 1280 # Tone freq. in hertz
chargap = 1 # Time between characters of a word, in units of e
wordgap = 7 # Time between words, in units of e
def gap(n=1):
time.sleep(n * e / 1000)
off = gap
def on(n=1):
winsound.Beep(f, n * e)
def dit():
on(); off()
def dah():
on(3); off()
def bloop(n=3):
winsound.Beep(f//2, n * e)
def windowsmorse(text):
for word in text.strip().upper().split():
for char in word:
for element in char2morse.get(char, '?'):
if element == '-':
dah()
elif element == '.':
dit()
else:
bloop()
gap(chargap)
gap(wordgap)
# Outputs its own source file as Morse. An audible quine!
#with open(sys.argv[0], 'r') as thisfile:
# windowsmorse(thisfile.read())
while True:
windowsmorse(input('A string to change into morse: '))
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Picat | Picat | go =>
_ = random2(), % different seed
member(Rounds,[1000,10_000,100_000,1_000_000,10_000_000]),
println(rounds=Rounds),
SwitchWins = 0,
StayWins = 0,
NumDoors = 3,
foreach(_ in 1..Rounds)
Winner = choice(NumDoors),
Choice = choice(NumDoors),
% Shown is not needed for the simulation
% Shown = pick([Door : Door in 1..NumDoors, Door != Winner, Door != Choice]),
if Choice == Winner then
StayWins := StayWins + 1
else
SwitchWins := SwitchWins + 1
end
end,
printf("Switch win ratio %0.5f%%\n", 100.0 * SwitchWins/Rounds),
printf("Stay win ratio %0.5f%%\n", 100.0 * StayWins/Rounds),
nl,
fail,
nl.
% pick a number from 1..N
choice(N) = random(1,N).
pick(L) = L[random(1,L.len)]. |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PicoLisp | PicoLisp | (de montyHall (Keep)
(let (Prize (rand 1 3) Choice (rand 1 3))
(if Keep # Keeping the first choice?
(= Prize Choice) # Yes: Monty's choice doesn't matter
(<> Prize Choice) ) ) ) # Else: Win if your first choice was wrong
(prinl
"Strategy KEEP -> "
(let Cnt 0
(do 10000 (and (montyHall T) (inc 'Cnt)))
(format Cnt 2) )
" %" )
(prinl
"Strategy SWITCH -> "
(let Cnt 0
(do 10000 (and (montyHall NIL) (inc 'Cnt)))
(format Cnt 2) )
" %" ) |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Haskell | Haskell | import Data.Maybe (fromMaybe, maybe)
------------------- MULTIPLICATION TABLE -----------------
mulTable :: [Int] -> [[Maybe Int]]
mulTable xs =
(Nothing : labels) :
zipWith
(:)
labels
[[upperMul x y | y <- xs] | x <- xs]
where
labels = Just <$> xs
upperMul x y
| x > y = Nothing
| otherwise = Just (x * y)
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn . unlines $
showTable . mulTable
<$> [ [13 .. 20],
[1 .. 12],
[95 .. 100]
]
------------------------ FORMATTING ----------------------
showTable :: [[Maybe Int]] -> String
showTable xs = unlines $ head rows : [] : tail rows
where
w = succ $ (length . show) (fromMaybe 0 $ (last . last) xs)
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
rjust n c = (drop . length) <*> (replicate n c <>) |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Raku | Raku | sub MAIN(\N = 8) {
sub collision(@field, $row) {
for ^$row -> $i {
my $distance = @field[$i] - @field[$row];
return True if $distance == any(0, $row - $i, $i - $row);
}
False;
}
sub search(@field, $row) {
return @field if $row == N;
for ^N -> $i {
@field[$row] = $i;
return search(@field, $row + 1) || next
unless collision(@field, $row);
}
()
}
for 0 .. N / 2 {
if search [$_], 1 -> @f {
say @f;
last;
}
}
} |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Quackery | Quackery | forward is f ( n --> n )
[ dup 0 = if done
dup 1 - recurse f - ] is m ( n --> n )
[ dup 0 = iff 1+ done
dup 1 - recurse m - ]
resolves f ( n --> n )
say "f = "
20 times [ i^ f echo sp ] cr
say "m = "
20 times [ i^ m echo sp ] cr |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Racket | Racket |
#lang racket
(require ffi/unsafe ffi/unsafe/define)
(define-ffi-definer defmm (ffi-lib "Winmm"))
(defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f]
[_pointer = #f] [_int32 = 0] -> _void -> h))
(defmm midiOutShortMsg (_fun _int32 _int32 -> _void))
(define M (midiOutOpen))
(define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z))))
(define raw-codes
'("a.-|b-...|c-.-.|d-..|e.|f..-.|g--.|h....|i..|j.---|k-.-|l.-..|m--|n-."
"|o---|p--.-|q--.-|r.-.|s...|t-|u..-|v...-|w.--|x-..-|y-.--|z--..|1.----"
"|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----"))
(define codes
(for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))])
(cons (string-ref x 0) (substring x 1))))
(define (morse str [unit 0.1])
(define (sound len)
(midi #x90 72 127) (sleep (* len unit))
(midi #x90 72 0) (sleep unit))
(define (play str)
(midi #xC0 #x35 0) ; use a cute voice
(for ([c str])
(case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))])))
(let* ([str (string-foldcase str)]
[str (regexp-replace* #rx"[,:;]+" str " ")]
[str (regexp-replace* #rx"[.!?]+" str ".")]
[str (string-normalize-spaces str)])
(for ([s (string-split str)])
(define m
(string-join
(for/list ([c s])
(cond [(assq c codes) => cdr]
[else (case c [(#\space) " "] [(#\.) " "] [else ""])]))))
(printf "~a: ~a\n" s m)
(play (string-append m " ")))))
(morse "Say something here")
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PL.2FI | PL/I | *process source attributes xref;
ziegen: Proc Options(main);
/* REXX ***************************************************************
* 30.08.2013 Walter Pachl derived from Java
**********************************************************************/
Dcl (switchWins,stayWins) Bin Fixed(31) Init(0);
Dcl doors(3) Bin Fixed(31);
Dcl (plays,r,choice) Bin Fixed(31) Init(0);
Dcl c17 Char(17) Init((datetime()));
Dcl p9 Pic'(9)9' def(c17) pos(5);
i=random(p9);
Do plays=1 To 1000000;
doors=0;
r=r3();
doors(r)=1;
choice=r3();
Do Until(shown^=choice & doors(shown)=0);
shown=r3();
End;
If doors(choice)=1 Then
stayWins+=1;
Else
switchWins+=1;
End;
Put Edit("Switching wins ",switchWins," times.")(Skip,a,f(6),a);
Put Edit("Staying wins ",stayWins ," times.")(Skip,a,f(6),a);
r3: Procedure Returns(Bin Fixed(31));
/*********************************************************************
* Return a random integer: 1, 2, or 3
*********************************************************************/
Dcl r Bin Float(53);
Dcl res Bin Fixed(31);
r=random();
res=(r*3)+1;
Return(res);
End;
End; |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #hexiscript | hexiscript | fun format n l
let n tostr n
while len n < l; let n (" " + n); endwhile
return n
endfun
print " |"
for let i 1; i <= 12; i++; print format i 4; endfor
print "\n --+"
for let i 1; i <= 12; i++; print "----"; endfor
println ""
for let i 1; i <= 12; i++
print format i 3 + "|"
for let j 1; j <= 12; j++
if j < i; print " "
else print format (i * j) 4; endif
endfor
println ""
endfor |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Rascal | Rascal | import Prelude;
public set[list[int]] Nqueens(int n){
cols = upTill(n);
result = {};
for (vector <- permutations(cols)){
if (n == size({vector[j] + j |j <- cols}) && n == size({vector[j] - j |j <- cols}))
result += vector;}
return result;
} |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #R | R | F <- function(n) ifelse(n == 0, 1, n - M(F(n-1)))
M <- function(n) ifelse(n == 0, 0, n - F(M(n-1))) |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Raku | Raku | my %m = ' ', '_ _ ',
|<
! ---.
" .-..-.
$ ...-..-
' .----.
( -.--.
) -.--.-
+ .-.-.
, --..--
- -....-
. .-.-.-
/ -..-.
: ---...
; -.-.-.
= -...-
? ..--..
@ .--.-.
[ -.--.
] -.--.-
_ ..--.-
0 -----
1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.
A .-
B -...
C -.-.
D -..
E .
F ..-.
G --.
H ....
I ..
J .---
K -.-
L .-..
M --
N -.
O ---
P .--.
Q --.-
R .-.
S ...
T -
U ..-
V ...-
W .--
X -..-
Y -.--
Z --..
>.map: -> $c, $m is copy {
$m.=subst(rx/'-'/, 'BGAAACK!!! ', :g);
$m.=subst(rx/'.'/, 'buck ', :g);
$c => $m ~ '_';
}
say prompt("Gimme a string: ").uc.comb.map: { %m{$_} // "<scratch> " } |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PostScript | PostScript | %!PS
/Courier % name the desired font
20 selectfont % choose the size in points and establish
% the font as the current one
% init random number generator
(%Calendar%) currentdevparams /Second get srand
1000000 % iteration count
0 0 % 0 wins on first selection 0 wins on switch
2 index % get iteration count
{
rand 3 mod % winning door
rand 3 mod % first choice
eq {
1 add
}
{
exch 1 add exch
} ifelse
} repeat
% compute percentages
2 index div 100 mul exch 2 index div 100 mul
% display result
70 600 moveto
(Switching the door: ) show
80 string cvs show (%) show
70 700 moveto
(Keeping the same: ) show
80 string cvs show (%) show
showpage % print all on the page |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #HicEst | HicEst | WRITE(Row=1) " x 1 2 3 4 5 6 7 8 9 10 11 12"
DO line = 1, 12
WRITE(Row=line+2, Format='i2') line
DO col = line, 12
WRITE(Row=line+2, Column=4*col, Format='i3') line*col
ENDDO
ENDDO |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #REXX | REXX | /*REXX program places N queens on an NxN chessboard (the eight queens problem). */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 8 /*Not specified: Then use the default.*/
if N<1 then call nOK /*display a message, the board is bad. */
rank= 1; file= 1; #= 0 /*starting rank&file; #≡number queens.*/
@.= 0; pad= left('', 9* (N<18) ) /*define empty board; set indentation.*/
/* [↓] rank&file ≡ chessboard row&cols*/
do while #<N; @.file.rank= 1 /*keep placing queens until we're done.*/
if ok(file, rank) then do; file= 1; #= #+1 /*Queen not being attacked? Then eureka*/
rank= rank+1 /*use another attempt at another rank. */
iterate /*go and try another queen placement. */
end /* [↑] found a good queen placement. */
@.file.rank= 0 /*It isn't safe. So remove this queen.*/
file= file + 1 /*So, try the next (higher) chess file.*/
do while file>N; rank= rank - 1; if rank==0 then call nOK
do j=1 for N; if \@.j.rank then iterate /*¿ocupado?*/
@.j.rank= 0; #= # - 1; file= j + 1; leave
end /*j*/
end /*while file>N*/
end /*while #<N*/
call show /*display the chess board with queens. */
exit 1 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
nOK: say; say "No solution for" N 'queens.'; say; exit 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
ok: parse arg f,r; fp= f + 1; rm= r - 1 /*if return≡0, then queen isn't safe. */
do k=1 for rm; if @.f.k then return 0; end
f= f-1; do k=rm by -1 for rm while f\==0; if @.f.k then return 0; f= f-1; end
f= fp; do k=rm by -1 for rm while f <=N; if @.f.k then return 0; f= f+1; end
return 1 /*1≡queen is safe. */ /* ↑↑↑↑↑↑↑↑ is queen under attack? */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: say 'A solution for ' N " queens:" /*display a title to the terminal.*/
g= substr( copies("╬═══", N) ,2) /*start of all cells on chessboard*/
say; say pad translate('╔'g"╗", '╦', "╬") /*display top rank (of the board).*/
line = '╠'g"╣"; dither= "▓"; ditherQ= '░' /*define a line for cell boundary.*/
bar = '║' ; queen = "Q" /*kinds: horiz., vert., salad.*/
Bqueen = ditherQ || queen || ditherQ /*glyph befitting a black square Q*/
Wqueen = ' 'queen" " /* " " " white " "*/
do rank=1 for N; if rank\==1 then say pad line; _= /*show rank sep. */
do file=1 for N
B = (file + rank) // 2 /*Is the square black ? Then B=1.*/
if B then Qgylph= Bqueen /*if black square, use dithered Q.*/
else Qgylph= Wqueen /* " white " " white " */
if @.file.rank then _= _ || bar || Qgylph /*Has queen? Use a 3─char Q symbol*/
else if B then _=_ || bar || copies(dither,3) /*dithering */
else _=_ || bar || copies( ' ' ,3) /* 3 blanks */
end /*file*/ /* [↑] preserve square─ish board.*/
say pad _ || bar /*show a single rank of the board.*/
end /*rank*/ /*80 cols can view a 19x19 board.*/
say pad translate('╚'g"╝", '╩', "╬"); return /*display the last rank (of board)*/ |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Racket | Racket | #lang racket
(define (F n)
(if (>= 0 n)
1
(- n (M (F (sub1 n))))))
(define (M n)
(if (>= 0 n)
0
(- n (F (M (sub1 n)))))) |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Red | Red | Red [
file: %morse.red ;; filename, could be ommited
]
; ";" is character for comment, i use double ones for better readability
DIT: 100 ;; constant : 100 ms for short Beep
FREQ: 700 ;; frequency for Beep
;; exported code for red/system win api calls to Beep / Sleep:
#include %api.reds
;; string with morse codes for alphabet:
;; ( caution, u must use "str: copy ..." if code ist to be executed multiple times ! )
str: "A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-."
append str "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.."
delim: charset [#"A" - #"Z"]
;; use of parse to generate "mc" morse code series / array containing codes for A - Z
;; use characters only as delimiter for each code
mc: parse str [ thru "A" collect some [ keep copy result to [delim | end ] skip ] ]
;;--------------------------------------------
send-code: func ["function to play morse code for character "
;;--------------------------------------------
chr [char!] ;; character A .. Z
][
sleep 500 ;; short break so u can read the character first
ind: to-integer chr - 64 ;; calculate index for morse array
foreach sym mc/:ind [ ;; foreach symbol of code for character ...
prin sym ;; prin(t) "." or "-"
either sym = #"." [ ;; short beep
beep FREQ DIT
][
beep FREQ 3 * DIT ;; or long beep = 3 x short
]
sleep DIT ;; short break after each character
]
]
;;----------------------------------------------
morse-text: func ["extract valid characters from sentence"
;;----------------------------------------------
msg [string!]
][
foreach chr uppercase msg [
prin chr prin " " ;; print character
;; valid character A-Z ?
either (chr >= #"A") and (chr <= #"Z") [
send-code chr
] [ ;; ... "else" word gap or unknown
sleep 6 * DIT ;; pause after word
]
prin newline ;; equal to : print """ ,( prin prints without crlf )
]
sleep 6 * DIT ;; pause after sentence
]
;;----------------------------------
morse-text "rosetta code"
morse-text "hello world"
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PowerShell | PowerShell | #Declaring variables
$intIterations = 10000
$intKept = 0
$intSwitched = 0
#Creating a function
Function Play-MontyHall()
{
#Using a .NET object for randomization
$objRandom = New-Object -TypeName System.Random
#Generating the winning door number
$intWin = $objRandom.Next(1,4)
#Generating the chosen door
$intChoice = $objRandom.Next(1,4)
#Generating the excluded number
#Because there is no method to exclude a number from a range,
#I let it re-generate in case it equals the winning number or
#in case it equals the chosen door.
$intLose = $objRandom.Next(1,4)
While (($intLose -EQ $intWin) -OR ($intLose -EQ $intChoice))
{$intLose = $objRandom.Next(1,4)}
#Generating the 'other' door
#Same logic applies as for the chosen door: it cannot be equal
#to the winning door nor to the chosen door.
$intSwitch = $objRandom.Next(1,4)
While (($intSwitch -EQ $intLose) -OR ($intSwitch -EQ $intChoice))
{$intSwitch = $objRandom.Next(1,4)}
#Simple counters per win for both categories
#Because a child scope cannot change variables in the parent
#scope, the scope of the counters is expanded script-wide.
If ($intChoice -EQ $intWin)
{$script:intKept++}
If ($intSwitch -EQ $intWin)
{$script:intSwitched++}
}
#Looping the Monty Hall function for $intIterations times
While ($intIterationCount -LT $intIterations)
{
Play-MontyHall
$intIterationCount++
}
#Output
Write-Host "Results through $intIterations iterations:"
Write-Host "Keep : $intKept ($($intKept/$intIterations*100)%)"
Write-Host "Switch: $intSwitched ($($intSwitched/$intIterations*100)%)"
Write-Host "" |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #HolyC | HolyC | U8 i, j, n = 12;
for (j = 1; j <= n; j++)
if (j != n)
Print("%3d%c", j, ' ');
else
Print("%3d%c", j, '\n');
for (j = 0; j <= n; j++)
if (j != n)
Print("----");
else
Print("+\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
if (j < i)
Print(" ");
else
Print("%3d ", i * j);
Print("| %d\n", i);
} |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Ring | Ring |
// Bert Mariani 2020-07-17
See "Enter value of N : " Give n // Ask User for Size of Board
n = 0 + n
x = 1:n
See "Possible placements: Value as Column of the Row "+ nl
nQueen(1,n) //===>>> START
See nl+ nl+"Enter to Exit program: " Give m // To Exit CMD window
//================================
// Returns true only and only if two queens can be placed in same row or column
Func Place(k,i)
for j = 1 to k-1
if( x[j] = i OR //two queens in same row
fabs(x[j]-i) = fabs(j-k) ) //two queens in same diagonal
return 0;
ok
next
return 1;
//================================
Func nQueen(k,n)
for i = 1 to n
if(place(k,i)) //===>>> Call
x[k] = i
if(k=n)
See nl
for i = 1 to n
See " "+ x[i]
next
else
nQueen(k+1,n) //===>>> RECURSION
ok
ok
next
return
//================================
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Raku | Raku | multi F(0) { 1 }; multi M(0) { 0 }
multi F(\𝑛) { 𝑛 - M(F(𝑛 - 1)) }
multi M(\𝑛) { 𝑛 - F(M(𝑛 - 1)) }
say map &F, ^20;
say map &M, ^20; |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #REXX | REXX | -∙-∙ --∙- -∙∙
-∙∙∙∙- -∙∙∙∙- -∙∙∙∙-
∙∙ -∙ -∙∙ ∙∙ -∙-∙ ∙- - ∙ ∙∙∙
- ∙∙∙∙ ∙
∙∙∙- ∙ ∙∙∙ ∙∙∙ ∙ ∙-∙∙
∙∙∙ ∙ -∙ -∙∙ ∙∙ -∙ --∙
∙∙ ∙∙∙
∙∙ -∙
-∙∙ ∙∙ ∙∙∙ - ∙-∙ ∙ ∙∙∙ ∙∙∙
∙- -∙ -∙∙
∙-∙ ∙ --∙- ∙∙- ∙∙ ∙-∙ ∙ ∙∙∙
∙∙ -- -- ∙ -∙∙ ∙∙ ∙- - ∙
∙- ∙∙∙ ∙∙∙ ∙∙ ∙∙∙ - ∙- -∙ -∙-∙ ∙ ∙-∙-∙-
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Prolog | Prolog |
:- initialization(main).
% Simulate a play.
play(Switch, Won) :-
% Random prize door
random(1, 4, P),
% Random contestant door
random(1, 4, C),
% Random reveal door, not prize or contestant door
repeat,
random(1, 4, R),
R \= P,
R \= C,
!,
% Final door
(
Switch, between(1, 3, F), F \= C, F \= R, !;
\+ Switch, F = C
),
% Check result.
(F = P -> Won = true ; Won = false).
% Count wins.
win_count(0, _, Total, Total).
win_count(I, Switch, A, Total) :-
I > 0,
I1 is I - 1,
play(Switch, Won),
(Won, A1 is A + 1;
\+ Won, A1 is A),
win_count(I1, Switch, A1, Total).
main :-
randomize,
win_count(1000, true, 0, SwitchTotal),
format('Switching wins ~d out of 1000.\n', [SwitchTotal]),
win_count(1000, false, 0, StayTotal),
format('Staying wins ~d out of 1000.\n', [StayTotal]).
|
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
lim := 13
wid := 5
every writes(right("* |" | (1 to lim) | "\n",wid)|right("\n",wid*(lim+1),"_")) # header row and separator
every (i := 1 to lim) &
writes(right( i||" |" | (j := 1 to lim, if j < i then "" else i*j) | "\n",wid)) # table content and triangle
end |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Ring_2 | Ring |
load "stdlib.ring"
load "guilib.ring"
size = 8
newSize = size
count = 0
sizeBoard = 0
Queens = list(size)
Board = []
badBoard = []
win = null
nMoves = 0
oldx = 0
oldy = 0
bWidth = 0
bHeight = 0
moveX = 550 moveY = 140 ### Open Window on Screen Position
sizeX = 800 sizeY = 800 ### Size of Window
Button = null
cmbSize = null
Pink = newlist(size,size)
Tiles = newlist(size,size)
TitleMoves = null
lineSize = null
LayoutButtonRow = list(size)
LayoutButtonMain = null
WQueen = "WQueen.png"
oPic = new QPixmap("WQueen.png")
oPicGray = new QPixmap("Gray.png")
oPicGreen = new QPixmap("Green.png")
nMoves = 0
wwidth = 0
wheight = 0
WinWidth = 0
WinHeight = 0
C_Spacing = 2
C_ButtonFirstStyle = 'border-radius:1px; color:black; background-color: rgb(229,249,203) ;' ### Square pale
###'border-style: outset; border-width: 2px; border-radius: 2px; border-color: gray;'
C_ButtonSecondStyle = 'border-radius:1px; color:black; background-color: rgb(179,200,93); ' ### Square dark
###'border-style: outset; border-width: 2px; border-radius: 2px; border-color: darkGray; '
C_ButtonPinkStyle = 'border-radius:1px; color:black; background-color: rgb(255,179,191); ' ### light pink
###'border-style: outset; border-width: 2px; border-radius: 2px; border-color: darkGray; '
app = new qApp
{
DrawWidget()
newWindow(size)
exec()
}
### FUNCTIONS
###============================================================
Func DrawWidget()
### Global definition for win
win = new qWidget()
{
# Set the Window Icon
setWindowIcon(new qIcon(new qPixmap(WQueen)))
win.setminimumwidth(700)
win.setminimumheight(700)
Button = newList(size, size) ### Internal Array with Letters
setWindowTitle('Eight Queens Game')
setStyleSheet('background-color:White')
workHeight = win.height()
fontSize = 8 + (workHeight / 100)
move(moveX, moveY)
resize(700,700)
wwidth = win.width()
wheight = win.height()
bwidth = wwidth/size
bheight = wheight/size
myfilter = new qallevents(win)
myfilter.setResizeEvent("resizeBoard()")
installeventfilter(myfilter)
###----------------------------------------------
### Title Top Row - Moves Count
TitleMoves = new qLineEdit(win)
{
setStyleSheet("background-color:rgb(255,255,204)")
setFont(new qFont("Calibri",fontsize,100,0))
setAlignment( Qt_AlignHCenter)
setAlignment( Qt_AlignVCenter)
setText(" Moves: "+ nMoves)
}
sizeBtn = new QPushButton(win)
{
setStyleSheet("background-color:rgb(255,255,204)")
setFont(new qFont("Calibri",fontsize,100,0))
setText(" Enter size: ")
}
lineSize = new qLineEdit(win)
{
setStyleSheet("background-color:rgb(255,255,204)")
setFont(new qFont("Calibri",fontsize,100,0))
setAlignment( Qt_AlignHCenter)
setAlignment( Qt_AlignVCenter)
setreturnPressedEvent("newBoardSize()")
setText(" 8 ")
}
SolveGame = new QPushButton(win)
{
setStyleSheet("background-color:rgb(255,204,229)")
setFont(new qFont("Calibri",fontsize,100,0))
setText(" Solve ")
setClickEvent("solveGame()")
}
NewGame = new QPushButton(win)
{
setStyleSheet("background-color:rgb(255,204,229)")
setFont(new qFont("Calibri",fontsize,100,0))
setText(" New ")
setClickEvent("newGame()")
}
btnQuit = new QPushButton(win)
{
setStyleSheet("background-color:rgb(255,204,229)")
setFont(new qFont("Calibri",fontsize,100,0))
setText("Exit")
setClickEvent("pQuit()")
}
###------------------------------------------------
### QVBoxLayout lays out widgets in a vertical column, from top to bottom.
### Vertical
LayoutButtonMain = new QVBoxLayout()
LayoutButtonMain.setSpacing(C_Spacing)
LayoutButtonMain.setContentsMargins(5,5,5,5)
### Horizontal - TOP ROW
LayoutTitleRow = new QHBoxLayout()
{
setSpacing(C_Spacing)
setContentsMargins(0,0,0,0)
}
LayoutTitleRow.AddWidget(TitleMoves)
LayoutTitleRow.AddWidget(sizeBtn)
LayoutTitleRow.AddWidget(lineSize)
LayoutTitleRow.AddWidget(SolveGame)
LayoutTitleRow.AddWidget(NewGame)
LayoutTitleRow.AddWidget(btnQuit)
LayoutButtonMain.AddLayout(LayoutTitleRow)
###----------------------------------------------
### BUTTON ROWS
LayoutButtonRow = list(size)
### QHBoxLayout lays out widgets in a horizontal row, from left to right
odd = 1
for Row = 1 to size
LayoutButtonRow[Row] = new QHBoxLayout() ### Horizontal
{
setSpacing(C_Spacing)
setContentsmargins(0,0,0,0)
}
for Col = 1 to size
### Create Buttons
Button[Row][Col] = new QPushButton(win)
{
if odd % 2 = 0
setStyleSheet(C_ButtonFirstStyle)
odd++
else
setStyleSheet(C_ButtonSecondStyle)
odd++
ok
setClickEvent("UserLeftClick(" + string(Row) +
"," + string(Col) + ")")
setSizePolicy(1,1)
resize(bwidth,bheight)
}
### Widget - Add HORZ BOTTON
LayoutButtonRow[Row].AddWidget(Button[Row][Col])
next
if size % 2 = 0
odd++
ok
### Layout - Add ROW of BUTTONS
LayoutButtonMain.AddLayout(LayoutButtonRow[Row])
next
###-------------------------------------------------
setLayout(LayoutButtonMain)
show()
}
return
###============================================================
func newSize()
nSize = cmbSize.currentText()
nSize = number(nSize)
count = 0
newWindow(nSize)
###============================================================
func newBoardSize()
nrSize = number(lineSize.text())
newWindow(nrSize)
###============================================================
func newWindow(newSize)
for Row = 1 to size
for Col = 1 to size
Button[Row][Col].delete()
next
next
size = newSize
nMoves = 0
TitleMoves.settext(" Moves: 0")
Tiles = newlist(size,size)
for Row = 1 to size
for Col = 1 to size
Tiles[Row][Col] = 0
next
next
wwidth = win.width()
wheight = win.height()
bwidth = wwidth/size
bheight = wheight/size
win.resize(500,500)
Button = newlist(size,size)
Pink = newlist(size,size)
LayoutButtonRow = list(size)
### QHBoxLayout lays out widgets in a horizontal row, from left to right
odd = 1
for Row = 1 to size
LayoutButtonRow[Row] = new QHBoxLayout() ### Horizontal
{
setSpacing(C_Spacing)
setContentsmargins(0,0,0,0)
}
for Col = 1 to size
### Create Buttons
Button[Row][Col] = new QPushButton(win)
{
if odd % 2 = 1
setStyleSheet(C_ButtonFirstStyle)
odd++
else
setStyleSheet(C_ButtonSecondStyle)
odd++
ok
setClickEvent("UserLeftClick(" + string(Row) +
"," + string(Col) + ")")
setSizePolicy(1,1)
resize(bwidth,bheight)
}
### Widget - Add HORZ BOTTON
LayoutButtonRow[Row].AddWidget(Button[Row][Col])
next
if size % 2 = 0
odd++
ok
### Layout - Add ROW of BUTTONS
LayoutButtonMain.AddLayout(LayoutButtonRow[Row])
next
###-------------------------------------------------
win.setLayout(LayoutButtonMain)
###============================================================
func solveGame()
newWindow(size)
for Row = 1 to size
for Col = 1 to size
Tiles[Row][Col] = 0
next
next
bwidth = (win.width() -8 ) / size // <<< QT FIX because of Win Title
bheight = (win.height() -32) / size // <<< QT FIX because of Win Title
odd = 1
for Row = 1 to size
for Col = 1 to size
if odd % 2 = 1
setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight)
odd++
else
setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight)
odd++
ok
next
if size % 2 = 0
odd++
ok
next
Queens = list(20)
n = size
count = count + 1
if count = 1
Board = []
queen(1,n)
ok
sizeBoard = len(Board)/size
num = random(sizeBoard-1) + 1
see "Solution = " + num + nl
for n = (num-1)*size+1 to num*size
x = Board[n][2]
y = Board[n][1]
Tiles[x][y] = 1
setButtonImage(Button[x][y],oPic,bwidth-8,bheight)
next
###============================================================
func prn(n)
for i = 1 to n
for j = 1 to n
if Queens[i] = j
add(Board,[i,j])
ok
next
next
###============================================================
func place(row,column)
for i = 1 to row-1
if Queens[i]=column
return 0
else
if fabs(Queens[i]-column) = fabs(i-row)
return 0
ok
ok
next
return 1
###============================================================
func queen(row,n)
for column = 1 to n
if place(row,column)
Queens[row] = column
if row = n
prn(n)
else
queen(row+1,n)
ok
ok
next
###============================================================
func newGame
newWindow(size)
return
###============================================================
func canPlace Row,Col
badBoard = []
add(badBoard,[Row,Col])
bwidth = (win.width() -8 ) / size // <<< QT FIX because of Win Title
bheight = (win.height() -32) / size // <<< QT FIX because of Win Title
cp1 = 1
for n = 1 to size
if Row < 9
if n != Col and Tiles[Row][n] = 1
cp1 = 0
add(badBoard,[Row,n])
exit
ok
ok
next
cp2 = 1
for n = 1 to size
if Col < 9
if n != Row and Tiles[n][Col] = 1
cp2 = 0
add(badBoard,[n,Col])
exit
ok
ok
next
cp3 = 1
for x = 1 to size
if Row + x < size + 1 and Col - x > 0
if Tiles[Row+x][Col-x] = 1
cp3 = 0
add(badBoard,[Row+x,Col-x])
exit
ok
ok
next
cp4 = 1
for x = 1 to size
if Row - x > 0 and Col + x < size + 1
if Tiles[Row-x][Col+x] = 1
cp4 = 0
add(badBoard,[Row-x,Col+x])
exit
ok
ok
next
cp5 = 1
for x = 1 to size
if Row + x < size + 1 and Col + x < size + 1
if Tiles[Row+x][Col+x] = 1
cp5 = 0
add(badBoard,[Row+x,Col+x])
exit
ok
ok
next
cp6 = 1
for x = 1 to size
if Row - x > 0 and Col - x > 0
if Tiles[Row-x][Col-x] = 1
cp6 = 0
add(badBoard,[Row-x,Col-x])
exit
ok
ok
next
cp7 = cp1 and cp2 and cp3 and cp4 and cp5 and cp6
return cp7
###============================================================
func resizeBoard
bwidth = (win.width() - 8) / size
bheight = (win.height() - 32) / size
for Row = 1 to size
for Col = 1 to size
if Tiles[Row][Col] = 1
setButtonImage(Button[Row][Col],oPic,bwidth - 8,bheight - 8)
ok
next
next
###============================================================
func UserLeftClick Row,Col
sleep(0.3)
Tiles[Row][Col] = 1
bWidthHeight()
bool = (Row = oldx) and (Col = oldy)
cp8 = canPlace(Row,Col)
if Pink[Row][Col] = 1
Pink[Row][Col] = 0
Tiles[Row][Col] = 0
if Row % 2 = 1 and Col % 2 = 1
Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
ok
if Row % 2 = 0 and Col % 2 = 0
Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
ok
if Row % 2 = 1 and Col % 2 = 0
Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
ok
if Row % 2 = 0 and Col % 2 = 1
Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
ok
checkBoard()
return
ok
if cp8 = 1 and bool = 0
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
Tiles[Row][Col] = 1
nMoves = nMoves + 1
oldx = Row
oldy = Col
TitleMoves.settext(" Moves: " + nMoves)
gameOver()
ok
if cp8 = 1 and bool = 1
if Row % 2 = 1 and Col % 2 = 1
setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
ok
if Row % 2 = 0 and Col % 2 = 0
setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
ok
if Row % 2 = 1 and Col % 2 = 0
setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
ok
if Row % 2 = 0 and Col % 2 = 1
setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
ok
Tiles[Row][Col] = 1
ok
for Row = 1 to size
for Col = 1 to size
if Tiles[Row][Col] = 1
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
ok
next
next
if cp8 = 0
pBadCell(Row,Col)
return
ok
###============================================================
func checkBoard()
for Row = 1 to size
for Col = 1 to size
if Pink[Row][Col] = 1
cp9 = canPlace(Row,Col)
if cp9 = 0
Button[Row][Col].setStyleSheet(C_ButtonPinkStyle)
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight)
else
if Row % 2 = 1 and Col % 2 = 1
Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
ok
if Row % 2 = 0 and Col % 2 = 0
Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
ok
if Row % 2 = 1 and Col % 2 = 0
Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
ok
if Row % 2 = 0 and Col % 2 = 1
Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
ok
ok
ok
next
next
###============================================================
func pBadCell(Row,Col)
for n = 1 to len(badBoard)
Row = badBoard[n][1]
Col = badBoard[n][2]
Pink[Row][Col] = 1
Button[Row][Col].setStyleSheet(C_ButtonPinkStyle)
setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight)
next
###============================================================
func setButtonImage oBtn,oPixmap,width,height
oBtn { setIcon(new qicon(oPixmap.scaled(width(),height(),0,0)))
setIconSize(new QSize(width,height))
}
###============================================================
func bWidthHeight()
bWidth = (win.width() -8 ) / size
bHeight = (win.height() -32) / size
###============================================================
func msgBox cText
mb = new qMessageBox(win) {
setWindowTitle('Eight Queens')
setText(cText)
setstandardbuttons(QMessageBox_OK)
result = exec()
}
###============================================================
func pQuit()
win.close()
###============================================================
func gameOver
total = 0
for Row = 1 to size
for Col = 1 to size
if Tiles[Row][Col] = 1
total = total + 1
ok
next
next
if total = size
for Row = 1 to size
for Col = 1 to size
Button[Row][Col].setenabled(false)
next
next
msgBox("You Win!")
ok
###============================================================
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #REBOL | REBOL | rebol [
Title: "Mutual Recursion"
URL: http://rosettacode.org/wiki/Mutual_Recursion
References: [http://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences]
]
f: func [
"Female."
n [integer!] "Value."
] [either 0 = n [1][n - m f n - 1]]
m: func [
"Male."
n [integer!] "Value."
] [either 0 = n [0][n - f m n - 1]]
fs: [] ms: [] for i 0 19 1 [append fs f i append ms m i]
print ["F:" mold fs crlf "M:" mold ms] |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Ring | Ring |
morsecode = [["a", ".-"],
["b", "-..."],
["c", "-.-."],
["d", "-.."],
["e", "."],
["f", "..-."],
["g", "--."],
["h", "...."],
["i", ".."],
["j", ".---"],
["k", "-.-"],
["l", ".-.."],
["m", "--"],
["n", "-."],
["o", "---"],
["p", ".--."],
["q", "--.-"],
["r", ".-."],
["s", "..."],
["t", "-"],
["u", "..-"],
["v", "...-"],
["w", ".--"],
["x", "-..-"],
["y", "-.--"],
["z", "--.."],
["0", "-----"],
["1", ".----"],
["2", "..---"],
["3", "...--"],
["4", "....-"],
["5", "....."],
["6", "-...."],
["7", "--..."],
["8", "---.."],
["9", "----."]]
strmorse = ""
str = "this is a test text"
for n = 1 to len(str)
pos = 0
for m = 1 to len(morsecode)
if morsecode[m][1] = str[n]
pos = m
ok
next
if str[n] = " "
strmorse = strmorse + " "
else
if pos > 0
strmorse = strmorse + morsecode[pos][2] + "|"
ok
ok
next
strmorse = left(strmorse,len(strmorse)-1)
see strmorse + nl
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #PureBasic | PureBasic | Structure wins
stay.i
redecide.i
EndStructure
#goat = 0
#car = 1
Procedure MontyHall(*results.wins)
Dim Doors(2)
Doors(Random(2)) = #car
player = Random(2)
Select Doors(player)
Case #car
*results\redecide + #goat
*results\stay + #car
Case #goat
*results\redecide + #car
*results\stay + #goat
EndSelect
EndProcedure
OpenConsole()
#Tries = 1000000
Define results.wins
For i = 1 To #Tries
MontyHall(@results)
Next
PrintN("Trial runs for each option: " + Str(#Tries))
PrintN("Wins when redeciding: " + Str(results\redecide) + " (" + StrD(results\redecide / #Tries * 100, 2) + "% chance)")
PrintN("Wins when sticking: " + Str(results\stay) + " (" + StrD(results\stay / #Tries * 100, 2) + "% chance)")
Input() |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #J | J | multtable=: <:/~ * */~
format=: 'b4.0' 8!:2 ]
(('*' ; ,.) ,. ({. ; ])@format@multtable) >:i.12
┌──┬────────────────────────────────────────────────┐
│* │ 1 2 3 4 5 6 7 8 9 10 11 12│
├──┼────────────────────────────────────────────────┤
│ 1│ 1 2 3 4 5 6 7 8 9 10 11 12│
│ 2│ 4 6 8 10 12 14 16 18 20 22 24│
│ 3│ 9 12 15 18 21 24 27 30 33 36│
│ 4│ 16 20 24 28 32 36 40 44 48│
│ 5│ 25 30 35 40 45 50 55 60│
│ 6│ 36 42 48 54 60 66 72│
│ 7│ 49 56 63 70 77 84│
│ 8│ 64 72 80 88 96│
│ 9│ 81 90 99 108│
│10│ 100 110 120│
│11│ 121 132│
│12│ 144│
└──┴────────────────────────────────────────────────┘ |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Ruby | Ruby | # 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens
# puzzle).
# 2. Write a list of the even numbers from 2 to n in order.
# 3. If the remainder is 3 or 9, move 2 to the end of the list.
# 4. Append the odd numbers from 1 to n in order, but, if the remainder is 8,
# switch pairs (i.e. 3, 1, 7, 5, 11, 9, …).
# 5. If the remainder is 2, switch the places of 1 and 3, then move 5 to the
# end of the list.
# 6. If the remainder is 3 or 9, move 1 and 3 to the end of the list.
# 7. Place the first-column queen in the row with the first number in the
# list, place the second-column queen in the row with the second number in
# the list, etc.
def n_queens(n)
if n == 1
return "Q"
elsif n < 4
puts "no solutions for n=#{n}"
return ""
end
evens = (2..n).step(2).to_a
odds = (1..n).step(2).to_a
rem = n % 12 # (1)
nums = evens # (2)
nums.rotate if rem == 3 or rem == 9 # (3)
# (4)
if rem == 8
odds = odds.each_slice(2).flat_map(&:reverse)
end
nums.concat(odds)
# (5)
if rem == 2
nums[nums.index(1)], nums[nums.index(3)] = nums[nums.index(3)], nums[nums.index(1)]
nums << nums.delete(5)
end
# (6)
if rem == 3 or rem == 9
nums << nums.delete(1)
nums << nums.delete(3)
end
# (7)
nums.map do |q|
a = Array.new(n,".")
a[q-1] = "Q"
a*(" ")
end
end
(1 .. 15).each {|n| puts "n=#{n}"; puts n_queens(n); puts} |
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.