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
#Octave
Octave
function p = montepi(samples) in_circle = 0; for samp = 1:samples v = [ unifrnd(-1,1), unifrnd(-1,1) ]; if ( v*v.' <= 1.0 ) in_circle++; endif endfor p = 4*in_circle/samples; endfunction   l = 1e4; while (l < 1e7) disp(montepi(l)); l *= 10; endwhile
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
#PARI.2FGP
PARI/GP
MonteCarloPi(tests)=4.*sum(i=1,tests,norml2([random(1.),random(1.)])<1)/tests;
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).
#Liberty_BASIC
Liberty BASIC
'The following code relies on the Windows API Input "Input the text to translate to Morse Code... "; string$ Print PlayMorse$(string$) End   Function PlayMorse$(string$) 'LetterGap = (3 * BaseTime) 'WordGap = (7 * BaseTime) BaseTime = 50 freq = 1250 PlayMorse$ = TranslateToMorse$(string$) morseCode$ = "./-" For i = 1 To Len(PlayMorse$) Scan dwDuration = (Instr(morseCode$, Mid$(PlayMorse$, i, 1)) * BaseTime) If (Mid$(PlayMorse$, i, 1) <> " ") Then CallDLL #kernel32, "Beep", freq As ulong, dwDuration As ulong, ret As long CallDLL #kernel32, "Sleep", BaseTime As long, ret As void End If If (Mid$(PlayMorse$, i, 1) <> " ") Then sleep = (3 * BaseTime) Else sleep = (7 * BaseTime) End If CallDLL #kernel32, "Sleep", sleep As long, ret As void Next i End Function   Function TranslateToMorse$(string$) string$ = Upper$(string$) For i = 1 To Len(string$) While desc$ <> "End" Read desc$, value$ If desc$ = "" Then desc$ = chr$(34) If desc$ = Mid$(string$, i, 1) Then If Mid$(string$, i, 1) <> " " Then value$ = " " + value$ TranslateToMorse$ = TranslateToMorse$ + value$ Exit While End If Wend If desc$ = "End" Then Notice Mid$(string$, i, 1) + " is not accounted for in the Morse Code Table." Restore Next i TranslateToMorse$ = Trim$(TranslateToMorse$) Data "A", ".-", "B", "-...", "C", "-.-.", "D", "-..", "E", ".", "F", "..-.", "G", "--." Data "H", "....", "I", "..", "J", ".---", "K", "-.-", "L", ".-..", "M", "--", "N", "-." Data "O", "---", "P", ".--.", "Q", "--.-", "R", ".-.", "S", "...", "T", "-", "U", "..-" Data "V", "...-", "W", ".--", "X", "-..-", "Y", "-.--", "Z", "--..", "Á", "--.-", "Ä", ".-.-" Data "É", "..-..", "Ñ", "--.--", "Ö", "---.", "Ü", "..--", "1", ".----", "2", "..---" Data "3", "...--", "4", "....-", "5", ".....", "6", "-....", "7", "--...", "8", "---.." Data "9", "----.", "0", "-----", ",", "--..--", ".", ".-.-.-", "?", "..--..", ";", "-.-.-" Data ":", "---...", "/", "-..-.", "-", "-....-", "'", ".----.", "+", ".-.-.", "", ".-..-." Data "@", ".--.-.", "(", "-.--.", ")", "-.--.-", "_", "..--.-", "$", "...-..-", "&", ".-..." Data "=", "-...-", "!", "..--.", " ", " ", "End", "" End Function
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.
#Io
Io
keepWins := 0 switchWins := 0 doors := 3 times := 100000 pickDoor := method(excludeA, excludeB, door := excludeA while(door == excludeA or door == excludeB, door = (Random value() * doors) floor ) door ) times repeat( playerChoice := pickDoor() carDoor := pickDoor() shownDoor := pickDoor(carDoor, playerChoice) switchDoor := pickDoor(playerChoice, shownDoor) (playerChoice == carDoor) ifTrue(keepWins = keepWins + 1) (switchDoor == carDoor) ifTrue(switchWins = switchWins + 1) ) ("Switching to the other door won #{switchWins} times.\n"\ .. "Keeping the same door won #{keepWins} times.\n"\ .. "Game played #{times} times with #{doors} doors.") interpolate println  
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.
#PicoLisp
PicoLisp
(de modinv (A B) (let (B0 B X0 0 X1 1 Q 0 T1 0) (while (< 1 A) (setq Q (/ A B) T1 B B (% A B) A T1 T1 X0 X0 (- X1 (* Q X0)) X1 T1 ) ) (if (lt0 X1) (+ X1 B0) X1) ) )   (println (modinv 42 2017) )   (bye)
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.
#PL.2FI
PL/I
*process source attributes xref or(!); /*-------------------------------------------------------------------- * 13.07.2015 Walter Pachl *-------------------------------------------------------------------*/ minv: Proc Options(main); Dcl (x,y) Bin Fixed(31); x=42; y=2017; Put Edit('modular inverse of',x,' by ',y,' ---> ',modinv(x,y)) (Skip,3(a,f(4))); modinv: Proc(a,b) Returns(Bin Fixed(31)); Dcl (a,b,ob,ox,d,t) Bin Fixed(31); ob=b; ox=0; d=1;   If b=1 Then; Else Do; Do While(a>1); q=a/b; r=mod(a,b); a=b; b=r; t=ox; ox=d-q*ox; d=t; End; End; If d<0 Then d=d+ob; Return(d); 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.
#EchoLisp
EchoLisp
  (lib 'matrix)   (define (mtable i j) (cond ((and (zero? i) (zero? j)) "😅") ((= i 0) j) ((= j 0) i) ((>= j i ) (* i j )) (else " ")))   (array-print (build-array 13 13 mtable))    
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: multiFact (in var integer: num, in integer: degree) is func result var integer: multiFact is 1; begin while num > 1 do multiFact *:= num; num -:= degree; end while; end func;   const proc: main is func local var integer: degree is 0; var integer: num is 0; begin for degree range 1 to 5 do write("Degree " <& degree <& ": "); for num range 1 to 10 do write(multiFact(num, degree) <& " "); end for; writeln; end for; end func;
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Sidef
Sidef
func mfact(s, n) { n > 0 ? (n * mfact(s, n-s)) : 1 }   { |s| say "step=#{s}: #{{|n| mfact(s, n)}.map(1..10).join(' ')}" } << 1..10
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
#Phix
Phix
with javascript_semantics -- -- demo\rosetta\n_queens.exw -- ========================= -- sequence co, -- columns occupied -- (ro is implicit) fd, -- forward diagonals bd, -- backward diagonals board atom count procedure solve(integer row, integer N, integer show) for col=1 to N do if not co[col] then integer fdi = col+row-1, bdi = row-col+N if not fd[fdi] and not bd[bdi] then board[row][col] = 'Q' co[col] = 1 fd[fdi] = 1 bd[bdi] = 1 if row=N then if show then puts(1,join(board,"\n")&"\n") puts(1,repeat('=',N)&"\n") end if count += 1 else solve(row+1,N,show) end if board[row][col] = '.' co[col] = 0 fd[fdi] = 0 bd[bdi] = 0 end if end if end for end procedure procedure n_queens(integer N=8, integer show=1) co = repeat(0,N) fd = repeat(0,N*2-1) bd = repeat(0,N*2-1) board = repeat(repeat('.',N),N) count = 0 solve(1,N,show) printf(1,"%d queens: %d solutions\n",{N,count}) end procedure for N=1 to iff(platform()=JS?12:14) do n_queens(N,N<5) end for
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.
#TypeScript
TypeScript
  // N'th function suffix(n: number): string { var nMod10: number = n % 10; var nMod100: number = n % 100; if (nMod10 == 1 && nMod100 != 11) return "st"; else if (nMod10 == 2 && nMod100 != 12) return "nd"; else if (nMod10 == 3 && nMod100 != 13) return "rd"; else return "th"; }   function printImages(loLim: number, hiLim: number) { for (i = loLim; i <= hiLim; i++) process.stdout.write(`${i}` + suffix(i) + " "); process.stdout.write("\n"); }   printImages( 0, 25); printImages( 250, 265); printImages(1000, 1025);  
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).
#Ol
Ol
  (letrec ((F (lambda (n) (if (= n 0) 1 (- n (M (F (- n 1))))))) (M (lambda (n) (if (= n 0) 0 (- n (F (M (- n 1)))))))) (print (F 19))) ; produces 12  
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
#Pascal
Pascal
Program MonteCarlo(output);   uses Math;   function MC_Pi(expo: integer): real; var x, y: real; i, hits, samples: longint; begin samples := 10**expo; hits := 0; randomize; for i := 1 to samples do begin x := random; y := random; if sqrt(x*x + y*y) < 1.0 then inc(hits); end; MC_Pi := 4.0 * hits / samples; end;   var i: integer; begin for i := 4 to 8 do writeln (10**i, ' samples give ', MC_Pi(i):7:5, ' as pi.'); 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).
#Lua
Lua
local M = {}   -- module-local variables local BUZZER = pio.PB_10 local dit_length, dah_length, word_length   -- module-local functions local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap   buzz = function(duration) pio.pin.output(BUZZER) pio.pin.setlow(BUZZER) tmr.delay(tmr.SYS_TIMER, duration) pio.pin.sethigh(BUZZER) pio.pin.input(BUZZER) end   dah = function() buzz(dah_length) end   dit = function() buzz(dit_length) end   init = function(baseline) dit_length = baseline dah_length = 2 * baseline word_length = 4 * baseline end   inter_element_gap = function() pause(dit_length) end   medium_gap = function() pause(word_length) end   pause = function(duration) tmr.delay(tmr.SYS_TIMER, duration) end   sequence = function(codes) if codes then for _,f in ipairs(codes) do f() inter_element_gap() end short_gap() end end   short_gap = function() pause(dah_length) end   local morse = { a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit },   ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit },   [" "] = { medium_gap } }   -- public interface M.beep = function(message) message = message:lower() for _,ch in ipairs { message:byte(1, #message) } do sequence(morse[string.char(ch)]) end end   M.set_dit = function(duration) init(duration) end   -- initialization code init(50000)   return M
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.
#J
J
pick=: {~ ?@#
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.
#Java
Java
import java.util.Random; public class Monty{ public static void main(String[] args){ int switchWins = 0; int stayWins = 0; Random gen = new Random(); for(int plays = 0;plays < 32768;plays++ ){ int[] doors = {0,0,0};//0 is a goat, 1 is a car doors[gen.nextInt(3)] = 1;//put a winner in a random door int choice = gen.nextInt(3); //pick a door, any door int shown; //the shown door do{ shown = gen.nextInt(3); //don't show the winner or the choice }while(doors[shown] == 1 || shown == choice);   stayWins += doors[choice];//if you won by staying, count it   //the switched (last remaining) door is (3 - choice - shown), because 0+1+2=3 switchWins += doors[3 - choice - shown]; } System.out.println("Switching wins " + switchWins + " times."); System.out.println("Staying wins " + stayWins + " times."); } }
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.
#PowerShell
PowerShell
function invmod($a,$n){ if ([int]$n -lt 0) {$n = -$n} if ([int]$a -lt 0) {$a = $n - ((-$a) % $n)}   $t = 0 $nt = 1 $r = $n $nr = $a % $n while ($nr -ne 0) { $q = [Math]::truncate($r/$nr) $tmp = $nt $nt = $t - $q*$nt $t = $tmp $tmp = $nr $nr = $r - $q*$nr $r = $tmp } if ($r -gt 1) {return -1} if ($t -lt 0) {$t += $n} return $t }   invmod 42 2017
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.
#Elixir
Elixir
defmodule RC do def multiplication_tables(n) do IO.write " X |" Enum.each(1..n, fn i -> :io.fwrite("~4B", [i]) end) IO.puts "\n---+" <> String.duplicate("----", n) Enum.each(1..n, fn j ->  :io.fwrite("~2B |", [j]) Enum.each(1..n, fn i -> if i<j, do: (IO.write " "), else: :io.fwrite("~4B", [i*j]) end) IO.puts "" end) end end   RC.multiplication_tables(12)
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Swift
Swift
func multiFactorial(_ n: Int, k: Int) -> Int { return stride(from: n, to: 0, by: -k).reduce(1, *) }   let multis = (1...5).map({degree in (1...10).map({member in multiFactorial(member, k: degree) }) })   for (i, degree) in multis.enumerated() { print("Degree \(i + 1): \(degree)") }
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Tcl
Tcl
package require Tcl 8.6   proc mfact {n m} { set mm [expr {-$m}] for {set r $n} {[incr n $mm] > 1} {set r [expr {$r * $n}]} {} return $r }   foreach n {1 2 3 4 5 6 7 8 9 10} { puts $n:[join [lmap m {1 2 3 4 5 6 7 8 9 10} {mfact $m $n}] ,] }
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
#PHP
PHP
  <html> <head> <title> n x n Queen solving program </title> </head> <body> <?php echo "<h1>n x n Queen solving program</h1>";   //Get the size of the board $boardX = $_POST['boardX']; $boardY = $_POST['boardX'];   // Function to rotate a board 90 degrees function rotateBoard($p, $boardX) { $a=0; while ($a < count($p)) { $b = strlen(decbin($p[$a]))-1; $tmp[$b] = 1 << ($boardX - $a - 1); ++$a; } ksort($tmp); return $tmp; }   // This function will find rotations of a solution function findRotation($p, $boardX,$solutions){ $tmp = rotateBoard($p,$boardX); // Rotated 90 if (in_array($tmp,$solutions)) {} else {$solutions[] = $tmp;}   $tmp = rotateBoard($tmp,$boardX); // Rotated 180 if (in_array($tmp,$solutions)){} else {$solutions[] = $tmp;}   $tmp = rotateBoard($tmp,$boardX); // Rotated 270 if (in_array($tmp,$solutions)){} else {$solutions[] = $tmp;}   // Reflected $tmp = array_reverse($p); if (in_array($tmp,$solutions)){} else {$solutions[] = $tmp;}   $tmp = rotateBoard($tmp,$boardX); // Reflected and Rotated 90 if (in_array($tmp,$solutions)){} else {$solutions[] = $tmp;}   $tmp = rotateBoard($tmp,$boardX); // Reflected and Rotated 180 if (in_array($tmp,$solutions)){} else {$solutions[] = $tmp;}   $tmp = rotateBoard($tmp,$boardX); // Reflected and Rotated 270 if (in_array($tmp,$solutions)){} else {$solutions[] = $tmp;} return $solutions; }   // This is a function which will render the board function renderBoard($p,$boardX) { $img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAAAABmJLR0QA/wD/AP+gvaeTAAAGFUlEQVRYhe2YXWibVRjHf2lqP9JmaRi4YW1IalY3rbZsaddMgsquBm676b6KyNDhLiaUeSEMvPNCcNuNyJjgLiboCnoxKFlv6lcHy7AtMhhaWTVZWhisjDTEtEuW5PHiPWnfvH2TvNk6vekfDm/O+Z/zPP/3PM/5eAMb2MAG/nfYn4LNVuBj4ENgB/Ar8Ogp+KkJbwLfqvKGgbMBPwKiK+Oq3aqNdcebQEEnqAC8ruO7KBVcLF012KiKuhpFv0/prNlU239qw0x0pdBJFXt30NJDjx9Uu1Ub1TSYdq4UutcNfI61oW0Bflb8T6quRzUbNafPFdbm4zcmTucV91kZO18o/osy/GeKnzcRVFWDMT2shO4X4IL6/UqZPv2GpxHFcReUvVo1lMAYunKh+UTxeeB5A/cMkFF8RtX1eF6NE2XHTIN+ltekoHGmf0HLqe9V3Qb8ZWK4Xjf+HQP3KtCgfjeouh7v6PzWsxZ6f98De1kbjbIovumoCfcp2gzkgb8p3cJOUjpTJ3WcTfXPq/Gfmtge1Y01RaV9+jv1fAsYMnAu3XgfENJxfUoU6tmn40Kqf9Gvi1IMKX96/zWJnlLP4i7wrIEvzkQeeFfXvltnt07Vi3iX1RcyzuSzrO46ev81YS+rYcqjbUVFfIl2CSryS4ATcKCF3biQHIpf0rU/UnaKuMLqAhXlv2a4Dc4FOKi4bwyiBTgBvGYyRlT7CUPbI1b334MmY9zlhFVKjwQQ09ULaDNTNKYPbx54j9L81aNP8XldW3G8W9kt6LiY8m8Ksy1Hj0mgA+3eXYeWd2eBRkpf2A4MoO3JOYPdHPA2sMtgu07ZOavsFnegvPL72PiItWEroB0axtwtmPStxOeUHbNxH1USVe1qOm3SVkA7NIwX+1phU3YKJpyZX8swW4y1FOMsVotG1UUI1mbrH9ZeL/UQi3b0C7dS/2W0LbIsqi1E0K6PL5oRdrudHTt22Px+Pz6fD6/XS3NzM21tbSt9FhcXWVpaIhqN2mKxGLOzs8zMzJDP581MQukHw2OLPgt8VRQZDAbZv38/wWCQnTt30tKyGoRUKsWDBw/IZrOkUimcTicNDQ1s3rwZp9O50i+dTjM9Pc2NGzcIh8NEIhH9S3xuQVNV2IArp06dkoWFBRERefjwoUxMTMi5c+fk8OHD0tPTIy6Xq2Keulwu6enpkSNHjsj58+dlYmJCMpmMiIgsLCzIxYsXBe1UfNIFvoL6M2fO/Hn58uXC4OCgtLa2PsniXClOp1MGBwfl0qVLhdOnT/+BtcjX9FYe4Pe+vj6Hy+Vat9lIJpMyOTm5BLwExNfL7gpCodAFeQoIhUIXqntfhaVwFHH9+nXp7+8vuFyuWv8vKYtkMlmYnJwse+F/Urzi9/ulqanJ6gFhqTQ1NeW7u7sF6Fx3xd3d3bdERNLptITDYRkeHpZgMCgOh6MmkQ6HQ/bs2SPDw8MSDoclnU6LiMju3buvlHG9BlYX1F5gfGhoiEAgwL59+9i+fTsAuVyOWCxGPB4nHo+TSCTIZrMkEgncbjeNjY243W46OjrweDx4vV7q67WsnJmZYWxsjGvXrjE+Pm5Zj1XRX3d2dg7Nz8/bs9ksAFu2bGHXrl0EAgG2bduG1+vF4/HgdDrZtGkTdrudXC5HKpUilUpx9+5dYrEYd+7cYXp6mqmpKe7fvw9AQ0MDXV1d3L59+2Xgd4uaKqO3t/cnEZFkMikjIyNy9OhRaW9vf6Jcbm9vl2PHjsnIyIgkk0kRETl06NAHVvRYnenA8ePHJ4PBIAcOHGDr1q0AxONxbt68yezsLNFolLm5ORKJBMvLy6TTaVpaWmhubl5JD5/Ph9/vZ2BgAI/HA8C9e/cYHR3l6tWry2NjY88Bi+slGqAHOFVXVxfq7e3tGhgYqAsGgwQCAfH5fLbGxsaqBjKZDNFoVKampmyRSIRIJFK4devWn4VC4TpwEfjNipDHPdlagADaf3X9NpvthY6Ojk6Px+Mq3vLsdjv5fJ7FxUWWl5eJx+OJubm5mIjMon1O/Yr2N0G6VufrdhwrtAJtaN9+bWihzqB9pNYsbgMbeAz8C3N/JQD4H5KCAAAAAElFTkSuQmCC'; echo "<table border=1 cellspacing=0 style='text-align:center;display:inline'>"; for ($y = 0; $y < $boardX; ++$y) { echo '<tr>'; for ($x = 0; $x < $boardX; ++$x){ if (($x+$y) & 1) { $cellCol = '#9C661F';} else {$cellCol = '#FCE6C9';}   if ($p[$y] == 1 << $x) { echo "<td bgcolor=".$cellCol."><img width=30 height=30 src='".$img."'></td>";} else { echo "<td bgcolor=".$cellCol."> </td>";} } echo '<tr>'; } echo '<tr></tr></table>&nbsp';   }   //This function allows me to generate the next order of rows. function pc_next_permutation($p) { $size = count($p) - 1; // slide down the array looking for where we're smaller than the next guy   for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }   // if this doesn't occur, we've finished our permutations // the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1) if ($i == -1) { return false; }   // slide down the array looking for a bigger number than what we found before for ($j = $size; $p[$j] <= $p[$i]; --$j) { } // swap them $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; // now reverse the elements in between by swapping the ends for (++$i, $j = $size; $i < $j; ++$i, --$j) { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } return $p; }   //This function needs to check the current state to see if there are any function checkBoard($p,$boardX) { $a = 0; //this is the row being checked while ($a < count($p)) { $b = 1; while ($b < ($boardX - $a)){ $x = $p[$a+$b] << $b; $y = $p[$a+$b] >> $b; if ($p[$a] == $x | $p[$a] == $y) { return false; } ++$b; } ++$a; } return true; }     if (isset($_POST['process']) && isset($_POST['boardX'])) { //Within here is the code that needs to be run if process is clicked.     //First I need to create the different possible rows for ($x = 0; $x < $boardX; ++$x){ $row[$x] = 1 << $x; }   //Now I need to create all the possible orders of rows, will be equal to [boardY]! $solcount = 0; $solutions = array(); while ($row != false) { if (checkBoard($row,$boardX)){ if(!in_array($row,$solutions)){ $solutions[] = $row; renderBoard($row,$boardX); $solutions = findRotation($row,$boardX,$solutions); ++$solcount; }   } $row = pc_next_permutation($row); } echo "<br><br>&nbsp&nbsp&nbsp&nbspRows/Columns: ".$boardX."<br>&nbsp&nbsp&nbsp&nbspUnique Solutions: ".$solcount."<br>&nbsp&nbsp&nbsp&nbspTotal Solutions: ".count($solutions)." - Note: This includes symmetrical solutions<br>"; //print_r($solutions); }   //This code collects the starting parameters echo <<<_END <form name="input" action="index.php" method="post"> &nbsp&nbsp&nbsp&nbspNumber of columns/rows <select name="boardX" /> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4" >Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8" selected="selected">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> <input type="hidden" name="process" value="yes" /> &nbsp<input type="submit" value="Process" /> </form>   _END;   ?> </body> </html>  
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.
#uBasic.2F4tH
uBasic/4tH
For x = 0 to 25 ' Test range 0..25 Push x : GoSub _PrintOrdinal Next x  : Print   For x = 250 to 265 ' Test range 250..265 Push x : GoSub _PrintOrdinal Next x : Print   For x = 1000 to 1025 ' Test range 1000..1025 Push x : GoSub _PrintOrdinal Next x : Print   End ' End test program ' ( n --) _PrintOrdinal ' Ordinal subroutine If Tos() > -1 Then ' If within range then Print Using "____#";Tos();"'"; ' Print the number ' Take care of 11, 12 and 13 If (Tos()%100 > 10) * (Tos()%100 < 14) Then Gosub (Pop() * 0) + 100 ' Clear stack and print "th" Return ' We're done here EndIf   Push Pop() % 10 ' Calculate n mod 10 GoSub 100 + 10 * ((Tos()>0) + (Tos()>1) + (Tos()>2) - (3 * (Pop()>3))) Else ' And decide which ordinal to use Print Pop();" is less than zero" ' Otherwise, it is an error EndIf   Return ' Select and print proper ordinal 100 Print "th"; : Return 110 Print "st"; : Return 120 Print "nd"; : Return 130 Print "rd"; : 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).
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8f \ ORDER_PP_FN(8fn(8N, \ 8if(8is_0(8N), \ 1, \ 8sub(8N, 8m(8f(8dec(8N)))))))   #define ORDER_PP_DEF_8m \ ORDER_PP_FN(8fn(8N, \ 8if(8is_0(8N), \ 0, \ 8sub(8N, 8f(8m(8dec(8N)))))))   //Test ORDER_PP(8for_each_in_range(8fn(8N, 8print(8f(8N))), 0, 19)) ORDER_PP(8for_each_in_range(8fn(8N, 8print(8m(8N))), 0, 19))
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
#Perl
Perl
sub pi { my $nthrows = shift; my $inside = 0; foreach (1 .. $nthrows) { my $x = rand() * 2 - 1; my $y = rand() * 2 - 1; if (sqrt($x*$x + $y*$y) < 1) { $inside++; } } return 4 * $inside / $nthrows; }   printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;
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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; (* gap should be equal to mark. But longer gap makes audio code easier to decode *) shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." };   MorseDictionary = # <> " " & /@ MorseDictionary; (* Force short gap silence after each letter/digit *)   Tones = { SoundNote[None, medgap], SoundNote[None, shortgap], {SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]}, {SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} (* Use F# short mark to denote unrecognized character *) };   codeRules = MapThread[Rule, {Dictionary, MorseDictionary}]; decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}]; soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}]; (* The order of the rules here is important. Otherwise medium gaps and short gaps get confounded *)   morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}] morseDecode[s_String] := StringReplace[s, decodeRules] sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]
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.
#JavaScript
JavaScript
  function montyhall(tests, doors) { 'use strict'; tests = tests ? tests : 1000; doors = doors ? doors : 3; var prizeDoor, chosenDoor, shownDoor, switchDoor, chosenWins = 0, switchWins = 0;   // randomly pick a door excluding input doors function pick(excludeA, excludeB) { var door; do { door = Math.floor(Math.random() * doors); } while (door === excludeA || door === excludeB); return door; }   // run tests for (var i = 0; i < tests; i ++) {   // pick set of doors prizeDoor = pick(); chosenDoor = pick(); shownDoor = pick(prizeDoor, chosenDoor); switchDoor = pick(chosenDoor, shownDoor);   // test set for both choices if (chosenDoor === prizeDoor) { chosenWins ++; } else if (switchDoor === prizeDoor) { switchWins ++; } }   // results return { stayWins: chosenWins + ' ' + (100 * chosenWins / tests) + '%', switchWins: switchWins + ' ' + (100 * switchWins / tests) + '%' }; }  
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.
#Prolog
Prolog
  egcd(_, 0, 1, 0) :- !. egcd(A, B, X, Y) :- divmod(A, B, Q, R), egcd(B, R, S, X), Y is S - Q*X.   modinv(A, B, N) :- egcd(A, B, X, Y), A*X + B*Y =:= 1, N is X mod 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.
#PureBasic
PureBasic
EnableExplicit Declare main() Declare.i mi(a.i, b.i)   If OpenConsole("MODULAR-INVERSE") main() : Input() : End EndIf   Macro ModularInverse(a, b) PrintN(~"\tMODULAR-INVERSE(" + RSet(Str(a),5) + "," + RSet(Str(b),5)+") = " + RSet(Str(mi(a, b)),5)) EndMacro   Procedure main() ModularInverse(42, 2017) ; = 1969 ModularInverse(40, 1) ; = 0 ModularInverse(52, -217) ; = 96 ModularInverse(-486, 217) ; = 121 ModularInverse(40, 2018) ; = -1 EndProcedure   Procedure.i mi(a.i, b.i) Define x.i = 1, y.i = Int(Abs(b)), r.i = 0 If y = 1 : ProcedureReturn 0 : EndIf While x < y r = (a * x) % b If r = 1 Or (y + r) = 1 Break EndIf x + 1 Wend If x > y - 1 : x = -1 : EndIf ProcedureReturn x EndProcedure
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.
#Erlang
Erlang
  -module( multiplication_tables ).   -export( [print_upto/1, task/0, upto/1] ).   print_upto( N ) -> Upto_tuples = [{X, {Y, Sum}} || {X, Y, Sum} <- upto(N)], io:fwrite( " " ), [io:fwrite( "~5B", [X]) || X <- lists:seq(1, N)], io:nl(), io:nl(), [print_upto(X, proplists:get_all_values(X, Upto_tuples)) || X <- lists:seq(1, N)].     task() -> print_upto( 12 ).   upto( N ) -> [{X, Y, X*Y} || X <- lists:seq(1, N), Y <- lists:seq(1, N), Y >= X].       print_upto( N, Uptos ) -> io:fwrite( "~2B", [N] ), io:fwrite( "~*s", [5*(N - 1), " "] ), [io:fwrite("~5B", [Sum]) || {_Y, Sum} <- Uptos], io:nl().  
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#uBasic.2F4tH
uBasic/4tH
print "Degree | Multifactorials 1 to 10" for x = 1 to 53 : print "-"; : next : print for d = 1 to 5 print d;" ";"| "; for n = 1 to 10 print FUNC(_multiFact(n, d));" "; next print next   end   _multiFact param (2) local (2) c@ = 1 for d@ = a@ to 2 step -b@ c@ = c@ * d@ next return (c@)
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#VBScript
VBScript
  Function multifactorial(n,d) If n = 0 Then multifactorial = 1 Else For i = n To 1 Step -d If i = n Then multifactorial = n Else multifactorial = multifactorial * i End If Next End If End Function   For j = 1 To 5 WScript.StdOut.Write "Degree " & j & ": " For k = 1 To 10 If k = 10 Then WScript.StdOut.Write multifactorial(k,j) Else WScript.StdOut.Write multifactorial(k,j) & " " End If Next WScript.StdOut.WriteLine Next  
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
#Solution_with_recursion
Solution with recursion
  <html> <body> <pre> <?php   /************************************************************************* * * This algorithm solves the 8 queens problem using backtracking. * Please try with N<=25 * * * *************************************************************************/ class Queens { var $size; var $arr; var $sol;   function Queens($n = 8) { $this->size = $n; $this->arr = array(); $this->sol = 0; // Inicialiate array; for($i=0; $i<$n; $i++) { $this->arr[$i] = 0; } }   function isSolution($n) { for ($i = 0; $i < $n; $i++) { if ($this->arr[$i] == $this->arr[$n] || ($this->arr[$i] - $this->arr[$n]) == ($n - $i) || ($this->arr[$n] - $this->arr[$i]) == ($n - $i)) { return false; } } return true; }   function PrintQueens() { echo("solution #".(++$this->sol)."\n"); // echo("solution #".($this->size)."\n"); for ($i = 0; $i < $this->size; $i++) { for ($j = 0; $j < $this->size; $j++) { if ($this->arr[$i] == $j) echo("& "); else echo(". "); } echo("\n"); } echo("\n"); }     // backtracking Algorithm function run($n = 0) { if ($n == $this->size){ $this->PrintQueens(); } else { for ($i = 0; $i < $this->size; $i++) { $this->arr[$n] = $i; if($this->isSolution($n)){ $this->run($n+1); } } } } }   $myprogram = new Queens(8); $myprogram->run();   ?> </pre> </body> </html>  
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.
#UNIX_Shell
UNIX Shell
nth() { local ordinals=(th st nd rd) local -i n=$1 i if (( n < 0 )); then printf '%s%s\n' - "$(nth $(( -n )) )" return 0 fi case $(( n % 100 )) in 11|12|13) i=0;; *) (( i= n%10 < 4 ? n%10 : 0 ));; esac printf '%d%s\n' "$n" "${ordinals[i]}" } for n in {0..25} {250..265} {1000..1025}; do nth $n done | column
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.
#VBA
VBA
Private Function ordinals() As Variant ordinals = [{"th","st","nd","rd"}] End Function   Private Function Nth(n As Variant, Optional apostrophe As Boolean = False) As String Dim mod10 As Integer: mod10 = n Mod 10 + 1 If mod10 > 4 Or n Mod 100 = mod10 + 9 Then mod10 = 1 Nth = CStr(n) & String$(Val(-apostrophe), "'") & ordinals()(mod10) End Function   Public Sub main() Ranges = [{0,25;250,265;1000,1025}] For i = 1 To UBound(Ranges) For j = Ranges(i, 1) To Ranges(i, 2) If j Mod 10 = 0 Then Debug.Print Debug.Print Format(Nth(j, i = 2), "@@@@@@@"); Next j Debug.Print Next i 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).
#Oz
Oz
declare fun {F N} if N == 0 then 1 elseif N > 0 then N - {M {F N-1}} end end   fun {M N} if N == 0 then 0 elseif N > 0 then N - {F {M N-1}} end end in {Show {Map {List.number 0 9 1} F}} {Show {Map {List.number 0 9 1} M}}
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
#Phix
Phix
with javascript_semantics integer N = 100 for i=1 to 6 do integer inside = 0 for n=1 to N do integer x = rand(N), y = rand(N) inside += (x*x+y*y<N*N) end for pp({N,4*inside/N}) N *= 10 end for
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
#PHP
PHP
<? $loop = 1000000; # loop to 1,000,000 $count = 0; for ($i=0; $i<$loop; $i++) { $x = rand() / getrandmax(); $y = rand() / getrandmax(); if(($x*$x) + ($y*$y)<=1) $count++; } echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4); ?>
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).
#MATLAB
MATLAB
function [morseText,morseSound] = text2morse(string,playSound)   %% Translate AlphaNumeric Text to Morse Text   string = lower(string);   %Defined such that the ascii code of the characters in the string map %to the indecies of the dictionary. morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},... {'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','--..'}};   %Iterates through each letter in the string and converts it to morse %code morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false);   %The output of the previous operation is a cell array, we want it to be %a string. This line accomplishes that. morseText = cell2mat(morseText);   morseText(end) = []; %delete extra pipe   %% Translate Morse Text to Morse Audio   %Generate the tones for each element of the code SamplingFrequency = 8192; %Hz ditLength = .1; %s dit = (0:1/SamplingFrequency:ditLength); dah = (0:1/SamplingFrequency:3*ditLength); dit = sin(3520*dit); dah = sin(3520*dah); silent = zeros(1,length(dit));   %A dictionary of the audio components of each symbol morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}}; morseSound = [];   for i = (1:length(morseText))   %Iterate through each cell in the morseTiming cell array and %find which timing sequence corresponds to the current morse %text symbol. cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming));   morseSound = [morseSound morseTiming{cellNum}{2}]; end   morseSound(end-length(silent):end) = []; %Delete the extra silent tone at the end   if(playSound) sound(morseSound,SamplingFrequency); %Play sound end   end %text2morse
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.
#jq
jq
cat /dev/urandom | tr -cd '0-9' | fold -w 1 | jq -nrf monty-hall.jq
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.
#Julia
Julia
using Printf   function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1) ncar < ncur || throw(DomainError()) curtains = shuffle(collect(1:ncur)) cars = curtains[1:ncar] goats = curtains[(ncar+1):end] pick = rand(1:ncur) isstickwin = pick in cars deleteat!(curtains, findin(curtains, pick)) if !isstickwin deleteat!(goats, findin(goats, pick)) end if length(goats) > 0 # reveal goat deleteat!(curtains, findin(curtains, shuffle(goats)[1])) else # no goats, so reveal car deleteat!(curtains, rand(1:(ncur-1))) end pick = shuffle(curtains)[1] isswitchwin = pick in cars return (isstickwin, isswitchwin) 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.
#Python
Python
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)   >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m   >>> 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.
#Quackery
Quackery
[ dup 1 != if [ tuck 1 0 [ swap temp put temp put over 1 > while tuck /mod swap temp take tuck * temp take swap - again ] 2drop temp release temp take dup 0 < if [ over + ] ] nip ] is modinv ( n n --> n )   42 2017 modinv echo
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.
#Euphoria
Euphoria
puts(1," x") for i = 1 to 12 do printf(1," %3d",i) end for   puts(1,'\n')   for i = 1 to 12 do printf(1,"%2d",i) for j = 1 to 12 do if j<i then puts(1," ") else printf(1," %3d",i*j) end if end for puts(1,'\n') end for
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Wortel
Wortel
@let { facd &[d n]?{<= n d n @prod@range[n 1 @-d]}  ; tacit implementation facdt ^(!?(/^> .1 ^(@prod @range ~1jdtShj &^!(@- @id))) @,)  ; recursive facdrec &[n d] ?{<= n d n *n !!facdrec -n d d}  ; output l @to 10 ~@each @to 5 &n !console.log "Degree {n}: {@join @s !*\facd n l}" }
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Wren
Wren
import "/fmt" for Fmt   var mf = Fn.new { |n, d| var prod = 1 while (n > 1) { prod = prod * n n = n - d } return prod }   for (d in 1..5) { System.write("degree %(d): ") for (n in 1..10) System.write(Fmt.d(8, mf.call(n, d))) System.print() }
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
#Picat
Picat
import sat. % import mip.   queens_sat(N,Q) => Q = new_array(N,N), Q :: 0..1,   foreach (K in 1-N..N-1) sum([Q[I,J] : I in 1..N, J in 1..N, I-J==K]) #=< 1 end,   foreach (K in 2..2*N) sum([Q[I,J] : I in 1..N, J in 1..N, I+J==K]) #=< 1 end,   foreach (I in 1..N) sum([Q[I,J] : J in 1..N]) #= 1 end,   foreach (J in 1..N) sum([Q[I,J] : I in 1..N]) #= 1 end, solve([inout],Q).
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.
#Vlang
Vlang
fn ord(n int) string { mut s := "th" c := n % 10 if c in [1,2,3] { if n%100/10 == 1 { return "$n$s" } match c { 1 { s = 'st' } 2 { s = 'nd' } 3 { s = 'rd' } else{} } } return "$n$s" }   fn main() { for n := 0; n <= 25; n++ { print("${ord(n)} ") } println('') for n := 250; n <= 265; n++ { print("${ord(n)} ") } println('') for n := 1000; n <= 1025; n++ { print("${ord(n)} ") } println('') }
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.
#Wren
Wren
import "/fmt" for Conv   var ranges = [ 0..25, 250..265, 1000..1025 ] for (r in ranges) { r.each { |i| System.write("%(Conv.ord(i)) ") } System.print("\n") }
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).
#PARI.2FGP
PARI/GP
F(n)=if(n,n-M(F(n-1)),1) M(n)=if(n,n-F(M(n-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
#Picat
Picat
  sim1(N, F) = C => C = 0, I = 0, while (I <= N) C := C + apply(F), I := I + 1 end.
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
#PicoLisp
PicoLisp
(de carloPi (Scl) (let (Dim (** 10 Scl) Dim2 (* Dim Dim) Pi 0) (do (* 4 Dim) (let (X (rand 0 Dim) Y (rand 0 Dim)) (when (>= Dim2 (+ (* X X) (* Y Y))) (inc 'Pi) ) ) ) (format Pi Scl) ) )   (for N 6 (prinl (carloPi 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).
#Modula-2
Modula-2
MODULE MorseCode; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteMorseCode(str : ARRAY OF CHAR); VAR i : CARDINAL; BEGIN WriteString(str); WriteLn; FOR i:=0 TO HIGH(str) DO CASE CAP(str[i]) OF 'A': WriteString(".-"); | 'B': WriteString("-..."); | 'C': WriteString("-.-"); | 'D': WriteString("-.."); | 'E': WriteString("."); | 'F': WriteString("..-."); | 'G': WriteString("--."); | 'H': WriteString("...."); | 'I': WriteString(".."); | 'J': WriteString(".---"); | 'K': WriteString("-.-"); | 'L': WriteString(".-.."); | 'M': WriteString("--"); | 'N': WriteString("-."); | 'O': WriteString("---"); | 'P': WriteString(".--."); | 'Q': WriteString("--.-"); | 'R': WriteString(".-."); | 'S': WriteString("..."); | 'T': WriteString("-"); | 'U': WriteString("..-"); | 'V': WriteString("...-"); | 'W': WriteString(".--"); | 'X': WriteString("-..-"); | 'Y': WriteString("-.--"); | 'Z': WriteString("--.."); | '0': WriteString("-----"); | '1': WriteString(".----"); | '2': WriteString("..---"); | '3': WriteString("...--"); | '4': WriteString("....-"); | '5': WriteString("....."); | '6': WriteString("-...."); | '7': WriteString("--..."); | '8': WriteString("---.."); | '9': WriteString("----."); | ' ': WriteString(" "); ELSE IF (str[i] # 0C) THEN WriteString("?"); END END; WriteString(" "); END; END WriteMorseCode;   BEGIN WriteMorseCode("hello world"); WriteLn;   ReadChar; END MorseCode.
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.
#Kotlin
Kotlin
// version 1.1.2   import java.util.Random   fun montyHall(games: Int) { var switchWins = 0 var stayWins = 0 val rnd = Random() (1..games).forEach { val doors = IntArray(3) // all zero (goats) by default doors[rnd.nextInt(3)] = 1 // put car in a random door val choice = rnd.nextInt(3) // choose a door at random var shown: Int do { shown = rnd.nextInt(3) // the shown door } while (doors[shown] == 1 || shown == choice) stayWins += doors[choice] switchWins += doors[3 - choice - shown] } println("Simulating $games games:") println("Staying wins $stayWins times") println("Switching wins $switchWins times") }   fun main(args: Array<String>) { montyHall(1_000_000) }
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.
#Racket
Racket
  (require math) (modular-inverse 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.
#Raku
Raku
sub inverse($n, :$modulo) { my ($c, $d, $uc, $vc, $ud, $vd) = ($n % $modulo, $modulo, 1, 0, 0, 1); my $q; while $c != 0 { ($q, $c, $d) = ($d div $c, $d % $c, $c); ($uc, $vc, $ud, $vd) = ($ud - $q*$uc, $vd - $q*$vc, $uc, $vc); } return $ud % $modulo; }   say inverse 42, :modulo(2017)
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.
#Excel
Excel
FNOVERHALFCARTESIANPRODUCT =LAMBDA(f, LAMBDA(n, LET( ixs, SEQUENCE(n, n, 1, 1),   REM, "1-based indices.", x, 1 + MOD(ixs - 1, n), y, 1 + QUOTIENT(ixs - 1, n),   IF(x >= y, f(x)(y), "" ) ) ) )
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#XPL0
XPL0
code ChOut=8, CrLf=9, IntOut=11;   func MultiFac(N, D); \Return multifactorial of N in degree D int N, D; int F; [F:= 1; repeat F:= F*N; N:= N-D; until N <= 1; return F; ];   int I, J; \generate table of multifactorials for J:= 1 to 5 do [for I:= 1 to 10 do [IntOut(0, MultiFac(I, J)); ChOut(0, 9\tab\)]; CrLf(0); ]
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#zkl
zkl
fcn mfact(n,m){ [n..1,-m].reduce('*,1) } foreach m in ([1..5]){ println("%d: %s".fmt(m,[1..10].apply(mfact.fp1(m)))) }
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
#PicoLisp
PicoLisp
(load "@lib/simul.l") # for 'permute'   (de queens (N) (let (R (range 1 N) Cnt 0) (for L (permute (range 1 N)) (when (= N # from the Python solution (length (uniq (mapcar + L R))) (length (uniq (mapcar - L R))) ) (inc 'Cnt) ) ) Cnt ) )
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.
#XBasic
XBasic
  PROGRAM "nth" VERSION "0.0002"   DECLARE FUNCTION Entry() INTERNAL FUNCTION Suffix$(n&&) INTERNAL FUNCTION PrintImages (loLim&&, hiLim&&)   FUNCTION Entry() PrintImages( 0, 25) PrintImages( 250, 265) PrintImages(1000, 1025) END FUNCTION   FUNCTION Suffix$(n&&) nMod10@@ = n&& MOD 10 nMod100@@ = n&& MOD 100 SELECT CASE TRUE CASE (nMod10@@ = 1) AND (nMod100@@ <> 11): RETURN ("st") CASE (nMod10@@ = 2) AND (nMod100@@ <> 12): RETURN ("nd") CASE (nMod10@@ = 3) AND (nMod100@@ <> 13): RETURN ("rd") CASE ELSE: RETURN ("th") END SELECT END FUNCTION   FUNCTION PrintImages(loLim&&, hiLim&&) FOR i&& = loLim&& TO hiLim&& PRINT TRIM$(STRING$(i&&)); Suffix$(i&&); " "; NEXT PRINT END FUNCTION END PROGRAM  
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).
#Pascal
Pascal
Program MutualRecursion;   {M definition comes after F which uses it} function M(n : Integer) : Integer; forward;   function F(n : Integer) : Integer; begin if n = 0 then F := 1 else F := n - M(F(n-1)); end;   function M(n : Integer) : Integer; begin if n = 0 then M := 0 else M := n - F(M(n-1)); end;   var i : Integer;   begin for i := 0 to 19 do begin write(F(i) : 4) end; writeln; for i := 0 to 19 do begin write(M(i) : 4) end; writeln; end.
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
#PowerShell
PowerShell
function Get-Pi ($Iterations = 10000) { $InCircle = 0 for ($i = 0; $i -lt $Iterations; $i++) { $x = Get-Random 1.0 $y = Get-Random 1.0 if ([Math]::Sqrt($x * $x + $y * $y) -le 1) { $InCircle++ } } $Pi = [decimal] $InCircle / $Iterations * 4 $RealPi = [decimal] "3.141592653589793238462643383280" $Diff = [Math]::Abs(($Pi - $RealPi) / $RealPi * 100) New-Object PSObject ` | Add-Member -PassThru NoteProperty Iterations $Iterations ` | Add-Member -PassThru NoteProperty Pi $Pi ` | Add-Member -PassThru NoteProperty "% Difference" $Diff }
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).
#Nim
Nim
import os, strutils, tables   const Morse = {'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': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.", '!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...", ':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-", '_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable   proc morse(s: string): string = var r: seq[string] for c in s: r.add Morse.getOrDefault(c.toUpperAscii, "") result = r.join(" ")   var m: seq[string] for arg in commandLineParams(): m.add morse(arg) echo m.join(" ")
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.
#Liberty_BASIC
Liberty BASIC
  'adapted from BASIC solution DIM doors(3) '0 is a goat, 1 is a car   total = 10000 'set desired number of iterations switchWins = 0 stayWins = 0   FOR plays = 1 TO total winner = INT(RND(1) * 3) + 1 doors(winner) = 1'put a winner in a random door choice = INT(RND(1) * 3) + 1'pick a door, any door DO shown = INT(RND(1) * 3) + 1 'don't show the winner or the choice LOOP WHILE doors(shown) = 1 OR shown = choice if doors(choice) = 1 then stayWins = stayWins + 1 'if you won by staying, count it else switchWins = switchWins + 1'could have switched to win end if doors(winner) = 0 'clear the doors for the next test NEXT PRINT "Result for ";total;" games." PRINT "Switching wins "; switchWins; " times." PRINT "Staying wins "; stayWins; " times."  
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.
#REXX
REXX
/*REXX program calculates and displays the modular inverse of an integer X modulo Y.*/ parse arg x y . /*obtain two integers from the C.L. */ if x=='' | x=="," then x= 42 /*Not specified? Then use the default.*/ if y=='' | y=="," then y= 2017 /* " " " " " " */ say 'modular inverse of ' x " by " y ' ───► ' modInv(x,y) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ modInv: parse arg a,b 1 ob; z= 0 /*B & OB are obtained from the 2nd arg.*/ $= 1 /*initialize modular inverse to unity. */ if b\=1 then do while a>1 parse value a/b a//b b z with q b a t z= $ - q * z $= trunc(t) end /*while*/   if $<0 then $= $ + ob /*Negative? Then add the original B. */ return $
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.
#Ring
Ring
  see "42 %! 2017 = " + multInv(42, 2017) + nl   func multInv a,b b0 = b x0 = 0 multInv = 1 if b = 1 return 0 ok while a > 1 q = floor(a / b) t = b b = a % b a = t t = x0 x0 = multInv - q * x0 multInv = t end if multInv < 0 multInv = multInv + b0 ok return multInv  
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.
#F.23
F#
  open System   let multTable () = Console.Write (" X".PadRight (4)) for i = 1 to 12 do Console.Write ((i.ToString "####").PadLeft 4) Console.Write "\n ___" for i = 1 to 12 do Console.Write " ___" Console.WriteLine () for row = 1 to 12 do Console.Write (row.ToString("###").PadLeft(3).PadRight(4)) for col = 1 to 12 do if row <= col then Console.Write ((row * col).ToString("###").PadLeft(4)) else Console.Write ("".PadLeft 4) Console.WriteLine () Console.WriteLine () Console.ReadKey () |> ignore   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
#PL.2FI
PL/I
  NQUEENS: PROC OPTIONS (MAIN); DCL A(35) BIN FIXED(31) EXTERNAL; DCL COUNT BIN FIXED(31) EXTERNAL; COUNT = 0; DECLARE SYSIN FILE; DCL ABS BUILTIN; DECLARE SYSPRINT FILE; DECLARE N BINARY FIXED (31); /* COUNTER */ /* MAIN LOOP STARTS HERE */ GET LIST (N) FILE(SYSIN); /* N QUEENS, N X N BOARD */ PUT SKIP (1) FILE(SYSPRINT); PUT SKIP LIST('BEGIN N QUEENS PROCESSING *****') FILE(SYSPRINT); PUT SKIP LIST('SOLUTIONS FOR N: ',N) FILE(SYSPRINT); PUT SKIP (1) FILE(SYSPRINT); IF N < 4 THEN DO; /* LESS THAN 4 MAKES NO SENSE */ PUT SKIP (2) FILE(SYSPRINT); PUT SKIP LIST (N,' N TOO LOW') FILE (SYSPRINT); PUT SKIP (2) FILE(SYSPRINT); RETURN (1); END; IF N > 35 THEN DO; /* WOULD TAKE WEEKS */ PUT SKIP (2) FILE(SYSPRINT); PUT SKIP LIST (N,' N TOO HIGH') FILE (SYSPRINT); PUT SKIP (2) FILE(SYSPRINT); RETURN (1); END;   CALL QUEEN(N);   PUT SKIP (2) FILE(SYSPRINT); PUT SKIP LIST (COUNT,' SOLUTIONS FOUND') FILE(SYSPRINT); PUT SKIP (1) FILE(SYSPRINT); PUT SKIP LIST ('END OF PROCESSING ****') FILE(SYSPRINT); RETURN(0); /* MAIN LOOP ENDS ABOVE */   PLACE: PROCEDURE (PS); DCL PS BIN FIXED(31); DCL I BIN FIXED(31) INIT(0); DCL A(50) BIN FIXED(31) EXTERNAL;   DO I=1 TO PS-1; IF A(I) = A(PS) THEN RETURN(0); IF ABS ( A(I) - A(PS) ) = (PS-I) THEN RETURN(0); END; RETURN (1); END PLACE;   QUEEN: PROCEDURE (N); DCL N BIN FIXED (31); DCL K BIN FIXED (31); DCL A(50) BIN FIXED(31) EXTERNAL; DCL COUNT BIN FIXED(31) EXTERNAL; K = 1; A(K) = 0; DO WHILE (K > 0); A(K) = A(K) + 1; DO WHILE ( ( A(K)<= N) & (PLACE(K) =0) ); A(K) = A(K) +1; END; IF (A(K) <= N) THEN DO; IF (K = N ) THEN DO; COUNT = COUNT + 1; END; ELSE DO; K= K +1; A(K) = 0; END; /* OF INSIDE ELSE */ END; /* OF FIRST IF */ ELSE DO; K = K -1; END; END; /* OF EXTERNAL WHILE LOOP */ END QUEEN;   END NQUEENS;
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.
#XLISP
XLISP
(DEFUN NTH (N) (COND ((AND (> (MOD N 100) 3) (< (MOD N 100) 21)) `(,N TH)) ((= (MOD N 10) 1) `(,N ST)) ((= (MOD N 10) 2) `(,N ND)) ((= (MOD N 10) 3) `(,N RD)) (T `(,N TH))))   (DEFUN RANGE (X Y) (IF (<= X Y) (CONS X (RANGE (+ X 1) Y))))   (DEFUN TEST-NTH () (DISPLAY (MAPCAR NTH (RANGE 1 25))) (NEWLINE) (DISPLAY (MAPCAR NTH (RANGE 250 265))) (NEWLINE) (DISPLAY (MAPCAR NTH (RANGE 1000 1025))))   (TEST-NTH)
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).
#Perl
Perl
sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 } sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 }   # Usage: foreach my $sequence (\&F, \&M) { print join(' ', map $sequence->($_), 0 .. 19), "\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
#PureBasic
PureBasic
OpenConsole()   Procedure.d MonteCarloPi(throws.d) inCircle.d = 0 For i = 1 To throws.d randX.d = (Random(2147483647)/2147483647)*2-1 randY.d = (Random(2147483647)/2147483647)*2-1 dist.d = Sqr(randX.d*randX.d + randY.d*randY.d) If dist.d < 1 inCircle = inCircle + 1 EndIf Next i pi.d = (4 * inCircle / throws.d) ProcedureReturn pi.d   EndProcedure   PrintN ("'built-in' #Pi = " + StrD(#PI,20)) PrintN ("MonteCarloPi(10000) = " + StrD(MonteCarloPi(10000),20)) PrintN ("MonteCarloPi(100000) = " + StrD(MonteCarloPi(100000),20)) PrintN ("MonteCarloPi(1000000) = " + StrD(MonteCarloPi(1000000),20)) PrintN ("MonteCarloPi(10000000) = " + StrD(MonteCarloPi(10000000),20))   PrintN("Press any key"): Repeat: Until Inkey() <> ""  
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).
#OCaml
OCaml
let 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', "--.."; '0', "-----"; '1', ".----"; '2', "..---"; '3', "...--"; '4', "....-"; '5', "....."; '6', "-...."; '7', "--..."; '8', "---.."; '9', "----."; ]   let oc = open_out "/dev/dsp"   let bip u = for i = 0 to pred u do let j = sin(0.6 *. (float i)) in let k = ((j +. 1.0) /. 2.0) *. 127.0 in output_byte oc (truncate k) done   let gap u = for i = 0 to pred u do output_byte oc 0 done   let morse = let u = 1000 in (* length of one unit *) let u2 = u * 2 in let u3 = u * 3 in let u6 = u * 6 in String.iter (function | ' ' -> gap u6 | 'a'..'z' | 'A'..'Z' | '0'..'9' as c -> let s = List.assoc c codes in String.iter (function '.' -> bip u; gap u | '-' -> bip u3; gap u | _ -> assert false ) s; gap u2 | _ -> prerr_endline "unknown char")   let () = morse "rosettacode 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.
#Lua
Lua
function playgame(player) local car = math.random(3) local pchoice = player.choice() local function neither(a, b) --slow, but it works local el = math.random(3) return (el ~= a and el ~= b) and el or neither(a, b) end local el = neither(car, pchoice) if(player.switch) then pchoice = neither(pchoice, el) end player.wins = player.wins + (pchoice == car and 1 or 0) end for _, v in ipairs{true, false} do player = {choice = function() return math.random(3) end, wins = 0, switch = v} for i = 1, 20000 do playgame(player) end print(player.wins) 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.
#Ruby
Ruby
#based on pseudo code from http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 and from translating the python implementation. def extended_gcd(a, b) last_remainder, remainder = a.abs, b.abs x, last_x, y, last_y = 0, 1, 1, 0 while remainder != 0 last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder) x, last_x = last_x - quotient*x, x y, last_y = last_y - quotient*y, y end   return last_remainder, last_x * (a < 0 ? -1 : 1) end   def invmod(e, et) g, x = extended_gcd(e, et) if g != 1 raise 'The maths are broken!' end x % et 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.
#Run_BASIC
Run BASIC
print multInv(42, 2017) end   function multInv(a,b) b0 = b multInv = 1 if b = 1 then goto [endFun] while a > 1 q = a / b t = b b = a mod b a = t t = x0 x0 = multInv - q * x0 multInv = int(t) wend if multInv < 0 then multInv = multInv + b0 [endFun] end function
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.
#Factor
Factor
USING: io kernel math math.parser math.ranges sequences ; IN: multiplication-table   : print-row ( n -- ) [ number>string 2 CHAR: space pad-head write " |" write ] [ 1 - [ " " write ] times ] [ dup 12 [a,b] [ * number>string 4 CHAR: space pad-head write ] with each ] tri nl ;   : print-table ( -- ) " " write 1 12 [a,b] [ number>string 4 CHAR: space pad-head write ] each nl " +" write 12 [ "----" write ] times nl 1 12 [a,b] [ print-row ] each ;
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
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL   SUB aux(n AS INTEGER, i AS INTEGER, a() AS INTEGER, _ u() AS INTEGER, v() AS INTEGER, m AS QUAD)   LOCAL j, k, p, q AS INTEGER IF i > n THEN INCR m FOR k = 1 TO n : PRINT a(k); : NEXT : PRINT ELSE FOR j = i TO n k = a(j) p = i - k + n q = i + k - 1 IF u(p) AND v(q) THEN u(p) = 0 : v(q) = 0 a(j) = a(i) : a(i) = k CALL aux(n, i + 1, a(), u(), v(), m) u(p) = 1 : v(q) = 1 a(i) = a(j) : a(j) = k END IF NEXT END IF END SUB   FUNCTION PBMAIN () AS LONG LOCAL n, i AS INTEGER LOCAL m AS QUAD IF COMMAND$(1) <> "" THEN n = VAL(COMMAND$(1)) REDIM a(1 TO n) AS INTEGER REDIM u(1 TO 2 * n - 1) AS INTEGER REDIM v(1 TO 2 * n - 1) AS INTEGER FOR i = 1 TO n a(i) = i NEXT FOR i = 1 TO 2 * n - 1 u(i) = 1 v(i) = 1 NEXT m = 0 CALL aux(n, 1, a(), u(), v(), m) PRINT m END IF END FUNCTION
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.
#XPL0
XPL0
  \N'th code Rem=2, CrLf=9, IntIn=10, IntOut=11, Text=12;   procedure Suf(N, S); integer N; character S; integer NMod10, NMod100; begin NMod10:= Rem(N/10); NMod100:= Rem(N/100); case of NMod10 = 1 & NMod100 # 11: S(0):= "st"; NMod10 = 2 & NMod100 # 12: S(0):= "nd"; NMod10 = 3 & NMod100 # 13: S(0):= "rd" other S(0):= "th"; end;   procedure PrintImages(LoLim, HiLim); integer LoLim, HiLim; integer I; character S; begin for I:= LoLim, HiLim do begin Suf(I, addr S); IntOut(0, I); Text(0, S); Text(0, " ") end; CrLf(0) end;   begin PrintImages(0, 25); PrintImages(250, 265); PrintImages(1000, 1025) end  
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).
#Phix
Phix
with javascript_semantics forward function M(integer n) function F(integer n) return iff(n?n-M(F(n-1)):1) end function function M(integer n) return iff(n?n-F(M(n-1)):0) end function for i=0 to 20 do printf(1," %d",F(i)) end for printf(1,"\n") for i=0 to 20 do printf(1," %d",M(i)) end for
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
#Python
Python
>>> import random, math >>> throws = 1000 >>> 4.0 * sum(math.hypot(*[random.random()*2-1 for q in [0,1]]) < 1 for p in xrange(throws)) / float(throws) 3.1520000000000001 >>> throws = 1000000 >>> 4.0 * sum(math.hypot(*[random.random()*2-1 for q in [0,1]]) < 1 for p in xrange(throws)) / float(throws) 3.1396359999999999 >>> throws = 100000000 >>> 4.0 * sum(math.hypot(*[random.random()*2-1 for q in [0,1]]) < 1 for p in xrange(throws)) / float(throws) 3.1415666400000002
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).
#Ol
Ol
  (display "Please, enter the string in lower case bounded by \" sign: ") (lfor (list->ff '( (#\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 . "-----") (#\space . " ") (#\. . " "))) (str-iter (read)) (lambda (codes char) (let ((out (getf codes char))) (if out (display out))) codes))   ; ==> Please, enter the string in lower case bounded by " sign: ; <== "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.
#Lua.2FTorch
Lua/Torch
function montyHall(n) local car = torch.LongTensor(n):random(3) -- door with car local choice = torch.LongTensor(n):random(3) -- player's choice local opens = torch.LongTensor(n):random(2):csub(1):mul(2):csub(1) -- -1 or +1 local iscarchoice = choice:eq(car) local nocarchoice = 1-iscarchoice opens[iscarchoice] = (((opens + choice - 1) % 3):abs() + 1)[iscarchoice] opens[nocarchoice] = (6 - car - choice)[nocarchoice] local change = torch.LongTensor(n):bernoulli() -- 0: stay, 1: change local win = iscarchoice:long():cmul(1-change) + nocarchoice:long():cmul(change) return car, choice, opens, change, win end   function montyStats(n) local car, pchoice, opens, change, win = montyHall(n)   local change_and_win = change [ win:byte()]:sum()/ change :sum()*100 local no_change_and_win = (1-change)[ win:byte()]:sum()/(1-change):sum()*100 local change_and_win_not = change [1-win:byte()]:sum()/ change :sum()*100 local no_change_and_win_not = (1-change)[1-win:byte()]:sum()/(1-change):sum()*100   print(string.format("  %9s  %9s" , "no change", "change" )) print(string.format("win  %8.4f%%  %8.4f%%", no_change_and_win , change_and_win )) print(string.format("win not  %8.4f%%  %8.4f%%", no_change_and_win_not, change_and_win_not)) end   montyStats(1e7)
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.
#Rust
Rust
fn mod_inv(a: isize, module: isize) -> isize { let mut mn = (module, a); let mut xy = (0, 1);   while mn.1 != 0 { xy = (xy.1, xy.0 - (mn.0 / mn.1) * xy.1); mn = (mn.1, mn.0 % mn.1); }   while xy.0 < 0 { xy.0 += module; } xy.0 }   fn main() { println!("{}", mod_inv(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.
#Scala
Scala
  def gcdExt(u: Int, v: Int): (Int, Int, Int) = { @tailrec def aux(a: Int, b: Int, x: Int, y: Int, x1: Int, x2: Int, y1: Int, y2: Int): (Int, Int, Int) = { if(b == 0) (x, y, a) else { val (q, r) = (a / b, a % b) aux(b, r, x2 - q * x1, y2 - q * y1, x, x1, y, y1) } } aux(u, v, 1, 0, 0, 1, 1, 0) }   def modInv(a: Int, m: Int): Option[Int] = { val (i, j, g) = gcdExt(a, m) if (g == 1) Option(if (i < 0) i + m else i) else Option.empty }
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.
#FALSE
FALSE
[$100\>[" "]?$10\>[" "]?." "]p: [$p;! m: 2[$m;\>][" "1+]# [$13\>][$m;*p;!1+]#%" "]l: 1[$13\>][$l;!1+]#%
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
#PowerShell
PowerShell
  function PlaceQueen ( [ref]$Board, $Row, $N ) { # For the current row, start with the first column $Board.Value[$Row] = 0   # While haven't exhausted all columns in the current row... While ( $Board.Value[$Row] -lt $N ) { # If not the first row, check for conflicts $Conflict = $Row -and ( (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] }.Count -or (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] - $Row + $_ }.Count -or (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] + $Row - $_ }.Count )   # If no conflicts and the current column is a valid column... If ( -not $Conflict -and $Board.Value[$Row] -lt $N ) {   # If this is the last row # Board completed successfully If ( $Row -eq ( $N - 1 ) ) { return $True }   # Recurse # If all nested recursions were successful # Board completed successfully If ( PlaceQueen $Board ( $Row + 1 ) $N ) { return $True } }   # Try the next column $Board.Value[$Row]++ }   # Everything was tried, nothing worked Return $False }   function Get-NQueensBoard ( $N ) { # Start with a default board (array of column positions for each row) $Board = @( 0 ) * $N   # Place queens on board # If successful... If ( PlaceQueen -Board ([ref]$Board) -Row 0 -N $N ) { # Convert board to strings for display $Board | ForEach { ( @( "" ) + @(" ") * $_ + "Q" + @(" ") * ( $N - $_ ) ) -join "|" } } Else { "There is no solution for N = $N" } }  
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.
#Yabasic
Yabasic
  sub ordinal$ (n) NMod10 = mod(n, 10) NMod100 = mod(n, 100) if (NMod10 = 1) and (NMod100 <> 11) then return "st" else if (NMod10 = 2) and (NMod100 <> 12) then return "nd" else if (NMod10 = 3) and (NMod100 <> 13) then return "rd" else return "th" end if end if end if end sub   sub imprimeOrdinal(a, b) for i = a to b print i, ordinal$(i), " "; next i print end sub   imprimeOrdinal (0, 25) imprimeOrdinal (250, 265) imprimeOrdinal (1000, 1025) end  
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).
#PHP
PHP
<?php function F($n) { if ( $n == 0 ) return 1; return $n - M(F($n-1)); }   function M($n) { if ( $n == 0) return 0; return $n - F(M($n-1)); }   $ra = array(); $rb = array(); for($i=0; $i < 20; $i++) { array_push($ra, F($i)); array_push($rb, M($i)); } echo implode(" ", $ra) . "\n"; echo implode(" ", $rb) . "\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
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ [ 64 bit ] constant dup random dup * over random dup * + swap dup * < ] is hit ( --> b )   [ 0 swap times [ hit if 1+ ] ] is sims ( n --> n )   [ dup echo say " trials " dup sims 4 * swap 20 point$ echo$ cr ] is trials ( n --> )   ' [ 10 100 1000 10000 100000 1000000 ] witheach trials
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
#R
R
# nice but not suitable for big samples! monteCarloPi <- function(samples) { x <- runif(samples, -1, 1) # for big samples, you need a lot of memory! y <- runif(samples, -1, 1) l <- sqrt(x*x + y*y) return(4*sum(l<=1)/samples) }   # this second function changes the samples number to be # multiple of group parameter (default 100). monteCarlo2Pi <- function(samples, group=100) { lim <- ceiling(samples/group) olim <- lim c <- 0 while(lim > 0) { x <- runif(group, -1, 1) y <- runif(group, -1, 1) l <- sqrt(x*x + y*y) c <- c + sum(l <= 1) lim <- lim - 1 } return(4*c/(olim*group)) }   print(monteCarloPi(1e4)) print(monteCarloPi(1e5)) print(monteCarlo2Pi(1e7))
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).
#PARI.2FGP
PARI/GP
sleep(ms)={ while((ms-=gettime()) > 0,); }; dot()=print1(Strchr([7]));sleep(250); dash()=print1(Strchr([7]));sleep(10);print1(Strchr([7]));sleep(10);print1(Strchr([7]));sleep(250); Morse(s)={ s=Vec(s); for(i=1,#s, if(s[i] == ".", dot(), if(s[i] == "-", dash(), sleep(250)) ) ) };   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.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Enum Strat {Stay, Random, Switch} total=10000 Print $("0.00") player_win_stay=0 player_win_switch=0 player_win_random=0 For i=1 to total { Dim doors(1 to 3)=False doors(Random(1,3))=True guess=Random(1,3) Inventory other for k=1 to 3 { If k <> guess Then Append other, k } If doors(guess) Then { Mont_Hall_show=other(Random(0,1)!) } Else { If doors(other(0!)) Then { Mont_Hall_show=other(1!) } Else Mont_Hall_show=other(0!) Delete Other, Mont_Hall_show } Strategy=Each(Strat) While Strategy { Select Case Eval(strategy) Case Random { If Random(1,2)=1 Then { If doors(guess) Then player_win_Random++ } else If doors(other(0!)) Then player_win_Random++ } Case Switch If doors(other(0!)) Then player_win_switch++ Else If doors(guess) Then player_win_stay++ End Select } } Print "Stay: ";player_win_stay/total*100;"%" Print "Random: ";player_win_Random/total*100;"%" Print "Switch: ";player_win_switch/total*100;"%" } CheckIt  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
montyHall[nGames_] := Module[{r, winningDoors, firstChoices, nStayWins, nSwitchWins, s}, r := RandomInteger[{1, 3}, nGames]; winningDoors = r; firstChoices = r; nStayWins = Count[Transpose[{winningDoors, firstChoices}], {d_, d_}]; nSwitchWins = nGames - nStayWins;   Grid[{{"Strategy", "Wins", "Win %"}, {"Stay", Row[{nStayWins, "/", nGames}], s=N[100 nStayWins/nGames]}, {"Switch", Row[{nSwitchWins, "/", nGames}], 100 - s}}, Frame -> All]]
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.
#Seed7
Seed7
const func bigInteger: modInverse (in var bigInteger: a, in var bigInteger: b) is func result var bigInteger: modularInverse is 0_; local var bigInteger: b_bak is 0_; var bigInteger: x is 0_; var bigInteger: y is 1_; var bigInteger: lastx is 1_; var bigInteger: lasty is 0_; var bigInteger: temp is 0_; var bigInteger: quotient is 0_; begin if b < 0_ then raise RANGE_ERROR; end if; if a < 0_ and b <> 0_ then a := a mod b; end if; b_bak := b; while b <> 0_ do temp := b; quotient := a div b; b := a rem b; a := temp;   temp := x; x := lastx - quotient * x; lastx := temp;   temp := y; y := lasty - quotient * y; lasty := temp; end while; if a = 1_ then modularInverse := lastx; if modularInverse < 0_ then modularInverse +:= b_bak; end if; else raise RANGE_ERROR; end if; end func;
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.
#Sidef
Sidef
say 42.modinv(2017)
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.
#Fantom
Fantom
  class Main { static Void multiplicationTable (Int n) { // print column headings echo (" |" + (1..n).map |Int a -> Str| { a.toStr.padl(4)}.join("") ) echo ("-----" + (1..n).map { "----" }.join("") ) // work through each row (1..n).each |i| { echo ( i.toStr.padl(4) + "|" + Str.spaces(4*(i-1)) + (i..n).map |Int j -> Str| { (i*j).toStr.padl(4)}.join("") ) } }   public static Void main () { multiplicationTable (12) } }  
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
#Processing
Processing
  int n = 8; int[] b = new int[n]; int s = 0; int y = 0;   void setup() { size(400, 400); textAlign(CENTER, CENTER); textFont(createFont("DejaVu Sans", 44)); b[0] = -1; }   void draw() { if (y >= 0) { do { b[y]++; } while ((b[y] < n) && unsafe(y)); if (b[y] < n) { if (y < (n-1)) { b[++y] = -1; } else { drawBoard(); } } else { y--; } } else { textSize(18); text("Press any key to restart", width / 2, height - 20); } }     boolean unsafe(int y) { int x = b[y]; for (int i = 1; i <= y; i++) { int t = b[y - i]; if (t == x || t == x - i || t == x + i) { return true; } } return false; }   void drawBoard() { float w = width / n; for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { fill(255 * ((x + y) % 2)); square(x * w, y * w, w); if (b[y] == x) { fill(255 - 255 * ((x + y) % 2)); textSize(42); text("♕", w / 2 + x *w, w /2 + y * w); } } } fill(255, 0, 0); textSize(18); text("Solution " + (++s), width / 2, height / 90); }   void keyPressed() { b = new int[n]; s = 0; y = 0; b[0] = -1; }  
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.
#zkl
zkl
#if 0 fcn addSuffix(n){ z:=n.abs()%100; if(11<=z<=13) return(String(n,"th")); z=z%10; String(n,(z==1 and "st") or (z==2 and "nd") or (z==3 and "rd") or "th"); } #else fcn addSuffix(n){ var suffixes=T("th","st","nd","rd","th","th","th","th","th","th"); //0..10 z:=n.abs()%100; String(n,(z<=10 or z>20) and suffixes[z%10] or "th"); } #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).
#Picat
Picat
table f(0) = 1. f(N) = N - m(f(N-1)), N > 0 => true.   table m(0) = 0. m(N) = N - f(m(N-1)), N > 0 => true.
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
#Racket
Racket
#lang racket   (define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1)) ;; point in ([-1,1], [-1,1]) (define (random-point-in-2x2-square) (values (* 2 (- (random) 1/2)) (* 2 (- (random) 1/2))))   ;; Area of circle is (pi r^2). r is 1, area of circle is pi ;; Area of square is 2^2 = 4 ;; There is a pi/4 chance of landing in circle ;; .: pi = 4*(proportion passed) = 4*(passed/samples) (define (passed:samples->pi passed samples) (* 4 (/ passed samples)))   ;; generic kind of monte-carlo simulation (define (monte-carlo run-length report-frequency sample-generator pass? interpret-result) (let inner ((samples 0) (passed 0) (cnt report-frequency)) (cond [(= samples run-length) (interpret-result passed samples)] [(zero? cnt) ; intermediate report (printf "~a samples of ~a: ~a passed -> ~a~%" samples run-length passed (interpret-result passed samples)) (inner samples passed report-frequency)] [else (inner (add1 samples) (if (call-with-values sample-generator pass?) (add1 passed) passed) (sub1 cnt))])))   ;; (monte-carlo ...) gives an "exact" result... which will be a fraction. ;; to see how it looks as a decimal we can exact->inexact it (let ((mc (monte-carlo 10000000 1000000 random-point-in-2x2-square in-unit-circle? passed:samples->pi))) (printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))