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/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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: suffix (in integer: num) is func result var string: suffix is ""; begin if num rem 10 = 1 and num rem 100 <> 11 then suffix := "st"; elsif num rem 10 = 2 and num rem 100 <> 12 then suffix := "nd"; elsif num rem 10 = 3 and num rem 100 <> 13 then suffix := "rd"; else suffix := "th"; end if; end func;   const proc: printImages (in integer: start, in integer: stop) is func local var integer: num is 0; begin for num range start to stop do write(num <& suffix(num) <& " "); end for; writeln; end func;   const proc: main is func begin printImages( 0, 25); printImages( 250, 265); printImages(1000, 1025); end func;
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Visual_Basic
Visual Basic
Option Explicit   Declare Function GetTickCount Lib "kernel32.dll" () As Long Declare Sub ZeroMemory Lib "kernel32.dll" Alias "RtlZeroMemory" (ByRef Destination As Any, ByVal Length As Long)     Sub Main() Dim i As Long, j As Long, n As Long, t As Long Dim sum As Double Dim n0 As Double Dim n1 As Double Dim n2 As Double Dim n3 As Double Dim n4 As Double Dim n5 As Double Dim n6 As Double Dim n7 As Double Dim n8 As Double Dim n9 As Double Dim ten1 As Double Dim ten2 As Double Dim s1 As Long Dim s2 As Long Dim s3 As Long Dim s4 As Long Dim s5 As Long Dim s6 As Long Dim s7 As Long Dim s8 As Long Dim pow(9) As Long, num(9) As Long Dim number As String, res As String   t = GetTickCount() ten2 = 10 For i = 1 To 9 pow(i) = i For j = 2 To i pow(i) = i * pow(i) Next j Next i For n = 1 To 11 For n9 = 0 To n For n8 = 0 To n - n9 s8 = n9 + n8 For n7 = 0 To n - s8 s7 = s8 + n7 For n6 = 0 To n - s7 s6 = s7 + n6 For n5 = 0 To n - s6 s5 = s6 + n5 For n4 = 0 To n - s5 s4 = s5 + n4 For n3 = 0 To n - s4 s3 = s4 + n3 For n2 = 0 To n - s3 s2 = s3 + n2 For n1 = 0 To n - s2 n0 = n - (s2 + n1) sum = n1 * pow(1) + n2 * pow(2) + n3 * pow(3) + _ n4 * pow(4) + n5 * pow(5) + n6 * pow(6) + _ n7 * pow(7) + n8 * pow(8) + n9 * pow(9) Select Case sum Case ten1 To ten2 - 1 number = CStr(sum) ZeroMemory num(0), 40 For i = 1 To n j = Asc(Mid$(number, i, 1)) - 48 num(j) = num(j) + 1 Next i If n0 = num(0) Then If n1 = num(1) Then If n2 = num(2) Then If n3 = num(3) Then If n4 = num(4) Then If n5 = num(5) Then If n6 = num(6) Then If n7 = num(7) Then If n8 = num(8) Then If n9 = num(9) Then res = res & CStr(sum) & vbNewLine End If End If End If End If End If End If End If End If End If End If End Select Next n1 Next n2 Next n3 Next n4 Next n5 Next n6 Next n7 Next n8 Next n9 ten1 = ten2 ten2 = ten2 * 10 Next n t = GetTickCount() - t res = res & "execution time:" & Str$(t) & " ms" MsgBox res 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).
#MMIX
MMIX
LOC Data_Segment   GREG @ NL BYTE #a,0 GREG @ buf OCTA 0,0   t IS $128 Ja IS $127   LOC #1000   GREG @ // print 2 digits integer with trailing space to StdOut // reg $3 contains int to be printed bp IS $71 0H GREG #0000000000203020 prtInt STO 0B,buf % initialize buffer LDA bp,buf+7 % points after LSD % REPEAT 1H SUB bp,bp,1 % move buffer pointer DIV $3,$3,10 % divmod (x,10) GET t,rR % get remainder INCL t,'0' % make char digit STB t,bp % store digit PBNZ $3,1B % UNTIL no more digits LDA $255,bp TRAP 0,Fputs,StdOut % print integer GO Ja,Ja,0 % 'return' // Female function F GET $1,rJ % save return addr PBNZ $0,1F % if N != 0 then F N INCL $0,1 % F 0 = 1 PUT rJ,$1 % restore return addr POP 1,0 % return 1 1H SUBU $3,$0,1 % N1 = N - 1 PUSHJ $2,F % do F (N - 1) ADDU $3,$2,0 % place result in arg. reg. PUSHJ $2,M % do M F ( N - 1) PUT rJ,$1 % restore ret addr SUBU $0,$0,$2 POP 1,0 % return N - M F ( N - 1 ) // Male function M GET $1,rJ PBNZ $0,1F PUT rJ,$1 POP 1,0 % return M 0 = 0 1H SUBU $3,$0,1 PUSHJ $2,M ADDU $3,$2,0 PUSHJ $2,F PUT rJ,$1 SUBU $0,$0,$2 POP 1,0 $ return N - F M ( N - 1 ) // do a female run Main SET $1,0 % for (i=0; i<25; i++){ 1H ADDU $4,$1,0 % PUSHJ $3,F % F (i) GO Ja,prtInt % print F (i) INCL $1,1 CMP t,$1,25 PBNZ t,1B % } LDA $255,NL TRAP 0,Fputs,StdOut // do a male run SET $1,0 % for (i=0; i<25; i++){ 1H ADDU $4,$1,0 % PUSHJ $3,M % M (i) GO Ja,prtInt % print M (i) INCL $1,1 CMP t,$1,25 PBNZ t,1B % } LDA $255,NL TRAP 0,Fputs,StdOut TRAP 0,Halt,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
#Jsish
Jsish
/* Monte Carlo methods, in Jsish */ function mcpi(n) { var x, y, m = 0;   for (var i = 0; i < n; i += 1) { x = Math.random(); y = Math.random();   if (x * x + y * y < 1) { m += 1; } }   return 4 * m / n; }   if (Interp.conf('unitTest')) { Math.srand(0); ; mcpi(1000); ; mcpi(10000); ; mcpi(100000); ; mcpi(1000000); }   /* =!EXPECTSTART!= mcpi(1000) ==> 3.108 mcpi(10000) ==> 3.1236 mcpi(100000) ==> 3.13732 mcpi(1000000) ==> 3.142124 =!EXPECTEND!= */
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
#Julia
Julia
using Printf   function monteπ(n) s = count(rand() ^ 2 + rand() ^ 2 < 1 for _ in 1:n) return 4s / n end   for n in 10 .^ (3:8) p = monteπ(n) println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π)) end
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#zkl
zkl
fcn encode(text){ //-->List st:=["a".."z"].pump(Data); //"abcd..z" as byte array text.reduce(fcn(st,c,sink){ n:=st.index(c); sink.write(n); st.del(n).insert(0,c); },st,sink:=L()); sink; }
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).
#Gambas
Gambas
'Requires component 'gb.sdl2.audio'   Public Sub Main() Dim sMessage As String = "Hello World" Dim sFile As String = File.Load("../morse.txt") 'Contains A,.- B,-... etc Dim sChar As New String[] Dim sMorse As New String[] Dim sOutPut As New String[] Dim sTemp As String Dim siCount, siLoop As Short Dim bTrigger As Boolean Dim fDelay As Float = 0.4   If Not Exist("/tmp/dot.ogg") Then Copy "../dot.ogg" To "/tmp/dot.ogg" 'Sounds downloaded from If Not Exist("/tmp/dash.ogg") Then Copy "../dash.ogg" To "/tmp/dash.ogg" 'https://en.wikipedia.org/wiki/Morse_code#Letters.2C_numbers.2C_punctuation.2C_prosigns_for_Morse_code_and_non-English_variants   For Each sTemp In Split(sFile, gb.NewLine) sChar.add(Split(Trim(sTemp))[0]) sMorse.add(Split(Trim(sTemp))[1]) Next   For siCount = 1 To Len(sMessage) For siLoop = 0 To sChar.Max If sChar[siLoop] = Mid(UCase(sMessage), siCount, 1) Then sOutPut.Add(sMorse[siLoop]) bTrigger = True Break End If Next If bTrigger = False Then sOutPut.Add(" ") bTrigger = False Next   Print sOutPut.Join(" ")   For siCount = 0 To Len(sMessage) - 1 For siLoop = 0 To Len(sOutPut[siCount]) - 1 If Mid(sOutPut[siCount], siLoop + 1, 1) = "." Then Music.Load("/tmp/dot.ogg") Music.Play Wait fDelay Else If Mid(sOutPut[siCount], siLoop + 1, 1) = "-" Then Music.Load("/tmp/dash.ogg") Music.Play Wait fDelay Else Wait fDelay Endif Next Next   End
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it. If both remaining doors have goats behind them, he chooses one randomly. After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door. Imagine that you chose Door 1 and the host opens Door 3, which has a goat. He then asks you "Do you want to switch to Door Number 2?" The question Is it to your advantage to change your choice? Note The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors. Task Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess. Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. References Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3 A YouTube video:   Monty Hall Problem - Numberphile.
#F.23
F#
open System let monty nSims = let rnd = new Random() let SwitchGame() = let winner, pick = rnd.Next(0,3), rnd.Next(0,3) if winner <> pick then 1 else 0   let StayGame() = let winner, pick = rnd.Next(0,3), rnd.Next(0,3) if winner = pick then 1 else 0   let Wins (f:unit -> int) = seq {for i in [1..nSims] -> f()} |> Seq.sum printfn "Stay: %d wins out of %d - Switch: %d wins out of %d" (Wins StayGame) nSims (Wins SwitchGame) nSims
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.
#MAD
MAD
NORMAL MODE IS INTEGER INTERNAL FUNCTION(AA, BB) ENTRY TO MULINV. A = AA B = BB WHENEVER B.L.0, B = -B WHENEVER A.L.0, A = B - (-(A-A/B*B)) T = 0 NT = 1 R = B NR = A-A/B*B LOOP WHENEVER NR.NE.0 Q = R/NR TMP = NT NT = T - Q*NT T = TMP TMP = NR NR = R - Q*NR R = TMP TRANSFER TO LOOP END OF CONDITIONAL WHENEVER R.G.1, FUNCTION RETURN -1 WHENEVER T.L.0, T = T+B FUNCTION RETURN T END OF FUNCTION   INTERNAL FUNCTION(AA, BB) VECTOR VALUES FMT = $I5,2H, ,I5,2H: ,I5*$ ENTRY TO SHOW. PRINT FORMAT FMT, AA, BB, MULINV.(AA, BB) END OF FUNCTION   SHOW.(42,2017) SHOW.(40,1) SHOW.(52,-217) SHOW.(-486,217) SHOW.(40,2018) END OF PROGRAM
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.
#Maple
Maple
  1/42 mod 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.
