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/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.
| #min | min | (:d (dup 0 <=) (pop 1) (dup d -) (*) linrec) :multifactorial
(:d 1 (dup d multifactorial print! " " print! succ) 10 times newline pop) :row
1 (dup "Degree " print! print ": " print! row succ) 5 times |
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
| #M2000_Interpreter | M2000 Interpreter |
Module N_queens {
Const l = 15 'number of queens
Const b = False 'print option
Dim a(0 to l), s(0 to l), u(0 to 4 * l - 2)
Def long n, m, i, j, p, q, r, k, t
For i = 1 To l: a(i) = i: Next i
For n = 1 To l
m = 0
i = 1
j = 0
r = 2 * n - 1
Do {
i--
j++
p = 0
q = -r
Do {
i++
u(p) = 1
u(q + r) = 1
Swap a(i), a(j)
p = i - a(i) + n
q = i + a(i) - 1
s(i) = j
j = i + 1
} Until j > n Or u(p) Or u(q + r)
If u(p) = 0 Then {
If u(q + r) = 0 Then {
m++ 'm: number of solutions
If b Then {
Print "n="; n; "m="; m
For k = 1 To n {
For t = 1 To n {
Print If$(a(n - k + 1) = t-> "Q", ".");
}
Print
}
}
}
}
j = s(i)
While j >= n And i <> 0 {
Do {
Swap a(i), a(j)
j--
} Until j < i
i--
p = i - a(i) + n
q = i + a(i) - 1
j = s(i)
u(p) = 0
u(q + r) = 0
}
} Until i = 0
Print n, m 'number of queens, number of solutions
Next n
}
N_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.
| #Raku | Raku | my %irregulars = <1 st 2 nd 3 rd>, (11..13 X=> 'th');
sub nth ($n) { $n ~ ( %irregulars{$n % 100} // %irregulars{$n % 10} // 'th' ) }
say .list».&nth for [^26], [250..265], [1000..1025]; |
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
| #Sidef | Sidef | func is_munchausen(n) {
n.digits.map{|d| d**d }.sum == n
}
say (1..5000 -> grep(is_munchausen)) |
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).
| #Maple | Maple | female_seq := proc(n)
if (n = 0) then
return 1;
else
return n - male_seq(female_seq(n-1));
end if;
end proc;
male_seq := proc(n)
if (n = 0) then
return 0;
else
return n - female_seq(male_seq(n-1));
end if;
end proc;
seq(female_seq(i), i=0..10);
seq(male_seq(i), i=0..10); |
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
| #Forth | Forth | include random.fs
10000 value r
: hit? ( -- ? )
r random dup *
r random dup * +
r dup * < ;
: sims ( n -- hits )
0 swap 0 do hit? if 1+ then loop ;
|
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
| #Fortran | Fortran | MODULE Simulation
IMPLICIT NONE
CONTAINS
FUNCTION Pi(samples)
REAL :: Pi
REAL :: coords(2), length
INTEGER :: i, in_circle, samples
in_circle = 0
DO i=1, samples
CALL RANDOM_NUMBER(coords)
coords = coords * 2 - 1
length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
IF (length <= 1) in_circle = in_circle + 1
END DO
Pi = 4.0 * REAL(in_circle) / REAL(samples)
END FUNCTION Pi
END MODULE Simulation
PROGRAM MONTE_CARLO
USE Simulation
INTEGER :: n = 10000
DO WHILE (n <= 100000000)
WRITE (*,*) n, Pi(n)
n = n * 10
END DO
END PROGRAM MONTE_CARLO |
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.)
| #REXX | REXX | /* REXX ***************************************************************
* 25.05.2014 Walter Pachl
* REXX strings start with position 1
**********************************************************************/
Call enc_dec 'broood'
Call enc_dec 'bananaaa'
Call enc_dec 'hiphophiphop'
Exit
enc_dec: Procedure
Parse Arg in
st='abcdefghijklmnopqrstuvwxyz'
sta=st /* remember this for decoding */
enc=''
Do i=1 To length(in)
c=substr(in,i,1)
p=pos(c,st)
enc=enc (p-1)
st=c||left(st,p-1)substr(st,p+1)
End
Say ' in='in
Say 'sta='sta 'original symbol table'
Say 'enc='enc
Say ' st='st 'symbol table after encoding'
out=''
Do i=1 To words(enc)
k=word(enc,i)+1
out=out||substr(sta,k,1)
sta=substr(sta,k,1)left(sta,k-1)substr(sta,k+1)
End
Say 'out='out
Say ' '
If out==in Then Nop
Else
Say 'all wrong!!'
Return
|
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #EasyLang | EasyLang | txt$ = "sos sos"
#
chars$[] = strchars "abcdefghijklmnopqrstuvwxyz "
code$[] = [ ".-" "-..." "-.-." "-.." "." "..-." "--." "...." ".." ".---" "-.-" ".-.." "--" "-." "---" ".--." "--.-" ".-." "..." "-" "..-" "...-" ".--" "-..-" "-.--" "--.." " " ]
#
func morse ch$ . .
while ind < len chars$[] and chars$[ind] <> ch$
ind += 1
.
if ind < len chars$[]
write ch$ & " "
sleep 0.4
for c$ in strchars code$[ind]
write c$
if c$ = "."
sound [ 440 0.2 ]
sleep 0.4
elif c$ = "-"
sound [ 440 0.6 ]
sleep 0.8
elif c$ = " "
sleep 0.8
.
.
.
print ""
.
for ch$ in strchars txt$
call morse ch$
. |
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.
| #Common_Lisp | Common Lisp | (defun make-round ()
(let ((array (make-array 3
:element-type 'bit
:initial-element 0)))
(setf (bit array (random 3)) 1)
array))
(defun show-goat (initial-choice array)
(loop for i = (random 3)
when (and (/= initial-choice i)
(zerop (bit array i)))
return i))
(defun won? (array i)
(= 1 (bit array i))) |
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.
| #Frink | Frink | println[modInverse[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.
| #FunL | FunL | import integers.egcd
def modinv( a, m ) =
val (g, x, _) = egcd( a, m )
if g != 1 then error( a + ' and ' + m + ' not coprime' )
val res = x % m
if res < 0 then res + m else res
println( modinv(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.
| #C | C | #include <stdio.h>
int main(void)
{
int i, j, n = 12;
for (j = 1; j <= n; j++) printf("%3d%c", j, j != n ? ' ' : '\n');
for (j = 0; j <= n; j++) printf(j != n ? "----" : "+\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf(j < i ? " " : "%3d ", i * j);
printf("| %d\n", i);
}
return 0;
} |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П1 <-> П0 П2 ИП0 ИП1 1 + - x>=0
23 ИП2 ИП0 ИП1 - * П2 ИП0 ИП1 -
П1 БП 04 ИП2 С/П |
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.
| #Nim | Nim | # Recursive
proc multifact(n, deg: int): int =
result = (if n <= deg: n else: n * multifact(n - deg, deg))
# Iterative
proc multifactI(n, deg: int): int =
result = n
var n = n
while n >= deg + 1:
result *= n - deg
n -= deg
for i in 1..5:
stdout.write "Degree ", i, ": "
for j in 1..10:
stdout.write multifactI(j, i), " "
stdout.write('\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
| #m4 | m4 | divert(-1)
The following macro find one solution to the eight-queens problem:
define(`solve_eight_queens',`_$0(1)')
define(`_solve_eight_queens',
`ifelse(none_of_the_queens_attacks_the_new_one($1),1,
`ifelse(len($1),8,`display_solution($1)',`$0($1`'1)')',
`ifelse(last_is_eight($1),1,`$0(incr_last(strip_eights($1)))',
`$0(incr_last($1))')')')
It works by backtracking.
Partial solutions are represented by strings. For example, queens at
a7,b3,c6 would be represented by the string "736". The first position
is the "a" file, the second is the "b" file, etc. The digit in a given
position represents the queen's rank.
When a new queen is appended to the string, it must satisfy the
following constraint:
define(`none_of_the_queens_attacks_the_new_one',
`_$0($1,decr(len($1)))')
define(`_none_of_the_queens_attacks_the_new_one',
`ifelse($2,0,1,
`ifelse(two_queens_attack($1,$2,len($1)),1,0,
`$0($1,decr($2))')')')
The `two_queens_attack' macro, used above, reduces to `1' if the
ith and jth queens attack each other; otherwise it reduces to `0':
define(`two_queens_attack',
`pushdef(`file1',eval($2))`'dnl
pushdef(`file2',eval($3))`'dnl
pushdef(`rank1',`substr($1,decr(file1),1)')`'dnl
pushdef(`rank2',`substr($1,decr(file2),1)')`'dnl
eval((rank1) == (rank2) ||
((rank1) + (file1)) == ((rank2) + (file2)) ||
((rank1) - (file1)) == ((rank2) - (file2)))`'dnl
popdef(`file1',`file2',`rank1',`rank2')')
Here is the macro that converts the solution string to a nice display:
define(`display_solution',
`pushdef(`rule',`+----+----+----+----+----+----+----+----+')`'dnl
rule
_$0($1,8)
rule
_$0($1,7)
rule
_$0($1,6)
rule
_$0($1,5)
rule
_$0($1,4)
rule
_$0($1,3)
rule
_$0($1,2)
rule
_$0($1,1)
rule`'dnl
popdef(`rule')')
define(`_display_solution',
`ifelse(index($1,$2),0,`| Q ',`| ')`'dnl
ifelse(index($1,$2),1,`| Q ',`| ')`'dnl
ifelse(index($1,$2),2,`| Q ',`| ')`'dnl
ifelse(index($1,$2),3,`| Q ',`| ')`'dnl
ifelse(index($1,$2),4,`| Q ',`| ')`'dnl
ifelse(index($1,$2),5,`| Q ',`| ')`'dnl
ifelse(index($1,$2),6,`| Q ',`| ')`'dnl
ifelse(index($1,$2),7,`| Q ',`| ')|')
Here are some simple macros used above:
define(`last',`substr($1,decr(len($1)))') Get the last char.
define(`drop_last',`substr($1,0,decr(len($1)))') Remove the last char.
define(`last_is_eight',`eval((last($1)) == 8)') Is the last char "8"?
define(`strip_eights',
`ifelse(last_is_eight($1),1,`$0(drop_last($1))',
`$1')') Backtrack by removing all final "8" chars.
define(`incr_last',
`drop_last($1)`'incr(last($1))') Increment the final char.
The macros here have been presented top-down. I believe the program
might be easier to understand were the macros presented bottom-up;
then there would be no "black boxes" (unexplained macros) as one reads
from top to bottom.
I leave such rewriting as an exercise for the reader. :)
divert`'dnl
dnl
solve_eight_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.
| #Red | Red | Red[]
nth: function [n][
d: n % 10
suffix: either any [d < 1 d > 4 1 = to-integer n / 10] [4] [d]
rejoin [n pick ["st" "nd" "rd" "th"] suffix]
]
test: function [low high][
repeat i high - low + 1 [
prin [nth i + low - 1 ""]
]
prin newline
]
test 0 25
test 250 265
test 1000 1025 |
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
| #SuperCollider | SuperCollider | (1..5000).select { |n| n == n.asDigits.sum { |x| pow(x, x) } } |
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).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | f[0]:=1
m[0]:=0
f[n_]:=n-m[f[n-1]]
m[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
| #FreeBASIC | FreeBASIC | ' version 23-10-2016
' compile with: fbc -s console
Randomize Timer 'seed the random function
Dim As Double x, y, pi, error_
Dim As UInteger m = 10, n, n_start, n_stop = m, p
Print
Print " Mumber of throws Ratio (Pi) Error"
Print
Do
For n = n_start To n_stop -1
x = Rnd
y = Rnd
If (x * x + y * y) <= 1 Then p = p +1
Next
Print Using " ############, "; m ;
pi = p * 4 / m
error_ = 3.141592653589793238462643383280 - pi
Print RTrim(Str(pi),"0");Tab(35); Using "##.#############"; error_
m = m * 10
n_start = n_stop
n_stop = m
Loop Until m > 1000000000 ' 1,000,000,000
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
| #Futhark | Futhark |
import "futlib/math"
default(f32)
fun dirvcts(): [2][30]i32 =
[
[
536870912, 268435456, 134217728, 67108864, 33554432, 16777216, 8388608, 4194304, 2097152, 1048576, 524288, 262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
],
[
536870912, 805306368, 671088640, 1006632960, 570425344, 855638016, 713031680, 1069547520, 538968064, 808452096, 673710080, 1010565120, 572653568, 858980352, 715816960, 1073725440, 536879104, 805318656, 671098880, 1006648320, 570434048, 855651072, 713042560, 1069563840, 538976288, 808464432, 673720360, 1010580540, 572662306, 858993459
]
]
fun grayCode(x: i32): i32 = (x >> 1) ^ x
----------------------------------------
--- Sobol Generator
----------------------------------------
fun testBit(n: i32, ind: i32): bool =
let t = (1 << ind) in (n & t) == t
fun xorInds(n: i32) (dir_vs: [num_bits]i32): i32 =
let reldv_vals = zipWith (\ dv i ->
if testBit(grayCode n,i)
then dv else 0)
dir_vs (iota num_bits)
in reduce (^) 0 reldv_vals
fun sobolIndI (dir_vs: [m][num_bits]i32, n: i32): [m]i32 =
map (xorInds n) dir_vs
fun sobolIndR(dir_vs: [m][num_bits]i32) (n: i32 ): [m]f32 =
let divisor = 2.0 ** f32(num_bits)
let arri = sobolIndI( dir_vs, n )
in map (\ (x: i32): f32 -> f32(x) / divisor) arri
fun main(n: i32): f32 =
let rand_nums = map (sobolIndR (dirvcts())) (iota n)
let dists = map (\xy ->
let (x,y) = (xy[0],xy[1]) in f32.sqrt(x*x + y*y))
rand_nums
let bs = map (\d -> if d <= 1.0f32 then 1 else 0) dists
let inside = reduce (+) 0 bs
in 4.0f32*f32(inside)/f32(n)
|
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.)
| #Ring | Ring |
# Project : Move-to-front algorithm
test("broood")
test("bananaaa")
test("hiphophiphop")
func encode(s)
symtab = "abcdefghijklmnopqrstuvwxyz"
res = ""
for i=1 to len(s)
ch = s[i]
k = substr(symtab, ch)
res = res + " " + (k-1)
for j=k to 2 step -1
symtab[j] = symtab[j-1]
next
symtab[1] = ch
next
return res
func decode(s)
s = str2list( substr(s, " ", nl) )
symtab = "abcdefghijklmnopqrstuvwxyz"
res = ""
for i=1 to len(s)
k = number(s[i]) + 1
ch = symtab[k]
res = res + " " + ch
for j=k to 2 step -1
symtab[j] = symtab[j-1]
next
symtab[1] = ch
next
return right(res, len(res)-2)
func test(s)
e = encode(s)
d = decode(e)
see "" + s + " => " + "(" + right(e, len(e) - 1) + ") " + " => " + substr(d, " ", "") + nl
|
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.)
| #Ruby | Ruby | module MoveToFront
ABC = ("a".."z").to_a.freeze
def self.encode(str)
ar = ABC.dup
str.chars.each_with_object([]) do |char, memo|
memo << (i = ar.index(char))
ar = m2f(ar,i)
end
end
def self.decode(indices)
ar = ABC.dup
indices.each_with_object("") do |i, str|
str << ar[i]
ar = m2f(ar,i)
end
end
private
def self.m2f(ar,i)
[ar.delete_at(i)] + ar
end
end
['broood', 'bananaaa', 'hiphophiphop'].each do |word|
p word == MoveToFront.decode(p MoveToFront.encode(p word))
end |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #EchoLisp | EchoLisp |
(require 'json)
(require 'hash)
(require 'timer)
;; json table from RUBY
(define morse-alphabet
#'{"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":"--..","[":"-.--.","]":"-.--.-","_":"..--.-"," ":"|"}'#)
(define MORSE (json->hash (string->json morse-alphabet)))
;; translates a string into morse string
;; use "|" as letters separator
(define (string->morse str morse)
(apply append (map string->list
(for/list [(a (string-diacritics str))]
(string-append
(or (hash-ref morse (string-upcase a)) "?") "|")))))
(define (play-morse)
(when EMIT ;; else return #f which stops (at-every)
(case (first EMIT)
((".") (play-sound 'digit) (write "dot"))
(("-") (play-sound 'tick) (write "dash"))
(else (writeln) (blink)))
(set! EMIT (rest EMIT))))
|
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.
| #D | D | import std.stdio, std.random;
void main() {
int switchWins, stayWins;
while (switchWins + stayWins < 100_000) {
immutable carPos = uniform(0, 3); // Which door is car behind?
immutable pickPos = uniform(0, 3); // Contestant's initial pick.
int openPos; // Which door is opened by Monty Hall?
// Monty can't open the door you picked or the one with the car
// behind it.
do {
openPos = uniform(0, 3);
} while(openPos == pickPos || openPos == carPos);
int switchPos;
// Find position that's not currently picked by contestant and
// was not opened by Monty already.
for (; pickPos==switchPos || openPos==switchPos; switchPos++) {}
if (pickPos == carPos)
stayWins++;
else if (switchPos == carPos)
switchWins++;
else
assert(0); // Can't happen.
}
writefln("Switching/Staying wins: %d %d", switchWins, stayWins);
} |
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.
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
} |
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.
| #GW-BASIC | GW-BASIC |
10 ' Modular inverse
20 LET E% = 42
30 LET T% = 2017
40 GOSUB 1000
50 PRINT MODINV%
60 END
990 ' increments e stp (step) times until bal is greater than t
992 ' repeats until bal = 1 (mod = 1) and returns count
994 ' bal will not be greater than t + e
1000 LET D% = 0
1010 IF E% >= T% THEN GOTO 1140
1020 LET BAL% = E%
1025 ' At least one iteration is necessary
1030 LET STP% = ((T% - BAL%) \ E%) + 1
1040 LET BAL% = BAL% + STP% * E%
1050 LET COUNT% = 1 + STP%
1060 LET BAL% = BAL% - T%
1070 WHILE BAL% <> 1
1080 LET STP% = ((T% - BAL%) \ E%) + 1
1090 LET BAL% = BAL% + STP% * E%
1100 LET COUNT% = COUNT% + STP%
1110 LET BAL% = BAL% - T%
1120 WEND
1130 LET D% = COUNT%
1140 LET MODINV% = D%
1150 RETURN
|
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.
| #C.23 | C# | using System;
namespace multtbl
{
class Program
{
static void Main(string[] args)
{
Console.Write(" X".PadRight(4));
for (int i = 1; i <= 12; i++)
Console.Write(i.ToString("####").PadLeft(4));
Console.WriteLine();
Console.Write(" ___");
for (int i = 1; i <= 12; i++)
Console.Write(" ___");
Console.WriteLine();
for (int row = 1; row <= 12; row++)
{
Console.Write(row.ToString("###").PadLeft(3).PadRight(4));
for (int col = 1; col <= 12; col++)
{
if (row <= col)
Console.Write((row * col).ToString("###").PadLeft(4));
else
Console.Write("".PadLeft(4));
}
Console.WriteLine();
}
Console.WriteLine();
Console.ReadLine();
}
}
}
|
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.
| #Objeck | Objeck |
class Multifact {
function : MultiFact(n : Int, deg : Int) ~ Int {
result := n;
while (n >= deg + 1){
result *= (n - deg);
n -= deg;
};
return result;
}
function : Main(args : String[]) ~ Nil {
for (i := 1; i <= 5; i+=1;){
IO.Console->Print("Degree ")->Print(i)->Print(": ");
for (j := 1; j <= 10; j+=1;){
IO.Console->Print(' ')->Print(MultiFact(j, i));
};
IO.Console->PrintLine();
};
}
}
|
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
| #Maple | Maple | queens:=proc(n)
local a,u,v,m,aux;
a:=[$1..n];
u:=[true$2*n-1];
v:=[true$2*n-1];
m:=[];
aux:=proc(i)
local j,k,p,q;
if i>n then
m:=[op(m),copy(a)];
else
for j from i to n do
k:=a[j];
p:=i-k+n;
q:=i+k-1;
if u[p] and v[q] then
u[p]:=false;
v[q]:=false;
a[j]:=a[i];
a[i]:=k;
aux(i+1);
u[p]:=true;
v[q]:=true;
a[i]:=a[j];
a[j]:=k;
fi;
od;
fi;
end;
aux(1);
m
end:
for a in queens(8) do printf("%a\n",a) od; |
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.
| #REXX | REXX | /*REXX program shows ranges of numbers with ordinal (st/nd/rd/th) suffixes attached.*/
call tell 0, 25 /*display the 1st range of numbers. */
call tell 250, 265 /* " " 2nd " " " */
call tell 1000, 1025 /* " " 3rd " " " */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: procedure; parse arg L,H,,$ /*get the Low and High #s, nullify list*/
do j=L to H; $=$ th(j); end /*process the range, from low ───► high*/
say 'numbers from ' L " to " H ' (inclusive):' /*display the title. */
say strip($); say; say /*display line; 2 sep*/
return /*return to invoker. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
th: parse arg z; x=abs(z); return z||word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) |
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
| #Swift | Swift | import Foundation
func isMünchhausen(_ n: Int) -> Bool {
let nums = String(n).map(String.init).compactMap(Int.init)
return Int(nums.map({ pow(Double($0), Double($0)) }).reduce(0, +)) == n
}
for i in 1...5000 where isMünchhausen(i) {
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).
| #MATLAB | MATLAB | function Fn = female(n)
if n == 0
Fn = 1;
return
end
Fn = n - male(female(n-1));
end |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func getPi(numThrows int) float64 {
inCircle := 0
for i := 0; i < numThrows; i++ {
//a square with a side of length 2 centered at 0 has
//x and y range of -1 to 1
randX := rand.Float64()*2 - 1 //range -1 to 1
randY := rand.Float64()*2 - 1 //range -1 to 1
//distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
dist := math.Hypot(randX, randY)
if dist < 1 { //circle with diameter of 2 has radius of 1
inCircle++
}
}
return 4 * float64(inCircle) / float64(numThrows)
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(getPi(10000))
fmt.Println(getPi(100000))
fmt.Println(getPi(1000000))
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
} |
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.)
| #Rust | Rust | fn main() {
let examples = vec!["broood", "bananaaa", "hiphophiphop"];
for example in examples {
let encoded = encode(example);
let decoded = decode(&encoded);
println!(
"{} encodes to {:?} decodes to {}",
example, encoded, decoded
);
}
}
fn get_symbols() -> Vec<u8> {
(b'a'..b'z').collect()
}
fn encode(input: &str) -> Vec<usize> {
input
.as_bytes()
.iter()
.fold((Vec::new(), get_symbols()), |(mut o, mut s), x| {
let i = s.iter().position(|c| c == x).unwrap();
let c = s.remove(i);
s.insert(0, c);
o.push(i);
(o, s)
})
.0
}
fn decode(input: &[usize]) -> String {
input
.iter()
.fold((Vec::new(), get_symbols()), |(mut o, mut s), x| {
o.push(s[*x]);
let c = s.remove(*x);
s.insert(0, c);
(o, s)
})
.0
.into_iter()
.map(|c| c as char)
.collect()
} |
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.)
| #Scala | Scala | package rosetta
import scala.annotation.tailrec
object MoveToFront {
/**
* Default radix
*/
private val R = 256
/**
* Default symbol table
*/
private def symbolTable = (0 until R).map(_.toChar).mkString
/**
* Apply move-to-front encoding using default symbol table.
*/
def encode(s: String): List[Int] = {
encode(s, symbolTable)
}
/**
* Apply move-to-front encoding using symbol table <tt>symTable</tt>.
*/
def encode(s: String, symTable: String): List[Int] = {
val table = symTable.toCharArray
@inline @tailrec def moveToFront(ch: Char, index: Int, tmpout: Char): Int = {
val tmpin = table(index)
table(index) = tmpout
if (ch != tmpin)
moveToFront(ch, index + 1, tmpin)
else {
table(0) = ch
index
}
}
@tailrec def encodeString(output: List[Int], s: List[Char]): List[Int] = s match {
case Nil => output
case x :: xs => {
encodeString(moveToFront(x, 0, table(0)) :: output, s.tail)
}
}
encodeString(Nil, s.toList).reverse
}
/**
* Apply move-to-front decoding using default symbol table.
*/
def decode(ints: List[Int]): String = {
decode(ints, symbolTable)
}
/**
* Apply move-to-front decoding using symbol table <tt>symTable</tt>.
*/
def decode(lst: List[Int], symTable: String): String = {
val table = symTable.toCharArray
@inline def moveToFront(c: Char, index: Int) {
for (i <- index-1 to 0 by -1)
table(i+1) = table(i)
table(0) = c
}
@tailrec def decodeList(output: List[Char], lst: List[Int]): List[Char] = lst match {
case Nil => output
case x :: xs => {
val c = table(x)
moveToFront(c, x)
decodeList(c :: output, xs)
}
}
decodeList(Nil, lst).reverse.mkString
}
def test(toEncode: String, symTable: String) {
val encoded = encode(toEncode, symTable)
println(toEncode + ": " + encoded)
val decoded = decode(encoded, symTable)
if (toEncode != decoded)
print("in")
println("correctly decoded to " + decoded)
}
}
/**
* Unit tests the <tt>MoveToFront</tt> data type.
*/
object RosettaCodeMTF extends App {
val symTable = "abcdefghijklmnopqrstuvwxyz"
MoveToFront.test("broood", symTable)
MoveToFront.test("bananaaa", symTable)
MoveToFront.test("hiphophiphop", symTable)
} |
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).
| #Elixir | Elixir | defmodule Morse do
@morse %{"!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.",
"(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--",
"-" => "-....-", "." => ".-.-.-", "/" => "-..-.",
"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" => "--..",
"[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" }
def code(text) do
String.upcase(text)
|> String.codepoints
|> Enum.map_join(" ", fn c -> Map.get(@morse, c, " ") end)
end
end
IO.puts Morse.code("Hello, World!") |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Dart | Dart | int rand(int max) => (Math.random()*max).toInt();
class Game {
int _prize;
int _open;
int _chosen;
Game() {
_prize=rand(3);
_open=null;
_chosen=null;
}
void choose(int door) {
_chosen=door;
}
void reveal() {
if(_prize==_chosen) {
int toopen=rand(2);
if (toopen>=_prize)
toopen++;
_open=toopen;
} else {
for(int i=0;i<3;i++)
if(_prize!=i && _chosen!=i) {
_open=i;
break;
}
}
}
void change() {
for(int i=0;i<3;i++)
if(_chosen!=i && _open!=i) {
_chosen=i;
break;
}
}
bool hasWon() => _prize==_chosen;
String toString() {
String res="Prize is behind door $_prize";
if(_chosen!=null) res+=", player has chosen door $_chosen";
if(_open!=null) res+=", door $_open is open";
return res;
}
}
void play(int count, bool swap) {
int wins=0;
for(int i=0;i<count;i++) {
Game game=new Game();
game.choose(rand(3));
game.reveal();
if(swap)
game.change();
if(game.hasWon())
wins++;
}
String withWithout=swap?"with":"without";
double percent=(wins*100.0)/count;
print("playing $withWithout switching won $percent%");
}
test() {
for(int i=0;i<5;i++) {
Game g=new Game();
g.choose(i%3);
g.reveal();
print(g);
g.change();
print(g);
print("win==${g.hasWon()}");
}
}
main() {
play(10000,false);
play(10000,true);
} |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #Delphi | Delphi | program MontyHall;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
const
numGames = 1000000; // Number of games to run
var
switchWins, stayWins, plays: Int64;
doors: array[0..2] of Integer;
i, winner, choice, shown: Integer;
begin
switchWins := 0;
stayWins := 0;
for plays := 1 to numGames do
begin
//0 is a goat, 1 is a car
for i := 0 to 2 do
doors[i] := 0;
//put a winner in a random door
winner := Random(3);
doors[winner] := 1;
//pick a door, any door
choice := Random(3);
//don't show the winner or the choice
repeat
shown := Random(3);
until (doors[shown] <> 1) and (shown <> choice);
//if you won by staying, count it
stayWins := stayWins + doors[choice];
//the switched (last remaining) door is (3 - choice - shown), because 0+1+2=3
switchWins := switchWins + doors[3 - choice - shown];
end;
WriteLn('Staying wins ' + IntToStr(stayWins) + ' times.');
WriteLn('Switching wins ' + IntToStr(switchWins) + ' times.');
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.
| #Haskell | Haskell | -- Given a and m, return Just x such that ax = 1 mod m.
-- If there is no such x return Nothing.
modInv :: Int -> Int -> Maybe Int
modInv a m
| 1 == g = Just (mkPos i)
| otherwise = Nothing
where
(i, _, g) = gcdExt a m
mkPos x
| x < 0 = x + m
| otherwise = x
-- Extended Euclidean algorithm.
-- Given non-negative a and b, return x, y and g
-- such that ax + by = g, where g = gcd(a,b).
-- Note that x or y may be negative.
gcdExt :: Int -> Int -> (Int, Int, Int)
gcdExt a 0 = (1, 0, a)
gcdExt a b =
let (q, r) = a `quotRem` b
(s, t, g) = gcdExt b r
in (t, s - q * t, g)
main :: IO ()
main = mapM_ print [2 `modInv` 4, 42 `modInv` 2017] |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#include <cmath> // for log10()
#include <algorithm> // for max()
size_t table_column_width(const int min, const int max)
{
unsigned int abs_max = std::max(max*max, min*min);
// abs_max is the largest absolute value we might see.
// If we take the log10 and add one, we get the string width
// of the largest possible absolute value.
// Add one more for a little whitespace guarantee.
size_t colwidth = 2 + std::log10(abs_max);
// If only one of them is less than 0, then some will
// be negative. If some values may be negative, then we need to add some space
// for a sign indicator (-)
if (min < 0 && max > 0)
++colwidth;
return colwidth;
}
struct Writer_
{
decltype(std::setw(1)) fmt_;
Writer_(size_t w) : fmt_(std::setw(w)) {}
template<class T_> Writer_& operator()(const T_& info) { std::cout << fmt_ << info; return *this; }
};
void print_table_header(const int min, const int max)
{
Writer_ write(table_column_width(min, max));
// table corner
write(" ");
for(int col = min; col <= max; ++col)
write(col);
// End header with a newline and blank line.
std::cout << std::endl << std::endl;
}
void print_table_row(const int num, const int min, const int max)
{
Writer_ write(table_column_width(min, max));
// Header column
write(num);
// Spacing to ensure only the top half is printed
for(int multiplicand = min; multiplicand < num; ++multiplicand)
write(" ");
// Remaining multiplicands for the row.
for(int multiplicand = num; multiplicand <= max; ++multiplicand)
write(num * multiplicand);
// End row with a newline and blank line.
std::cout << std::endl << std::endl;
}
void print_table(const int min, const int max)
{
// Header row
print_table_header(min, max);
// Table body
for(int row = min; row <= max; ++row)
print_table_row(row, min, max);
}
int main()
{
print_table(1, 12);
return 0;
}
|
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Oforth | Oforth | : multifact(n, deg) 1 while( n 0 > ) [ n * n deg - ->n ] ;
: printMulti
| i |
5 loop: i [ System.Out i << " : " << 10 seq map(#[ i multifact]) << 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.
| #PARI.2FGP | PARI/GP | fac(n,d)=prod(k=0,(n-1)\d,n-k*d)
for(k=1,5,for(n=1,10,print1(fac(n,k)" "));print) |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | safe[q_List, n_] :=
With[{l = Length@q},
Length@Union@q == Length@Union[q + Range@l] ==
Length@Union[q - Range@l] == l]
nQueen[q_List: {}, n_] :=
If[safe[q, n],
If[Length[q] == n, {q},
Cases[nQueen[Append[q, #], n] & /@ Range[n],
Except[{Null} | {}], {2}]], Null] |
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.
| #Ring | Ring |
for nr = 0 to 25
see Nth(nr) + Nth(nr + 250) + Nth(nr + 1000) + nl
next
func getSuffix n
lastTwo = n % 100
lastOne = n % 10
if lastTwo > 3 and lastTwo < 21 "th" ok
if lastOne = 1 return "st" ok
if lastOne = 2 return "nd" ok
if lastOne = 3 return "rd" ok
return "th"
func Nth n
return "" + n + "'" + getSuffix(n) + " "
|
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
| #Symsyn | Symsyn |
x : 10 1
(2^2) x.2
(3^3) x.3
(4^4) x.4
(5^5) x.5
(6^6) x.6
(7^7) x.7
(8^8) x.8
(9^9) x.9
1 i
if i <= 5000
~ i $i | convert binary to string
#$i j | length to j
y | set y to 0
if j > 0
$i.j $j 1 | move digit j to string j
~ $j n | convert j string to binary
+ x.n y | add value x at n to y
- j | dec j
goif
endif
if i = y
i [] | output to console
endif
+ i
goif
endif
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Maxima | Maxima | f[0]: 1$
m[0]: 0$
f[n] := n - m[f[n - 1]]$
m[n] := n - f[m[n - 1]]$
makelist(f[i], i, 0, 10);
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6]
makelist(m[i], i, 0, 10);
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6]
remarray(m, f)$
f(n) := if n = 0 then 1 else n - m(f(n - 1))$
m(n) := if n = 0 then 0 else n - f(m(n - 1))$
makelist(f(i), i, 0, 10);
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6]
makelist(m(i), i, 0, 10);
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6]
remfunction(f, m)$ |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Haskell | Haskell | import Control.Monad
import System.Random
getPi throws = do
results <- replicateM throws one_trial
return (4 * fromIntegral (sum results) / fromIntegral throws)
where
one_trial = do
rand_x <- randomRIO (-1, 1)
rand_y <- randomRIO (-1, 1)
let dist :: Double
dist = sqrt (rand_x * rand_x + rand_y * rand_y)
return (if dist < 1 then 1 else 0) |
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.)
| #Sidef | Sidef | func encode(str) {
var table = ('a'..'z' -> join);
str.chars.map { |c|
var s = '';
table.sub!(Regex('(.*?)' + c), {|s1| s=s1; c + s1});
s.len;
}
}
func decode(nums) {
var table = ('a'..'z' -> join);
nums.map { |n|
var s = '';
table.sub!(Regex('(.{' + n + '})(.)'), {|s1, s2| s=s2; s2 + s1});
s;
}.join;
}
%w(broood bananaaa hiphophiphop).each { |test|
var encoded = encode(test);
say "#{test}: #{encoded}";
var decoded = decode(encoded);
print "in" if (decoded != test);
say "correctly decoded to #{decoded}";
} |
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).
| #F.23 | F# |
open System
open System.Threading
let morse = Map.ofList
[('a', "._ "); ('b', "_... "); ('c', "_._. "); ('d', "_.. ");
('e', ". "); ('f', ".._. "); ('g', "__. "); ('h', ".... ");
('i', ".. "); ('j', ".___ "); ('k', "_._ "); ('l', "._.. ");
('m', "__ "); ('n', "_. "); ('o', "___ "); ('p', ".__. ");
('q', "__._ "); ('r', "._. "); ('s', "... "); ('t', "_ ");
('u', ".._ "); ('v', "..._ "); ('w', ".__ "); ('x', "_.._ ");
('y', "_.__ "); ('z', "__.. "); ('0', "_____ "); ('1', ".____ ");
('2', "..___ "); ('3', "...__ "); ('4', "...._ "); ('5', "..... ");
('6', "_.... "); ('7', "__... "); ('8', "___.. "); ('9', "____. ")]
let beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
|
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.
| #Dyalect | Dyalect | var switchWins = 0
var stayWins = 0
for plays in 0..1000000 {
var doors = [0 ,0, 0]
var winner = rnd(max: 3)
doors[winner] = 1
var choice = rnd(max: 3)
var shown = rnd(max: 3)
while doors[shown] == 1 || shown == choice {
shown = rnd(max: 3)
}
stayWins += doors[choice]
switchWins += doors[3 - choice - shown]
}
print("Staying wins \(stayWins) times.")
print("Switching wins \(switchWins) times.") |
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.
| #Eiffel | Eiffel |
note
description: "[
Monty Hall Problem as an Eiffel Solution
1. Set the stage: Randomly place car and two goats behind doors 1, 2 and 3.
2. Monty offers choice of doors --> Contestant will choose a random door or always one door.
2a. Door has Goat - door remains closed
2b. Door has Car - door remains closed
3. Monty offers cash --> Contestant takes or refuses cash.
3a. Takes cash: Contestant is Cash winner and door is revealed. Car Loser if car door revealed.
3b. Refuses cash: Leads to offer to switch doors.
4. Monty offers door switch --> Contestant chooses to stay or change.
5. Door reveal: Contestant refused cash and did or did not door switch. Either way: Reveal!
6. Winner and Loser based on door reveal of prize.
Car Winner: Chooses car door
Cash Winner: Chooses cash over any door
Goat Loser: Chooses goat door
Car Loser: Chooses cash over car door or switches from car door to goat door
]"
date: "$Date$"
revision: "$Revision$"
class
MH_APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Initialize Current.
do
play_lets_make_a_deal
ensure
played_1000_games: game_count = times_to_play
end
feature {NONE} -- Implementation: Access
live_contestant: attached like contestant
-- Attached version of `contestant'
do
if attached contestant as al_contestant then
Result := al_contestant
else
create Result
check not_attached_contestant: False end
end
end
contestant: detachable TUPLE [first_door_choice, second_door_choice: like door_number_anchor; takes_cash, switches_door: BOOLEAN]
-- Contestant for Current.
active_stage_door (a_door: like door_anchor): attached like door_anchor
-- Attached version of `a_door'.
do
if attached a_door as al_door then
Result := al_door
else
create Result
check not_attached_door: False end
end
end
door_1, door_2, door_3: like door_anchor
-- Doors with prize names and flags for goat and open (revealed).
feature {NONE} -- Implementation: Status
game_count, car_win_count, cash_win_count, car_loss_count, goat_loss_count, goat_avoidance_count: like counter_anchor
switch_count, switch_win_count: like counter_anchor
no_switch_count, no_switch_win_count: like counter_anchor
-- Counts of games played, wins and losses based on car, cash or goat.
feature {NONE} -- Implementation: Basic Operations
prepare_stage
-- Prepare the stage in terms of what doors have what prizes.
do
inspect new_random_of (3)
when 1 then
door_1 := door_with_car
door_2 := door_with_goat
door_3 := door_with_goat
when 2 then
door_1 := door_with_goat
door_2 := door_with_car
door_3 := door_with_goat
when 3 then
door_1 := door_with_goat
door_2 := door_with_goat
door_3 := door_with_car
end
active_stage_door (door_1).number := 1
active_stage_door (door_2).number := 2
active_stage_door (door_3).number := 3
ensure
door_has_prize: not active_stage_door (door_1).is_goat or
not active_stage_door (door_2).is_goat or
not active_stage_door (door_3).is_goat
consistent_door_numbers: active_stage_door (door_1).number = 1 and
active_stage_door (door_2).number = 2 and
active_stage_door (door_3).number = 3
end
door_number_having_prize: like door_number_anchor
-- What door number has the car?
do
if not active_stage_door (door_1).is_goat then
Result := 1
elseif not active_stage_door (door_2).is_goat then
Result := 2
elseif not active_stage_door (door_3).is_goat then
Result := 3
else
check prize_not_set: False end
end
ensure
one_to_three: between_1_and_x_inclusive (3, Result)
end
door_with_car: attached like door_anchor
-- Create a door with a car.
do
create Result
Result.name := prize
ensure
not_empty: not Result.name.is_empty
name_is_prize: Result.name.same_string (prize)
end
door_with_goat: attached like door_anchor
-- Create a door with a goat
do
create Result
Result.name := gag_gift
Result.is_goat := True
ensure
not_empty: not Result.name.is_empty
name_is_prize: Result.name.same_string (gag_gift)
is_gag_gift: Result.is_goat
end
next_contestant: attached like live_contestant
-- The next contestant on Let's Make a Deal!
do
create Result
Result.first_door_choice := new_random_of (3)
Result.second_door_choice := choose_another_door (Result.first_door_choice)
Result.takes_cash := random_true_or_false
if not Result.takes_cash then
Result.switches_door := random_true_or_false
end
ensure
choices_one_to_three: Result.first_door_choice <= 3 and Result.second_door_choice <= 3
switch_door_implies_no_cash_taken: Result.switches_door implies not Result.takes_cash
end
choose_another_door (a_first_choice: like door_number_anchor): like door_number_anchor
-- Make a choice from the remaining doors
require
one_to_three: between_1_and_x_inclusive (3, a_first_choice)
do
Result := new_random_of (3)
from until Result /= a_first_choice
loop
Result := new_random_of (3)
end
ensure
first_choice_not_second: a_first_choice /= Result
result_one_to_three: between_1_and_x_inclusive (3, Result)
end
play_lets_make_a_deal
-- Play the game 1000 times
local
l_car_win, l_car_loss, l_cash_win, l_goat_loss, l_goat_avoided: BOOLEAN
do
from
game_count := 0
invariant
consistent_win_loss_counts: (game_count = (car_win_count + cash_win_count + goat_loss_count))
consistent_loss_avoidance_counts: (game_count = (car_loss_count + goat_avoidance_count))
until
game_count >= times_to_play
loop
prepare_stage
contestant := next_contestant
l_cash_win := (live_contestant.takes_cash)
l_car_win := (not l_cash_win and
(not live_contestant.switches_door and live_contestant.first_door_choice = door_number_having_prize) or
(live_contestant.switches_door and live_contestant.second_door_choice = door_number_having_prize))
l_car_loss := (not live_contestant.switches_door and live_contestant.first_door_choice /= door_number_having_prize) or
(live_contestant.switches_door and live_contestant.second_door_choice /= door_number_having_prize)
l_goat_loss := (not l_car_win and not l_cash_win)
l_goat_avoided := (not live_contestant.switches_door and live_contestant.first_door_choice = door_number_having_prize) or
(live_contestant.switches_door and live_contestant.second_door_choice = door_number_having_prize)
check consistent_goats: l_goat_loss implies not l_goat_avoided end
check consistent_car_win: l_car_win implies not l_car_loss and not l_cash_win and not l_goat_loss end
check consistent_cash_win: l_cash_win implies not l_car_win and not l_goat_loss end
check consistent_goat_avoidance: l_goat_avoided implies (l_car_win or l_cash_win) and not l_goat_loss end
check consistent_car_loss: l_car_loss implies l_cash_win or l_goat_loss end
if l_car_win then car_win_count := car_win_count + 1 end
if l_cash_win then cash_win_count := cash_win_count + 1 end
if l_goat_loss then goat_loss_count := goat_loss_count + 1 end
if l_car_loss then car_loss_count := car_loss_count + 1 end
if l_goat_avoided then goat_avoidance_count := goat_avoidance_count + 1 end
if live_contestant.switches_door then
switch_count := switch_count + 1
if l_car_win then
switch_win_count := switch_win_count + 1
end
else -- if not live_contestant.takes_cash and not live_contestant.switches_door then
no_switch_count := no_switch_count + 1
if l_car_win or l_cash_win then
no_switch_win_count := no_switch_win_count + 1
end
end
game_count := game_count + 1
end
print ("%NCar Wins:%T%T " + car_win_count.out +
"%NCash Wins:%T%T " + cash_win_count.out +
"%NGoat Losses:%T%T " + goat_loss_count.out +
"%N-----------------------------" +
"%NTotal Win/Loss:%T%T" + (car_win_count + cash_win_count + goat_loss_count).out +
"%N%N" +
"%NCar Losses:%T%T " + car_loss_count.out +
"%NGoats Avoided:%T%T " + goat_avoidance_count.out +
"%N-----------------------------" +
"%NTotal Loss/Avoid:%T" + (car_loss_count + goat_avoidance_count).out +
"%N-----------------------------" +
"%NStaying Count/Win:%T" + no_switch_count.out + "/" + no_switch_win_count.out + " = " + (no_switch_win_count / no_switch_count * 100).out + " %%" +
"%NSwitch Count/Win:%T" + switch_count.out + "/" + switch_win_count.out + " = " + (switch_win_count / switch_count * 100).out + " %%"
)
end
feature {NONE} -- Implementation: Random Numbers
last_random: like random_number_anchor
-- The last random number chosen.
random_true_or_false: BOOLEAN
-- A randome True or False
do
Result := new_random_of (2) = 2
end
new_random_of (a_number: like random_number_anchor): like door_number_anchor
-- A random number from 1 to `a_number'.
do
Result := (new_random \\ a_number + 1).as_natural_8
end
new_random: like random_number_anchor
-- Random integer
-- Each call returns another random number.
do
random_sequence.forth
Result := random_sequence.item
last_random := Result
ensure
old_random_not_new: old last_random /= last_random
end
random_sequence: RANDOM
-- Random sequence seeded from clock when called.
attribute
create Result.set_seed ((create {TIME}.make_now).milli_second)
end
feature {NONE} -- Implementation: Constants
times_to_play: NATURAL_16 = 1000
-- Times to play the game.
prize: STRING = "Car"
-- Name of the prize
gag_gift: STRING = "Goat"
-- Name of the gag gift
door_anchor: detachable TUPLE [number: like door_number_anchor; name: STRING; is_goat, is_open: BOOLEAN]
-- Type anchor for door tuples.
door_number_anchor: NATURAL_8
-- Type anchor for door numbers.
random_number_anchor: INTEGER
-- Type anchor for random numbers.
counter_anchor: NATURAL_16
-- Type anchor for counters.
feature {NONE} -- Implementation: Contract Support
between_1_and_x_inclusive (a_number, a_value: like door_number_anchor): BOOLEAN
-- Is `a_value' between 1 and `a_number'?
do
Result := (a_value > 0) and (a_value <= a_number)
end
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(args)
a := integer(args[1]) | 42
b := integer(args[2]) | 2017
write(mul_inv(a,b))
end
procedure mul_inv(a,b)
if b == 1 then return 1
(b0 := b, x0 := 0, x1 := 1)
while a > 1 do {
q := a/b
(t := b, b := a%b, a := t)
(t := x0, x0 := x1-q*x0, x1 := t)
}
return if (x1 > 0) then x1 else x1+b0
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.
| #IS-BASIC | IS-BASIC | 100 PRINT MODINV(42,2017)
120 DEF MODINV(A,B)
130 LET B=ABS(B)
140 IF A<0 THEN LET A=B-MOD(-A,B)
150 LET T=0:LET NT=1:LET R=B:LET NR=MOD(A,B)
160 DO WHILE NR<>0
170 LET Q=INT(R/NR)
180 LET TMP=NT:LET NT=T-Q*NT:LET T=TMP
190 LET TMP=NR:LET NR=R-Q*NR:LET R=TMP
200 LOOP
210 IF R>1 THEN
220 LET MODINV=-1
230 ELSE IF T<0 THEN
240 LET MODINV=T+B
250 ELSE
260 LET MODINV=T
270 END IF
280 END DEF |
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.
| #Chef | Chef | Multigrain Bread.
Prints out a multiplication table.
Ingredients.
12 cups flour
12 cups grains
12 cups seeds
1 cup water
9 dashes yeast
1 cup nuts
40 ml honey
1 cup sugar
Method.
Sift the flour.
Put flour into the 1st mixing bowl.
Put yeast into the 1st mixing bowl.
Shake the flour until sifted.
Put grains into the 2nd mixing bowl.
Fold flour into the 2nd mixing bowl.
Put water into the 2nd mixing bowl.
Add yeast into the 2nd mixing bowl.
Combine flour into the 2nd mixing bowl.
Fold nuts into the 2nd mixing bowl.
Liquify nuts.
Put nuts into the 1st mixing bowl.
Pour contents of the 1st mixing bowl into the baking dish.
Sieve the flour.
Put yeast into the 2nd mixing bowl.
Add water into the 2nd mixing bowl.
Sprinkle the seeds.
Put flour into the 2nd mixing bowl.
Combine seeds into the 2nd mixing bowl.
Put yeast into the 2nd mixing bowl.
Put seeds into the 2nd mixing bowl.
Remove flour from the 2nd mixing bowl.
Fold honey into the 2nd mixing bowl.
Put water into the 2nd mixing bowl.
Fold sugar into the 2nd mixing bowl.
Squeeze the honey.
Put water into the 2nd mixing bowl.
Remove water from the 2nd mixing bowl.
Fold sugar into the 2nd mixing bowl.
Set aside.
Drip until squeezed.
Scoop the sugar.
Crush the seeds.
Put yeast into the 2nd mixing bowl.
Grind the seeds until crushed.
Put water into the 2nd mixing bowl.
Fold seeds into the 2nd mixing bowl.
Set aside.
Drop until scooped.
Randomize the seeds until sprinkled.
Fold honey into the 2nd mixing bowl.
Put flour into the 2nd mixing bowl.
Put grains into the 2nd mixing bowl.
Fold seeds into the 2nd mixing bowl.
Shake the flour until sieved.
Put yeast into the 2nd mixing bowl.
Add water into the 2nd mixing bowl.
Pour contents of the 2nd mixing bowl into the 2nd baking dish.
Serves 2. |
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.
| #Perl | Perl | { # <-- scoping the cache and bigint clause
my @cache;
use bigint;
sub mfact {
my ($s, $n) = @_;
return 1 if $n <= 0;
$cache[$s][$n] //= $n * mfact($s, $n - $s);
}
}
for my $s (1 .. 10) {
print "step=$s: ";
print join(" ", map(mfact($s, $_), 1 .. 10)), "\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
| #MATLAB | MATLAB | n=8;
solutions=[[]];
v = 1:n;
P = perms(v);
for i=1:length(P)
for j=1:n
sub(j)=P(i,j)-j;
add(j)=P(i,j)+j;
end
if n==length(unique(sub)) && n==length(unique(add))
solutions(end+1,:)=P(i,:);
end
end
fprintf('Number of solutions with %i queens: %i', n, length(solutions));
if ~isempty(solutions)
%Print first possible solution
board=solutions(1,:);
s = repmat('-',n);
for k=1:length(board)
s(k,board(k)) = 'Q';
end
s
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.
| #Ruby | Ruby | class Integer
def ordinalize
num = self.abs
ordinal = if (11..13).include?(num % 100)
"th"
else
case num % 10
when 1; "st"
when 2; "nd"
when 3; "rd"
else "th"
end
end
"#{self}#{ordinal}"
end
end
[(0..25),(250..265),(1000..1025)].each{|r| puts r.map(&:ordinalize).join(", "); puts}
|
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
| #TI-83_BASIC | TI-83 BASIC | For(I,1,5000)
0→S:I→K
For(J,1,4)
10^(4-J)→D
iPart(K/D)→N
remainder(K,D)→R
If N≠0:S+N^N→S
R→K
End
If S=I:Disp I
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).
| #Mercury | Mercury |
:- module mutual_recursion.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list.
main(!IO) :-
io.write(list.map(f, 0..19), !IO), io.nl(!IO),
io.write(list.map(m, 0..19), !IO), io.nl(!IO).
:- func f(int) = int.
f(N) = ( if N = 0 then 1 else N - m(f(N - 1)) ).
:- func m(int) = int.
m(N) = ( if N = 0 then 0 else 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
| #HicEst | HicEst | FUNCTION Pi(samples)
inside = 0
DO i = 1, samples
inside = inside + ( (RAN(1)^2 + RAN(1)^2)^0.5 <= 1)
ENDDO
Pi = 4 * inside / samples
END
WRITE(ClipBoard) Pi(1E4) ! 3.1504
WRITE(ClipBoard) Pi(1E5) ! 3.14204
WRITE(ClipBoard) Pi(1E6) ! 3.141672
WRITE(ClipBoard) Pi(1E7) ! 3.1412856 |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every t := 10 ^ ( 5 to 9 ) do
printf("Rounds=%d Pi ~ %r\n",t,getPi(t))
end
link printf
procedure getPi(rounds)
incircle := 0.
every 1 to rounds do
if 1 > sqrt((?0 * 2 - 1) ^ 2 + (?0 * 2 - 1) ^ 2) then
incircle +:= 1
return 4 * incircle / rounds
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.)
| #Swift | Swift |
var str="broood"
var number:[Int]=[1,17,15,0,0,5]
//function to encode the string
func encode(st:String)->[Int]
{
var array:[Character]=["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"]
var num:[Int]=[]
var temp:Character="a"
var i1:Int=0
for i in st.characters
{
for j in 0...25
{
if i==array[j]
{
num.append(j)
temp=array[j]
i1=j
while(i1>0)
{
array[i1]=array[i1-1]
i1=i1-1
}
array[0]=temp
}
}
}
return num
}
func decode(s:[Int])->[Character]
{
var st1:[Character]=[]
var alph:[Character]=["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"]
var temp1:Character="a"
var i2:Int=0
for i in 0...s.character.count-1
{
i2=s[i]
st1.append(alph[i2])
temp1=alph[i2]
while(i2>0)
{
alph[i2]=alph[i2-1]
i2=i2-1
}
alph[0]=temp1
}
return st1
}
var encarr:[Int]=encode(st:str)
var decarr:[Character]=decode(s:number)
print(encarr)
print(decarr)
|
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.)
| #Tcl | Tcl | package require Tcl 8.6
oo::class create MoveToFront {
variable symbolTable
constructor {symbols} {
set symbolTable [split $symbols ""]
}
method MoveToFront {table index} {
list [lindex $table $index] {*}[lreplace $table $index $index]
}
method encode {text} {
set t $symbolTable
set r {}
foreach c [split $text ""] {
set i [lsearch -exact $t $c]
lappend r $i
set t [my MoveToFront $t $i]
}
return $r
}
method decode {numbers} {
set t $symbolTable
set r ""
foreach n $numbers {
append r [lindex $t $n]
set t [my MoveToFront $t $n]
}
return $r
}
}
MoveToFront create mtf "abcdefghijklmnopqrstuvwxyz"
foreach tester {"broood" "bananaaa" "hiphophiphop"} {
set enc [mtf encode $tester]
set dec [mtf decode $enc]
puts [format "'%s' encodes to %s. This decodes to '%s'. %s" \
$tester $enc $dec [expr {$tester eq $dec ? "Correct!" : "WRONG!"}]]
} |
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).
| #Factor | Factor | USE: morse
"Hello world!" play-as-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.
| #Elixir | Elixir | defmodule MontyHall do
def simulate(n) do
{stay, switch} = simulate(n, 0, 0)
:io.format "Staying wins ~w times (~.3f%)~n", [stay, 100 * stay / n]
:io.format "Switching wins ~w times (~.3f%)~n", [switch, 100 * switch / n]
end
defp simulate(0, stay, switch), do: {stay, switch}
defp simulate(n, stay, switch) do
doors = Enum.shuffle([:goat, :goat, :car])
guess = :rand.uniform(3) - 1
[choice] = [0,1,2] -- [guess, shown(doors, guess)]
if Enum.at(doors, choice) == :car, do: simulate(n-1, stay, switch+1),
else: simulate(n-1, stay+1, switch)
end
defp shown(doors, guess) do
[i, j] = Enum.shuffle([0,1,2] -- [guess])
if Enum.at(doors, i) == :goat, do: i, else: j
end
end
MontyHall.simulate(10000) |
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.
| #Emacs_Lisp | Emacs Lisp | (defun montyhall (keep)
(let ((prize (random 3))
(choice (random 3)))
(if keep (= prize choice)
(/= prize choice))))
(let ((cnt 0))
(dotimes (i 10000)
(and (montyhall t) (setq cnt (1+ cnt))))
(message "Strategy keep: %.3f%%" (/ cnt 100.0)))
(let ((cnt 0))
(dotimes (i 10000)
(and (montyhall nil) (setq cnt (1+ cnt))))
(message "Strategy switch: %.3f%%" (/ cnt 100.0))) |
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.
| #J | J | modInv =: dyad def 'x y&|@^ <: 5 p: y'"0 |
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.
| #Java | Java | System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(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.
| #Clojure | Clojure | (let [size 12
trange (range 1 (inc size))
fmt-width (+ (.length (str (* size size))) 1)
fmt-str (partial format (str "%" fmt-width "s"))
fmt-dec (partial format (str "% " fmt-width "d"))]
(doseq [s (cons
(apply str (fmt-str " ") (map #(fmt-dec %) trange))
(for [i trange]
(apply str (fmt-dec i) (map #(fmt-str (str %))
(map #(if (>= % i) (* i %) " ")
(for [j trange] j))))))]
(println s)))
|
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.
| #Phix | Phix | with javascript_semantics
function multifactorial(integer n, order)
atom res = 1
if n>0 then
res = n*multifactorial(n-order,order)
end if
return res
end function
sequence s = repeat(0,10)
for i=1 to 5 do
for j=1 to 10 do
s[j] = multifactorial(j,i)
end for
pp(s)
end for
|
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
| #Maxima | Maxima | /* translation of Fortran 77, return solutions as permutations */
queens(n) := block([a, i, j, m, p, q, r, s, u, v, w, y, z],
a: makelist(i, i, 1, n), s: a*0, u: makelist(0, i, 1, 4*n - 2),
m: 0, i: 1, r: 2*n - 1, w: [ ], go(L40), L30, s[i]: j, u[p]: 1,
u[q + r]: 1, i: i + 1, L40, if i > n then go(L80), j: i, L50,
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 go(L30), L60, j: j + 1,
if j <= n then go(L50), L70, j: j - 1, if j = i then go(L90),
z: a[i], a[i]: a[j], a[j]: z, go(L70), L80, m: m + 1,
w: endcons(copylist(a), w), L90, i: i - 1, if i = 0 then go(L100),
p: i - a[i] + n, q: i + a[i] - 1, j: s[i], u[p]: 0, u[q + r]: 0,
go(L60), L100, w)$
queens(8); /* [[1, 5, 8, 6, 3, 7, 2, 4],
[1, 6, 8, 3, 7, 4, 2, 5],
...]] */
length(%); /* 92 */ |
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.
| #Rust | Rust | fn nth(num: isize) -> String {
format!("{}{}", num, match (num % 10, num % 100) {
(1, 11) | (2, 12) | (3, 13) => "th",
(1, _) => "st",
(2, _) => "nd",
(3, _) => "rd",
_ => "th",
})
}
fn main() {
let ranges = [(0, 26), (250, 266), (1000, 1026)];
for &(s, e) in &ranges {
println!("[{}, {}) :", s, e);
for i in s..e {
print!("{}, ", nth(i));
}
println!();
}
} |
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
| #VBA | VBA |
Option Explicit
Sub Main_Munchausen_numbers()
Dim i&
For i = 1 To 5000
If IsMunchausen(i) Then Debug.Print i & " is a munchausen number."
Next i
End Sub
Function IsMunchausen(Number As Long) As Boolean
Dim Digits, i As Byte, Tot As Long
Digits = Split(StrConv(Number, vbUnicode), Chr(0))
For i = 0 To UBound(Digits) - 1
Tot = (Digits(i) ^ Digits(i)) + Tot
Next i
IsMunchausen = (Tot = Number)
End Function
|
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).
| #MiniScript | MiniScript | f = function(n)
if n > 0 then return n - m(f(n - 1))
return 1
end function
m = function(n)
if n > 0 then return n - f(m(n - 1))
return 0
end function
print f(12)
print m(12) |
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #J | J | piMC=: monad define "0
4* y%~ +/ 1>: %: +/ *: <: +: (2,y) ?@$ 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
| #Java | Java | public class MC {
public static void main(String[] args) {
System.out.println(getPi(10000));
System.out.println(getPi(100000));
System.out.println(getPi(1000000));
System.out.println(getPi(10000000));
System.out.println(getPi(100000000));
}
public static double getPi(int numThrows){
int inCircle= 0;
for(int i= 0;i < numThrows;i++){
//a square with a side of length 2 centered at 0 has
//x and y range of -1 to 1
double randX= (Math.random() * 2) - 1;//range -1 to 1
double randY= (Math.random() * 2) - 1;//range -1 to 1
//distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
double dist= Math.sqrt(randX * randX + randY * randY);
//^ or in Java 1.5+: double dist= Math.hypot(randX, randY);
if(dist < 1){//circle with diameter of 2 has radius of 1
inCircle++;
}
}
return 4.0 * inCircle / numThrows;
}
} |
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.)
| #VBScript | VBScript | Function mtf_encode(s)
'create the array list and populate it with the initial symbol position
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122 'a to z in decimal.
symbol_table.Add Chr(j)
Next
output = ""
For i = 1 To Len(s)
char = Mid(s,i,1)
If i = Len(s) Then
output = output & symbol_table.IndexOf(char,0)
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
Else
output = output & symbol_table.IndexOf(char,0) & " "
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_encode = output
End Function
Function mtf_decode(s)
'break the function argument into an array
code = Split(s," ")
'create the array list and populate it with the initial symbol position
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122 'a to z in decimal.
symbol_table.Add Chr(j)
Next
output = ""
For i = 0 To UBound(code)
char = symbol_table(code(i))
output = output & char
If code(i) <> 0 Then
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_decode = output
End Function
'Testing the functions
wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
mtf_decode(mtf_encode(word)) & "."
WScript.StdOut.WriteBlankLines(1)
Next |
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).
| #Forth | Forth |
HEX
\ PC speaker hardware control (requires GIVEIO or DOSBOX for windows operation)
042 constant fctrl
043 constant tctrl
061 constant sctrl
0FC constant smask
\ PC@ is Port char fetch (Intel IN instruction). PC! is port char store (Intel OUT instruction)
: speak ( -- ) sctrl pc@ 03 or sctrl pc! ;
: silence ( -- ) sctrl pc@ smask and 01 or sctrl pc! ;
: tone ( freq -- ) \ freq is actually just a divisor value
?dup \ check for non-zero input
if 0B6 tctrl pc! \ enable PC speaker
dup fctrl pc! \ set freq
8 rshift fctrl pc!
speak
else
silence
then ;
\ morse demonstration begins here
DECIMAL
1000 value freq \ arbitrary value that sounded ok
90 value adit \ 1 dit will be 90 ms
: dit_dur adit ms ;
: dah_dur adit 3 * ms ;
: wordgap adit 5 * ms ;
: off_dur adit 2/ ms ;
: lettergap dah_dur ;
: sound ( -- ) freq tone ;
: MORSE-EMIT ( char -- )
dup bl = \ check for space character
if
wordgap drop \ and delay if detected
else
pad C! \ write char to buffer
pad 1 evaluate \ evaluate 1 character
lettergap \ pause for correct sounding morse code
then ;
: TRANSMIT ( ADDR LEN -- )
cr \ newline,
bounds \ convert loop indices to address ranges
do
I C@ dup emit \ dup and send char to console
morse-emit \ send the morse code
loop ;
VOCABULARY MORSE \ prevent name conflicts with letters and numbers
MORSE DEFINITIONS \ the following definitions go into MORSE namespace
: . ( -- ) sound dit_dur silence off_dur ;
: - ( -- ) sound dah_dur silence off_dur ;
\ define morse letters as Forth words. They transmit when executed
: 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 - - - - . ;
: ' - . . - . ;
: \ . - - - . ;
: ! . - . - . ;
: ? . . - - . . ;
: , - - . . - - ;
: / - . . - . ;
: . . - . - . - ;
PREVIOUS DEFINITIONS \ go back to previous namespace
: TRANSMIT MORSE TRANSMIT PREVIOUS ; |
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.
| #Erlang | Erlang | -module(monty_hall).
-export([main/0]).
main() ->
random:seed(now()),
{WinStay, WinSwitch} = experiment(100000, 0, 0),
io:format("Switching wins ~p times.\n", [WinSwitch]),
io:format("Staying wins ~p times.\n", [WinStay]).
experiment(0, WinStay, WinSwitch) ->
{WinStay, WinSwitch};
experiment(N, WinStay, WinSwitch) ->
Doors = setelement(random:uniform(3), {0,0,0}, 1),
SelectedDoor = random:uniform(3),
OpenDoor = open_door(Doors, SelectedDoor),
experiment(
N - 1,
WinStay + element(SelectedDoor, Doors),
WinSwitch + element(6 - (SelectedDoor + OpenDoor), Doors) ).
open_door(Doors,SelectedDoor) ->
OpenDoor = random:uniform(3),
case (element(OpenDoor, Doors) =:= 1) or (OpenDoor =:= SelectedDoor) of
true -> open_door(Doors, SelectedDoor);
false -> OpenDoor
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.
| #JavaScript | JavaScript | var modInverse = function(a, b) {
a %= b;
for (var x = 1; x < b; x++) {
if ((a*x)%b == 1) {
return x;
}
}
} |
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.
| #jq | jq | # Integer division:
# If $j is 0, then an error condition is raised;
# otherwise, assuming infinite-precision integer arithmetic,
# if the input and $j are integers, then the result will be an integer.
def idivide($j):
. as $i
| ($i % $j) as $mod
| ($i - $mod) / $j ;
# the multiplicative inverse of . modulo $n
def modInv($n):
if $n == 1 then 1
else . as $this
| { r : $n,
t : 0,
newR: length, # abs
newT: 1}
| until(.newR == 0;
.newR as $newR
| (.r | idivide($newR)) as $q
| {r : $newR,
t : .newT,
newT: (.t - $q * .newT),
newR: (.r - $q * $newR) } )
| if (.r|length) != 1 then "\($this) and \($n) are not co-prime." | error
else .t
| if . < 0 then . + $n
elif $this < 0 then - .
else .
end
end
end ;
# Example:
42 | modInv(2017)
|
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #COBOL | COBOL | identification division.
program-id. multiplication-table.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 multiplication.
05 rows occurs 12 times.
10 colm occurs 12 times.
15 num pic 999.
77 cand pic 99.
77 ier pic 99.
77 ind pic z9.
77 show pic zz9.
procedure division.
sample-main.
perform varying cand from 1 by 1 until cand greater than 12
after ier from 1 by 1 until ier greater than 12
multiply cand by ier giving num(cand, ier)
end-perform
perform varying cand from 1 by 1 until cand greater than 12
move cand to ind
display "x " ind "| " with no advancing
perform varying ier from 1 by 1 until ier greater than 12
if ier greater than or equal to cand then
move num(cand, ier) to show
display show with no advancing
if ier equal to 12 then
display "|"
else
display space with no advancing
end-if
else
display " " with no advancing
end-if
end-perform
end-perform
goback.
end program multiplication-table.
|
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.
| #Picat | Picat | multifactorial(N,Degree) = prod([ I : I in N..-Degree..1]). |
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.
| #PicoLisp | PicoLisp | (de multifact (N Deg)
(let Res N
(while (> N Deg)
(setq Res (* Res (dec 'N Deg))) )
Res ) )
(for I 5
(prin "Degree " I ":")
(for J 10
(prin " " (multifact J I)) )
(prinl) ) |
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
| #MiniZinc | MiniZinc | int: n;
array [1..n] of var 1..n: q; % queen in column i is in row q[i]
include "alldifferent.mzn";
constraint alldifferent(q); % distinct rows
constraint alldifferent([ q[i] + i | i in 1..n]); % distinct diagonals
constraint alldifferent([ q[i] - i | i in 1..n]); % upwards+downwards
% search
solve :: int_search(q, first_fail, indomain_min)
satisfy;
output [ if fix(q[j]) == i then "Q" else "." endif ++
if j == n then "\n" else "" endif | i,j in 1..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.
| #Scala | Scala | object Nth extends App {
def abbrevNumber(i: Int) = print(s"$i${ordinalAbbrev(i)} ")
def ordinalAbbrev(n: Int) = {
val ans = "th" //most of the time it should be "th"
if (n % 100 / 10 == 1) ans //teens are all "th"
else (n % 10) match {
case 1 => "st"
case 2 => "nd"
case 3 => "rd"
case _ => ans
}
}
(0 to 25).foreach(abbrevNumber)
println()
(250 to 265).foreach(abbrevNumber)
println();
(1000 to 1025).foreach(abbrevNumber)
} |
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
| #VBScript | VBScript |
for i = 1 to 5000
if Munch(i) Then
Wscript.Echo i, "is a Munchausen number"
end if
next
'Returns True if num is a Munchausen number. This is true if the sum of
'each digit raised to that digit's power is equal to the given number.
'Example: 3435 = 3^3 + 4^4 + 3^3 + 5^5
Function Munch (num)
dim str: str = Cstr(num) 'input num as a string
dim sum: sum = 0 'running sum of n^n
dim i 'loop index
dim n 'extracted digit
for i = 1 to len(str)
n = CInt(Mid(str,i,1))
sum = sum + n^n
next
Munch = (sum = num)
End Function
|
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).
| #MiniZinc | MiniZinc |
function var int: F(var int:n) =
if n == 0 then
1
else
n - M(F(n - 1))
endif;
function var int: M(var int:n) =
if (n == 0) then
0
else
n - F(M(n - 1))
endif;
|
http://rosettacode.org/wiki/Monte_Carlo_methods | Monte Carlo methods | A Monte Carlo Simulation is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #JavaScript | JavaScript | 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;
}
console.log(mcpi(1000));
console.log(mcpi(10000));
console.log(mcpi(100000));
console.log(mcpi(1000000));
console.log(mcpi(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
| #jq | jq | # In case gojq is used, trim leading 0s:
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
}
prng | jq -nMr -f program.jq |
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.)
| #Wren | Wren | import "/fmt" for Fmt
import "/seq" for Lst
var encode = Fn.new { |s|
if (s.isEmpty) return []
var symbols = "abcdefghijklmnopqrstuvwxyz".toList
var result = List.filled(s.count, 0)
var i = 0
for (c in s) {
var index = Lst.indexOf(symbols, c)
if (index == -1) Fiber.abort("%(s) contains a non-alphabetic character")
result[i] = index
if (index > 0) {
for (j in index-1..0) symbols[j + 1] = symbols[j]
symbols[0] = c
}
i = i + 1
}
return result
}
var decode = Fn.new { |a|
if (a.isEmpty) return ""
var symbols = "abcdefghijklmnopqrstuvwxyz".toList
var result = List.filled(a.count, "")
var i = 0
for (n in a) {
if (n < 0 || n > 25) Fiber.abort("%(a) contains an invalid number")
result[i] = symbols[n]
if (n > 0) {
for (j in n-1..0) symbols[j + 1] = symbols[j]
symbols[0] = result[i]
}
i = i + 1
}
return result.join()
}
var strings = ["broood", "bananaaa", "hiphophiphop"]
var encoded = List.filled(strings.count, null)
var i = 0
for (s in strings) {
encoded[i] = encode.call(s)
Fmt.print("$-12s -> $n", s, encoded[i])
i = i + 1
}
System.print()
var decoded = List.filled(encoded.count, null)
i = 0
for (a in encoded) {
decoded[i] = decode.call(a)
var correct = (decoded[i] == strings[i]) ? "correct" : "incorrect"
Fmt.print("$-38n -> $-12s -> $s", a, decoded[i], correct)
i = i + 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).
| #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64
' Using Beep function in Win32 API
Dim As Any Ptr library = DyLibLoad("kernel32")
Dim Shared beep_ As Function (ByVal As ULong, ByVal As ULong) As Long
beep_ = DyLibSymbol(library, "Beep")
Sub playMorse(m As String)
For i As Integer = 0 To Len(m) - 1
If m[i] = 46 Then '' ascii code for dot
beep_(1000, 250)
Else '' must be ascii code for dash (45)
beep_(1000, 750)
End If
Sleep 50
Next
Sleep 150
End Sub
Dim morse(0 To 35) As String => _
{ _
".-", _ '' 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
}
Dim s As String = "The quick brown fox"
For i As Integer = 0 To Len(s) -1
Select Case As Const s[i]
Case 65 To 90 '' A - Z
playMorse(morse(s[i] - 65))
Case 97 To 122 '' a - z
playMorse(morse(s[i] - 97))
Case 48 To 57 '' 0 - 9
playMorse(morse(s[i] - 22))
Case Else
'' ignore any other character
Sleep 250
End Select
Next
DyLibFree(library)
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.
| #Euphoria | Euphoria | integer switchWins, stayWins
switchWins = 0
stayWins = 0
integer winner, choice, shown
for plays = 1 to 10000 do
winner = rand(3)
choice = rand(3)
while 1 do
shown = rand(3)
if shown != winner and shown != choice then
exit
end if
end while
stayWins += choice = winner
switchWins += 6-choice-shown = winner
end for
printf(1, "Switching wins %d times\n", switchWins)
printf(1, "Staying wins %d times\n", stayWins)
|
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.
| #Julia | Julia | invmod(a, b) |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Kotlin | Kotlin | // version 1.0.6
import java.math.BigInteger
fun main(args: Array<String>) {
val a = BigInteger.valueOf(42)
val m = BigInteger.valueOf(2017)
println(a.modInverse(m))
} |
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.
| #CoffeeScript | CoffeeScript |
print_multiplication_tables = (n) ->
width = 4
pad = (s, n=width, c=' ') ->
s = s.toString()
result = ''
padding = n - s.length
while result.length < padding
result += c
result + s
s = pad('') + '|'
for i in [1..n]
s += pad i
console.log s
s = pad('', width, '-') + '+'
for i in [1..n]
s += pad '', width, '-'
console.log s
for i in [1..n]
s = pad i
s += '|'
s += pad '', width*(i - 1)
for j in [i..n]
s += pad i*j
console.log s
print_multiplication_tables 12
|
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #PL.2FI | PL/I |
multi: procedure options (main); /* 29 October 2013 */
declare (i, j, n) fixed binary;
declare text character (6) static initial ('n!!!!!');
do i = 1 to 5;
put skip edit (substr(text, 1, i+1), '=' ) (A, COLUMN(8));
do n = 1 to 10;
put edit ( trim( multifactorial(n,i) ) ) (X(1), A);
end;
end;
multifactorial: procedure (n, j) returns (fixed(15));
declare (n, j) fixed binary;
declare f fixed (15), m fixed(15);
f, m = n;
do while (m > j); f = f * (m-fixed(j)); m = m - j; end;
return (f);
end multifactorial;
end multi;
|
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.
| #Plain_TeX | Plain TeX | \long\def\antefi#1#2\fi{#2\fi#1}
\def\fornum#1=#2to#3(#4){%
\edef#1{\number\numexpr#2}\edef\fornumtemp{\noexpand\fornumi\expandafter\noexpand\csname fornum\string#1\endcsname
{\number\numexpr#3}{\ifnum\numexpr#4<0 <\else>\fi}{\number\numexpr#4}\noexpand#1}\fornumtemp
}
\long\def\fornumi#1#2#3#4#5#6{\def#1{\unless\ifnum#5#3#2\relax\antefi{#6\edef#5{\number\numexpr#5+(#4)\relax}#1}\fi}#1}
\newcount\result
\def\multifact#1#2{%
\result=1
\fornum\multifactiter=#1 to 1(-#2){\multiply\result\multifactiter}%
\number\result
}
\fornum\degree=1 to 5(+1){Degree \degree: \fornum\ii=1 to 10(+1){\multifact\ii\degree\space\space}\par}
\bye |
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
| #Modula-2 | Modula-2 | MODULE NQueens;
FROM InOut IMPORT Write, WriteCard, WriteString, WriteLn;
CONST N = 8;
VAR hist: ARRAY [0..N-1] OF CARDINAL;
count: CARDINAL;
PROCEDURE Solve(n, col: CARDINAL);
VAR i, j: CARDINAL;
PROCEDURE Attack(i, j: CARDINAL): BOOLEAN;
VAR diff: CARDINAL;
BEGIN
IF hist[j] = i THEN RETURN TRUE;
ELSE
IF hist[j] < i THEN diff := i - hist[j];
ELSE diff := hist[j] - i;
END;
RETURN diff = col-j;
END;
END Attack;
BEGIN
IF col = n THEN
INC(count);
WriteLn;
WriteString("No. ");
WriteCard(count, 0);
WriteLn;
WriteString("---------------");
WriteLn;
FOR i := 0 TO n-1 DO
FOR j := 0 TO n-1 DO
IF j = hist[i] THEN Write('Q');
ELSIF (i + j) MOD 2 = 1 THEN Write(' ');
ELSE Write('.');
END;
END;
WriteLn;
END;
ELSE
FOR i := 0 TO n-1 DO
j := 0;
WHILE (j < col) AND (NOT Attack(i,j)) DO INC(j); END;
IF j >= col THEN
hist[col] := i;
Solve(n, col+1);
END;
END;
END;
END Solve;
BEGIN
count := 0;
Solve(N, 0);
END NQueens. |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.