task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Prolog | Prolog | nth(N, N_Th) :-
( tween(N) -> Th = "th"
; 1 is N mod 10 -> Th = "st"
; 2 is N mod 10 -> Th = "nd"
; 3 is N mod 10 -> Th = "rd"
; Th = "th" ),
string_concat(N, Th, N_Th).
tween(N) :- Tween is N mod 100, between(11, 13, Tween).
test :-
forall( between(0,25, N), (nth(N, N_Th), format('~w, ', N_Th)) ),
nl, nl,
forall( between(250,265,N), (nth(N, N_Th), format('~w, ', N_Th)) ),
nl, nl,
forall( between(1000,1025,N), (nth(N, N_Th), format('~w, ', N_Th)) ).
|
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
| #Quackery | Quackery | [ dup 0 swap
[ dup 0 != while
10 /mod dup **
rot + swap again ]
drop = ] is munchausen ( n --> b )
5000 times
[ i^ 1+ munchausen if
[ i^ 1+ echo sp ] ] |
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).
| #Logo | Logo | to m :n
if 0 = :n [output 0]
output :n - f m :n-1
end
to f :n
if 0 = :n [output 1]
output :n - m f :n-1
end
show cascade 20 [lput m #-1 ?] []
[1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12]
show cascade 20 [lput f #-1 ?] []
[0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12] |
http://rosettacode.org/wiki/Monads/Maybe_monad | Monads/Maybe monad | Demonstrate in your programming language the following:
Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #REXX | REXX | /*REXX program mimics a bind operation when trying to perform addition upon arguments. */
call add 1, 2
call add 1, 2.0
call add 1, 2.0, -6
call add self, 2
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
add: void= 'VOID'; f= /*define in terms of a function&binding*/
do j=1 for arg() /*process, classify, bind each argument*/
call bind( arg(j) ); f= f arg(j)
end /*j*/
say
say 'adding' f; call sum f /*telegraph what's being performed next*/
return /*Note: REXX treats INT & FLOAT as num.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
bind: arg a; type.a= datatype(a); return /*bind argument's kind with its "type".*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
sum: parse arg a; $= 0 /*sum all arguments that were specified*/
do k=1 for words(a); ?= word(a, k)
if type.?==num & $\==void then $= ($ + word(a, k)) / 1
else $= void
end /*k*/
say 'sum=' $
return $ |
http://rosettacode.org/wiki/Monads/Maybe_monad | Monads/Maybe monad | Demonstrate in your programming language the following:
Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #Ruby | Ruby | class Maybe
def initialize(value)
@value = value
end
def map
if @value.nil?
self
else
Maybe.new(yield @value)
end
end
end
Maybe.new(3).map { |n| 2*n }.map { |n| n+1 }
#=> #<Maybe @value=7>
Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 }
#=> #<Maybe @value=nil>
Maybe.new(3).map { |n| nil }.map { |n| n+1 }
#=> #<Maybe @value=nil>
# alias Maybe#new and write bind to be in line with task
class Maybe
class << self
alias :unit :new
end
def initialize(value)
@value = value
end
def bind
if @value.nil?
self
else
yield @value
end
end
end
Maybe.unit(3).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) }
#=> #<Maybe @value=7>
Maybe.unit(nil).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) }
#=> #<Maybe @value=nil>
|
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
| #Dart | Dart |
import 'dart:async';
import 'dart:html';
import 'dart:math' show Random;
// We changed 5 lines of code to make this sample nicer on
// the web (so that the execution waits for animation frame,
// the number gets updated in the DOM, and the program ends
// after 500 iterations).
main() async {
print('Compute π using the Monte Carlo method.');
var output = querySelector("#output");
await for (var estimate in computePi().take(500)) {
print('π ≅ $estimate');
output.text = estimate.toStringAsFixed(5);
await window.animationFrame;
}
}
/// Generates a stream of increasingly accurate estimates of π.
Stream<double> computePi({int batch: 100000}) async* {
var total = 0;
var count = 0;
while (true) {
var points = generateRandom().take(batch);
var inside = points.where((p) => p.isInsideUnitCircle);
total += batch;
count += inside.length;
var ratio = count / total;
// Area of a circle is A = π⋅r², therefore π = A/r².
// So, when given random points with x ∈ <0,1>,
// y ∈ <0,1>, the ratio of those inside a unit circle
// should approach π / 4. Therefore, the value of π
// should be:
yield ratio * 4;
}
}
Iterable<Point> generateRandom([int seed]) sync* {
final random = new Random(seed);
while (true) {
yield new Point(random.nextDouble(), random.nextDouble());
}
}
class Point {
final double x, y;
const Point(this.x, this.y);
bool get isInsideUnitCircle => x * x + y * y <= 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
| #E | E | def pi(n) {
var inside := 0
for _ ? (entropy.nextFloat() ** 2 + entropy.nextFloat() ** 2 < 1) in 1..n {
inside += 1
}
return inside * 4 / 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.)
| #Picat | Picat | import util.
go =>
Strings = ["broood", "bananaaa", "hiphophiphop"],
foreach(String in Strings)
check(String)
end,
nl.
% adjustments to 1-based index
encode(String) = [Pos,Table] =>
Table = "abcdefghijklmnopqrstuvwxyz",
Pos = [],
Len = String.length,
foreach({C,I} in zip(String,1..Len))
Pos := Pos ++ [find_first_of(Table,C)-1],
if Len > I then
Table := [C] ++ delete(Table,C)
end
end.
decode(Pos) = String =>
Table = "abcdefghijklmnopqrstuvwxyz",
String = [],
foreach(P in Pos)
C = Table[P+1],
Table := [C] ++ delete(Table,C),
String := String ++ [C]
end.
% Check the result
check(String) =>
[Pos,Table] = encode(String),
String2 = decode(Pos),
if length(String) < 100 then
println(pos=Pos),
println(table=Table),
println(string2=String2)
else
printf("String is too long to print (%d chars)\n", length(String))
end,
println(cond(String != String2, "not ", "") ++ "same"),
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.)
| #PicoLisp | PicoLisp | (de encode (Str)
(let Table (chop "abcdefghijklmnopqrstuvwxyz")
(mapcar
'((C)
(dec
(prog1
(index C Table)
(rot Table @) ) ) )
(chop Str) ) ) )
(de decode (Lst)
(let Table (chop "abcdefghijklmnopqrstuvwxyz")
(pack
(mapcar
'((N)
(prog1
(get Table (inc 'N))
(rot Table N) ) )
Lst ) ) ) ) |
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).
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace Morse
{
class Morse
{
static void Main(string[] args)
{
string word = "sos";
Dictionary<string, string> Codes = new Dictionary<string, 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", "----."}
};
foreach (char c in word.ToCharArray())
{
string rslt = Codes[c.ToString()].Trim();
foreach (char c2 in rslt.ToCharArray())
{
if (c2 == '.')
Console.Beep(1000, 250);
else
Console.Beep(1000, 750);
}
System.Threading.Thread.Sleep(50);
}
}
}
}
|
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.
| #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
int switchWins = 0;
int stayWins = 0;
Random gen = new Random();
for(int plays = 0; plays < 1000000; plays++ )
{
int[] doors = {0,0,0};//0 is a goat, 1 is a car
var winner = gen.Next(3);
doors[winner] = 1; //put a winner in a random door
int choice = gen.Next(3); //pick a door, any door
int shown; //the shown door
do
{
shown = gen.Next(3);
}
while (doors[shown] == 1 || shown == choice); //don't show the winner or the choice
stayWins += doors[choice]; //if you won by staying, count it
//the switched (last remaining) door is (3 - choice - shown), because 0+1+2=3
switchWins += doors[3 - choice - shown];
}
Console.Out.WriteLine("Staying wins " + stayWins + " times.");
Console.Out.WriteLine("Switching wins " + switchWins + " times.");
}
} |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #D | D | T modInverse(T)(T a, T b) pure nothrow {
if (b == 1)
return 1;
T b0 = b,
x0 = 0,
x1 = 1;
while (a > 1) {
immutable q = a / b;
auto t = b;
b = a % b;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
return (x1 < 0) ? (x1 + b0) : x1;
}
void main() {
import std.stdio;
writeln(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.
| #dc | dc |
dc -e "[m=]P?dsm[a=]P?dsa1sv[dsb~rsqlbrldlqlv*-lvsdsvd0<x]dsxxldd[dlmr+]sx0>xdla*lm%[p]sx1=x"
|
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #BASIC256 | BASIC256 | print " X| 1 2 3 4 5 6 7 8 9 10 11 12"
print "---+------------------------------------------------"
for i = 1 to 12
nums$ = right(" " + string(i), 3) + "|"
for j = 1 to 12
if i <= j then
if j >= 1 then
nums$ += left(" ", (4 - length(string(i * j))))
end if
nums$ += string(i * j)
else
nums$ += " "
end if
next j
print nums$
next i |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #Wren | Wren | import "/matrix" for Matrix
var multipleRegression = Fn.new { |y, x|
var cy = y.transpose
var cx = x.transpose
return ((x * cx).inverse * x * cy).transpose[0]
}
var ys = [
Matrix.new([ [1, 2, 3, 4, 5] ]),
Matrix.new([ [3, 4, 5] ]),
Matrix.new([ [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29,
63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46] ])
]
var a = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83]
var xs = [
Matrix.new([ [2, 1, 3, 4, 5] ]),
Matrix.new([ [1, 2, 1], [1, 1, 2] ]),
Matrix.new([ List.filled(a.count, 1), a, a.map { |e| e * e }.toList ])
]
for (i in 0...ys.count) {
var v = multipleRegression.call(ys[i], xs[i])
System.print(v)
System.print()
} |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #JavaScript | JavaScript |
function multifact(n, deg){
var result = n;
while (n >= deg + 1){
result *= (n - deg);
n -= deg;
}
return result;
}
|
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.
| #jq | jq | # Input: n
# Output: n * (n - d) * (n - 2d) ...
def multifactorial(d):
. as $n
| ($n / d | floor) as $k
| reduce ($n - (d * range(0; $k))) as $i (1; . * $i); |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Raku | Raku | use java::awt::MouseInfo:from<java>;
given MouseInfo.getPointerInfo.getLocation {
say .getX, 'x', .getY;
} |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Ring | Ring |
Load "guilib.ring"
lPress = false
nX = 0
nY = 0
new qApp {
win1 = new qWidget()
{
setWindowTitle("Move this label!")
setGeometry(100,100,400,400)
setstylesheet("background-color:white;")
Label1 = new qLabel(Win1){
setGeometry(100,100,200,50)
setText("Welcome")
setstylesheet("font-size: 30pt")
myfilter = new qallevents(label1)
myfilter.setEnterevent("pEnter()")
myfilter.setLeaveevent("pLeave()")
myfilter.setMouseButtonPressEvent("pPress()")
myfilter.setMouseButtonReleaseEvent("pRelease()") myfilter.setMouseMoveEvent("pMove()")
installeventfilter(myfilter)
}
show()
}
exec()
}
Func pEnter
Label1.setStyleSheet("background-color: purple; color:white;font-size: 30pt;")
Func pLeave
Label1.setStyleSheet("background-color: white; color:black;font-size: 30pt;")
Func pPress
lPress = True
nX = myfilter.getglobalx()
ny = myfilter.getglobaly()
Func pRelease
lPress = False
pEnter()
Func pMove
nX2 = myfilter.getglobalx()
ny2 = myfilter.getglobaly()
ndiffx = nX2 - nX
ndiffy = nY2 - nY
if lPress
Label1 {
move(x()+ndiffx,y()+ndiffy)
setStyleSheet("background-color: Green;
color:white;font-size: 30pt;")
nX = nX2
ny = nY2
}
ok
|
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
| #Kotlin | Kotlin | // version 1.1.3
var count = 0
var c = IntArray(0)
var f = ""
fun nQueens(row: Int, n: Int) {
outer@ for (x in 1..n) {
for (y in 1..row - 1) {
if (c[y] == x) continue@outer
if (row - y == Math.abs(x - c[y])) continue@outer
}
c[row] = x
if (row < n) nQueens(row + 1, n)
else if (++count == 1) f = c.drop(1).map { it - 1 }.toString()
}
}
fun main(args: Array<String>) {
for (n in 1..14) {
count = 0
c = IntArray(n + 1)
f = ""
nQueens(1, n)
println("For a $n x $n board:")
println(" Solutions = $count")
if (count > 0) println(" First is $f")
println()
}
} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #PureBasic | PureBasic | Procedure.s Suffix(n.i)
Select n%10
Case 1 : If n%100<>11 : ProcedureReturn "st" : EndIf
Case 2 : If n%100<>12 : ProcedureReturn "nd" : EndIf
Case 3 : If n%100<>13 : ProcedureReturn "rd" : EndIf
EndSelect
ProcedureReturn "th"
EndProcedure
Procedure put(a.i,b.i)
For i=a To b : Print(Str(i)+Suffix(i)+" ") : Next
PrintN("")
EndProcedure
If OpenConsole()=0 : End 1 : EndIf
put(0,25)
put(250,265)
put(1000,1025)
Input() |
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
| #Racket | Racket | #lang racket
(define (expt:0^0=1 r p)
(if (zero? r) 0 (expt r p)))
(define (munchausen-number? n (t n))
(if (zero? n)
(zero? t)
(let-values (([q r] (quotient/remainder n 10)))
(munchausen-number? q (- t (expt:0^0=1 r r))))))
(module+ main
(for-each displayln (filter munchausen-number? (range 1 (add1 5000)))))
(module+ test
(require rackunit)
;; this is why we have the (if (zero? r)...) test
(check-equal? (expt 0 0) 1)
(check-equal? (expt:0^0=1 0 0) 0)
(check-equal? (expt:0^0=1 0 4) 0)
(check-equal? (expt:0^0=1 3 4) (expt 3 4))
;; given examples
(check-true (munchausen-number? 1))
(check-true (munchausen-number? 3435))
(check-false (munchausen-number? 3))
(check-false (munchausen-number? -45) "no recursion on -ve numbers")) |
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).
| #LSL | LSL | integer iDEPTH = 100;
integer f(integer n) {
if(n==0) {
return 1;
} else {
return n-m(f(n - 1));
}
}
integer m(integer n) {
if(n==0) {
return 0;
} else {
return n-f(m(n - 1));
}
}
default {
state_entry() {
integer x = 0;
string s = "";
for(x=0 ; x<iDEPTH ; x++) {
s += (string)(f(x))+" ";
}
llOwnerSay(llList2CSV(llParseString2List(s, [" "], [])));
s = "";
for(x=0 ; x<iDEPTH ; x++) {
s += (string)(m(x))+" ";
}
llOwnerSay(llList2CSV(llParseString2List(s, [" "], [])));
}
} |
http://rosettacode.org/wiki/Monads/Maybe_monad | Monads/Maybe monad | Demonstrate in your programming language the following:
Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #Wren | Wren | import "/fmt" for Fmt
class Maybe {
construct new(value) {
_value = value
}
value { _value }
bind(f) { f.call(_value) }
static unit(i) { Maybe.new(i) }
}
var decrement = Fn.new { |i|
if (!i) return Maybe.unit(null)
return Maybe.unit(i - 1)
}
var triple = Fn.new { |i|
if (!i) return Maybe.unit(null)
return Maybe.unit(3 * i)
}
for (i in [3, 4, null, 5]) {
var m1 = Maybe.unit(i)
var m2 = m1.bind(decrement).bind(triple)
var s1 = (m1.value) ? "%(m1.value)" : "none"
var s2 = (m2.value) ? "%(m2.value)" : "none"
System.print("%(Fmt.s(4, s1)) -> %(s2)")
} |
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
| #EasyLang | EasyLang | func mc n . .
for i range n
x = randomf
y = randomf
if x * x + y * y < 1
hit += 1
.
.
print 4.0 * hit / n
.
fscale 4
call mc 10000
call mc 100000
call mc 1000000
call mc 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
| #Elixir | Elixir | defmodule MonteCarlo do
def pi(n) do
count = Enum.count(1..n, fn _ ->
x = :rand.uniform
y = :rand.uniform
:math.sqrt(x*x + y*y) <= 1
end)
4 * count / n
end
end
Enum.each([1000, 10000, 100000, 1000000, 10000000], fn n ->
:io.format "~8w samples: PI = ~f~n", [n, MonteCarlo.pi(n)]
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.)
| #PL.2FI | PL/I | *process source attributes xref or(!);
/*********************************************************************
* 25.5.2014 Walter Pachl translated from REXX
*********************************************************************/
ed: Proc Options(main);
Call enc_dec('broood');
Call enc_dec('bananaaa');
Call enc_dec('hiphophiphop');
enc_dec: Proc(in);
Dcl in Char(*);
Dcl out Char(20) Var Init('');
Dcl st Char(26) Init('abcdefghijklmnopqrstuvwxyz');
Dcl sta Char(26) Init((st));
Dcl enc(20) Bin Fixed(31);
Dcl encn Bin Fixed(31) Init(0);
Dcl (i,p.k) Bin Fixed(31);
Dcl c Char(1);
Do i=1 To length(in);
c=substr(in,i,1);
p=index(st,c);
encn+=1;
enc(encn)=p-1;
st=c!!left(st,p-1)!!substr(st,p+1);
End;
Put Skip List(' in='!!in);
Put Skip List('sta='!!sta!!' original symbol table');
Put Skip Edit('enc=',(enc(i) do i=1 To encn))(a,20(F(3)));
Put Skip List(' st='!!st!!' symbol table after encoding');
Do i=1 To encn;
k=enc(i)+1;
out=out!!substr(sta,k,1);
sta=substr(sta,k,1)!!left(sta,k-1)!!substr(sta,k+1);
End;
Put Skip List('out='!!out);
Put Skip List(' ');
If out=in Then;
Else
Put Skip List('all wrong!!');
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).
| #C.2B.2B | C++ |
/*
Michal Sikorski
06/07/2016
*/
#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
string inpt;
char ascii[28] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ", lwcAscii[28] = " abcdefghijklmnopqrstuvwxyz";
string morse[27] = {" ", ".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. ", "--. ", ".... ", ".. ", ".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--.", "--.- ", ".-. ", "... ", "- ", "..- ", "...- ", ".-- ", "-..- ", "-.-- ", "--.. "};
string outpt;
getline(cin,inpt);
int xx=0;
int size = inpt.length();
cout<<"Length:"<<size<<endl;
xx=0;
while(xx<inpt.length())
{
int x=0;
bool working = false;
while(!working)
{
if(ascii[x] != inpt[xx]&&lwcAscii[x] != inpt[xx])
{
x++;
}
else
{
working = !working;
}
}
cout<<morse[x];
outpt = outpt + morse[x];
xx++;
}
xx=0;
while(xx<outpt.length()+1)
{
if(outpt[xx] == '.')
{
Beep(1000,250);
}
else
{
if(outpt[xx] == '-')
{
Beep(1000,500);
}
else
{
if(outpt[xx] == ' ')
{
Sleep(500);
}
}
}
xx++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
|
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.
| #C.2B.2B | C++ | #include <iostream>
#include <cstdlib>
#include <ctime>
int randint(int n)
{
return (1.0*n*std::rand())/(1.0+RAND_MAX);
}
int other(int doorA, int doorB)
{
int doorC;
if (doorA == doorB)
{
doorC = randint(2);
if (doorC >= doorA)
++doorC;
}
else
{
for (doorC = 0; doorC == doorA || doorC == doorB; ++doorC)
{
// empty
}
}
return doorC;
}
int check(int games, bool change)
{
int win_count = 0;
for (int game = 0; game < games; ++game)
{
int const winning_door = randint(3);
int const original_choice = randint(3);
int open_door = other(original_choice, winning_door);
int const selected_door = change?
other(open_door, original_choice)
: original_choice;
if (selected_door == winning_door)
++win_count;
}
return win_count;
}
int main()
{
std::srand(std::time(0));
int games = 10000;
int wins_stay = check(games, false);
int wins_change = check(games, true);
std::cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n";
} |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Delphi | Delphi | proc mulinv(int a, b) int:
int t, nt, r, nr, q, tmp;
if b<0 then b := -b fi;
if a<0 then a := b - (-a % b) fi;
t := 0; nt := 1; r := b; nr := a % b;
while nr /= 0 do
q := r / nr;
tmp := nt; nt := t - q*nt; t := tmp;
tmp := nr; nr := r - q*nr; r := tmp
od;
if r>1 then -1
elif t<0 then t+b
else t
fi
corp
proc show(int a, b) void:
int mi;
mi := mulinv(a, b);
if mi>=0
then writeln(a:5, ", ", b:5, " -> ", mi:5)
else writeln(a:5, ", ", b:5, " -> no inverse")
fi
corp
proc main() void:
show(42, 2017);
show(40, 1);
show(52, -217);
show(-486, 217);
show(40, 2018)
corp |
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.
| #Draco | Draco | proc mulinv(int a, b) int:
int t, nt, r, nr, q, tmp;
if b<0 then b := -b fi;
if a<0 then a := b - (-a % b) fi;
t := 0; nt := 1; r := b; nr := a % b;
while nr /= 0 do
q := r / nr;
tmp := nt; nt := t - q*nt; t := tmp;
tmp := nr; nr := r - q*nr; r := tmp
od;
if r>1 then -1
elif t<0 then t+b
else t
fi
corp
proc show(int a, b) void:
int mi;
mi := mulinv(a, b);
if mi>=0
then writeln(a:5, ", ", b:5, " -> ", mi:5)
else writeln(a:5, ", ", b:5, " -> no inverse")
fi
corp
proc main() void:
show(42, 2017);
show(40, 1);
show(52, -217);
show(-486, 217);
show(40, 2018)
corp |
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.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
::The Main Thing...
cls
set colum=12&set row=12
call :multable
echo.
pause
exit /b 0
::/The Main Thing.
::The Functions...
:multable
echo.
for /l %%. in (1,1,%colum%) do (
call :numstr %%.
set firstline=!firstline!!space!%%.
set seconline=!seconline!-----
)
echo !firstline!
echo !seconline!
::The next lines here until the "goto :EOF" prints the products...
for /l %%X in (1,1,%row%) do (
for /l %%Y in (1,1,%colum%) do (
if %%Y lss %%X (set "line%%X=!line%%X! ") else (
set /a ans=%%X*%%Y
call :numstr !ans!
set "line%%X=!line%%X!!space!!ans!"
)
)
echo.!line%%X! ^| %%X
)
goto :EOF
:numstr
::This function returns the number of whitespaces to be applied on each numbers.
set cnt=0&set proc=%1&set space=
:loop
set currchar=!proc:~%cnt%,1!
if not "!currchar!"=="" set /a cnt+=1&goto loop
set /a numspaces=5-!cnt!
for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
::/The Functions. |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
height:=GSL.VectorFromData(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83);
weight:=GSL.VectorFromData(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93,
61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46);
v:=GSL.polyFit(height,weight,2);
v.format().println();
GSL.Helpers.polyString(v).println();
GSL.Helpers.polyEval(v,height).format().println(); |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Julia | Julia | using Printf
function multifact(n::Integer, k::Integer)
n > 0 && k > 0 || throw(DomainError())
k > 1 || factorial(n)
return prod(n:-k:2)
end
const khi = 5
const nhi = 10
println("Showing multifactorial for n in [1, $nhi] and k in [1, $khi].")
for k = 1:khi
a = multifact.(1:nhi, k)
lab = "n" * "!" ^ k
@printf(" %-6s → %s\n", lab, a)
end |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Kotlin | Kotlin | fun multifactorial(n: Long, d: Int) : Long {
val r = n % d
return (1..n).filter { it % d == r } .reduce { i, p -> i * p }
}
fun main(args: Array<String>) {
val m = 5
val r = 1..10L
for (d in 1..m) {
print("%${m}s:".format( "!".repeat(d)))
r.forEach { print(" " + multifactorial(it, d)) }
println()
}
} |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Ruby | Ruby | Shoes.app(:title => "Mouse Position", :width => 400, :height => 400) do
@position = para "Position : ?, ?", :size => 12, :margin => 10
motion do |x, y|
@position.text = "Position : #{x}, #{y}"
end
end |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Rust | Rust | // rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800)
use std::libc::{BOOL, HANDLE, LONG};
use std::ptr::mut_null;
type HWND = HANDLE;
#[deriving(Eq)]
struct POINT {
x: LONG,
y: LONG
}
#[link_name = "user32"]
extern "system" {
fn GetCursorPos(lpPoint:&mut POINT) -> BOOL;
fn GetForegroundWindow() -> HWND;
fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT);
}
fn main() {
let mut pt = POINT{x:0, y:0};
loop {
std::io::timer::sleep(100); // sleep duration in milliseconds
let pt_prev = pt;
unsafe { GetCursorPos(&mut pt) };
if pt != pt_prev {
let h = unsafe { GetForegroundWindow() };
if h == mut_null() { continue }
let mut pt_client = pt;
unsafe { ScreenToClient(h, &mut pt_client) };
println!("x: {}, y: {}", pt_client.x, pt_client.y);
}
}
} |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Scala | Scala | import java.awt.MouseInfo
object MousePosition extends App {
val mouseLocation = MouseInfo.getPointerInfo.getLocation
println (mouseLocation)
} |
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
| #Liberty_BASIC | Liberty BASIC |
'N queens
'>10 would not work due to way permutations used
'anyway, 10 doesn't fit in memory
Input "Input N for N queens puzzle (4..9) ";N
if N<4 or N>9 then print "N out of range - quitting": end
ABC$= " "
dash$ = ""
for i = 0 to N-1
ABC$=ABC$+" "+chr$(asc("a")+i)
dash$ = dash$+"--"
next
dim q(N)
t0=time$("ms")
fact = 1
for i = 1 to N
fact = fact*i
next
dim anagram$(fact)
global nPerms
print "Filling permutations array"
t0=time$("ms")
res$=permutation$("", left$("0123456789", N))
t1=time$("ms")
print "Created all possible permutations ";t1-t0
t0=time$("ms")
'actually fact = nPerms
for k=1 to nPerms
for i=0 to N-1
q(i)=val(mid$(anagram$(k),i+1,1))
'print q(i);
next
'print
fail = 0
for i=0 to N-1
for j=i+1 to N-1
'check rows are different
if q(i)=q(j) then fail = 1: exit for
'check diagonals are different
if i+q(i)=j+q(j) then fail = 1: exit for
'check other diagonals are different
if i-q(i)=j-q(j) then fail = 1: exit for
next
if fail then exit for
next
if not(fail) then
num=num+1
print " ";dash$
for i=0 to N-1
print N-i; space$(2*q(i));" *"
next
print " ";dash$
print ABC$
end if
next
t1=time$("ms")
print "Time taken ";t1-t0
print "Number of solutions ";num
'----------------------------------
'from
'http://babek.info/libertybasicfiles/lbnews/nl124/wordgames.htm
'Programming a Word Game by Janet Terra,
'The Liberty Basic Newsletter - Issue #124 - September 2004
Function permutation$(pre$, post$)
'Note the variable nPerms must first be stated as a global variable.
lgth = Len(post$)
If lgth < 2 Then
nPerms = nPerms + 1
anagram$(nPerms) = pre$;post$
Else
For i = 1 To lgth
tmp$=permutation$(pre$+Mid$(post$,i,1),Left$(post$,i-1)+Right$(post$,lgth-i))
Next i
End If
End Function
|
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Python | Python | _suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
def nth(n):
return "%i'%s" % (n, _suffix[n%10] if n % 100 <= 10 or n % 100 > 20 else 'th')
if __name__ == '__main__':
for j in range(0,1001, 250):
print(' '.join(nth(i) for i in list(range(j, j+25)))) |
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
| #Raku | Raku | sub is_munchausen ( Int $n ) {
constant @powers = 0, |map { $_ ** $_ }, 1..9;
$n == @powers[$n.comb].sum;
}
.say if .&is_munchausen for 1..5000; |
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).
| #Lua | Lua |
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end |
http://rosettacode.org/wiki/Monads/Maybe_monad | Monads/Maybe monad | Demonstrate in your programming language the following:
Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #zkl | zkl | fcn bind(a,type,b){ if(type.isType(a)) b else Void }
fcn just(x){ if(Deferred.isType(x)) x() else x } // force lazy evaluation
fcn rtn(x) { just(x) } |
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
| #Erlang | Erlang |
-module(monte).
-export([main/1]).
monte(N)->
monte(N,0,0).
monte(0,InCircle,NumPoints) ->
4 * InCircle / NumPoints;
monte(N,InCircle,NumPoints)->
Xcoord = rand:uniform(),
Ycoord = rand:uniform(),
monte(N-1,
if Xcoord*Xcoord + Ycoord*Ycoord < 1 -> InCircle + 1; true -> InCircle end,
NumPoints + 1).
main(N) -> io:format("PI: ~w~n", [ monte(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.)
| #PowerShell | PowerShell | Function Test-MTF
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,Position=0)]
[string]$word,
[Parameter(Mandatory=$false)]
[string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz'
)
Begin
{
Function Encode
{
Param
(
[Parameter(Mandatory=$true,Position=0)]
[string]$word,
[Parameter(Mandatory=$false)]
[string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz'
)
foreach ($letter in $word.ToCharArray())
{
$index = $SymbolTable.IndexOf($letter)
$prop = [ordered]@{
Input = $letter
Output = [int]$index
SymbolTable = $SymbolTable
}
New-Object PSobject -Property $prop
$SymbolTable = $SymbolTable.Remove($index,1).Insert(0,$letter)
}
}
Function Decode
{
Param
(
[Parameter(Mandatory=$true,Position=0)]
[int[]]$index,
[Parameter(Mandatory=$false)]
[string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz'
)
foreach ($i in $index)
{
#Write-host $i -ForegroundColor Red
$letter = $SymbolTable.Chars($i)
$prop = [ordered]@{
Input = $i
Output = $letter
SymbolTable = $SymbolTable
}
New-Object PSObject -Property $prop
$SymbolTable = $SymbolTable.Remove($i,1).Insert(0,$letter)
}
}
}
Process
{
#Encoding
Write-Host "Encoding $word" -NoNewline
$Encoded = (Encode -word $word).output
Write-Host -NoNewline ": $($Encoded -join ',')"
#Decoding
Write-Host "`nDecoding $($Encoded -join ',')" -NoNewline
$Decoded = (Decode -index $Encoded).output -join ''
Write-Host -NoNewline ": $Decoded`n"
}
End{}
} |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow (e.g. with a different pitch).
| #Clojure | Clojure | (import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\A ".-" \J ".---" \S "..." \1 ".----" \. ".-.-.-" \: "---..."
\B "-..." \K "-.-" \T "-" \2 "..---" \, "--..--" \; "-.-.-."
\C "-.-." \L ".-.." \U "..-" \3 "...--" \? "..--.." \= "-...-"
\D "-.." \M "--" \V "...-" \4 "....-" \' ".----." \+ ".-.-."
\E "." \N "-." \W ".--" \5 "....." \! "-.-.--" \- "-....-"
\F "..-." \O "---" \X "-..-" \6 "-...." \/ "-..-." \_ "..--.-"
\G "--." \P ".--." \Y "-.--" \7 "--..." \( "-.--." \" ".-..-." ;"
\H "...." \Q "--.-" \Z "--.." \8 "---.." \) "-.--.-" \$ "...-..-"
\I ".." \R ".-." \0 "-----" \9 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))})) ;includes letter-gap on either side
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,))) |
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.
| #Chapel | Chapel | use Random;
param doors: int = 3;
config const games: int = 1000;
config const maxTasks = 32;
var numTasks = 1;
while( games / numTasks > 1000000 && numTasks < maxTasks ) do numTasks += 1;
const tasks = 1..#numTasks;
const games_per_task = games / numTasks ;
const remaining_games = games % numTasks ;
var wins_by_stay: [tasks] int;
coforall task in tasks {
var rand = new RandomStream();
for game in 1..#games_per_task {
var player_door = (rand.getNext() * 1000): int % doors ;
var winning_door = (rand.getNext() * 1000): int % doors ;
if player_door == winning_door then
wins_by_stay[ task ] += 1;
}
if task == tasks.last then {
for game in 1..#remaining_games {
var player_door = (rand.getNext() * 1000): int % doors ;
var winning_door = (rand.getNext() * 1000): int % doors ;
if player_door == winning_door then
wins_by_stay[ task ] += 1;
}
}
}
var total_by_stay = + reduce wins_by_stay;
var total_by_switch = games - total_by_stay;
var percent_by_stay = ((total_by_stay: real) / games) * 100;
var percent_by_switch = ((total_by_switch: real) / games) * 100;
writeln( "Wins by staying: ", total_by_stay, " or ", percent_by_stay, "%" );
writeln( "Wins by switching: ", total_by_switch, " or ", percent_by_switch, "%" );
if ( total_by_stay > total_by_switch ){
writeln( "Staying is the superior method." );
} else if( total_by_stay < total_by_switch ){
writeln( "Switching is the superior method." );
} else {
writeln( "Both methods are equal." );
}
|
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.
| #EchoLisp | EchoLisp |
(lib 'math) ;; for egcd = extended gcd
(define (mod-inv x m)
(define-values (g inv q) (egcd x m))
(unless (= 1 g) (error 'not-coprimes (list x m) ))
(if (< inv 0) (+ m inv) inv))
(mod-inv 42 2017) → 1969
(mod-inv 42 666)
🔴 error: not-coprimes (42 666)
|
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.
| #BBC_BASIC | BBC BASIC | @% = 5 : REM Set column width
FOR row% = 1 TO 12
PRINT row% TAB(row% * @%) ;
FOR col% = row% TO 12
PRINT row% * col% ;
NEXT col%
PRINT
NEXT row% |
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.
| #Lambdatalk | Lambdatalk |
{def multifact
{lambda {:n :deg}
{if {<= :n :deg}
then :n
else {* :n {multifact {- :n :deg} :deg}}}}}
-> multifact
{S.map {lambda {:deg} {br} Degree :deg:
{S.map {{lambda {:deg :n} {multifact :n :deg}} :deg}
{S.serie 1 10}}}
{S.serie 1 5}}
->
Degree 1: 1 2 6 24 120 720 5040 40320 362880 3628800
Degree 2: 1 2 3 8 15 48 105 384 945 3840
Degree 3: 1 2 3 4 10 18 28 80 162 280
Degree 4: 1 2 3 4 5 12 21 32 45 120
Degree 5: 1 2 3 4 5 6 14 24 36 50
|
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Seed7 | Seed7 | xPos := pointerXPos(curr_win);
yPos := pointerYPos(curr_win); |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Smalltalk | Smalltalk |
World activeHand position. " (394@649.0)"
|
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
| #Locomotive_Basic | Locomotive Basic | 10 mode 1:defint a-z
20 while n<4:input "How many queens (N>=4)";n:wend
30 dim q(n),e(n),o(n)
40 r=n mod 6
50 if r<>2 and r<>3 then gosub 320:goto 220
60 for i=1 to int(n/2)
70 e(i)=2*i
80 next
90 for i=1 to round(n/2)
100 o(i)=2*i-1
110 next
120 if r=2 then gosub 410
130 if r=3 then gosub 460
140 s=1
150 for i=1 to n
160 if e(i)>0 then q(s)=e(i):s=s+1
170 next
180 for i=1 to n
190 if o(i)>0 then q(s)=o(i):s=s+1
200 next
210 ' print board
220 cls
230 for i=1 to n
240 locate i,26-q(i):print chr$(238);
250 locate i,24-n :print chr$(96+i);
260 locate n+1,26-i :print i;
270 next
280 locate 1,1
290 call &bb06
300 end
310 ' the simple case
320 p=1
330 for i=1 to n
340 if i mod 2=0 then q(p)=i:p=p+1
350 next
360 for i=1 to n
370 if i mod 2 then q(p)=i:p=p+1
380 next
390 return
400 ' edit list when remainder is 2
410 for i=1 to n
420 if o(i)=3 then o(i)=1 else if o(i)=1 then o(i)=3
430 if o(i)=5 then o(i)=-1 else if o(i)=0 then o(i)=5:return
440 next
450 ' edit list when remainder is 3
460 for i=1 to n
470 if e(i)=2 then e(i)=-1 else if e(i)=0 then e(i)=2:goto 500
480 next
490 ' edit list some more
500 for i=1 to n
510 if o(i)=1 or o(i)=3 then o(i)=-1 else if o(i)=0 then o(i)=1:o(i+1)=3:return
520 next |
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.
| #Quackery | Quackery | [ table ] is suffix ( n --> $ )
$ "th st nd rd th th th th th th"
nest$ witheach [ ' suffix put ]
[ dup number$
swap dup 100 mod
10 21 within iff
[ drop $ "th" join ]
else
[ 10 mod
suffix join ] ] is ordinal$ ( n --> $ )
[ over - 1+
[] swap times
[ over i^ + ordinal$
nested join ]
nip 50 wrap$ ] is test ( n n --> )
0 25 test
cr
250 265 test
cr
1000 1025 test |
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
| #REXX | REXX | Do n=0 To 10000
If n=m(n) Then
Say n
End
Exit
m: Parse Arg z
res=0
Do While z>''
Parse Var z c +1 z
res=res+c**c
End
Return res |
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).
| #M2000_Interpreter | M2000 Interpreter |
\\ set console 70 characters by 40 lines
Form 70, 40
Module CheckSubs {
Flush
Document one$, two$
For i =0 to 20
Print format$("{0::-3}",i);
f(i)
\\ number pop then top value of stack
one$=format$("{0::-3}",number)
m(i)
two$=format$("{0::-3}",number)
Next i
Print
Print one$
Print two$
Sub f(x)
if x<=0 then Push 1 : Exit sub
f(x-1) ' leave result to for m(x)
m()
push x-number
End Sub
Sub m(x)
if x<=0 then Push 0 : Exit sub
m(x-1)
f()
push x-number
End Sub
}
CheckSubs
Module Checkit {
Function global f(n) {
if n=0 then =1: exit
if n>0 then =n-m(f(n-1))
}
Function global m(n) {
if n=0 then =0
if n>0 then =n-f(m(n-1))
}
Document one$, two$
For i =0 to 20
Print format$("{0::-3}",i);
one$=format$("{0::-3}",f(i))
two$=format$("{0::-3}",m(i))
Next i
Print
Print one$
Print two$
}
Checkit
Module Checkit2 {
Group Alfa {
function f(n) {
if n=0 then =1: exit
if n>0 then =n-.m(.f(n-1))
}
function m(n) {
if n=0 then =0
if n>0 then =n-.f(.m(n-1))
}
}
Document one$, two$
For i =0 to 20
Print format$("{0::-3}",i);
one$=format$("{0::-3}",Alfa.f(i))
two$=format$("{0::-3}",Alfa.m(i))
Next i
Print
Print one$
Print two$
Clipboard one$+{
}+two$
}
Checkit2
|
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
| #ERRE | ERRE |
PROGRAM RANDOM_PI
!
! for rosettacode.org
!
!$DOUBLE
PROCEDURE MONTECARLO(T->RES)
LOCAL I,N
FOR I=1 TO T DO
IF RND(1)^2+RND(1)^2<1 THEN N+=1 END IF
END FOR
RES=4*N/T
END PROCEDURE
BEGIN
RANDOMIZE(TIMER) ! init rnd number generator
MONTECARLO(1000->RES) PRINT(RES)
MONTECARLO(10000->RES) PRINT(RES)
MONTECARLO(100000->RES) PRINT(RES)
MONTECARLO(1000000->RES) PRINT(RES)
MONTECARLO(10000000->RES) PRINT(RES)
END PROGRAM |
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
| #Euler_Math_Toolbox | Euler Math Toolbox |
>function map MonteCarloPI (n,plot=false) ...
$ X:=random(1,n);
$ Y:=random(1,n);
$ if plot then
$ plot2d(X,Y,>points,style=".");
$ plot2d("sqrt(1-x^2)",color=2,>add);
$ endif
$ return sum(X^2+Y^2<1)/n*4;
$endfunction
>MonteCarloPI(10^(1:7))
[ 3.6 2.96 3.224 3.1404 3.1398 3.141548 3.1421492 ]
>pi
3.14159265359
>MonteCarloPI(10000,true):
|
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.)
| #Python | Python | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!' |
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).
| #CoffeeScript | CoffeeScript | class Morse
constructor : (@unit=0.05, @freq=700) ->
@cont = new AudioContext()
@time = @cont.currentTime
@alfabet = "..etianmsurwdkgohvf.l.pjbxcyzq..54.3...2.......16.......7...8.90"
getCode : (letter) ->
i = @alfabet.indexOf letter
result = ""
while i > 1
result = ".-"[i%2] + result
i //= 2
result
makecode : (data) ->
for letter in data
code = @getCode letter
if code != undefined then @maketime code else @time += @unit * 7
maketime : (data) ->
for timedata in data
timedata = @unit * ' . _'.indexOf timedata
if timedata > 0
@maketone timedata
@time += timedata
@time += @unit * 1
@time += @unit * 2
maketone : (data) ->
start = @time
stop = @time + data
@gain.gain.linearRampToValueAtTime 0, start
@gain.gain.linearRampToValueAtTime 1, start + @unit / 8
@gain.gain.linearRampToValueAtTime 1, stop - @unit / 16
@gain.gain.linearRampToValueAtTime 0, stop
send : (text) ->
osci = @cont.createOscillator()
osci.frequency.value = @freq
@gain = @cont.createGain()
@gain.gain.value = 0
osci.connect @gain
@gain.connect @cont.destination
osci.start @time
@makecode text
@cont
morse = new Morse()
morse.send 'hello world 0123456789' |
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.
| #Clojure | Clojure | (ns monty-hall-problem
(:use [clojure.contrib.seq :only (shuffle)]))
(defn play-game [staying]
(let [doors (shuffle [:goat :goat :car])
choice (rand-int 3)
[a b] (filter #(not= choice %) (range 3))
alternative (if (= :goat (nth doors a)) b a)]
(= :car (nth doors (if staying choice alternative)))))
(defn simulate [staying times]
(let [wins (reduce (fn [counter _] (if (play-game staying) (inc counter) counter))
0
(range times))]
(str "wins " wins " times out of " times)))
|
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Elixir | Elixir | defmodule Modular do
def extended_gcd(a, b) do
{last_remainder, last_x} = extended_gcd(abs(a), abs(b), 1, 0, 0, 1)
{last_remainder, last_x * (if a < 0, do: -1, else: 1)}
end
defp extended_gcd(last_remainder, 0, last_x, _, _, _), do: {last_remainder, last_x}
defp extended_gcd(last_remainder, remainder, last_x, x, last_y, y) do
quotient = div(last_remainder, remainder)
remainder2 = rem(last_remainder, remainder)
extended_gcd(remainder, remainder2, x, last_x - quotient*x, y, last_y - quotient*y)
end
def inverse(e, et) do
{g, x} = extended_gcd(e, et)
if g != 1, do: raise "The maths are broken!"
rem(x+et, et)
end
end
IO.puts Modular.inverse(42,2017) |
http://rosettacode.org/wiki/Modular_inverse | Modular inverse | From Wikipedia:
In modular arithmetic, the modular multiplicative inverse of an integer a modulo m is an integer x such that
a
x
≡
1
(
mod
m
)
.
{\displaystyle a\,x\equiv 1{\pmod {m}}.}
Or in other words, such that:
∃
k
∈
Z
,
a
x
=
1
+
k
m
{\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #ERRE | ERRE | PROGRAM MOD_INV
!$INTEGER
PROCEDURE MUL_INV(A,B->T)
LOCAL NT,R,NR,Q,TMP
IF B<0 THEN B=-B
IF A<0 THEN A=B-(-A MOD B)
T=0 NT=1 R=B NR=A MOD B
WHILE NR<>0 DO
Q=R DIV NR
TMP=NT NT=T-Q*NT T=TMP
TMP=NR NR=R-Q*NR R=TMP
END WHILE
IF (R>1) THEN T=-1 EXIT PROCEDURE ! NO INVERSE
IF (T<0) THEN T+=B
END PROCEDURE
BEGIN
MUL_INV(42,2017->T) PRINT(T)
MUL_INV(40,1->T) PRINT(T)
MUL_INV(52,-217->T) PRINT(T) ! pari semantics for negative modulus
MUL_INV(-486,217->T) PRINT(T)
MUL_INV(40,2018->T) PRINT(T)
END PROGRAM
|
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.
| #Befunge | Befunge | 0>51p0>52p51g52g*:51g52g`!*\!51g52g+*+0\3>01p::55+%68*+\!28v
w^p2<y|!`+66:+1,+*84*"\"!:g25$_,#!>#:<$$_^#!:-1g10/+55\-**<<
"$9"^x>$55+,51g1+:66+`#@_055+68*\>\#<1#*-#9:#5_$"+---">:#,_$ |
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.
| #Latitude | Latitude | use 'format importAllSigils.
multiFactorial := {
Range make ($1, 0, - $2) product.
}.
1 upto 6 visit {
takes '[degree].
answers := 1 upto 11 to (Array) map { multiFactorial ($1, degree). }.
$stdout printf: ~fmt "Degree ~S: ~S", degree, answers.
}. |
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.
| #Lua | Lua | function multiFact (n, degree)
local fact = 1
for i = n, 2, -degree do
fact = fact * i
end
return fact
end
print("Degree\t|\tMultifactorials 1 to 10")
print(string.rep("-", 52))
for d = 1, 5 do
io.write(" " .. d, "\t| ")
for n = 1, 10 do
io.write(multiFact(n, d) .. " ")
end
print()
end |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Standard_ML | Standard ML | open XWindows ;
val dp = XOpenDisplay "" ;
val w = XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ;
XMapWindow w;
val (focus,_)=( Posix.Process.sleep (Time.fromReal 2.0); (* time to move from interpreter + activate arbitrary window *)
XGetInputFocus dp
) ;
XQueryPointer focus ;
XQueryPointer w; |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Tcl | Tcl | package require Tk 8.5
set curWindow [lindex [wm stackorder .] end]
# Everything below will work with anything from Tk 8.0 onwards
set x [expr {[winfo pointerx .] - [winfo rootx $curWindow]}]
set y [expr {[winfo pointery .] - [winfo rooty $curWindow]}]
tk_messageBox -message "the mouse is at ($x,$y) in window $curWindow" |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Visual_Basic | Visual Basic | Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
'X and Y are in "twips" -- 15 twips per pixel
Me.Print "X:" & X
Me.Print "Y:" & Y
End Sub |
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
| #Logo | Logo | to try :files :diag1 :diag2 :tried
if :files = 0 [make "solutions :solutions+1 show :tried stop]
localmake "safe (bitand :files :diag1 :diag2)
until [:safe = 0] [
localmake "f bitnot bitand :safe minus :safe
try bitand :files :f ashift bitand :diag1 :f -1 (ashift bitand :diag2 :f 1)+1 fput bitnot :f :tried
localmake "safe bitand :safe :safe-1
]
end
to queens :n
make "solutions 0
try (lshift 1 :n)-1 -1 -1 []
output :solutions
end
print queens 8 ; 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.
| #R | R | nth <- function(n)
{
if (length(n) > 1) return(sapply(n, nth))
mod <- function(m, n) ifelse(!(m%%n), n, m%%n)
suffices <- c("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")
if (n %% 100 <= 10 || n %% 100 > 20)
suffix <- suffices[mod(n+1, 10)]
else
suffix <- 'th'
paste(n, "'", suffix, sep="")
}
range <- list(0:25, 250:275, 500:525, 750:775, 1000:1025)
sapply(range, nth) |
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
| #Ring | Ring |
# Project : Munchausen numbers
limit = 5000
for n=1 to limit
sum = 0
msum = string(n)
for m=1 to len(msum)
ms = number(msum[m])
sum = sum + pow(ms, ms)
next
if sum = n
see n + nl
ok
next
|
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
| #Ruby | Ruby | class Integer
def munchausen?
self.digits.map{|d| d**d}.sum == self
end
end
puts (1..5000).select(&: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).
| #M4 | M4 | define(`female',`ifelse(0,$1,1,`eval($1 - male(female(decr($1))))')')dnl
define(`male',`ifelse(0,$1,0,`eval($1 - female(male(decr($1))))')')dnl
define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl
loop(0,20,`female')
loop(0,20,`male') |
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
| #F.23 | F# |
let print x = printfn "%A" x
let MonteCarloPiGreco niter =
let eng = System.Random()
let action () =
let x: float = eng.NextDouble()
let y: float = eng.NextDouble()
let res: float = System.Math.Sqrt(x**2.0 + y**2.0)
if res < 1.0 then
1
else
0
let res = [ for x in 1..niter do yield action() ]
let tmp: float = float(List.reduce (+) res) / float(res.Length)
4.0*tmp
MonteCarloPiGreco 1000 |> print
MonteCarloPiGreco 10000 |> print
MonteCarloPiGreco 100000 |> print
|
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.)
| #Quackery | Quackery | [ []
26 times
[ char a i^ +
join ] ] constant is symbols ( --> $ )
[ [] symbols rot
witheach
[ over find
tuck pluck
swap join
dip join ]
drop ] is encode ( $ --> [ )
[ $ "" symbols rot
witheach
[ pluck
dup rot join
dip join ]
drop ] is decode ( [ --> $ )
[ dup echo$
say " --> "
dup encode
dup echo
say " --> "
decode
dup echo$
= iff
[ say " :-)" ]
else
[ say " :-(" ]
cr cr ] is task ( $ --> )
$ "broood bananaaa hiphophiphop"
nest$ witheach task |
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.)
| #Racket | Racket | #lang racket
(define default-symtab "abcdefghijklmnopqrstuvwxyz")
(define (move-to-front:encode in (symtab default-symtab))
(define inner-encode
(match-lambda**
[((? string? (app string->list in)) st acc) ; make input all listy
(inner-encode in st acc)]
[(in (? string? (app string->list st)) acc) ; make symtab all listy
(inner-encode in st acc)]
[((list) _ (app reverse rv)) ; nothing more to encode
rv]
[((list a tail ...) (list left ... a right ...) acc) ; encode and recur
(inner-encode tail `(,a ,@left ,@right) (cons (length left) acc))]))
(inner-encode in symtab null))
(define (move-to-front:decode in (symtab default-symtab))
(define inner-decode
(match-lambda**
[(in (? string? (app string->list st)) acc) ; make symtab all listy
(inner-decode in st acc)]
[((list) _ (app (compose list->string reverse) rv)) ; nothing more to encode
rv]
[((list a tail ...) symbols acc) ; decode and recur
(match/values
(split-at symbols a)
[(l (cons ra rd))
(inner-decode tail (cons ra (append l rd)) (cons ra acc))])]))
(inner-decode in symtab null))
(module+ test
;; Test against the example in the task
(require rackunit)
(check-equal? (move-to-front:encode "broood") '(1 17 15 0 0 5))
(check-equal? (move-to-front:decode '(1 17 15 0 0 5)) "broood")
(check-equal? (move-to-front:decode (move-to-front:encode "broood")) "broood"))
(module+ main
(define (encode+decode-string str)
(define enc (move-to-front:encode str))
(define dec (move-to-front:decode enc))
(define crt (if (equal? dec str) "correctly" "incorrectly"))
(printf "~s encodes to ~s, which decodes ~s to ~s.~%" str enc crt dec))
(for-each encode+decode-string '("broood" "bananaaa" "hiphophiphop"))) |
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).
| #D | D |
import std.conv;
import std.stdio;
immutable string[char] morsecode;
static this() {
morsecode = [
'a': ".-",
'b': "-...",
'c': "-.-.",
'd': "-..",
'e': ".",
'f': "..-.",
'g': "--.",
'h': "....",
'i': "..",
'j': ".---",
'k': "-.-",
'l': ".-..",
'm': "--",
'n': "-.",
'o': "---",
'p': ".--.",
'q': "--.-",
'r': ".-.",
's': "...",
't': "-",
'u': "..-",
'v': "...-",
'w': ".--",
'x': "-..-",
'y': "-.--",
'z': "--..",
'0': "-----",
'1': ".----",
'2': "..---",
'3': "...--",
'4': "....-",
'5': ".....",
'6': "-....",
'7': "--...",
'8': "---..",
'9': "----."
];
}
void main(string[] args) {
foreach (arg; args[1..$]) {
writeln(arg);
foreach (ch; arg) {
if (ch in morsecode) {
write(morsecode[ch]);
}
write(' ');
}
writeln();
}
}
|
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. monty-hall.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 Num-Games VALUE 1000000.
*> These are needed so the values are passed to
*> get-rand-int correctly.
01 One PIC 9 VALUE 1.
01 Three PIC 9 VALUE 3.
01 doors-area.
03 doors PIC 9 OCCURS 3 TIMES.
01 choice PIC 9.
01 shown PIC 9.
01 winner PIC 9.
01 switch-wins PIC 9(7).
01 stay-wins PIC 9(7).
01 stay-wins-percent PIC Z9.99.
01 switch-wins-percent PIC Z9.99.
PROCEDURE DIVISION.
PERFORM Num-Games TIMES
MOVE 0 TO doors (winner)
CALL "get-rand-int" USING CONTENT One, Three,
REFERENCE winner
MOVE 1 TO doors (winner)
CALL "get-rand-int" USING CONTENT One, Three,
REFERENCE choice
PERFORM WITH TEST AFTER
UNTIL NOT(shown = winner OR choice)
CALL "get-rand-int" USING CONTENT One, Three,
REFERENCE shown
END-PERFORM
ADD doors (choice) TO stay-wins
ADD doors (6 - choice - shown) TO switch-wins
END-PERFORM
COMPUTE stay-wins-percent ROUNDED =
stay-wins / Num-Games * 100
COMPUTE switch-wins-percent ROUNDED =
switch-wins / Num-Games * 100
DISPLAY "Staying wins " stay-wins " times ("
stay-wins-percent "%)."
DISPLAY "Switching wins " switch-wins " times ("
switch-wins-percent "%)."
.
IDENTIFICATION DIVISION.
PROGRAM-ID. get-rand-int.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 call-flag PIC X VALUE "Y".
88 first-call VALUE "Y", FALSE "N".
01 num-range PIC 9.
LINKAGE SECTION.
01 min-num PIC 9.
01 max-num PIC 9.
01 ret PIC 9.
PROCEDURE DIVISION USING min-num, max-num, ret.
*> Seed RANDOM once.
IF first-call
MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:8))
TO num-range
SET first-call TO FALSE
END-IF
COMPUTE num-range = max-num - min-num + 1
COMPUTE ret =
FUNCTION MOD(FUNCTION RANDOM * 100000, num-range)
+ min-num
.
END PROGRAM get-rand-int.
END PROGRAM monty-hall. |
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.
| #F.23 | F# |
// Calculate the inverse of a (mod m)
// See here for eea specs:
// https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
let modInv m a =
let rec eea t t' r r' =
match r' with
| 0 -> t
| _ ->
let div = r/r'
eea t' (t - div * t') r' (r - div * r')
(m + eea 0 1 m a) % m
|
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.
| #Factor | Factor | USE: math.functions
42 2017 mod-inv |
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.
| #BQN | BQN | Table ← {
m ← •Repr¨ ×⌜˜1+↕𝕩 # The numbers, formatted individually
main ← ⟨ # Bottom part: three sections
>(-⌈10⋆⁼𝕩)↑¨⊏m # Original numbers
𝕩⥊'|' # Divider
∾˘(-1+⌈10⋆⁼𝕩×𝕩)↑¨(≤⌜˜↕𝕩)/¨m # Multiplied numbers, padded and joined
⟩
head ← ' '¨⌾⊑ ⊏¨ main # Header: first row but with space left of |
∾ >⟨head, "-+-"⊣¨¨head, main⟩ # Header, divider, and main
}
•Out˘ Table 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.
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(N,DEG)
ENTRY TO MLTFAC.
RSLT = 1
THROUGH MULT, FOR MPC=N, -DEG, MPC.L.1
MULT RSLT = RSLT * MPC
FUNCTION RETURN RSLT
END OF FUNCTION
THROUGH SHOW, FOR I=1, 1, I.G.10
SHOW PRINT FORMAT OUTP, MLTFAC.(I,1), MLTFAC.(I,2),
0 MLTFAC.(I,3), MLTFAC.(I,4), MLTFAC.(I,5)
VECTOR VALUES OUTP = $5(I10,S1)*$
END OF PROGRAM |
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.
| #Maple | Maple |
f := proc (n, m)
local fac, i;
fac := 1;
for i from n by -m to 1 do
fac := fac*i;
end do;
return fac;
end proc:
a:=Matrix(5,10):
for i from 1 to 5 do
for j from 1 to 10 do
a[i,j]:=f(j,i);
end do;
end do;
a;
|
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas
import "input" for Mouse
class Game {
static init() {
Window.title = "Mouse position"
Canvas.resize(400, 400)
Window.resize(400, 400)
// get initial mouse coordinates
__px = Mouse.x
__py = Mouse.y
__ticks = 0
System.print("The coordinates of the mouse relative to the canvas are:")
}
static update() {
__ticks = __ticks + 1
if (__ticks%60 == 0) {
// get current mouse coordinates
var cx = Mouse.x
var cy = Mouse.y
// if it's moved in the last second, report new position
if (cx != __px || cy != __py) {
System.print([cx, cy])
__px = cx
__py = cy
}
}
}
static draw(alpha) {}
} |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #XPL0 | XPL0 | include c:\cxpl\stdlib;
if not OpenMouse then Text(0, "A mouse is required")
else [ShowMouse(true);
IntOut(0, GetMousePosition(0)); ChOut(0, ^,);
IntOut(0, GetMousePosition(1)); CrLf(0);
] |
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
| #Lua | Lua | N = 8
-- We'll use nil to indicate no queen is present.
grid = {}
for i = 0, N do
grid[i] = {}
end
function can_find_solution(x0, y0)
local x0, y0 = x0 or 0, y0 or 1 -- Set default vals (0, 1).
for x = 1, x0 - 1 do
if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then
return false
end
end
grid[x0][y0] = true
if x0 == N then return true end
for y0 = 1, N do
if can_find_solution(x0 + 1, y0) then return true end
end
grid[x0][y0] = nil
return false
end
if can_find_solution() then
for y = 1, N do
for x = 1, N do
-- Print "|Q" if grid[x][y] is true; "|_" otherwise.
io.write(grid[x][y] and "|Q" or "|_")
end
print("|")
end
else
print(string.format("No solution for %d queens.\n", N))
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.
| #Racket | Racket | #lang racket
(define (teen? n) (<= 11 (modulo n 100) 19))
(define (Nth n)
(format
"~a'~a" n
(match* ((modulo n 10) n)
[((or 1 2 3) (? teen?)) 'th] [(1 _) 'st] [(2 _) 'nd] [(3 _) 'rd] [(_ _) 'th])))
(for ((range (list (in-range 26) (in-range 250 266) (in-range 1000 1026))))
(displayln (string-join (for/list ((nth (sequence-map Nth range))) nth) " "))) |
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
| #Rust | Rust | fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
} |
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
| #Scala | Scala |
object Munch {
def main(args: Array[String]): Unit = {
import scala.math.pow
(1 to 5000).foreach {
i => if (i == (i.toString.toCharArray.map(d => pow(d.asDigit,d.asDigit))).sum)
println( i + " (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).
| #MAD | MAD | NORMAL MODE IS INTEGER
R SET UP STACK SPACE
DIMENSION STACK(100)
SET LIST TO STACK
R DEFINE RECURSIVE FUNCTIONS
R INPUT ARGUMENT ASSUMED TO BE IN N
INTERNAL FUNCTION(DUMMY)
ENTRY TO FREC.
WHENEVER N.LE.0, FUNCTION RETURN 1
SAVE RETURN
SAVE DATA N
N = N-1
N = FREC.(0)
X = MREC.(0)
RESTORE DATA N
RESTORE RETURN
FUNCTION RETURN N-X
END OF FUNCTION
INTERNAL FUNCTION(DUMMY)
ENTRY TO MREC.
WHENEVER N.LE.0, FUNCTION RETURN 0
SAVE RETURN
SAVE DATA N
N = N-1
N = MREC.(0)
X = FREC.(0)
RESTORE DATA N
RESTORE RETURN
FUNCTION RETURN N-X
END OF FUNCTION
R DEFINE FRONT-END FUNCTIONS THAT CAN BE CALLED WITH ARGMT
INTERNAL FUNCTION(NN)
ENTRY TO F.
N = NN
FUNCTION RETURN FREC.(0)
END OF FUNCTION
INTERNAL FUNCTION(NN)
ENTRY TO M.
N = NN
FUNCTION RETURN MREC.(0)
END OF FUNCTION
R PRINT F(0..19) AND M(0..19)
THROUGH SHOW, FOR I=0, 1, I.GE.20
SHOW PRINT FORMAT FMT,I,F.(I),I,M.(I)
VECTOR VALUES FMT =
0 $2HF(,I2,4H) = ,I2,S8,2HM(,I2,4H) = ,I2*$
END OF PROGRAM |
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
| #Factor | Factor | USING: kernel math math.functions random sequences ;
: limit ( -- n ) 2 32 ^ ; inline
: in-circle ( x y -- ? ) limit [ sq ] tri@ [ + ] [ <= ] bi* ;
: rand ( -- r ) limit random ;
: pi ( n -- pi ) [ [ drop rand rand in-circle ] count ] keep / 4 * >float ; |
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
| #Fantom | Fantom |
class MontyCarlo
{
// assume square/circle of width 1 unit
static Float findPi (Int samples)
{
Int insideCircle := 0
samples.times
{
x := Float.random
y := Float.random
if ((x*x + y*y).sqrt <= 1.0f) insideCircle += 1
}
return insideCircle * 4.0f / samples
}
public static Void main ()
{
[100, 1000, 10000, 1000000, 10000000].each |sample|
{
echo ("Sample size $sample gives PI as ${findPi(sample)}")
}
}
}
|
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.)
| #Raku | Raku | sub encode ( Str $word ) {
my @sym = 'a' .. 'z';
gather for $word.comb -> $c {
die "Symbol '$c' not found in @sym" if $c eq @sym.none;
@sym[0 .. take (@sym ... $c).end] .= rotate(-1);
}
}
sub decode ( @enc ) {
my @sym = 'a' .. 'z';
[~] gather for @enc -> $pos {
take @sym[$pos];
@sym[0..$pos] .= rotate(-1);
}
}
use Test;
plan 3;
for <broood bananaaa hiphophiphop> -> $word {
my $enc = encode($word);
my $dec = decode($enc);
is $word, $dec, "$word.fmt('%-12s') ($enc[])";
} |
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).
| #Delphi | Delphi |
program Morse;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.Generics.Collections,
SysUtils,
Windows;
const
Codes: array[0..35, 0..1] of 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', '----.'));
var
Dictionary: TDictionary<String, String>;
procedure InitCodes;
var
i: Integer;
begin
for i := 0 to High(Codes) do
Dictionary.Add(Codes[i, 0], Codes[i, 1]);
end;
procedure SayMorse(const Word: String);
var
s: String;
begin
for s in Word do
if s = '.' then
Windows.Beep(1000, 250)
else if s = '-' then
Windows.Beep(1000, 750)
else
Windows.Beep(1000, 1000);
end;
procedure ParseMorse(const Word: String);
var
s, Value: String;
begin
for s in word do
if Dictionary.TryGetValue(s, Value) then
begin
Write(Value + ' ');
SayMorse(Value);
end;
end;
begin
Dictionary := TDictionary<String, String>.Create;
try
InitCodes;
if ParamCount = 0 then
ParseMorse('sos')
else if ParamCount = 1 then
ParseMorse(LowerCase(ParamStr(1)))
else
Writeln('Usage: Morse.exe anyword');
Readln;
finally
Dictionary.Free;
end;
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.
| #ColdFusion | ColdFusion | <cfscript>
function runmontyhall(num_tests) {
// number of wins when player switches after original selection
switch_wins = 0;
// number of wins when players "sticks" with original selection
stick_wins = 0;
// run all the tests
for(i=1;i<=num_tests;i++) {
// unconditioned potential for selection of each door
doors = [0,0,0];
// winning door is randomly assigned...
winner = randrange(1,3);
// ...and actualized in the array of real doors
doors[winner] = 1;
// player chooses one of three doors
choice = randrange(1,3);
do {
// monty randomly reveals a door...
shown = randrange(1,3);
}
// ...but monty only reveals empty doors;
// he will not reveal the door that the player has choosen
// nor will he reveal the winning door
while(shown==choice || doors[shown]==1);
// when the door the player originally selected is the winner, the "stick" option gains a point
stick_wins += doors[choice];
// to calculate the number of times the player would have won with a "switch", subtract the
// "value" of the chosen, "stuck-to" door from 1, the possible number of wins if the player
// chose and stuck with the winning door (1), the player would not have won by switching, so
// the value is 1-1=0 if the player chose and stuck with a losing door (0), the player would
// have won by switching, so the value is 1-0=1
switch_wins += 1-doors[choice];
}
// finally, simply run the percentages for each outcome
stick_percentage = (stick_wins/num_tests)*100;
switch_percentage = (switch_wins/num_tests)*100;
writeoutput('Number of Tests: ' & num_tests);
writeoutput('<br />Stick Wins: ' & stick_wins & ' ['& stick_percentage &'%]');
writeoutput('<br />Switch Wins: ' & switch_wins & ' ['& switch_percentage &'%]');
}
runmontyhall(10000);
</cfscript> |
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.
| #Forth | Forth |
: invmod { a m | v b c -- inv }
m to v
1 to c
0 to b
begin a
while v a / >r
c b s>d c s>d r@ 1 m*/ d- d>s to c to b
a v s>d a s>d r> 1 m*/ d- d>s to a to v
repeat b m mod dup to b 0<
if m b + else b then ;
|
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.
| #FreeBASIC | FreeBASIC | ' version 10-07-2018
' compile with: fbc -s console
Type ext_euclid
Dim As Integer a, b
End Type
' "Table method" aka "The Magic Box"
Function magic_box(x As Integer, y As Integer) As ext_euclid
Dim As Integer a(1 To 128), b(1 To 128), d(1 To 128), k(1 To 128)
a(1) = 1 : b(1) = 0 : d(1) = x
a(2) = 0 : b(2) = 1 : d(2) = y : k(2) = x \ y
Dim As Integer i = 2
While Abs(d(i)) <> 1
i += 1
a(i) = a(i -2) - k(i -1) * a(i -1)
b(i) = b(i -2) - k(i -1) * b(i -1)
d(i) = d(i -2) Mod d(i -1)
k(i) = d(i -1) \ d(i)
'Print a(i),b(i),d(i),k(i)
If d(i -1) Mod d(i) = 0 Then Exit While
Wend
If d(i) = -1 Then ' -1 * (ab + by) = -1 * -1 ==> -ab -by = 1
a(i) = -a(i)
b(i) = -b(i)
End If
Function = Type( a(i), b(i) )
End Function
' ------=< MAIN >=------
Dim As Integer x, y, gcd
Dim As ext_euclid result
Do
Read x, y
If x = 0 AndAlso y = 0 Then Exit Do
result = magic_box(x, y)
With result
gcd = .a * x + .b * y
Print "a * "; Str(x); " + b * "; Str(y);
Print " = GCD("; Str(x); ", "; Str(y); ") ="; gcd
If gcd > 1 Then
Print "No solution, numbers are not coprime"
Else
Print "a = "; .a; ", b = ";.b
Print "The Modular inverse of "; x; " modulo "; y; " = ";
While .a < 0 : .a += IIf(y > 0, y, -y) : Wend
Print .a
'Print "The Modular inverse of "; y; " modulo "; x; " = ";
'While .b < 0 : .b += IIf(x > 0, x, -x) : Wend
'Print .b
End if
End With
Print
Loop
Data 42, 2017
Data 40, 1
Data 52, -217
Data -486, 217
Data 40, 2018
Data 0, 0
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Bracmat | Bracmat | ( multiplicationTable
= high i j row row2 matrix padFnc tmp
, celPad leftCelPad padFnc celDashes leftDashes
. !arg:?high
& ( padFnc
= L i w d
. @(!arg:? [?L)
& 1+(!L:?i):?L
& " ":?w
& "-":?d
& whl
' ( !i+-1:~<0:?i
& " " !w:?w
& "-" !d:?d
)
& str$!w:?w
& (
' (
. @(str$(rev$!arg ()$w):?arg [($L) ?)
& rev$!arg
)
. str$!d
)
)
& padFnc$(!high^2):((=?celPad).?celDashes)
& @(!high:?tmp [-2 ?)
& padFnc$!tmp:((=?leftCelPad).?leftDashes)
& 0:?i
& :?row:?row2
& whl
' ( 1+!i:~>!high:?i
& !row celPad$!i:?row
& !celDashes !row2:?row2
)
& str$(leftCelPad$X "|" !row \n !leftDashes "+" !row2 \n)
: ?matrix
& 0:?j
& whl
' ( 1+!j:~>!high:?j
& 0:?i
& :?row
& whl
' ( 1+!i:<!j:?i
& celPad$() !row:?row
)
& leftCelPad$!j "|" !row:?row
& whl
' ( 1+!i:~>!high:?i
& !row celPad$(!i*!j):?row
)
& !matrix str$(!row \n):?matrix
)
& str$!matrix
)
& out$(multiplicationTable$12)
& done; |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Multifactorial[n_, d_] := Product[x, {x, n, 1, -d}]
Table[Multifactorial[j, i], {i, 5}, {j, 10}]//TableForm |
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.