#Common_Lisp
Common Lisp
  (do ((m 0 (if (= 12 m) 0 (1+ m))) (n 0 (if (= 12 m) (1+ n) n))) ((= n 13)) (if (zerop n) (case m (0 (format t " *|")) (12 (format t " 12~&---+------------------------------------------------~&")) (otherwise (format t "~4,D" m))) (case m (0 (format t "~3,D|" n)) (12 (format t "~4,D~&" (* n m))) (otherwise (if (>= m n) (format t "~4,D" (* m n)) (format t " "))))))  
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.
#Python
Python
>>> from functools import reduce >>> from operator import mul >>> def mfac(n, m): return reduce(mul, range(n, 0, -m))   >>> for m in range(1, 11): print("%2i: %r" % (m, [mfac(n, m) for n in range(1, 11)]))   1: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] 2: [1, 2, 3, 8, 15, 48, 105, 384, 945, 3840] 3: [1, 2, 3, 4, 10, 18, 28, 80, 162, 280] 4: [1, 2, 3, 4, 5, 12, 21, 32, 45, 120] 5: [1, 2, 3, 4, 5, 6, 14, 24, 36, 50] 6: [1, 2, 3, 4, 5, 6, 7, 16, 27, 40] 7: [1, 2, 3, 4, 5, 6, 7, 8, 18, 30] 8: [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] 9: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 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
#MUMPS
MUMPS
Queens New count,flip,row,sol Set sol=0 For row(1)=1:1:4 Do try(2)  ; Not 8, the other 4 are symmetric... ; ; Remove symmetric solutions Set sol="" For Set sol=$Order(sol(sol)) Quit:sol="" Do . New xx,yy . Kill sol($Translate(sol,12345678,87654321)) ; Vertical flip . Kill sol($Reverse(sol)) ; Horizontal flip . Set flip="--------" for xx=1:1:8 Do  ; Flip over top left to bottom right diagonal . . New nx,ny . . Set yy=$Extract(sol,xx),nx=8+1-xx,ny=8+1-yy . . Set $Extract(flip,ny)=nx . . Quit . Kill sol(flip) . Set flip="--------" for xx=1:1:8 Do  ; Flip over top right to bottom left diagonal . . New nx,ny . . Set yy=$Extract(sol,xx),nx=xx,ny=yy . . Set $Extract(flip,ny)=nx . . Quit . Kill sol(flip) . Quit ; ; Display remaining solutions Set count=0,sol="" For Set sol=$Order(sol(sol)) Quit:sol="" Do Quit:sol="" . New s1,s2,s3,txt,x,y . Set s1=sol,s2=$Order(sol(s1)),s3="" Set:s2'="" s3=$Order(sol(s2)) . Set txt="+--+--+--+--+--+--+--+--+" . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt . For y=8:-1:1 Do . . Write !,y," |" . . For x=1:1:8 Write $Select($Extract(s1,x)=y:" Q",x+y#2:" ",1:"##"),"|" . . If s2'="" Write " |" . . If s2'="" For x=1:1:8 Write $Select($Extract(s2,x)=y:" Q",x+y#2:" ",1:"##"),"|" . . If s3'="" Write " |" . . If s3'="" For x=1:1:8 Write $Select($Extract(s3,x)=y:" Q",x+y#2:" ",1:"##"),"|" . . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt . . Quit . Set txt=" A B C D E F G H" . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt Write ! . Set sol=s3 . Quit Quit try(col) New ok,pcol If col>8 Do Quit . New out,x . Set out="" For x=1:1:8 Set out=out_row(x) . Set sol(out)=1 . Quit For row(col)=1:1:8 Do . Set ok=1 . For pcol=1:1:col-1 If row(pcol)=row(col) Set ok=0 Quit . Quit:'ok . For pcol=1:1:col-1 If col-pcol=$Translate(row(pcol)-row(col),"-") Set ok=0 Quit . Quit:'ok . Do try(col+1) . Quit Quit Do Queens  
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.
#Set_lang
Set lang
set o 49 set t 50 set h 51 set n ! set ! n set ! 39 [n=o] set ? 13 [n=t] set ? 16 [n=h] set ? 19 set ! T set ! H set ? 21 set ! S set ! T set ? 21 set ! N set ! D set ? 12 set ! R set ! D > EOF
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Visual_Basic_.NET
Visual Basic .NET
Imports System   Module Program Sub Main() Dim i, j, n, n1, n2, n3, n4, n5, n6, n7, n8, n9, s2, s3, s4, s5, s6, s7, s8 As Integer, sum, ten1 As Long, ten2 As Long = 10 Dim pow(9) As Long, num() As Byte For i = 1 To 9 : pow(i) = i : For j = 2 To i : pow(i) *= i : Next : Next For n = 1 To 11 : For n9 = 0 To n : For n8 = 0 To n - n9 : s8 = n9 + n8 : For n7 = 0 To n - s8 s7 = s8 + n7 : For n6 = 0 To n - s7 : s6 = s7 + n6 : For n5 = 0 To n - s6 s5 = s6 + n5 : For n4 = 0 To n - s5 : s4 = s5 + n4 : For n3 = 0 To n - s4 s3 = s4 + n3 : For n2 = 0 To n - s3 : s2 = s3 + n2 : For n1 = 0 To n - s2 sum = n1 * pow(1) + n2 * pow(2) + n3 * pow(3) + n4 * pow(4) + n5 * pow(5) + n6 * pow(6) + n7 * pow(7) + n8 * pow(8) + n9 * pow(9) If sum < ten1 OrElse sum >= ten2 Then Continue For redim num(9) For Each ch As Char In sum.ToString() : num(Convert.ToByte(ch) - 48) += 1 : Next If n - (s2 + n1) = num(0) AndAlso n1 = num(1) AndAlso n2 = num(2) AndAlso n3 = num(3) AndAlso n4 = num(4) AndAlso n5 = num(5) AndAlso n6 = num(6) AndAlso n7 = num(7) AndAlso n8 = num(8) AndAlso n9 = num(9) Then Console.WriteLine(sum) Next : Next : Next : Next : Next : Next : Next : Next : Next ten1 = ten2 : ten2 *= 10 Next End Sub End Module
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).
#Modula-2
Modula-2
MODULE MutualRecursion; FROM InOut IMPORT WriteCard, WriteString, WriteLn;   TYPE Fn = PROCEDURE(CARDINAL): CARDINAL;   PROCEDURE F(n: CARDINAL): CARDINAL; BEGIN IF n=0 THEN RETURN 1; ELSE RETURN n-M(F(n-1)); END; END F;   PROCEDURE M(n: CARDINAL): CARDINAL; BEGIN IF n=0 THEN RETURN 0; ELSE RETURN n-F(M(n-1)); END; END M;   (* Print the first few values of one of the functions *) PROCEDURE Show(name: ARRAY OF CHAR; fn: Fn); CONST Max = 15; VAR i: CARDINAL; BEGIN WriteString(name); WriteString(": "); FOR i := 0 TO Max DO WriteCard(fn(i), 0); WriteString(" "); END; WriteLn; END Show;   (* Show the first values of both F and M *) BEGIN Show("F", F); Show("M", M); END MutualRecursion.
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
#K
K
sim:{4*(+/{~1<+/(2_draw 0)^2}'!x)%x}   sim 10000 3.103   sim'10^!8 4 2.8 3.4 3.072 3.1212 3.14104 3.14366 3.1413
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
#Kotlin
Kotlin
// version 1.1.0   fun mcPi(n: Int): Double { var inside = 0 (1..n).forEach { val x = Math.random() val y = Math.random() if (x * x + y * y <= 1.0) inside++ } return 4.0 * inside / n }   fun main(args: Array<String>) { println("Iterations -> Approx Pi -> Error%") println("---------- ---------- ------") var n = 1_000 while (n <= 100_000_000) { val pi = mcPi(n) val err = Math.abs(Math.PI - pi) / Math.PI * 100.0 println(String.format("%9d -> %10.8f -> %6.4f", n, pi, err)) n *= 10 } }
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow   (e.g. with a different pitch).
#Go
Go
// Command morse translates an input string into morse code, // showing the output on the console, and playing it as sound. // Only works on ubuntu. package main   import ( "flag" "fmt" "log" "regexp" "strings" "syscall" "time" "unicode" )   // A key represents an action on the morse key. // It's either on or off, for the given duration. type key struct { duration int on bool sym string // for debug output }   var ( runeToKeys = map[rune][]key{} interCharGap = []key{{1, false, ""}} punctGap = []key{{7, false, " / "}} charGap = []key{{3, false, " "}} wordGap = []key{{7, false, " / "}} )   const rawMorse = ` A:.- J:.--- S:... 1:.---- .:.-.-.-  ::---... B:-... K:-.- T:- 2:..--- ,:--..--  ;:-.-.-. C:-.-. L:.-.. U:..- 3:...--  ?:..--.. =:-...- D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. E:. N:-. W:.-- 5:.....  !:-.-.-- -:-....- F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. `   func init() { // Convert the rawMorse table into a map of morse key actions. r := regexp.MustCompile("([^ ]):([.-]+)") for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { c := m[1][0] keys := []key{} for i, dd := range m[2] { if i > 0 { keys = append(keys, interCharGap...) } if dd == '.' { keys = append(keys, key{1, true, "."}) } else if dd == '-' { keys = append(keys, key{3, true, "-"}) } else { log.Fatalf("found %c in morse for %c", dd, c) } runeToKeys[rune(c)] = keys runeToKeys[unicode.ToLower(rune(c))] = keys } } }   // MorseKeys translates an input string into a series of keys. func MorseKeys(in string) ([]key, error) { afterWord := false afterChar := false result := []key{} for _, c := range in { if unicode.IsSpace(c) { afterWord = true continue } morse, ok := runeToKeys[c] if !ok { return nil, fmt.Errorf("can't translate %c to morse", c) } if unicode.IsPunct(c) && afterChar { result = append(result, punctGap...) } else if afterWord { result = append(result, wordGap...) } else if afterChar { result = append(result, charGap...) } result = append(result, morse...) afterChar = true afterWord = false } return result, nil }   func main() { var ditDuration time.Duration flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") flag.Parse() in := "hello world." if len(flag.Args()) > 1 { in = strings.Join(flag.Args(), " ") } keys, err := MorseKeys(in) if err != nil { log.Fatalf("failed to translate: %s", err) } for _, k := range keys { if k.on { if err := note(true); err != nil { log.Fatalf("failed to play note: %s", err) } } fmt.Print(k.sym) time.Sleep(ditDuration * time.Duration(k.duration)) if k.on { if err := note(false); err != nil { log.Fatalf("failed to stop note: %s", err) } } } fmt.Println() }   // Implement sound on ubuntu. Needs permission to access /dev/console.   var consoleFD uintptr   func init() { fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) if err != nil { log.Fatalf("failed to get console device: %s", err) } consoleFD = uintptr(fd) }   const KIOCSOUND = 0x4B2F const clockTickRate = 1193180 const freqHz = 600   // note either starts or stops a note. func note(on bool) error { arg := uintptr(0) if on { arg = clockTickRate / freqHz } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) if errno != 0 { return errno } return nil   }  
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.
#Forth
Forth
include random.fs   variable stay-wins variable switch-wins   : trial ( -- ) 3 random 3 random ( prize choice ) = if 1 stay-wins +! else 1 switch-wins +! then ; : trials ( n -- ) 0 stay-wins ! 0 switch-wins ! dup 0 do trial loop cr stay-wins @ . [char] / emit dup . ." staying wins" cr switch-wins @ . [char] / emit . ." switching wins" ;   1000 trials
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.
#Fortran
Fortran
PROGRAM MONTYHALL   IMPLICIT NONE   INTEGER, PARAMETER :: trials = 10000 INTEGER :: i, choice, prize, remaining, show, staycount = 0, switchcount = 0 LOGICAL :: door(3) REAL :: rnum   CALL RANDOM_SEED DO i = 1, trials door = .FALSE. CALL RANDOM_NUMBER(rnum) prize = INT(3*rnum) + 1 door(prize) = .TRUE. ! place car behind random door   CALL RANDOM_NUMBER(rnum) choice = INT(3*rnum) + 1 ! choose a door   DO CALL RANDOM_NUMBER(rnum) show = INT(3*rnum) + 1 IF (show /= choice .AND. show /= prize) EXIT ! Reveal a goat END DO   SELECT CASE(choice+show) ! Calculate remaining door index CASE(3) remaining = 3 CASE(4) remaining = 2 CASE(5) remaining = 1 END SELECT   IF (door(choice)) THEN ! You win by staying with your original choice staycount = staycount + 1 ELSE IF (door(remaining)) THEN ! You win by switching to other door switchcount = switchcount + 1 END IF   END DO   WRITE(*, "(A,F6.2,A)") "Chance of winning by not switching is", real(staycount)/trials*100, "%" WRITE(*, "(A,F6.2,A)") "Chance of winning by switching is", real(switchcount)/trials*100, "%"   END PROGRAM MONTYHALL
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
modInv[a_, m_] := Block[{x,k}, x /. FindInstance[a x == 1 + k m, {x, k}, Integers]]
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.
#.D0.9C.D0.9A-61.2F52
МК-61/52
П1 П2 <-> П0 0 П5 1 П6 ИП1 1 - x=0 14 С/П ИП0 1 - /-/ x<0 50 ИП0 ИП1 / [x] П4 ИП1 П3 ИП0 ^ ИП1 / [x] ИП1 * - П1 ИП3 П0 ИП5 П3 ИП6 ИП4 ИП5 * - П5 ИП3 П6 БП 14 ИП6 x<0 55 ИП2 + С/П
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#D
D
void main() { import std.stdio, std.array, std.range, std.algorithm;   enum n = 12; writefln("  %(%4d%)\n%s", iota(1, n+1), "-".replicate(4*n + 4)); foreach (immutable y; 1 .. n + 1) writefln("%4d" ~ " ".replicate(4 * (y - 1)) ~ "%(%4d%)", y, iota(y, n + 1).map!(x => 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.
#Quackery
Quackery
[ 1 rot times [ i 1+ * dip [ over step ] ] nip ] is m! ( n --> n! )   5 times [ i^ 1+ 10 times [ i^ 1+ over m! echo sp ] drop cr ]
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.
#R
R
#x is Input #n is Factorial Number multifactorial=function(x,n){ if(x<=n+1){ return(x) }else{ return(x*multifactorial(x-n,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
#Nim
Nim
const BoardSize = 8   proc underAttack(col: int; queens: seq[int]): bool = if col in queens: return true for i, x in queens: if abs(col - x) == queens.len - i: return true return false   proc solve(n: int): seq[seq[int]] = result = newSeq[seq[int]]() result.add(@[]) var newSolutions = newSeq[seq[int]]() for row in 1..n: for solution in result: for i in 1..BoardSize: if not underAttack(i, solution): newSolutions.add(solution & i) swap result, newSolutions newSolutions.setLen(0)   echo "Solutions for a chessboard of size ", BoardSize, 'x', BoardSize echo ""   for i, answer in solve(BoardSize): for row, col in answer: if row > 0: stdout.write ' ' stdout.write chr(ord('a') + row), col stdout.write if i mod 4 == 3: "\n" else: " "
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.
#Sidef
Sidef
func nth(n) { static irregulars = Hash(<1 ˢᵗ 2 ⁿᵈ 3 ʳᵈ 11 ᵗʰ 12 ᵗʰ 13 ᵗʰ>...) n.to_s + (irregulars{n % 100} \\ irregulars{n % 10} \\ 'ᵗʰ') }   for r in [0..25, 250..265, 1000..1025] { say r.map {|n| nth(n) }.join(" ") }
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Wren
Wren
var powers = List.filled(10, 0) for (i in 1..9) powers[i] = i.pow(i).round // cache powers   var munchausen = Fn.new {|n| if (n <= 0) Fiber.abort("Argument must be a positive integer.") var nn = n var sum = 0 while (n > 0) { var digit = n % 10 sum = sum + powers[digit] n = (n/10).floor } return nn == sum }   System.print(powers) System.print("The Munchausen numbers <= 5000 are:") for (i in 1..5000) { if (munchausen.call(i)) System.print(i) }
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).
#Nemerle
Nemerle
using System; using System.Console;   module Hofstadter { F(n : int) : int { |0 => 1 |_ => n - M(F(n - 1)) }   M(n : int) : int { |0 => 0 |_ => n - F(M(n - 1)) }   Main() : void { foreach (n in [0 .. 20]) Write("{0} ", F(n)); WriteLine(); foreach (n in [0 .. 20]) Write("{0} ", M(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
#Liberty_BASIC
Liberty BASIC
  for pow = 2 to 6 n = 10^pow print n, getPi(n) next   end   function getPi(n) incircle = 0 for throws=0 to n scan incircle = incircle + (rnd(1)^2+rnd(1)^2 < 1) next getPi = 4*incircle/throws end function    
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
#Locomotive_Basic
Locomotive Basic
10 mode 1:randomize time:defint a-z 20 input "How many samples";n 30 u=n/100+1 40 r=100 50 for i=1 to n 60 if i mod u=0 then locate 1,3:print using "##% done"; i/n*100 70 x=rnd*2*r-r 80 y=rnd*2*r-r 90 if sqr(x*x+y*y)<r then m=m+1 100 next 110 pi2!=4*m/n 120 locate 1,3 130 print m;"points in circle" 140 print "Computed value of pi:"pi2! 150 print "Difference to real value of pi: "; 160 print using "+#.##%"; (pi2!-pi)/pi*100
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).
#Haskell
Haskell
  import System.IO import MorseCode import MorsePlaySox   -- Read standard input, converting text to Morse code, then playing the result. -- We turn off buffering on stdin so it will play as you type. main = do hSetBuffering stdin NoBuffering text <- getContents play $ toMorse text  
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.
#FreeBASIC
FreeBASIC
' version 19-01-2019 ' compile with: fbc -s console   Const As Integer max = 1000000 Randomize Timer   Dim As UInteger i, car_door, chosen_door, montys_door, stay, switch   For i = 1 To max car_door = Fix(Rnd * 3) + 1 chosen_door = Fix(Rnd * 3) + 1 If car_door <> chosen_door Then montys_door = 6 - car_door - chosen_door Else Do montys_door = Fix(Rnd * 3) + 1 Loop Until montys_door <> car_door End If 'Print car_door,chosen_door,montys_door ' stay If car_door = chosen_door Then stay += 1 ' switch If car_door = 6 - montys_door - chosen_door Then switch +=1 Next   Print Using "If you stick to your choice, you have a ##.## percent" _ + " chance to win"; stay / max * 100 Print Using "If you switched, you have a ##.## percent chance to win"; _ switch / max * 100   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep 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.
#Modula-2
Modula-2
MODULE ModularInverse; FROM InOut IMPORT WriteString, WriteInt, WriteLn;   TYPE Data = RECORD x : INTEGER; y : INTEGER END;   VAR c  : INTEGER; ab : ARRAY [1..5] OF Data;   PROCEDURE mi(VAR a, b : INTEGER): INTEGER; VAR t, nt, r, nr, q, tmp : INTEGER;   BEGIN b := ABS(b); IF a < 0 THEN a := b - (-a MOD b) END; t := 0; nt := 1; r := b; nr := a MOD b; WHILE (nr # 0) DO q := r / nr; tmp := nt; nt := t - q * nt; t := tmp; tmp := nr; nr := r - q * nr; r := tmp; END; IF (r > 1) THEN RETURN -1 END; IF (t < 0) THEN RETURN t + b END; RETURN t; END mi;   BEGIN ab[1].x := 42; ab[1].y := 2017; ab[2].x := 40; ab[2].y := 1; ab[3].x := 52; ab[3].y := -217; ab[4].x := -486; ab[4].y := 217; ab[5].x := 40; ab[5].y := 2018; WriteLn; WriteString("Modular inverse"); WriteLn; FOR c := 1 TO 5 DO WriteInt(ab[c].x, 6); WriteString(", "); WriteInt(ab[c].y, 6); WriteString(" = "); WriteInt(mi(ab[c].x, ab[c].y),6); WriteLn; END; END ModularInverse.
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.
#newLISP
newLISP
  (define (modular-multiplicative-inverse a n) (if (< n 0) (setf n (abs n)))   (if (< a 0) (setf a (- n (% (- 0 a) n))))   (setf t 0) (setf nt 1) (setf r n) (setf nr (mod a n))   (while (not (zero? nr)) (setf q (int (div r nr))) (setf tmp nt) (setf nt (sub t (mul q nt))) (setf t tmp) (setf tmp nr) (setf nr (sub r (mul q nr))) (setf r tmp))   (if (> r 1) (setf retvalue nil))   (if (< t 0) (setf retvalue (add t n)) (setf retvalue t)) retvalue)   (println (modular-multiplicative-inverse 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.
#DCL
DCL
$ max = 12 $ h = f$fao( "!4* " ) $ r = 0 $ loop1: $ o = "" $ c = 0 $ loop2: $ if r .eq. 0 then $ h = h + f$fao( "!4SL", c ) $ p = r * c $ if c .ge. r $ then $ o = o + f$fao( "!4SL", p ) $ else $ o = o + f$fao( "!4* " ) $ endif $ c = c + 1 $ if c .le. max then $ goto loop2 $ if r .eq. 0 $ then $ write sys$output h $ n = 4 * ( max + 2 ) $ write sys$output f$fao( "!''n*-" ) $ endif $ write sys$output f$fao( "!4SL", r ) + o $ r = r + 1 $ if r .le. max then $ goto loop1
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.
#Racket
Racket
#lang racket   (define (multi-factorial-fn m) (lambda (n) (let inner ((acc 1) (n n)) (if (<= n m) (* acc n) (inner (* acc n) (- n m))))))   ;; using (multi-factorial-fn m) as a first-class function (for*/list ([m (in-range 1 (add1 5))] [mf-m (in-value (multi-factorial-fn m))]) (for/list ([n (in-range 1 (add1 10))]) (mf-m n)))   (define (multi-factorial m n) ((multi-factorial-fn m) n))   (for/list ([m (in-range 1 (add1 5))]) (for/list ([n (in-range 1 (add1 10))]) (multi-factorial m n)))
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.
#Raku
Raku
for 1 .. 5 -> $degree { sub mfact($n) { [*] $n, *-$degree ...^ * <= 0 }; say "$degree: ", map &mfact, 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
#Objeck
Objeck
bundle Default { class NQueens { b : static : Int[]; s : static : Int;   function : Main(args : String[]) ~ Nil { b := Int->New[8]; s := 0;   y := 0; b[0] := -1;   while (y >= 0) { do { b[y]+=1; } while((b[y] < 8) & Unsafe(y));   if(b[y] < 8) { if (y < 7) { b[y + 1] := -1; y += 1; } else { PutBoard(); }; } else { y-=1; }; }; }   function : Unsafe(y : Int) ~ Bool { x := b[y]; for(i := 1; i <= y; i+=1;) { t := b[y - i]; if(t = x | t = x - i | t = x + i) { return true; }; };   return false; }   function : PutBoard() ~ Nil { IO.Console->Print("\n\nSolution ")->PrintLine(s + 1); s += 1; for(y := 0; y < 8; y+=1;) { for(x := 0; x < 8; x+=1;) { IO.Console->Print((b[y] = x) ? "|Q" : "|_"); }; "|"->PrintLine(); }; } } }  
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.
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 FOR N=0 TO 25 20 GOSUB 160 30 PRINT N$;" "; 40 NEXT N 50 PRINT 60 FOR N=250 TO 265 70 GOSUB 160 80 PRINT N$;" "; 90 NEXT N 100 PRINT 110 FOR N=1000 TO 1025 120 GOSUB 160 130 PRINT N$;" "; 140 NEXT N 150 STOP 160 LET N$=STR$ N 170 LET S$="TH" 180 IF LEN N$=1 THEN GOTO 200 190 IF N$(LEN N$-1)="1" THEN GOTO 230 200 IF N$(LEN N$)="1" THEN LET S$="ST" 210 IF N$(LEN N$)="2" THEN LET S$="ND" 220 IF N$(LEN N$)="3" THEN LET S$="RD" 230 LET N$=N$+S$ 240 RETURN
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#XPL0
XPL0
int Pow, A, B, C, D, N; [Pow:= [0, 1, 4, 27, 256, 3125]; for A:= 0 to 5 do for B:= 0 to 5 do for C:= 0 to 5 do for D:= 0 to 5 do [N:= A*1000 + B*100 + C*10 + D; if Pow(A) + Pow(B) + Pow(C) + Pow(D) = N then if N>=1 & N<= 5000 then [IntOut(0, N); CrLf(0)]; ]; ]
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#zkl
zkl
[1..5000].filter(fcn(n){ n==n.split().reduce(fcn(s,n){ s + n.pow(n) },0) }) .println();
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).
#Nim
Nim
proc m(n: int): int   proc f(n: int): int = if n == 0: 1 else: n - m(f(n-1))   proc m(n: int): int = if n == 0: 0 else: n - f(m(n-1))   for i in 1 .. 10: echo f(i) echo m(i)
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
#Logo
Logo
  to square :n output :n * :n end to trial :r output less? sum square random :r square random :r square :r end to sim :n :r make "hits 0 repeat :n [if trial :r [make "hits :hits + 1]] output 4 * :hits / :n end   show sim 1000 10000  ; 3.18 show sim 10000 10000  ; 3.1612 show sim 100000 10000  ; 3.145 show sim 1000000 10000  ; 3.140828  
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
#LSL
LSL
integer iMIN_SAMPLE_POWER = 0; integer iMAX_SAMPLE_POWER = 6; default { state_entry() { llOwnerSay("Estimating Pi ("+(string)PI+")"); integer iSample = 0; for(iSample=iMIN_SAMPLE_POWER ; iSample<=iMAX_SAMPLE_POWER  ; iSample++) { integer iInCircle = 0; integer x = 0; integer iMaxSamples = (integer)llPow(10, iSample); for(x=0 ; x<iMaxSamples ; x++) { if(llSqrt(llPow(llFrand(2.0)-1.0, 2.0)+llPow(llFrand(2.0)-1.0, 2.0))<1.0) { iInCircle++; } } float fPi = ((4.0*iInCircle)/llPow(10, iSample)); float fError = llFabs(100.0*(PI-fPi)/PI); llOwnerSay((string)iSample+": "+(string)iMaxSamples+" = "+(string)fPi+", Error = "+(string)fError+"%"); } llOwnerSay("Done."); } }
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).
#J
J
require'strings media/wav' morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper 79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122 121 202 229 238 241 715 637 0 203 0 400 475 5 67 70 22 1 43 25 40 4 53 23 49 8 7 26 52 77 16 13 2 14 41 17 68 71 76 214 0 644 0 401 )   onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.] playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur 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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/rand" "time" )   func main() { games := 100000 r := rand.New(rand.NewSource(time.Now().UnixNano()))   var switcherWins, keeperWins, shown int for i := 0; i < games; i++ { doors := []int{0, 0, 0} doors[r.Intn(3)] = 1 // Set which one has the car choice := r.Intn(3) // Choose a door for shown = r.Intn(3); shown == choice || doors[shown] == 1; shown = r.Intn(3) {} switcherWins += doors[3 - choice - shown] keeperWins += doors[choice] } floatGames := float32(games) fmt.Printf("Switcher Wins: %d (%3.2f%%)\n", switcherWins, (float32(switcherWins) / floatGames * 100)) fmt.Printf("Keeper Wins: %d (%3.2f%%)", keeperWins, (float32(keeperWins) / floatGames * 100)) }
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.
#Nim
Nim
proc modInv(a0, b0: int): int = var (a, b, x0) = (a0, b0, 0) result = 1 if b == 1: return while a > 1: result = result - (a div b) * x0 a = a mod b swap a, b swap x0, result if result < 0: result += b0   echo modInv(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.
#OCaml
OCaml
let mul_inv a = function 1 -> 1 | b -> let rec aux a b x0 x1 = if a <= 1 then x1 else if b = 0 then failwith "mul_inv" else aux b (a mod b) (x1 - (a / b) * x0) x0 in let x = aux a b 0 1 in if x < 0 then x + b else x
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.
#Delphi
Delphi
program MultiplicationTables;   {$APPTYPE CONSOLE}   uses SysUtils;   const MAX_COUNT = 12; var lRow, lCol: Integer; begin Write(' | '); for lRow := 1 to MAX_COUNT do Write(Format('%4d', [lRow])); Writeln(''); Writeln('--+-' + StringOfChar('-', MAX_COUNT * 4)); for lRow := 1 to MAX_COUNT do begin Write(Format('%2d', [lRow])); Write('| '); for lCol := 1 to MAX_COUNT do begin if lCol < lRow then Write(' ') else Write(Format('%4d', [lRow * lCol])); end; Writeln; end; end.
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.
#REXX
REXX
/*REXX program calculates and displays K-fact (multifactorial) of non-negative integers.*/ numeric digits 1000 /*get ka-razy with the decimal digits. */ parse arg num deg . /*get optional arguments from the C.L. */ if num=='' | num=="," then num=15 /*Not specified? Then use the default.*/ if deg=='' | deg=="," then deg=10 /* " " " " " " */ say '═══showing multiple factorials (1 ──►' deg") for numbers 1 ──►" num say do d=1 for deg /*the factorializing (degree) of  !'s.*/ _= /*the list of factorials (so far). */ do f=1 for num /* ◄── perform a ! from 1 ───► number.*/ _=_ Kfact(f, d) /*build a list of factorial products.*/ end /*f*/ /* [↑] D can default to unity. */   say right('n'copies("!", d), 1+deg) right('['d"]", 2+length(num) )':' _ end /*d*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Kfact: procedure; !=1; do j=arg(1) to 2 by -word(arg(2) 1,1);  !=!*j; end; return !
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
#OCaml
OCaml
(* Authors: Nicolas Barnier, Pascal Brisset Copyright 2004 CENA. All rights reserved. This code is distributed under the terms of the GNU LGPL *)   open Facile open Easy   (* Print a solution *) let print queens = let n = Array.length queens in if n <= 10 then (* Pretty printing *) for i = 0 to n - 1 do let c = Fd.int_value queens.(i) in (* queens.(i) is bound *) for j = 0 to n - 1 do Printf.printf "%c " (if j = c then '*' else '-') done; print_newline () done else (* Short print *) for i = 0 to n-1 do Printf.printf "line %d : col %a\n" i Fd.fprint queens.(i) done; flush stdout; ;;   (* Solve the n-queens problem *) let queens n = (* n decision variables in 0..n-1 *) let queens = Fd.array n 0 (n-1) in   (* 2n auxiliary variables for diagonals *) let shift op = Array.mapi (fun i qi -> Arith.e2fd (op (fd2e qi) (i2e i))) queens in let diag1 = shift (+~) and diag2 = shift (-~) in   (* Global constraints *) Cstr.post (Alldiff.cstr queens); Cstr.post (Alldiff.cstr diag1); Cstr.post (Alldiff.cstr diag2);   (* Heuristic Min Size, Min Value *) let h a = (Var.Attr.size a, Var.Attr.min a) in let min_min = Goals.Array.choose_index (fun a1 a2 -> h a1 < h a2) in   (* Search goal *) let labeling = Goals.Array.forall ~select:min_min Goals.indomain in   (* Solve *) let bt = ref 0 in if Goals.solve ~control:(fun b -> bt := b) (labeling queens) then begin Printf.printf "%d backtracks\n" !bt; print queens end else prerr_endline "No solution"   let _ = if Array.length Sys.argv <> 2 then raise (Failure "Usage: queens <nb of queens>"); Gc.set ({(Gc.get ()) with Gc.space_overhead = 500}); (* May help except with an underRAMed system *) queens (int_of_string Sys.argv.(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.
#SQL
SQL
  SELECT level card, to_char(to_date(level,'j'),'fmjth') ord FROM dual CONNECT BY level <= 15;   SELECT to_char(to_date(5373485,'j'),'fmjth') FROM dual;  
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).
#Objeck
Objeck
  class MutualRecursion { function : Main(args : String[]) ~ Nil { for(i := 0; i < 20; i+=1;) { f(i)->PrintLine(); }; "---"->PrintLine(); for (i := 0; i < 20; i+=1;) { m(i)->PrintLine(); }; }   function : f(n : Int) ~ Int { return n = 0 ? 1 : n - m(f(n - 1)); }   function : m(n : Int) ~ Int { return n = 0 ? 0 : n - f(m(n - 1)); } }  
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\displaystyle \pi } . If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π / 4 {\displaystyle \pi /4} . So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π / 4 {\displaystyle \pi /4} . Task Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number π {\displaystyle \pi } is not built-in, we give π {\displaystyle \pi } as a number of digits: 3.141592653589793238462643383280
#Lua
Lua
function MonteCarlo ( n_throws ) math.randomseed( os.time() )   n_inside = 0 for i = 1, n_throws do if math.random()^2 + math.random()^2 <= 1.0 then n_inside = n_inside + 1 end end   return 4 * n_inside / n_throws end   print( MonteCarlo( 10000 ) ) print( MonteCarlo( 100000 ) ) print( MonteCarlo( 1000000 ) ) print( MonteCarlo( 10000000 ) )
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MonteCarloPi[samplesize_Integer] := N[4Mean[If[# > 1, 0, 1] & /@ Norm /@ RandomReal[1, {samplesize, 2}]]]
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).
#Java
Java
import java.util.*;   public class MorseCode {   final static String[][] code = { {"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", "----. "}, {"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "}, {"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "}, {"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "}, {"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; // cheat a little   final static Map<Character, String> map = new HashMap<>();   static { for (String[] pair : code) map.put(pair[0].charAt(0), pair[1].trim()); }   public static void main(String[] args) { printMorse("sos"); printMorse(" Hello World!"); printMorse("Rosetta Code"); }   static void printMorse(String input) { System.out.printf("%s %n", input);   input = input.trim().replaceAll("[ ]+", " ").toUpperCase(); for (char c : input.toCharArray()) { String s = map.get(c); if (s != null) System.out.printf("%s ", s); } System.out.println("\n"); } }
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.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() { games := 100000 r := rand.New(rand.NewSource(time.Now().UnixNano()))   var switcherWins, keeperWins, shown int for i := 0; i < games; i++ { doors := []int{0, 0, 0} doors[r.Intn(3)] = 1 // Set which one has the car choice := r.Intn(3) // Choose a door for shown = r.Intn(3); shown == choice || doors[shown] == 1; shown = r.Intn(3) {} switcherWins += doors[3 - choice - shown] keeperWins += doors[choice] } floatGames := float32(games) fmt.Printf("Switcher Wins: %d (%3.2f%%)\n", switcherWins, (float32(switcherWins) / floatGames * 100)) fmt.Printf("Keeper Wins: %d (%3.2f%%)", keeperWins, (float32(keeperWins) / floatGames * 100)) }
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.
#Oforth
Oforth
// euclid ( a b -- u v r ) // Return r = gcd(a, b) and (u, v) / r = au + bv   : euclid(a, b) | q u u1 v v1 |   b 0 < ifTrue: [ b neg ->b ] a 0 < ifTrue: [ b a neg b mod - ->a ]   1 dup ->u ->v1 0 dup ->v ->u1   while(b) [ b a b /mod ->q ->b ->a u1 u u1 q * - ->u1 ->u v1 v v1 q * - ->v1 ->v ] u v a ;   : invmod(a, modulus) a modulus euclid 1 == ifFalse: [ drop drop null return ] drop dup 0 < ifTrue: [ modulus + ] ;
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.
#PARI.2FGP
PARI/GP
Mod(1/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.
#Draco
Draco
/* Print N-by-N multiplication table */ proc nonrec multab(byte n) void: byte i,j;   /* write header */ write(" |"); for i from 1 upto n do write(i:4) od; writeln(); write("----+"); for i from 1 upto n do write("----") od; writeln();   /* write lines */ for i from 1 upto n do write(i:4, "|"); for j from 1 upto n do if i <= j then write(i*j:4) else write(" ") fi od; writeln() od corp   /* Print 12-by-12 multiplication table */ proc nonrec main() void: multab(12) corp
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.
#Ring
Ring
  see "Degree " + "|" + " Multifactorials 1 to 10" + nl see copy("-", 52) + nl for d = 1 to 5 see "" + d + " " + "| " for n = 1 to 10 see "" + multiFact(n, d) + " " next see nl next   func multiFact n, degree fact = 1 for i = n to 2 step -degree fact = fact * i next return fact  
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.
#Ruby
Ruby
def multifact(n, d) n.step(1, -d).inject( :* ) end   (1..5).each {|d| puts "Degree #{d}: #{(1..10).map{|n| multifact(n, d)}.join "\t"}"}
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
#Oz
Oz
declare fun {Queens N} proc {$ Board} %% a board is a N-tuple of rows Board = {MakeTuple queens N} for Y in 1..N do %% a row is a N-tuple of values in [0,1] %% (0: no queen, 1: queen) Board.Y = {FD.tuple row N 0#1} end   {ForAll {Rows Board} SumIs1} {ForAll {Columns Board} SumIs1}   %% for every two points on a diagonal for [X1#Y1 X2#Y2] in {DiagonalPairs N} do %$ at most one of them has a queen Board.Y1.X1 + Board.Y2.X2 =<: 1 end   %% enumerate all such boards {FD.distribute naive {FlatBoard Board}} end end   fun {Rows Board} {Record.toList Board} end   fun {Columns Board} for X in {Arity Board.1} collect:C1 do {C1 for Y in {Arity Board} collect:C2 do {C2 Board.Y.X} end} end end   proc {SumIs1 Xs} {FD.sum Xs '=:' 1} end   fun {DiagonalPairs N} proc {Coords Root} [X1#Y1 X2#Y2] = Root Diff in X1::1#N Y1::1#N X2::1#N Y2::1#N %% (X1,Y1) and (X2,Y2) are on a diagonal if {Abs X2-X1} = {Abs Y2-Y1} Diff::1#N-1 {FD.distance X2 X1 '=:' Diff} {FD.distance Y2 Y1 '=:' Diff} %% enumerate all such coordinates {FD.distribute naive [X1 Y1 X2 Y2]} end in {SearchAll Coords} end   fun {FlatBoard Board} {Flatten {Record.toList {Record.map Board Record.toList}}} end   Solutions = {SearchAll {Queens 8}} in {Length Solutions} = 92 %% assert {Inspect {List.take Solutions 3}}
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.
#Standard_ML
Standard ML
local val v = Vector.tabulate (10, fn 1 => "st" | 2 => "nd" | 3 => "rd" | _ => "th") fun getSuffix x = if 3 < x andalso x < 21 then "th" else Vector.sub (v, x mod 10) in fun nth n = Int.toString n ^ getSuffix (n mod 100) end   (* some test ouput *) val () = (print o concat o List.tabulate) (26, fn i => String.concatWith "\t" (map nth [i, i + 250, i + 1000]) ^ "\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).
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface Hofstadter : NSObject + (int)M: (int)n; + (int)F: (int)n; @end   @implementation Hofstadter + (int)M: (int)n { if ( n == 0 ) return 0; return n - [self F: [self M: (n-1)]]; } + (int)F: (int)n { if ( n == 0 ) return 1; return n - [self M: [self F: (n-1)]]; } @end   int main() { int i;   for(i=0; i < 20; i++) { printf("%3d ", [Hofstadter F: i]); } printf("\n"); for(i=0; i < 20; i++) { printf("%3d ", [Hofstadter M: i]); } printf("\n"); return 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
#MATLAB
MATLAB
function piEstimate = monteCarloPi(numDarts)   %The square has a sides of length 2, which means the circle has radius %1.   %Generate a table of random x-y value pairs in the range [0,1] sampled %from the uniform distribution for each axis. darts = rand(numDarts,2);   %Any darts that are in the circle will have position vector whose %length is less than or equal to 1 squared. dartsInside = ( sum(darts.^2,2) <= 1 );   piEstimate = 4*sum(dartsInside)/numDarts;   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
#Maxima
Maxima
load("distrib"); approx_pi(n):= block( [x: random_continuous_uniform(0, 1, n), y: random_continuous_uniform(0, 1, n), r, cin: 0, listarith: true], r: x^2 + y^2, for r0 in r do if r0<1 then cin: cin + 1, 4*cin/n);   float(approx_pi(100));
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).
#JavaScript
JavaScript
  var globalAudioContext = new webkitAudioContext();   function morsecode(text, unit, freq) { 'use strict';   // defaults unit = unit ? unit : 0.05; freq = freq ? freq : 700; var cont = globalAudioContext; var time = cont.currentTime;   // morsecode var code = { 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: '____.' };   // generate code for text function makecode(data) { for (var i = 0; i <= data.length; i ++) { var codedata = data.substr(i, 1).toLowerCase(); codedata = code[codedata]; // recognised character if (codedata !== undefined) { maketime(codedata); } // unrecognised character else { time += unit * 7; } } }   // generate time for code function maketime(data) { for (var i = 0; i <= data.length; i ++) { var timedata = data.substr(i, 1); timedata = (timedata === '.') ? 1 : (timedata === '_') ? 3 : 0; timedata *= unit; if (timedata > 0) { maketone(timedata); time += timedata; // tone gap time += unit * 1; } } // char gap time += unit * 2; }   // generate tone for time function maketone(data) { var start = time; var stop = time + data; // filter: envelope the tone slightly gain.gain.linearRampToValueAtTime(0, start); gain.gain.linearRampToValueAtTime(1, start + (unit / 8)); gain.gain.linearRampToValueAtTime(1, stop - (unit / 16)); gain.gain.linearRampToValueAtTime(0, stop); }   // create: oscillator, gain, destination var osci = cont.createOscillator(); osci.frequency.value = freq; var gain = cont.createGainNode(); gain.gain.value = 0; var dest = cont.destination; // connect: oscillator -> gain -> destination osci.connect(gain); gain.connect(dest); // start oscillator osci.start(time);   // begin encoding: text -> code -> time -> tone makecode(text);   // return web audio context for reuse / control return cont; }  
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.
#Haskell
Haskell
import System.Random (StdGen, getStdGen, randomR)   trials :: Int trials = 10000   data Door = Car | Goat deriving Eq   play :: Bool -> StdGen -> (Door, StdGen) play switch g = (prize, new_g) where (n, new_g) = randomR (0, 2) g d1 = [Car, Goat, Goat] !! n prize = case switch of False -> d1 True -> case d1 of Car -> Goat Goat -> Car   cars :: Int -> Bool -> StdGen -> (Int, StdGen) cars n switch g = f n (0, g) where f 0 (cs, g) = (cs, g) f n (cs, g) = f (n - 1) (cs + result, new_g) where result = case prize of Car -> 1; Goat -> 0 (prize, new_g) = play switch g   main = do g <- getStdGen let (switch, g2) = cars trials True g (stay, _) = cars trials False g2 putStrLn $ msg "switch" switch putStrLn $ msg "stay" stay where msg strat n = "The " ++ strat ++ " strategy succeeds " ++ percent n ++ "% of the time." percent n = show $ round $ 100 * (fromIntegral n) / (fromIntegral trials)
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.
#Pascal
Pascal
  // increments e step times until bal is greater than t // repeats until bal = 1 (mod = 1) and returns count // bal will not be greater than t + e   function modInv(e, t : integer) : integer; var d : integer; bal, count, step : integer; begin d := 0; if e < t then begin count := 1; bal := e; repeat step := ((t-bal) DIV e)+1; bal := bal + step * e; count := count + step; bal := bal - t; until bal = 1; d := count; end; modInv := d; 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.
#Perl
Perl
use bigint; say 42->bmodinv(2017); # or use Math::ModInt qw/mod/; say mod(42, 2017)->inverse->residue; # or use Math::Pari qw/PARI lift/; say lift PARI "Mod(1/42,2017)"; # or use Math::GMP qw/:constant/; say 42->bmodinv(2017); # or use ntheory qw/invmod/; say 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.
#DWScript
DWScript
const size = 12; var row, col : Integer;   Print(' | '); for row:=1 to size do Print(Format('%4d', [row])); PrintLn(''); PrintLn('--+-'+StringOfChar('-', size*4)); for row:=1 to size do begin Print(Format('%2d', [row])); Print('| '); for col:=1 to size do begin if col<row then Print(' ') else Print(Format('%4d', [row*col])); end; PrintLn(''); end;  
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.
#Run_BASIC
Run BASIC
  print "Degree " + "|" + " Multifactorials 1 to 10" + nl print copy("-", 52) + nl for d = 1 to 5 print "" + d + " " + "| " for n = 1 to 10 print "" + multiFact(n, d) + " "; next print next   function multiFact(n,degree) fact = 1 for i = n to 2 step -degree fact = fact * i next multiFact = fact end function
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.
#Rust
Rust
fn multifactorial(n: i32, deg: i32) -> i32 { if n < 1 { 1 } else { n * multifactorial(n - deg, deg) } }   fn main() { for i in 1..6 { for j in 1..11 { print!("{} ", multifactorial(j, i)); } println!(""); } }
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Pascal
Pascal
program queens;   const l=16;   var i,j,k,m,n,p,q,r,y,z: integer; a,s: array[1..l] of integer; u: array[1..4*l-2] of integer;   label L3,L4,L5,L6,L7,L8,L9,L10;   begin for i:=1 to l do a[i]:=i; for i:=1 to 4*l-2 do u[i]:=0; for n:=1 to l do begin m:=0; i:=1; r:=2*n-1; goto L4; L3: s[i]:=j; u[p]:=1; u[q+r]:=1; i:=i+1; L4: if i>n then goto L8; j:=i; L5: z:=a[i]; y:=a[j]; p:=i-y+n; q:=i+y-1; a[i]:=y; a[j]:=z; if (u[p]=0) and (u[q+r]=0) then goto L3; L6: j:=j+1; if j<=n then goto L5; L7: j:=j-1; if j=i then goto L9; z:=a[i]; a[i]:=a[j]; a[j]:=z; goto L7; L8: m:=m+1; { uncomment the following to print solutions } { write(n,' ',m,':'); for k:=1 to n do write(' ',a[k]); writeln; } L9: i:=i-1; if i=0 then goto L10; p:=i-a[i]+n; q:=i+a[i]-1; j:=s[i]; u[p]:=0; u[q+r]:=0; goto L6; L10: writeln(n,' ',m); end; end.   { 1 1 2 0 3 0 4 2 5 10 6 4 7 40 8 92 9 352 10 724 11 2680 12 14200 13 73712 14 365596 15 2279184 16 14772512 }
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.
#Stata
Stata
mata function maps(f,a) { nr = rows(a) nc = cols(a) b = J(nr,nc,"") for (i=1;i<=nr;i++) { for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) } return(b) }   function nth(n) { k = max((min((mod(n-1,10)+1,4)),4*(mod(n-10,100)<10))) return(strofreal(n)+("st","nd","rd","th")[k]) }   maps(&nth(),((0::25),(250::275),(1000::1025))) end
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.
#Swift
Swift
func addSuffix(n:Int) -> String { if n % 100 / 10 == 1 { return "th" }   switch n % 10 { case 1: return "st" case 2: return "nd" case 3: return "rd" default: return "th" } }   for i in 0...25 { print("\(i)\(addSuffix(i)) ") } println() for i in 250...265 { print("\(i)\(addSuffix(i)) ") } println() for i in 1000...1025 { print("\(i)\(addSuffix(i)) ") } println()
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).
#OCaml
OCaml
let rec f = function | 0 -> 1 | n -> n - m(f(n-1)) and m = function | 0 -> 0 | n -> n - f(m(n-1)) ;;
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\displaystyle \pi } . If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π / 4 {\displaystyle \pi /4} . So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π / 4 {\displaystyle \pi /4} . Task Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number π {\displaystyle \pi } is not built-in, we give π {\displaystyle \pi } as a number of digits: 3.141592653589793238462643383280
#MAXScript
MAXScript
fn monteCarlo iterations = ( radius = 1.0 pointsInCircle = 0 for i in 1 to iterations do ( testPoint = [(random -radius radius), (random -radius radius)] if length testPoint <= radius then ( pointsInCircle += 1 ) ) 4.0 * pointsInCircle / iterations )
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 П1 0 П4 СЧ x^2 ^ СЧ x^2 + 1 - x<0 15 КИП4 L0 04 ИП4 4 * ИП1 / С/П
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow   (e.g. with a different pitch).
#Julia
Julia
using PortAudio   const pstream = PortAudioStream(0, 2) sendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t/1000)s)   char2morse = Dict[ "!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "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" => "--..", "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-"]   function sendmorsesound(freq, duration) cpause() = sleep(0.080) wpause = sleep(0.400)   dit() = sendmorsesound(0.070, 700) dash() = sensmorsesound(0.210, 700) sendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end sendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end sendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end   sendmorse("sos sos sos") sendmorse("The case of letters in Morse coding is ignored."  
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.
#HicEst
HicEst
REAL :: ndoors=3, doors(ndoors), plays=1E4   DLG(NameEdit = plays, DNum=1, Button='Go')   switchWins = 0 stayWins = 0   DO play = 1, plays doors = 0 ! clear the doors winner = 1 + INT(RAN(ndoors)) ! door that has the prize doors(winner) = 1 guess = 1 + INT(RAN(doors)) ! player chooses his door   IF( guess == winner ) THEN ! Monty decides which door to open: show = 1 + INT(RAN(2)) ! select 1st or 2nd goat-door checked = 0 DO check = 1, ndoors checked = checked + (doors(check) == 0) IF(checked == show) open = check ENDDO ELSE open = (1+2+3) - winner - guess ENDIF new_guess_if_switch = (1+2+3) - guess - open   stayWins = stayWins + doors(guess) ! count if guess was correct switchWins = switchWins + doors(new_guess_if_switch) ENDDO   WRITE(ClipBoard, Name) plays, switchWins, stayWins   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.
#Phix
Phix
function mul_inv(integer a, n) if n<0 then n = -n end if if a<0 then a = n - mod(-a,n) end if integer t = 0, nt = 1, r = n, nr = a; while nr!=0 do integer q = floor(r/nr) {t, nt} = {nt, t-q*nt} {r, nr} = {nr, r-q*nr} end while if r>1 then return "a is not invertible" end if if t<0 then t += n end if return t end function ?mul_inv(42,2017) ?mul_inv(40, 1) ?mul_inv(52, -217) /* Pari semantics for negative modulus */ ?mul_inv(-486, 217) ?mul_inv(40, 2018)
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.
#E
E
def size := 12 println(`{|style="border-collapse: collapse; text-align: right;"`) println(`|`) for x in 1..size { println(`|style="border-bottom: 1px solid black; " | $x`) } for y in 1..size { println(`|-`) println(`|style="border-right: 1px solid black;" | $y`) for x in 1..size { println(`| &nbsp;${if (x >= y) { x*y } else {""}}`) } } println("|}")
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.
#Scala
Scala
  def multiFact(n : BigInt, degree : BigInt) = (n to 1 by -degree).product   for{ degree <- 1 to 5 str = (1 to 10).map(n => multiFact(n, degree)).mkString(" ") } println(s"Degree $degree: $str")  
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
#PDP-11_Assembly
PDP-11 Assembly
  ; "eight queens problem" benchmark test   .radix 16   .loc 0   nop  ; mov #scr,@#E800 mov #88C6,@#E802 ; clear the display RAM mov #scr,r0 mov #1E0,r1 cls: clr (r0)+ sob r1,cls ; display the initial counter value clr r3 mov #scr,r0 jsr pc,number ; perform the test jsr pc,queens ; display the counter mov #scr,r0 jsr pc,number finish: br finish   ; display the character R1 at the screen address R0, ; advance the pointer R0 to the next column putc: mov r2,-(sp) ; R1 <- 6 * R1 asl r1  ;* 2 mov r1,-(sp) asl r1  ;* 4 add (sp)+,r1  ;* 6 add #chars,r1 mov #6,r2 putc1: movb (r1)+,(r0) add #1E,r0 sob r2,putc1 sub #B2,r0  ;6 * 1E - 2 = B2 mov (sp)+,r2 rts pc   print1: jsr pc,putc ; print a string pointed to by R2 at the screen address R0, ; advance the pointer R0 to the next column, ; the string should be terminated by a negative byte print: movb (r2)+,r1 bpl print1 rts pc   ; display the word R3 decimal at the screen address R0 number: mov sp,r1 mov #A0A,-(sp) mov (sp),-(sp) mov (sp),-(sp) movb #80,-(r1) numb1: clr r2 div #A,r2 movb r3,-(r1) mov r2,r3 bne numb1 mov sp,r2 jsr pc,print add #6,sp rts pc   queens: mov #64,r5  ;100 l06: clr r3 clr r0 l00: cmp #8,r0 beq l05 inc r0 movb #8,ary(r0) l01: inc r3 mov r0,r1 l02: dec r1 beq l00 movb ary(r0),r2 movb ary(r1),r4 sub r2,r4 beq l04 bcc l03 neg r4 l03: add r1,r4 sub r0,r4 bne l02 l04: decb ary(r0) bne l01 sob r0,l04 l05: sob r5,l06 mov r3,cnt rts pc   ; characters, width = 8 pixels, height = 6 pixels chars: .byte 3C, 46, 4A, 52, 62, 3C  ;digit '0' .byte 18, 28, 8, 8, 8, 3E  ;digit '1' .byte 3C, 42, 2, 3C, 40, 7E  ;digit '2' .byte 3C, 42, C, 2, 42, 3C  ;digit '3' .byte 8, 18, 28, 48, 7E, 8  ;digit '4' .byte 7E, 40, 7C, 2, 42, 3C  ;digit '5' .byte 3C, 40, 7C, 42, 42, 3C  ;digit '6' .byte 7E, 2, 4, 8, 10, 10  ;digit '7' .byte 3C, 42, 3C, 42, 42, 3C  ;digit '8' .byte 3C, 42, 42, 3E, 2, 3C  ;digit '9' .byte 0, 0, 0, 0, 0, 0  ;space   .even   cnt: .blkw 1 ary: .blkb 9   .loc 200   scr:  ;display RAM  
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.
#Tcl
Tcl
proc ordinal {n} { if {$n%100<10 || $n%100>20} { set suff [lindex {th st nd rd th th th th th th} [expr {$n % 10}]] } else { set suff th } return "$n'$suff" }   foreach start {0 250 1000} { for {set n $start; set l {}} {$n<=$start+25} {incr n} { lappend l [ordinal $n] } puts $l }
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).
#Octave
Octave
function r = F(n) for i = 1:length(n) if (n(i) == 0) r(i) = 1; else r(i) = n(i) - M(F(n(i)-1)); endif endfor endfunction   function r = M(n) for i = 1:length(n) if (n(i) == 0) r(i) = 0; else r(i) = n(i) - F(M(n(i)-1)); endif endfor endfunction
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
#Nim
Nim
import math, random   randomize()   proc pi(nthrows: float): float = var inside = 0.0 for i in 1..int64(nthrows): if hypot(rand(1.0), rand(1.0)) < 1: inside += 1 result = 4 * inside / nthrows   for n in [10e4, 10e6, 10e7, 10e8]: echo pi(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
#OCaml
OCaml
let get_pi throws = let rec helper i count = if i = throws then count else let rand_x = Random.float 2.0 -. 1.0 and rand_y = Random.float 2.0 -. 1.0 in let dist = sqrt (rand_x *. rand_x +. rand_y *. rand_y) in if dist < 1.0 then helper (i+1) (count+1) else helper (i+1) count in float (4 * helper 0 0) /. float throws
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).
#Kotlin
Kotlin
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem   val morseCode = hashMapOf( 'a' to ".-", 'b' to "-...", 'c' to "-.-.", 'd' to "-..", 'e' to ".", 'f' to "..-.", 'g' to "--.", 'h' to "....", 'i' to "..", 'j' to ".---", 'k' to "-.-", 'l' to ".-..", 'm' to "--", 'n' to "-.", 'o' to "---", 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", 's' to "...", 't' to "-", 'u' to "..-", 'v' to "...-", 'w' to ".--", 'x' to "-..-", 'y' to "-.--", 'z' to "--..",   '0' to ".....", '1' to "-....", '2' to "--...", '3' to "---..", '4' to "----.", '5' to "-----", '6' to ".----", '7' to "..---", '8' to "...--", '9' to "....-",   ' ' to "/", ',' to "--..--", '!' to "-.-.--", '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", '\'' to ".----.", '/' to "-..-.", '-' to "-....-", '(' to "-.--.-", ')' to "-.--.-" )   val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000)     fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } .fold("") { acc, ch -> acc + morseCode[ch]!! }   fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) }   fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() }   val audioFormat = AudioFormat( /*sampleRate*/ 8000F, /*sampleSizeInBits*/ 8, /*channels*/ 1, /*signed*/ true, /*bigEndian*/ false ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat)   start() write(soundBuffer, 0, soundBuffer.size) drain()   close() } }   fun main(args: Array<String>) { args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } }
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.
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist)   rounds := integer(arglist[1]) | 10000 doors := '123' strategy1 := strategy2 := 0   every 1 to rounds do { goats := doors -- ( car := ?doors ) guess1 := ?doors show := goats -- guess1 if guess1 == car then strategy1 +:= 1 else strategy2 +:= 1 }   write("Monty Hall simulation for ", rounds, " rounds.") write("Strategy 1 'Staying' won ", real(strategy1) / rounds ) write("Strategy 2 'Switching' won ", real(strategy2) / rounds )   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.
#PHP
PHP
<?php function invmod($a,$n){ if ($n < 0) $n = -$n; if ($a < 0) $a = $n - (-$a % $n); $t = 0; $nt = 1; $r = $n; $nr = $a % $n; while ($nr != 0) { $quot= intval($r/$nr); $tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp; $tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp; } if ($r > 1) return -1; if ($t < 0) $t += $n; return $t; } printf("%d\n", 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.
#EasyLang
EasyLang
n = 12 func out h . . if h < 10 write " " elif h < 100 write " " . write " " write h . write " " for i = 1 to n call out i . print "" write " " for i = 1 to n write "----" . print "" for i = 1 to n call out i write "|" for j = 1 to n if j < i write " " else call out i * j . . print "" .
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.
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 1))   (define (multi-factorial n m) (fold * 1 (iota (ceiling (/ n m)) n (- m))))   (for-each (lambda (degree) (display (string-append "degree " (number->string degree) ": ")) (for-each (lambda (num) (display (string-append (number->string (multi-factorial num degree)) " "))) (iota 10 1)) (newline)) (iota 5 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
#Perl
Perl
my ($board_size, @occupied, @past, @solutions);   sub try_column { my ($depth, @diag) = shift; if ($depth == $board_size) { push @solutions, "@past\n"; return; }   # @diag: marks cells diagonally attackable by any previous queens. # Here it's pre-allocated to double size just so we don't need # to worry about negative indices. $#diag = 2 * $board_size; for (0 .. $#past) { $diag[ $past[$_] + $depth - $_ ] = 1; $diag[ $past[$_] - $depth + $_ ] = 1; }   for my $row (0 .. $board_size - 1) { next if $occupied[$row] || $diag[$row];   # @past: row numbers of previous queens # @occupied: rows already used. This gets inherited by each # recursion so we don't need to repeatedly look them up push @past, $row; $occupied[$row] = 1;   try_column($depth + 1);   # clean up, for next recursion $occupied[$row] = 0; pop @past; } }   $board_size = 12; try_column(0);   #print for @solutions; # un-comment to see all solutions print "total " . @solutions . " solutions\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.
#True_BASIC
True BASIC
  SUB sufijo (n) LET n = INT(n) LET NMod10 = MOD(n, 10) LET NMod100 = MOD(n, 100) IF (NMod10 = 1) AND (NMod100 <> 11) THEN LET sufi$ = "st" ELSE IF (NMod10 = 2) AND (NMod100 <> 12) THEN LET sufi$ = "nd" ELSE IF (NMod10 = 3) AND (NMod100 <> 13) THEN LET sufi$ = "rd" ELSE LET sufi$ = "th" END IF END IF END IF PRINT sufi$; END SUB   SUB imprimeOrdinal (loLim, hiLim) LET loLim = INT(loLim) LET hiLim = INT(hiLim) FOR i = loLim TO hiLim PRINT i; CALL sufijo (i) PRINT " "; NEXT i PRINT END SUB   CALL imprimeOrdinal (0, 25) CALL imprimeOrdinal (250, 265) CALL 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).
#Oforth
Oforth
Method new: M   Integer method: F self 0 == ifTrue: [ 1 return ] self self 1 - F M - ;   Integer method: M self 0 == ifTrue: [ 0 return ] self self 1 - M F - ;   0 20 seqFrom map(#F) println 0 20 seqFrom map(#M) println