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/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Python
Python
>>> from pprint import pprint as pp # Pretty printer >>> from itertools import product >>> >>> def dict_as_mdarray(dimensions=(2, 3), init=0.0): ... return {indices: init for indices in product(*(range(i) for i in dimensions))} ... >>> >>> mdarray = dict_as_mdarray((2, 3, 4, 5)) >>> pp(mdarray) {(0, 0, 0, 0): 0.0, (0, 0, 0, 1): 0.0, (0, 0, 0, 2): 0.0, (0, 0, 0, 3): 0.0, (0, 0, 0, 4): 0.0, (0, 0, 1, 0): 0.0, ... (1, 2, 3, 0): 0.0, (1, 2, 3, 1): 0.0, (1, 2, 3, 2): 0.0, (1, 2, 3, 3): 0.0, (1, 2, 3, 4): 0.0} >>> mdarray[(0, 1, 2, 3)] 0.0 >>> mdarray[(0, 1, 2, 3)] = 6.78 >>> mdarray[(0, 1, 2, 3)] 6.78 >>> mdarray[(0, 1, 2, 3)] = 5.4321 >>> mdarray[(0, 1, 2, 3)] 5.4321 >>> pp(mdarray) {(0, 0, 0, 0): 0.0, (0, 0, 0, 1): 0.0, (0, 0, 0, 2): 0.0, ... (0, 1, 2, 2): 0.0, (0, 1, 2, 3): 5.4321, (0, 1, 2, 4): 0.0, ... (1, 2, 3, 3): 0.0, (1, 2, 3, 4): 0.0} >>>
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.
#ALGOL_W
ALGOL W
begin  % print a school style multiplication table  % i_w := 3; s_w := 0; % set output formating  % write( " " ); for i := 1 until 12 do writeon( " ", i ); write( " +" ); for i := 1 until 12 do writeon( "----" ); for i := 1 until 12 do begin write( i, "|" ); for j := 1 until i - 1 do writeon( " " ); for j := i until 12 do writeon( " ", i * j ); end;   end.
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).
#PARI.2FGP
PARI/GP
pseudoinv(M)=my(sz=matsize(M),T=conj(M))~;if(sz[1]<sz[2],T/(M*T),(T*M)^-1*T) addhelp(pseudoinv, "pseudoinv(M): Moore pseudoinverse of the matrix M.");   y*pseudoinv(X)
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.
#Factor
Factor
USING: formatting io kernel math math.ranges prettyprint sequences ; IN: rosetta-code.multifactorial   : multifactorial ( n degree -- m ) neg 1 swap <range> product ;   : mf-row ( degree -- ) dup "Degree %d: " printf 10 [1,b] [ swap multifactorial pprint bl ] with each ;   : main ( -- ) 5 [1,b] [ mf-row nl ] each ;   MAIN: main
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.
#Forth
Forth
: !n negate swap 1 dup rot do i * over +loop nip ; : test cr 6 1 ?do 11 1 ?do i j !n . loop cr loop ;
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.
#Lingo
Lingo
put _mouse.mouseLoc -- point(310, 199)
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.
#xTalk
xTalk
  -- Method 1: -- this script in either the stack script or the card script to get position relative to the current stack window on mouseMove pMouseH,pMouseV put pMouseH,pMouse end mouseMove   -- Method 2: -- this script can go anywhere to get current position relative to the current stack window put mouseLoc()   -- Method 3: -- this script can go anywhere to get current position relative to the current stack window put the mouseLoc   -- Method 4: -- this script can go anywhere to get current position relative to the current window put the mouseH &","& the mouseV   To get the mousePosition relative to the current screen instead of relative to the current stack window use the screenMouseLoc keyword example results: 117,394 -- relative to current window 117,394 -- relative to current window 117,394 -- relative to current window 148,521 -- relative to current screen    
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
#Groovy
Groovy
def listOrder = { a, b -> def k = [a.size(), b.size()].min() def i = (0..<k).find { a[it] != b[it] } (i != null) ? a[i] <=> b[i] : a.size() <=> b.size() }   def orderedPermutations = { list -> def n = list.size() (0..<n).permutations().sort(listOrder) }   def diagonalSafe = { list -> def n = list.size() n == 1 || (0..<(n-1)).every{ i -> ((i+1)..<n).every{ j -> !([list[i]+j-i, list[i]+i-j].contains(list[j])) } } }   def queensDistinctSolutions = { n -> // each permutation is an N-Rooks solution orderedPermutations((0..<n)).findAll (diagonalSafe) }
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#VBA
VBA
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x '-- absolute accuracy If d > -e And d < e Then Exit Do End If Loop Debug.Print y; n; x; y ^ (1 / n) End Function Public Sub main() nth_root 1024, 10 nth_root 27, 3 nth_root 2, 2 nth_root 5642, 125 nth_root 7, 0.5 nth_root 4913, 3 nth_root 8, 3 nth_root 16, 2 nth_root 16, 4 nth_root 125, 3 nth_root 1000000000, 3 nth_root 1000000000, 9 End Sub
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.
#Oforth
Oforth
: nth(n) | r | n "th" over 10 mod ->r r 1 == ifTrue: [ n 100 mod 11 == ifFalse: [ drop "st" ] ] r 2 == ifTrue: [ n 100 mod 12 == ifFalse: [ drop "nd" ] ] r 3 == ifTrue: [ n 100 mod 13 == ifFalse: [ drop "rd" ] ] + ;
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
#PHP
PHP
  <?php   $pwr = array_fill(0, 10, 0);   function isMunchhausen($n) { global $pwr; $sm = 0; $temp = $n; while ($temp) { $sm= $sm + $pwr[($temp % 10)]; $temp = (int)($temp / 10); } return $sm == $n; }   for ($i = 0; $i < 10; $i++) { $pwr[$i] = pow((float)($i), (float)($i)); }   for ($i = 1; $i < 5000 + 1; $i++) { if (isMunchhausen($i)) { echo $i . PHP_EOL; } }
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).
#Java
Java
  import java.util.HashMap; import java.util.Map;   public class MutualRecursion {   public static void main(final String args[]) { int max = 20; System.out.printf("First %d values of the Female sequence:  %n", max); for (int i = 0; i < max; i++) { System.out.printf(" f(%d) = %d%n", i, f(i)); } System.out.printf("First %d values of the Male sequence:  %n", max); for (int i = 0; i < 20; i++) { System.out.printf(" m(%d) = %d%n", i, m(i)); } }   private static Map<Integer,Integer> F_MAP = new HashMap<>();   private static int f(final int n) { if ( F_MAP.containsKey(n) ) { return F_MAP.get(n); } int fn = n == 0 ? 1 : n - m(f(n - 1)); F_MAP.put(n, fn); return fn; }   private static Map<Integer,Integer> M_MAP = new HashMap<>();   private static int m(final int n) { if ( M_MAP.containsKey(n) ) { return M_MAP.get(n); } int mn = n == 0 ? 0 : n - f(m(n - 1)); M_MAP.put(n, mn); return mn; }     }  
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#zkl
zkl
n:=3; n.pump(List) //-->L(0,1,2)   n.pump(List,List) //-->L(0,1,2), not expected because the second list can be used to describe a calculation n.pump(List,List(Void,List)) //--> L(L(),L(),L()) all same List(Void,List) means returns List, which is a "known" value n.pump(List,List.fpM("-")) //--> L(L(),L(),L()) all distinct fpM is partial application: call List.create()   n.pump(List,(0.0).random.fp(1)) //--> 3 [0,1) randoms L(0.902645,0.799657,0.0753809)   n.pump(String) //-->"012", default action is id function   class C{ var n; fcn init(x){n=x} } n.pump(List,C) //--> L(C,C,C) n.pump(List,C).apply("n") //-->L(0,1,2) ie all classes distinct
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.
#F.23
F#
  // We can use Some as return, Option.bind and the pipeline operator in order to have a very concise code     let f1 (v:int) = Some v // int -> Option<int> let f2 (v:int) = Some(string v) // int -> Option<sting>   f1 4 |> Option.bind f2 |> printfn "Value is %A" // bind when option (maybe) has data None |> Option.bind f2 |> printfn "Value is %A" // bind when option (maybe) does not have data  
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.
#Factor
Factor
USING: monads ; FROM: monads => do ;   ! Prints "T{ just { value 7 } }" 3 maybe-monad return >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call .   ! Prints "nothing" nothing >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call .
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
#Arturo
Arturo
Pi: function [throws][ inside: new 0.0 do.times: throws [ if 1 > hypot random 0 1.0 random 0 1.0 -> inc 'inside ] return 4 * inside / throws ]   loop [100 1000 10000 100000 1000000] 'n -> print [pad to :string n 8 "=>" Pi n]
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\displaystyle \pi } . If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π / 4 {\displaystyle \pi /4} . So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π / 4 {\displaystyle \pi /4} . Task Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number π {\displaystyle \pi } is not built-in, we give π {\displaystyle \pi } as a number of digits: 3.141592653589793238462643383280
#AutoHotkey
AutoHotkey
  MsgBox % MontePi(10000) ; 3.154400 MsgBox % MontePi(100000) ; 3.142040 MsgBox % MontePi(1000000) ; 3.142096   MontePi(n) { Loop %n% { Random x, -1, 1.0 Random y, -1, 1.0 p += x*x+y*y < 1 } Return 4*p/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.)
#jq
jq
# Input is the string to be encoded, st is the initial symbol table (an array) # Output: the encoded string (an array) def m2f_encode(st): reduce explode[] as $ch ( [ [], st]; # state: [ans, st] (.[1]|index($ch)) as $ix | .[1] as $st | [ (.[0] + [ $ix ]), [$st[$ix]] + $st[0:$ix] + $st[$ix+1:] ] ) | .[0];   # Input should be the encoded string (an array) # and st should be the initial symbol table (an array) def m2f_decode(st): reduce .[] as $ix ( [ [], st]; # state: [ans, st] .[1] as $st | [ (.[0] + [ $st[$ix] ]), [$st[$ix]] + $st[0:$ix] + $st[$ix+1:] ] ) | .[0] | implode;
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.)
#Julia
Julia
function encodeMTF(str::AbstractString, symtable::Vector{Char}=collect('a':'z')) function encode(ch::Char) r = findfirst(symtable, ch) deleteat!(symtable, r) prepend!(symtable, ch) return r end collect(encode(ch) for ch in str) end   function decodeMTF(arr::Vector{Int}, symtable::Vector{Char}=collect('a':'z')) function decode(i::Int) r = symtable[i] deleteat!(symtable, i) prepend!(symtable, r) return r end join(decode(i) for i in arr) end   testset = ["broood", "bananaaa", "hiphophiphop"] encoded = encodeMTF.(testset) decoded = decodeMTF.(encoded) for (str, enc, dec) in zip(testset, encoded, decoded) println("Test string: $str\n -> Encoded: $enc\n -> Decoded: $dec") end   using Base.Test @testset "Decoded string equal to original" begin for (str, dec) in zip(testset, decoded) @test str == dec end 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).
#Ada
Ada
package Morse is   type Symbols is (Nul, '-', '.', ' '); -- Nul is the letter separator, space the word separator; Dash : constant Symbols := '-'; Dot : constant Symbols := '.'; type Morse_Str is array (Positive range <>) of Symbols; pragma Pack (Morse_Str);   function Convert (Input : String) return Morse_Str; procedure Morsebeep (Input : Morse_Str);   private subtype Reschars is Character range ' ' .. 'Z'; -- restricted set of characters from 16#20# to 16#60# subtype Length is Natural range 1 .. 5; subtype Codes is Morse_Str (Length); -- using the current ITU standard with 5 signs -- only alphanumeric characters are taken into consideration   type Codings is record L : Length; Code : Codes; end record; Table : constant array (Reschars) of Codings := ('A' => (2, ".- "), 'B' => (4, "-... "), 'C' => (4, "-.-. "), 'D' => (3, "-.. "), 'E' => (1, ". "), 'F' => (4, "..-. "), 'G' => (3, "--. "), 'H' => (4, ".... "), 'I' => (2, ".. "), 'J' => (4, ".--- "), 'K' => (3, "-.- "), 'L' => (4, ".-.. "), 'M' => (2, "-- "), 'N' => (2, "-. "), 'O' => (3, "--- "), 'P' => (4, ".--. "), 'Q' => (4, "--.- "), 'R' => (3, ".-. "), 'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "), 'V' => (4, "...- "), 'W' => (3, ".-- "), 'X' => (4, "-..- "), 'Y' => (4, "-.-- "), 'Z' => (4, "--.. "), '1' => (5, ".----"), '2' => (5, "..---"), '3' => (5, "...--"), '4' => (5, "....-"), '5' => (5, "....."), '6' => (5, "-...."), '7' => (5, "--..."), '8' => (5, "---.."), '9' => (5, "----."), '0' => (5, "-----"), others => (1, " ")); -- Dummy => Other characters do not need code.   end Morse;
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it. If both remaining doors have goats behind them, he chooses one randomly. After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door. Imagine that you chose Door 1 and the host opens Door 3, which has a goat. He then asks you "Do you want to switch to Door Number 2?" The question Is it to your advantage to change your choice? Note The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors. Task Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess. Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. References Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3 A YouTube video:   Monty Hall Problem - Numberphile.
#Ada
Ada
-- Monty Hall Game   with Ada.Text_Io; use Ada.Text_Io; with Ada.Float_Text_Io; use Ada.Float_Text_Io; with ada.Numerics.Discrete_Random;   procedure Monty_Stats is Num_Iterations : Positive := 100000; type Action_Type is (Stay, Switch); type Prize_Type is (Goat, Pig, Car); type Door_Index is range 1..3; package Random_Prize is new Ada.Numerics.Discrete_Random(Door_Index); use Random_Prize; Seed : Generator; Doors : array(Door_Index) of Prize_Type;   procedure Set_Prizes is Prize_Index : Door_Index; Booby_Prize : Prize_Type := Goat; begin Reset(Seed); Prize_Index := Random(Seed); Doors(Prize_Index) := Car; for I in Doors'range loop if I /= Prize_Index then Doors(I) := Booby_Prize; Booby_Prize := Prize_Type'Succ(Booby_Prize); end if; end loop; end Set_Prizes;   function Play(Action : Action_Type) return Prize_Type is Chosen : Door_Index := Random(Seed); Monty : Door_Index; begin Set_Prizes; for I in Doors'range loop if I /= Chosen and Doors(I) /= Car then Monty := I; end if; end loop; if Action = Switch then for I in Doors'range loop if I /= Monty and I /= Chosen then Chosen := I; exit; end if; end loop; end if; return Doors(Chosen); end Play; Winners : Natural; Pct : Float; begin Winners := 0; for I in 1..Num_Iterations loop if Play(Stay) = Car then Winners := Winners + 1; end if; end loop; Put("Stay : count" & Natural'Image(Winners) & " = "); Pct := Float(Winners * 100) / Float(Num_Iterations); Put(Item => Pct, Aft => 2, Exp => 0); Put_Line("%"); Winners := 0; for I in 1..Num_Iterations loop if Play(Switch) = Car then Winners := Winners + 1; end if; end loop; Put("Switch : count" & Natural'Image(Winners) & " = "); Pct := Float(Winners * 100) / Float(Num_Iterations); Put(Item => Pct, Aft => 2, Exp => 0); Put_Line("%");   end Monty_Stats;
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.
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion %== Calls the "function" ==% call :ModInv 42 2017 result echo !result! call :ModInv 40 1 result echo !result! call :ModInv 52 -217 result echo !result! call :ModInv -486 217 result echo !result! call :ModInv 40 2018 result echo !result! pause>nul exit /b 0   %== The "function" ==% :ModInv set a=%1 set b=%2   if !b! lss 0 (set /a b=-b) if !a! lss 0 (set /a a=b - ^(-a %% b^))   set t=0&set nt=1&set r=!b!&set /a nr=a%%b   :while_loop if !nr! neq 0 ( set /a q=r/nr set /a tmp=nt set /a nt=t - ^(q*nt^) set /a t=tmp   set /a tmp=nr set /a nr=r - ^(q*nr^) set /a r=tmp goto while_loop )   if !r! gtr 1 (set %3=-1&goto :EOF) if !t! lss 0 set /a t+=b set %3=!t! goto :EOF
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#Phix
Phix
with javascript_semantics function bind(object m, integer f) return f(m) end function function unit(object m) return m end function function root(sequence al) {atom a, string lg} = al atom res = sqrt(a) return {res,lg&sprintf("took root: %f -> %f\n",{a,res})} end function function addOne(sequence al) {atom a, string lg} = al atom res = a + 1 return {res,lg&sprintf("added one: %f -> %f\n",{a,res})} end function function half(sequence al) {atom a, string lg} = al atom res = a / 2 return {res,lg&sprintf("halved it: %f -> %f\n",{a,res})} end function printf(1,"%f obtained by\n%s", bind(bind(bind({5,""},root),addOne),half))
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Perl
Perl
use strict; use feature 'say'; use Data::Monad::List;   # Cartesian product to 'count' in binary my @cartesian = [( list_flat_map_multi { scalar_list(join '', @_) } scalar_list(0..1), scalar_list(0..1), scalar_list(0..1) )->scalars]; say join "\n", @{shift @cartesian};   say '';   # Pythagorean triples my @triples = [( list_flat_map_multi { scalar_list( { $_[0] < $_[1] && $_[0]**2+$_[1]**2 == $_[2]**2 ? join(',',@_) : () } ) } scalar_list(1..10), scalar_list(1..10), scalar_list(1..10) )->scalars];   for (@{shift @triples}) { say keys %$_ if keys %$_; }
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Racket
Racket
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly common idiom though. You can assign an infinite lazy list to an array and it will only produce the values when they are accessed.   my @integers = 1 .. Inf; # an infinite array containing all positive integers   say @integers[100000]; #100001 (arrays are zero indexed.)   # Multi dimension arrays may be predeclared which constrains the indices to the declared size:   my @dim5[3,3,3,3,3];   #Creates a preallocated 5 dimensional array where each branch has 3 storage slots and constrains the size to the declared size. #It can then be accessed like so:   @dim5[0;1;2;1;0] = 'Raku';   say @dim5[0;1;2;1;0]; # prints 'Raku'   #@dim5[0;1;2;1;4] = 'error'; # runtime error: Index 4 for dimension 5 out of range (must be 0..2)   # Note that the dimensions do not _need_ to be predeclared / allocated. Raku will auto-vivify the necessary storage slots on first access.   my @a2;   @a2[0;1;2;1;0] = 'Raku';   @a2[0;1;2;1;4] = 'not an error';   # It is easy to access array "slices" in Raku.   my @b = map { [$_ X~ 1..5] }, <a b c d>;   .say for @b; # [a1 a2 a3 a4 a5] # [b1 b2 b3 b4 b5] # [c1 c2 c3 c4 c5] # [d1 d2 d3 d4 d5]   say @b[*;2]; # Get the all of the values in the third "column" # (a3 b3 c3 d3)   # By default, Raku can store any object in an array, and it is not very compact. You can constrain the type of values that may be stored which can allow the optimizer to store them much more efficiently.   my @c = 1 .. 10; # Stores integers, but not very compactly since there are no constraints on what the values _may_ be   my uint16 @d = 1 .. 10 # Since there are and only can be unsigned 16 bit integers, the optimizer will use a much more compact memory layout.   # Indices must be a positive integer. Negative indices are not permitted, fractional indices will be truncated to an integer.
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.
#AppleScript
AppleScript
set n to 12 -- Size of table. repeat with x from 0 to n if x = 0 then set {table, x} to {{return}, -1} repeat with y from 0 to n if y's contents = 0 then if x > 0 then set row to {f(x)} if x = -1 then set {row, x} to {{f("x")}, 1} else if y ≥ x then set end of row to f(x * y) if y < x then set end of row to f("") end if end repeat set end of table to row & return end repeat return table as string   -- Handler/Function for formatting fixed width integer string. on f(x) set text item delimiters to "" return (characters -4 thru -1 of (" " & x)) as string end f
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).
#Perl
Perl
use strict; use warnings; use Statistics::Regression;   my @y = (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); my @x = ( 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);   my @model = ('const', 'X', 'X**2'); my $reg = Statistics::Regression->new( '', [@model] ); $reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1; my @coeff = $reg->theta();   printf "%-6s %8.3f\n", $model[$_], $coeff[$_] for 0..@model-1;
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Fortran
Fortran
program test implicit none integer :: i, j, n   do i = 1, 5 write(*, "(a, i0, a)", advance = "no") "Degree ", i, ": " do j = 1, 10 n = multifactorial(j, i) write(*, "(i0, 1x)", advance = "no") n end do write(*,*) end do   contains   function multifactorial (range, degree) integer :: multifactorial, range, degree integer :: k   multifactorial = product((/(k, k=range, 1, -degree)/))   end function multifactorial end program test
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.
#LiveCode_Builder
LiveCode Builder
  LiveCode Builder (LCB) is a slightly lower level, strictly typed variant of LiveCode Script (LCS) used for making add-on extensions to LiveCode Script   -- results will be a point array struct like [117.0000,394.0000] relative to the current widget's view port use com.livecode.widget -- include the required module --- in your handler: variable tPosition as Point -- type declaration, tPosition is a point array struct put the mouse position into tPosition variable tRect as Rectangle -- type declaration, tRect is a rect array struct, something like [0,1024,0,768] put my bounds into tRect if tPosition is within tRect then log "mouse position is within the widget bounds" end if  
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.
#Logo
Logo
show mousepos  ; [-250 250]
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
#Haskell
Haskell
import Control.Monad import Data.List   -- given n, "queens n" solves the n-queens problem, returning a list of all the -- safe arrangements. each solution is a list of the columns where the queens are -- located for each row queens :: Int -> [[Int]] queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where   -- foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a -- foldM folds (from left to right) in the list monad, which is convenient for -- "nondeterminstically" finding "all possible solutions" of something. the -- initial value [] corresponds to the only safe arrangement of queens in 0 rows   -- given a safe arrangement y of queens in the first i rows, and a list of -- possible choices, "oneMoreQueen y _" returns a list of all the safe -- arrangements of queens in the first (i+1) rows along with remaining choices oneMoreQueen (y,d) _ = [(x:y, delete x d) | x <- d, safe x] where   -- "safe x" tests whether a queen at column x is safe from previous queens safe x = and [x /= c + n && x /= c - n | (n,c) <- zip [1..] y]   -- prints what the board looks like for a solution; with an extra newline printSolution y = do let n = length y mapM_ (\x -> putStrLn [if z == x then 'Q' else '.' | z <- [1..n]]) y putStrLn ""   -- prints all the solutions for 6 queens main = mapM_ printSolution $ queens 6
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Wren
Wren
var nthRoot = Fn.new { |x, n| if (n < 2) Fiber.abort("n must be more than 1") if (x <= 0) Fiber.abort("x must be positive") var np = n - 1 var iter = Fn.new { |g| (np*g + x/g.pow(np))/n } var g1 = x var g2 = iter.call(g1) while (g1 != g2) { g1 = iter.call(g1) g2 = iter.call(iter.call(g2)) } return g1 }   var trios = [ [1728, 3, 2], [1024, 10, 1], [2, 2, 5] ] for (trio in trios) { System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))") }
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#PARI.2FGP
PARI/GP
ordinal(n)=my(k=n%10,m=n%100); Str(n,if(m<21&&m>3,"th",k==1,"st",k==2,"nd",k==3,"rd","th")); apply(ordinal, [0..25]) apply(ordinal, [250..265]) apply(ordinal, [1000..1025]) apply(ordinal, [111, 1012])
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
#Picat
Picat
go => println([N : N in 1..5000, munchhausen_number(N)]).   munchhausen_number(N) => N == sum([T : I in N.to_string(),II = I.to_int(), T = II**II]).
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).
#JavaScript
JavaScript
function f(num) { return (num === 0) ? 1 : num - m(f(num - 1)); }   function m(num) { return (num === 0) ? 0 : num - f(m(num - 1)); }   function range(m, n) { return Array.apply(null, Array(n - m + 1)).map( function (x, i) { return m + i; } ); }   var a = range(0, 19);   //return a new array of the results and join with commas to print console.log(a.map(function (n) { return f(n); }).join(', ')); console.log(a.map(function (n) { return m(n); }).join(', '));
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.
#Go
Go
package main   import ( "fmt" "strconv" )   type maybe struct{ value *int }   func (m maybe) bind(f func(p *int) maybe) maybe { return f(m.value) }   func unit(p *int) maybe { return maybe{p} }   func decrement(p *int) maybe { if p == nil { return unit(nil) } else { q := *p - 1 return unit(&q) } }   func triple(p *int) maybe { if p == nil { return unit(nil) } else { q := (*p) * 3 return unit(&q) } }   func main() { i, j, k := 3, 4, 5 for _, p := range []*int{&i, &j, nil, &k} { m1 := unit(p) m2 := m1.bind(decrement).bind(triple) var s1, s2 string = "none", "none" if m1.value != nil { s1 = strconv.Itoa(*m1.value) } if m2.value != nil { s2 = strconv.Itoa(*m2.value) } fmt.Printf("%4s -> %s\n", 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
#AWK
AWK
  # --- with command line argument "throws" ---   BEGIN{ th=ARGV[1]; for(i=0; i<th; i++) cin += (rand()^2 + rand()^2) < 1 printf("Pi = %8.5f\n",4*cin/th) }   usage: awk -f pi 2300   Pi = 3.14333    
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.)
#Kotlin
Kotlin
// version 1.1.2   fun encode(s: String): IntArray { if (s.isEmpty()) return intArrayOf() val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray() val result = IntArray(s.length) for ((i, c) in s.withIndex()) { val index = symbols.indexOf(c) if (index == -1) throw IllegalArgumentException("$s contains a non-alphabetic character") result[i] = index if (index == 0) continue for (j in index - 1 downTo 0) symbols[j + 1] = symbols[j] symbols[0] = c } return result }   fun decode(a: IntArray): String { if (a.isEmpty()) return "" val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray() val result = CharArray(a.size) for ((i, n) in a.withIndex()) { if (n !in 0..25) throw IllegalArgumentException("${a.contentToString()} contains an invalid number") result[i] = symbols[n] if (n == 0) continue for (j in n - 1 downTo 0) symbols[j + 1] = symbols[j] symbols[0] = result[i] } return result.joinToString("") }   fun main(args: Array<String>) { val strings = arrayOf("broood", "bananaaa", "hiphophiphop") val encoded = Array<IntArray?>(strings.size) { null } for ((i, s) in strings.withIndex()) { encoded[i] = encode(s) println("${s.padEnd(12)} -> ${encoded[i]!!.contentToString()}") } println() val decoded = Array<String?>(encoded.size) { null } for ((i, a) in encoded.withIndex()) { decoded[i] = decode(a!!) print("${a.contentToString().padEnd(38)} -> ${decoded[i]!!.padEnd(12)}") println(" -> ${if (decoded[i] == strings[i]) "correct" else "incorrect"}") } }
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).
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation" use framework "AppKit"   on morseCode(msg) script morse -- Unit duration in seconds and sounds used. property units : 0.075 property morseSound : current application's class "NSSound"'s soundNamed:("Glass") property unknownCharacterSound : current application's class "NSSound"'s soundNamed:("Frog") -- Unicode IDs of in-range but uncatered-for punctuation characters. property unrecognisedPunctuation : {35, 37, 42, 60, 62, 91, 92, 93, 94} -- Dits and dahs for recognised characters, in units. property letters : {{1, 3}, {3, 1, 1, 1}, {3, 1, 3, 1}, {3, 1, 1}, {1}, {1, 1, 3, 1}, {3, 3, 1}, {1, 1, 1, 1}, {1, 1}, ¬ {1, 3, 3, 3}, {3, 1, 3}, {1, 3, 1, 1}, {3, 3}, {3, 1}, {3, 3, 3}, {1, 3, 3, 1}, {3, 3, 1, 3}, {1, 3, 1}, {1, 1, 1}, ¬ {3}, {1, 1, 3}, {1, 1, 1, 3}, {1, 3, 3}, {3, 1, 1, 3}, {3, 1, 3, 3}, {3, 3, 1, 1}} property underscore : {1, 1, 3, 3, 1, 3} property digitsAndPunctuation : {{3, 3, 3, 3, 3}, {1, 3, 3, 3, 3}, {1, 1, 3, 3, 3}, {1, 1, 1, 3, 3}, ¬ {1, 1, 1, 1, 3}, {1, 1, 1, 1, 1}, {3, 1, 1, 1, 1}, {3, 3, 1, 1, 1}, {3, 3, 3, 1, 1}, {3, 3, 3, 3, 1}, ¬ {3, 3, 3, 1, 1, 1}, {3, 1, 3, 1, 3, 1}, missing value, {3, 1, 1, 1, 3}, missing value, ¬ {1, 1, 3, 3, 1, 1}, {1, 3, 3, 1, 3, 1}} property |punctuation| : {{3, 1, 3, 1, 3, 3}, {1, 3, 1, 1, 3, 1}, missing value, {1, 1, 1, 3, 1, 1, 3}, missing value, ¬ {1, 3, 1, 1, 1}, {1, 3, 3, 3, 3, 1}, {3, 1, 3, 3, 1}, {3, 1, 3, 3, 1, 3}, missing value, ¬ {1, 3, 1, 3, 1}, {3, 3, 1, 1, 3, 3}, {3, 1, 1, 1, 1, 3}, {1, 3, 1, 3, 1, 3}, {3, 1, 1, 3, 1}} -- Unicode IDs of the message's characters. property UnicodeIDs : (id of msg) as list   on sendCharacter(ditsAndDahs) repeat with ditOrDah in ditsAndDahs tell morseSound to play() delay (ditOrDah * units) tell morseSound to stop() delay (1 * units) end repeat delay (2 * units) -- Previous 1 unit + 2 units = 3 units between characters. end sendCharacter   on sendMessage() -- Play an extremely short sound to ensure the sound system's awake for the first morse beep. tell morse to sendCharacter({0}) -- Output the message. repeat with i from 1 to (count UnicodeIDs) set thisID to item i of my UnicodeIDs if ((thisID > 122) or (thisID < 32) or (thisID is in unrecognisedPunctuation)) then -- Character not catered for. Play alternative sound. tell unknownCharacterSound to play() delay (3 * units) tell unknownCharacterSound to stop() delay (3 * units) else if ((thisID > 64) and ((thisID < 91) or (thisID > 96))) then -- English letter. sendCharacter(item (thisID mod 32) of my letters) else if (thisID is 95) then -- Underscore. sendCharacter(underscore) else if (thisID > 47) then -- Digit, colon, semicolon, equals, or question mark. sendCharacter(item (thisID - 47) of my digitsAndPunctuation) else if (thisID > 32) then -- Other recognised punctuation. sendCharacter(item (thisID - 32) of my |punctuation|) else -- Space. delay (4 * units) -- Previous 3 units + 4 units = 7 units between "words". end if end repeat end sendMessage end script   tell morse to sendMessage() end morseCode   -- Test code: morseCode("Coded in AppleScrip†.")
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.
#ALGOL_68
ALGOL 68
INT trials=100 000;   PROC brand = (INT n)INT: 1 + ENTIER (n * random);   PROC percent = (REAL x)STRING: fixed(100.0*x/trials,0,2)+"%";   main: ( INT prize, choice, show, not shown, new choice; INT stay winning:=0, change winning:=0, random winning:=0; INT doors = 3; [doors-1]INT other door;   TO trials DO # put the prize somewhere # prize := brand(doors); # let the user choose a door # choice := brand(doors); # let us take a list of unchoosen doors # INT k := LWB other door; FOR j TO doors DO IF j/=choice THEN other door[k] := j; k+:=1 FI OD; # Monty opens one... # IF choice = prize THEN # staying the user will win... Monty opens a random port# show := other door[ brand(doors - 1) ]; not shown := other door[ (show+1) MOD (doors - 1 ) + 1] ELSE # no random, Monty can open just one door... # IF other door[1] = prize THEN show := other door[2]; not shown := other door[1] ELSE show := other door[1]; not shown := other door[2] FI FI;   # the user randomly choose one of the two closed doors (one is his/her previous choice, the second is the one not shown ) # other door[1] := choice; other door[2] := not shown; new choice := other door[ brand(doors - 1) ]; # now let us count if it takes it or not # IF choice = prize THEN stay winning+:=1 FI; IF not shown = prize THEN change winning+:=1 FI; IF new choice = prize THEN random winning+:=1 FI OD;   print(("Staying: ", percent(stay winning), new line )); print(("Changing: ", percent(change winning), new line )); print(("New random choice: ", percent(random winning), new line )) )
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.
#BCPL
BCPL
get "libhdr"   let mulinv(a, b) = b<0 -> mulinv(a, -b), a<0 -> mulinv(b - (-a rem b), b), valof $( let t, nt, r, nr = 0, 1, b, a rem b until nr = 0 $( let tmp, q = ?, r / nr tmp := nt ; nt := t - q*nt ; t := tmp tmp := nr ; nr := r - q*nr ; r := tmp $) resultis r>1 -> -1, t<0 -> t + b, t $)   let show(a, b) be $( let mi = mulinv(a, b) test mi>=0 do writef("%N, %N -> %N*N", a, b, mi) or writef("%N, %N -> no inverse*N", a, b) $)   let start() be $( show(42, 2017) show(40, 1) show(52, -217) show(-486, 217) show(40, 2018) $)
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.
#Bracmat
Bracmat
( ( mod-inv = a b b0 x0 x1 q .  !arg:(?a.?b) & ( !b:1 | (!b.0.1):(?b0.?x0.?x1) & whl ' ( !a:>1 & div$(!a.!b):?q & (!b.mod$(!a.!b)):(?a.?b) & (!x1+-1*!q*!x0.!x0):(?x0.?x1) ) & (!x:>0|!x1+!b0) ) ) & out$(mod-inv$(42.2017)) };
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#PHP
PHP
class WriterMonad {   /** @var mixed */ private $value; /** @var string[] */ private $logs;   private function __construct($value, array $logs = []) { $this->value = $value; $this->logs = $logs; }   public static function unit($value, string $log): WriterMonad { return new WriterMonad($value, ["{$log}: {$value}"]); }   public function bind(callable $mapper): WriterMonad { $mapped = $mapper($this->value); assert($mapped instanceof WriterMonad); return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]); }   public function value() { return $this->value; }   public function logs(): array { return $this->logs; } }   $root = fn(float $i): float => sqrt($i); $addOne = fn(float $i): float => $i + 1; $half = fn(float $i): float => $i / 2;   $m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);   $result = WriterMonad::unit(5, "Initial value") ->bind($m($root, "square root")) ->bind($m($addOne, "add one")) ->bind($m($half, "half"));   print "The Golden Ratio is: {$result->value()}\n"; print join("\n", $result->logs());
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Phix
Phix
function bindf(sequence m, integer f) return f(m) end function function unit(sequence m) return m end function function increment(sequence l) return unit(sq_add(l,1)) end function function double(sequence l) return unit(sq_mul(l,2)) end function sequence m1 = unit({3, 4, 5}), m2 = bindf(bindf(m1,increment),double) printf(1,"%v -> %v\n", {m1, m2})
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Python
Python
"""A List Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations from itertools import chain   from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar     T = TypeVar("T")     class MList(List[T]): @classmethod def unit(cls, value: Iterable[T]) -> MList[T]: return cls(value)   def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]: return MList(chain.from_iterable(map(func, self)))   def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]: return self.bind(func)     if __name__ == "__main__": # Chained int and string functions print( MList([1, 99, 4]) .bind(lambda val: MList([val + 1])) .bind(lambda val: MList([f"${val}.00"])) )   # Same, but using `>>` as the bind operator. print( MList([1, 99, 4]) >> (lambda val: MList([val + 1])) >> (lambda val: MList([f"${val}.00"])) )   # Cartesian product of [1..5] and [6..10] print( MList(range(1, 6)).bind( lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)])) ) )   # Pythagorean triples with elements between 1 and 25 print( MList(range(1, 26)).bind( lambda x: MList(range(x + 1, 26)).bind( lambda y: MList(range(y + 1, 26)).bind( lambda z: MList([(x, y, z)]) if x * x + y * y == z * z else MList([]) ) ) ) )  
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Raku
Raku
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly common idiom though. You can assign an infinite lazy list to an array and it will only produce the values when they are accessed.   my @integers = 1 .. Inf; # an infinite array containing all positive integers   say @integers[100000]; #100001 (arrays are zero indexed.)   # Multi dimension arrays may be predeclared which constrains the indices to the declared size:   my @dim5[3,3,3,3,3];   #Creates a preallocated 5 dimensional array where each branch has 3 storage slots and constrains the size to the declared size. #It can then be accessed like so:   @dim5[0;1;2;1;0] = 'Raku';   say @dim5[0;1;2;1;0]; # prints 'Raku'   #@dim5[0;1;2;1;4] = 'error'; # runtime error: Index 4 for dimension 5 out of range (must be 0..2)   # Note that the dimensions do not _need_ to be predeclared / allocated. Raku will auto-vivify the necessary storage slots on first access.   my @a2;   @a2[0;1;2;1;0] = 'Raku';   @a2[0;1;2;1;4] = 'not an error';   # It is easy to access array "slices" in Raku.   my @b = map { [$_ X~ 1..5] }, <a b c d>;   .say for @b; # [a1 a2 a3 a4 a5] # [b1 b2 b3 b4 b5] # [c1 c2 c3 c4 c5] # [d1 d2 d3 d4 d5]   say @b[*;2]; # Get the all of the values in the third "column" # (a3 b3 c3 d3)   # By default, Raku can store any object in an array, and it is not very compact. You can constrain the type of values that may be stored which can allow the optimizer to store them much more efficiently.   my @c = 1 .. 10; # Stores integers, but not very compactly since there are no constraints on what the values _may_ be   my uint16 @d = 1 .. 10 # Since there are and only can be unsigned 16 bit integers, the optimizer will use a much more compact memory layout.   # Indices must be a positive integer. Negative indices are not permitted, fractional indices will be truncated to an integer.
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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program multtable.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall .equ MAXI, 12 /*********************************/ /* Initialized data */ /*********************************/ .data sMessValeur: .fill 11, 1, ' ' @ size => 11 szCarriageReturn: .asciz "\n" sBlanc1: .asciz " " sBlanc2: .asciz " " sBlanc3: .asciz " " /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program push {fp,lr} @ saves 2 registers @ display first line mov r4,#0 1: @ begin loop mov r0,r4 ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function mov r2,#0 @ final zéro strb r2,[r1,r0] @ on display value ldr r0,iAdrsMessValeur bl affichageMess @ display message cmp r4,#10 @ one or two digit in résult ldrgt r0,iAdrsBlanc2 @ two display two spaces ldrle r0,iAdrsBlanc3 @ one display 3 spaces bl affichageMess @ display message add r4,#1 @ increment counter cmp r4,#MAXI ble 1b @ loop ldr r0,iAdrszCarriageReturn bl affichageMess @ display carriage return   mov r5,#1 @ line counter 2: @ begin loop lines mov r0,r5 @ display column 1 with N° line ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function mov r2,#0 @ final zéro strb r2,[r1,r0] ldr r0,iAdrsMessValeur bl affichageMess @ display message cmp r5,#10 @ one or two digit in N° line ldrge r0,iAdrsBlanc2 ldrlt r0,iAdrsBlanc3 bl affichageMess mov r4,#1 @ counter column 3: @ begin loop columns mul r0,r4,r5 @ multiplication mov r3,r0 @ save résult ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function mov r2,#0 strb r2,[r1,r0] ldr r0,iAdrsMessValeur bl affichageMess @ display message cmp r3,#100 @ 3 digits in résult ? ldrge r0,iAdrsBlanc1 @ yes, display one space bge 4f cmp r3,#10 @ 2 digits in result ldrge r0,iAdrsBlanc2 @ yes display 2 spaces ldrlt r0,iAdrsBlanc3 @ no display 3 spaces 4: bl affichageMess @ display message add r4,#1 @ increment counter column cmp r4,r5 @ < counter lines ble 3b @ loop ldr r0,iAdrszCarriageReturn bl affichageMess @ display carriage return add r5,#1 @ increment line counter cmp r5,#MAXI @ MAXI ? ble 2b @ loop   100: @ standard end of the program mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrsMessValeur: .int sMessValeur iAdrszCarriageReturn: .int szCarriageReturn iAdrsBlanc1: .int sBlanc1 iAdrsBlanc2: .int sBlanc2 iAdrsBlanc3: .int sBlanc3 /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL   1: @ start loop bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 */ subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value mov r3,#0xCCCD @ r3 <- magic_number lower movt r3,#0xCCCC @ r3 <- magic_number upper umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function        
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).
#Phix
Phix
with javascript_semantics constant N = 15, M=3 sequence x = {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}, y = {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}, s = repeat(0,N), t = repeat(0,N), a = repeat(repeat(0,M+1),M) for k=1 to 2*M do for i=1 to N do s[k] += power(x[i],k-1) if k<=M then t[k] += y[i]*power(x[i],k-1) end if end for end for -- build linear system for row=1 to M do for col=1 to M do a[row,col] = s[row+col-1] end for a[row,M+1] = t[row] end for puts(1,"Linear system coefficents:\n") pp(a,{pp_Nest,1,pp_IntFmt,"%7.1f",pp_FltFmt,"%7.1f"}) for j=1 to M do integer i = j while a[i,j]=0 do i += 1 end while if i=M+1 then ?"SINGULAR MATRIX !" ?9/0 end if for k=1 to M+1 do {a[j,k],a[i,k]} = {a[i,k],a[j,k]} end for atom Y = 1/a[j,j] a[j] = sq_mul(a[j],Y) for k=1 to M do if k<>j then Y=-a[k,j] for m=1 to M+1 do a[k,m] += Y*a[j,m] end for end if end for end for puts(1,"Solutions:\n") ?columnize(a,M+1)[1]
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function multiFactorial (n As UInteger, degree As Integer) As UInteger If n < 2 Then Return 1 Var result = n For i As Integer = n - degree To 2 Step -degree result *= i Next Return result End Function   For degree As Integer = 1 To 5 Print "Degree"; degree; " => "; For n As Integer = 1 To 10 Print multiFactorial(n, degree); " "; Next n Print Next degree   Print Print "Press any key to quit" Sleep
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.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ works when console is the active window \\ pressing right mouse button exit the loop While mouse<>2 Print mouse.x, mouse.y End While \\ end of part one, now we make a form with title Form1 (same name as the variable name) Declare Form1 Form Layer Form1 { window 16, 10000,8000 ' 16pt font at maximum 10000 twips x 8000 twips cls #335522, 1 \\ from 2nd line start the split screen (for form's layer) pen 15 ' white } Function Form1.MouseMove { Read new button, shift, x, y ' we use new because call is local, same scope as Checkit. Layer Form1 { print x, y, button refresh } } Function Form1.MouseDown { Read new button, shift, x, y \\ when we press mouse button we print in console \\ but only the first time print x, y, button refresh } \\ open Form1 as modal window above console Method Form1, "Show", 1 Declare Form1 Nothing } CheckIt  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MousePosition["WindowAbsolute"]
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
#Heron
Heron
module NQueens { inherits { Heron.Windows.Console; } fields { n : Int = 4; sols : List = new List(); } methods { PosToString(row : Int, col : Int) : String { return "row " + row.ToString() + ", col " + col.ToString(); } AddQueen(b : Board, row : Int, col : Int) { if (!b.TryAddQueen(row, col)) return; if (row < n - 1) foreach (i in 0..n-1) AddQueen(new Board(b), row + 1, i); else sols.Add(b); } Main() { foreach (i in 0..n-1) AddQueen(new Board(), 0, i); foreach (b in sols) { b.Output(); WriteLine(""); } WriteLine("Found " + sols.Count().ToString() + " solutions"); } } }   class Board { fields { rows = new List(); } methods { Constructor() { foreach (r in 0..n-1) { var col = new List(); foreach (c in 0..n-1) col.Add(false); rows.Add(col); } } Constructor(b : Board) { Constructor(); foreach (r in 0..n-1) foreach (c in 0..n-1) SetSpaceOccupied(r, c, b.SpaceOccupied(r, c)); } SpaceOccupied(row : Int, col : Int) : Bool { return rows[row][col]; } SetSpaceOccupied(row : Int, col : Int, b : Bool) { rows[row][col] = b; } ValidPos(row : Int, col : Int) : Bool { return ((row >= 0) && (row < n)) && ((col >= 0) && (col < n)); } VectorOccupied(row : Int, col : Int, rowDir : Int, colDir : Int) : Bool { var nextRow = row + rowDir; var nextCol = col + colDir; if (!ValidPos(nextRow, nextCol)) return false; if (SpaceOccupied(nextRow, nextCol)) return true; return VectorOccupied(nextRow, nextCol, rowDir, colDir); } TryAddQueen(row : Int, col : Int) : Bool { foreach (rowDir in -1..1) foreach (colDir in -1..1) if (rowDir != 0 || colDir != 0) if (VectorOccupied(row, col, rowDir, colDir)) return false; SetSpaceOccupied(row, col, true); return true; } Output() { foreach (row in 0..n-1) { foreach (col in 0..n-1) { if (SpaceOccupied(row, col)) { Write("Q"); } else { Write("."); } } WriteLine(""); } } } }
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#XBS
XBS
func nthRoot(x,a){ send x^(1/a); }{a=2}; log(nthRoot(8,3));
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#XPL0
XPL0
include c:\cxpl\stdlib;   func real NRoot(A, N); \Return the Nth root of A real A, N; real X, X0, Y; int I; [X:= 1.0; \initial guess repeat X0:= X; Y:= 1.0; for I:= 1 to fix(N)-1 do Y:= Y*X0; X:= ((N-1.0)*X0 + A/Y) / N; until abs(X-X0) < 1.0E-15; \(until X=X0 doesn't always work) return X; ];   [Format(5, 15); RlOut(0, NRoot( 2., 2.)); CrLf(0); RlOut(0, Power( 2., 0.5)); CrLf(0); \for comparison RlOut(0, NRoot(27., 3.)); CrLf(0); RlOut(0, NRoot(1024.,10.)); CrLf(0); ]
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.
#Pascal
Pascal
Program n_th;   function Suffix(N: NativeInt):AnsiString; var res: AnsiString; begin res:= 'th'; case N mod 10 of 1:IF N mod 100 <> 11 then res:= 'st'; 2:IF N mod 100 <> 12 then res:= 'nd'; 3:IF N mod 100 <> 13 then res:= 'rd'; else end; Suffix := res; end;   procedure Print_Images(loLim, HiLim: NativeInt); var i : NativeUint; begin for I := LoLim to HiLim do write(i,Suffix(i),' '); writeln; end;   begin Print_Images( 0, 25); Print_Images( 250, 265); Print_Images(1000, 1025); end.
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
#PicoLisp
PicoLisp
(for N 5000 (and (= N (sum '((N) (** N N)) (mapcar format (chop N)) ) ) (println N) ) )
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#jq
jq
  def M: def F: if . == 0 then 1 else . - ((. - 1) | F | M) end; if . == 0 then 0 else . - ((. - 1) | M | F) end;   def F: if . == 0 then 1 else . - ((. - 1) | F | M) 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.
#Haskell
Haskell
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1)) -- prints "Just 7" print $ Nothing >>= (return . (*2)) >>= (return . (+1)) -- prints "Nothing"
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.
#Hoon
Hoon
  :-  %say |= [^ [[txt=(unit ,@tas) ~] ~]] :-  %noun |^  %+ biff txt  ;~ biff m-parse m-double == ++ m-parse |= a=@tas ^- (unit ,@ud) (rust (trip a) dem)  :: ++ m-double |= a=@ud ^- (unit ,@ud) (some (mul a 2)) --  
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
#BASIC
BASIC
DECLARE FUNCTION getPi! (throws!) CLS PRINT getPi(10000) PRINT getPi(100000) PRINT getPi(1000000) PRINT getPi(10000000)   FUNCTION getPi (throws) inCircle = 0 FOR i = 1 TO throws 'a square with a side of length 2 centered at 0 has 'x and y range of -1 to 1 randX = (RND * 2) - 1'range -1 to 1 randY = (RND * 2) - 1'range -1 to 1 'distance from (0,0) = sqrt((x-0)^2+(y-0)^2) dist = SQR(randX ^ 2 + randY ^ 2) IF dist < 1 THEN 'circle with diameter of 2 has radius of 1 inCircle = inCircle + 1 END IF NEXT i getPi = 4! * inCircle / throws END FUNCTION
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.)
#Lua
Lua
-- Return table of the alphabet in lower case function getAlphabet () local letters = {} for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end return letters end   -- Move the table value at ind to the front of tab function moveToFront (tab, ind) local toMove = tab[ind] for i = ind - 1, 1, -1 do tab[i + 1] = tab[i] end tab[1] = toMove end   -- Perform move-to-front encoding on input function encode (input) local symbolTable, output, index = getAlphabet(), {} for pos = 1, #input do for k, v in pairs(symbolTable) do if v == input:sub(pos, pos) then index = k end end moveToFront(symbolTable, index) table.insert(output, index - 1) end return table.concat(output, " ") end   -- Perform move-to-front decoding on input function decode (input) local symbolTable, output = getAlphabet(), "" for num in input:gmatch("%d+") do output = output .. symbolTable[num + 1] moveToFront(symbolTable, num + 1) end return output end   -- Main procedure local testCases, output = {"broood", "bananaaa", "hiphophiphop"} for _, case in pairs(testCases) do output = encode(case) print("Original string: " .. case) print("Encoded: " .. output) print("Decoded: " .. decode(output)) print() 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).
#Arturo
Arturo
; set the morse code   code: #[ ; letters 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: "--.."   ; digits "0": "-----" "1": ".----" "2": "..---" "3": "...--" "4": "....-" "5": "....." "6": "-...." "7": "--..." "8": "---.." "9": "----." ]   ; print an encoded message   str: "hello world 2019" out: ""   loop split str 'ch [ if not? whitespace? ch -> 'out ++ code\[ch] 'out ++ " " ]   print out
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.
#APL
APL
∇ Run runs;doors;i;chosen;cars;goats;swap;stay;ix;prices [1] ⍝0: Monthy Hall problem [2] ⍝1: http://rosettacode.org/wiki/Monty_Hall_problem [3] [4] (⎕IO ⎕ML)←0 1 [5] prices←0 0 1 ⍝ 0=Goat, 1=Car [6] [7] ix←⊃,/{3?3}¨⍳runs ⍝ random indexes of doors (placement of car) [8] doors←(runs 3)⍴prices[ix] ⍝ matrix of doors [9] stay←+⌿doors[;?3] ⍝ chose randomly one door - is it a car? [10] swap←runs-stay ⍝ If not, then the other one is! [11] [12] ⎕←'Swap: ',(2⍕100×(swap÷runs)),'% it''s a car' [13] ⎕←'Stay: ',(2⍕100×(stay÷runs)),'% it''s a car' ∇
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.
#C
C
#include <stdio.h>   int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; }   int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#Python
Python
"""A Writer Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations   import functools import math import os   from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union     T = TypeVar("T")     class Writer(Generic[T]): def __init__(self, value: Union[T, Writer[T]], *msgs: str): if isinstance(value, Writer): self.value: T = value.value self.msgs: List[str] = value.msgs + list(msgs) else: self.value = value self.msgs = list(f"{msg}: {self.value}" for msg in msgs)   def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: writer = func(self.value) return Writer(writer, *self.msgs)   def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: return self.bind(func)   def __str__(self): return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"   def __repr__(self): return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"     def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]: """Return a writer monad version of the simple function `func`."""   @functools.wraps(func) def wrapped(value): return Writer(func(value), msg)   return wrapped     if __name__ == "__main__": square_root = lift(math.sqrt, "square root") add_one = lift(lambda x: x + 1, "add one") half = lift(lambda x: x / 2, "div two")   print(Writer(5, "initial") >> square_root >> add_one >> half)  
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Racket
Racket
#lang racket   (define (bind x f) (append-map f x)) (define return list) (define ((lift f) x) (list (f x)))   (define listy-inc (lift add1)) (define listy-double (lift (λ (x) (* 2 x))))   (bind (bind '(3 4 5) listy-inc) listy-double) ;; => '(8 10 12)   (define (pythagorean-triples n) (bind (range 1 n) (λ (x) (bind (range (add1 x) n) (λ (y) (bind (range (add1 y) n) (λ (z) (if (= (+ (* x x) (* y y)) (* z z)) (return (list x y z)) '()))))))))   (pythagorean-triples 25) ;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))   (require syntax/parse/define)   (define-syntax-parser do-macro [(_ [x {~datum <-} y] . the-rest) #'(bind y (λ (x) (do-macro . the-rest)))] [(_ e) #'e])   (define (pythagorean-triples* n) (do-macro [x <- (range 1 n)] [y <- (range (add1 x) n)] [z <- (range (add1 y) n)] (if (= (+ (* x x) (* y y)) (* z z)) (return (list x y z)) '())))   (pythagorean-triples* 25) ;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Raku
Raku
multi bind (@list, &code) { @list.map: &code };   multi bind ($item, &code) { $item.&code };   sub divisors (Int $int) { gather for 1 .. $int { .take if $int %% $_ } }   put (^10).&bind(* + 3).&bind(&divisors)».&bind(*.base: 2).join: "\n";
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#REXX
REXX
g = antenna.2.0
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Ring
Ring
# Project : Multi-dimensional array   a4 = newlist4(5,4,3,2)   func main() m = 1 for i = 1 to 5 for j = 1 to 4 for k = 1 to 3 for l = 1 to 2 a4[i][j][k][l] = m m = m + 1 next next next next see "First element = " + a4[1][1][1][1] + nl a4[1][1][1][1] = 121 see nl for i = 1 to 5 for j = 1 to 4 for k = 1 to 3 for l = 1 to 2 see "" + a4[i][j][k][l] + " " next next next next   func newlist(x, y) if isstring(x) x=0+x ok if isstring(y) y=0+y ok alist = list(x) for t in alist t = list(y) next return alist   func newlist3(x, y, z) if isstring(x) x=0+x ok if isstring(y) y=0+y ok if isstring(z) z=0+z ok alist = list(x) for t in alist t = newlist(y,z) next return alist   func newlist4(x, y, z, w) if isstring(x) x=0+x ok if isstring(y) y=0+y ok if isstring(z) z=0+z ok if isstring(w) w=0+w ok alist = list(x) for t in alist t = newlist3(y,z,w) next return alist
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.
#Arturo
Arturo
mulTable: function [n][ print [" |"] ++ map 1..n => [pad to :string & 3] print "----+" ++ join map 1..n => "----" loop 1..n 'x [ prints (pad to :string x 3) ++ " |" if x>1 -> loop 1..x-1 'y [prints " "] loop x..n 'y [prints " " ++ pad to :string x*y 3] print "" ] ]   mulTable 12
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).
#PicoLisp
PicoLisp
(scl 20)   # Matrix transposition (de matTrans (Mat) (apply mapcar Mat list) )   # Matrix multiplication (de matMul (Mat1 Mat2) (mapcar '((Row) (apply mapcar Mat2 '(@ (sum */ Row (rest) (1.0 .))) ) ) Mat1 ) )   # Matrix identity (de matIdent (N) (let L (need N (1.0) 0) (mapcar '(() (copy (rot L))) L) ) )   # Reduced row echelon form (de reducedRowEchelonForm (Mat) (let (Lead 1 Cols (length (car Mat))) (for (X Mat X (cdr X)) (NIL (loop (T (seek '((R) (n0 (get R 1 Lead))) X) @ ) (T (> (inc 'Lead) Cols)) ) ) (xchg @ X) (let D (get X 1 Lead) (map '((R) (set R (*/ (car R) 1.0 D))) (car X) ) ) (for Y Mat (unless (== Y (car X)) (let N (- (get Y Lead)) (map '((Dst Src) (inc Dst (*/ N (car Src) 1.0)) ) Y (car X) ) ) ) ) (T (> (inc 'Lead) Cols)) ) ) Mat )
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).
#Python
Python
import numpy as np   height = [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 = [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]   X = np.mat(height**np.arange(3)[:, None]) y = np.mat(weight)   print(y * X.T * (X*X.T).I)
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.
#FunL
FunL
def multifactorial( n, d ) = product( n..1 by -d )   for d <- 1..5 println( d, [multifactorial(i, d) | i <- 1..10] ))
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.
#GAP
GAP
MultiFactorial := function(n, k) local r; r := 1; while n > 1 do r := r*n; n := n - k; od; return r; end;   PrintArray(List([1 .. 10], n -> List([1 .. 5], k -> MultiFactorial(n, k)))); [ [ 1, 1, 1, 1, 1 ], [ 2, 2, 2, 2, 2 ], [ 6, 3, 3, 3, 3 ], [ 24, 8, 4, 4, 4 ], [ 120, 15, 10, 5, 5 ], [ 720, 48, 18, 12, 6 ], [ 5040, 105, 28, 21, 14 ], [ 40320, 384, 80, 32, 24 ], [ 362880, 945, 162, 45, 36 ], [ 3628800, 3840, 280, 120, 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.
#MATLAB
MATLAB
get(0,'PointerLocation')
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.
#MAXScript
MAXScript
  try destroydialog mousePos catch ()   rollout mousePos "Mouse position" width:200 ( label mousePosText "Current mouse position:" pos:[0,0] label mousePosX "" pos:[130,0] label mousePosSep "x" pos:[143,0] label mousePosY "" pos:[160,0]   timer updateTimer interval:50 active:true   on updateTimer tick do ( mousePosX.text = (mouse.screenpos.x as integer) as string mousePosY.text = (mouse.screenpos.y as integer) as string )   )   createdialog mousepos  
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
#Icon_and_Unicon
Icon and Unicon
procedure main() write(q(1), " ", q(2), " ", q(3), " ", q(4), " ", q(5), " ", q(6), " ", q(7), " ", q(8)) end   procedure q(c) static udiag, ddiag, row   initial { udiag := list(15, 0) ddiag := list(15, 0) row := list(8, 0) }   every 0 = row[r := 1 to 8] = ddiag[r + c - 1] = udiag[8 + r - c] do # test if free suspend row[r] <- ddiag[r + c - 1] <- udiag[8 + r - c] <- r # place and yield end
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Yabasic
Yabasic
data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0   do read e, b if e = 0 break print "The ", e, "th root of ", b, " is ", b^(1/e), " (", nthroot(b, e), ")" loop     sub nthroot(y, n) local eps, x, d, e   eps = 1e-15 // relative accuracy x = 1 repeat d = ( y / ( x^(n-1) ) - x ) / n x = x + d e = eps * x // absolute accuracy   until(not(d < -e or d > e ))   return x end sub
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#zkl
zkl
fcn nthroot(nth,a,precision=1.0e-5){ x:=prev:=a=a.toFloat(); n1:=nth-1; do{ prev=x; x=( prev*n1 + a/prev.pow(n1) ) / nth; } while( not prev.closeTo(x,precision) ); x }   nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041
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.
#Perl
Perl
use 5.10.0; my %irregulars = ( 1 => 'st', 2 => 'nd', 3 => 'rd', 11 => 'th', 12 => 'th', 13 => 'th'); sub nth { my $n = shift; $n . # q(') . # Uncomment this to add apostrophes to output ($irregulars{$n % 100} // $irregulars{$n % 10} // 'th'); }   sub range { join ' ', map { nth($_) } @{$_[0]} } print range($_), "\n" for ([0..25], [250..265], [1000..1025]);
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#PL.2FI
PL/I
munchausen: procedure options(main); /* precalculate powers */ declare (pows(0:5), i) fixed; pows(0) = 0; /* 0^0=0 for Munchausen numbers */ do i=1 to 5; pows(i) = i**i; end;   declare (d1, d2, d3, d4, num, dpow) fixed; do d1=0 to 5; do d2=0 to 5; do d3=0 to 5; do d4=1 to 5; num = d1*1000 + d2*100 + d3*10 + d4; dpow = pows(d1) + pows(d2) + pows(d3) + pows(d4); if num=dpow then put skip list(num); end; end; end; end; end 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).
#Jsish
Jsish
/* Mutual recursion, is jsish */ function f(num):number { return (num === 0) ? 1 : num - m(f(num - 1)); } function m(num):number { return (num === 0) ? 0 : num - f(m(num - 1)); }   function range(n=10, start=0, step=1):array { var a = Array(n).fill(0); for (var i in a) a[i] = start+i*step; return a; }   var a = range(21); puts(a.map(function (n) { return f(n); }).join(', ')); puts(a.map(function (n) { return m(n); }).join(', '));   /* =!EXPECTSTART!= 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 12 =!EXPECTEND!= */
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.
#J
J
  NB. monad implementation: unit=: < bind=: (@>)( :: ])   NB. monad utility safeVersion=: (<@) ( ::((<_.)"_)) safeCompose=:dyad define dyad def 'x`:6 bind y'/x,unit y )   NB. unsafe functions (fail with infinite arguments) subtractFromSelf=: -~ divideBySelf=: %~   NB. wrapped functions: safeSubtractFromSelf=: subtractFromSelf safeVersion safeDivideBySelf=: divideBySelf safeVersion   NB. task example: safeSubtractFromSelf bind safeDivideBySelf 1 ┌─┐ │0│ └─┘ safeSubtractFromSelf bind safeDivideBySelf _ ┌──┐ │_.│ └──┘
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.
#JavaScript
JavaScript
(function () { 'use strict';   // START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS:   // Returns Infinity if n === 0 function reciprocal(n) { return 1 / n; }   // Returns NaN if n < 0 function root(n) { return Math.sqrt(n); }   // Returns -Infinity if n === 0 // Returns NaN if n < 0 function log(n) { return Math.log(n); }     // NOW DERIVE SAFE VERSIONS OF THESE SIMPLE FUNCTIONS: // These versions use a validity test, and return a wrapped value // with a boolean .isValid property as well as a .value property   function safeVersion(f, fnSafetyCheck) { return function (v) { return maybe(fnSafetyCheck(v) ? f(v) : undefined); } }   var safe_reciprocal = safeVersion(reciprocal, function (n) { return n !== 0; });   var safe_root = safeVersion(root, function (n) { return n >= 0; });     var safe_log = safeVersion(log, function (n) { return n > 0; });     // THE DERIVATION OF THE SAFE VERSIONS USED THE 'UNIT' OR 'RETURN' // FUNCTION OF THE MAYBE MONAD   // Named maybe() here, the unit function of the Maybe monad wraps a raw value // in a datatype with two elements: .isValid (Bool) and .value (Number)   // a -> Ma function maybe(n) { return { isValid: (typeof n !== 'undefined'), value: n }; }   // THE PROBLEM FOR FUNCTION NESTING (COMPOSITION) OF THE SAFE FUNCTIONS // IS THAT THEIR INPUT AND OUTPUT TYPES ARE DIFFERENT   // Our safe versions of the functions take simple numeric arguments, but return // wrapped results. If we feed a wrapped result as an input to another safe function, // it will choke on the unexpected type. The solution is to write a higher order // function (sometimes called 'bind' or 'chain') which handles composition, taking a // a safe function and a wrapped value as arguments,   // The 'bind' function of the Maybe monad: // 1. Applies a 'safe' function directly to the raw unwrapped value, and // 2. returns the wrapped result.   // Ma -> (a -> Mb) -> Mb function bind(maybeN, mf) { return (maybeN.isValid ? mf(maybeN.value) : maybeN); }   // Using the bind function, we can nest applications of safe_ functions, // without their choking on unexpectedly wrapped values returned from // other functions of the same kind. var rootOneOverFour = bind( bind(maybe(4), safe_reciprocal), safe_root ).value;   // -> 0.5     // We can compose a chain of safe functions (of any length) with a simple foldr/reduceRight // which starts by 'lifting' the numeric argument into a Maybe wrapping, // and then nests function applications (working from right to left) function safeCompose(lstFunctions, value) { return lstFunctions .reduceRight(function (a, f) { return bind(a, f); }, maybe(value)); }   // TEST INPUT VALUES WITH A SAFELY COMPOSED VERSION OF LOG(SQRT(1/X))   var safe_log_root_reciprocal = function (n) { return safeCompose([safe_log, safe_root, safe_reciprocal], n).value; }   return [-2, -1, -0.5, 0, 1 / Math.E, 1, 2, Math.E, 3, 4, 5].map( safe_log_root_reciprocal );   })();
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
#BASIC256
BASIC256
  # Monte Carlo Simulator # Determine value of pi # 21010513     tosses = 1000 in_c = 0 i = 0   for i = 1 to tosses x = rand y = rand x2 = x * x y2 = y * y xy = x2 + y2 d_xy = sqr(xy) if d_xy <= 1 then in_c += 1 endif next i   print float(4*in_c/tosses)
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
#BBC_BASIC
BBC BASIC
PRINT FNmontecarlo(1000) PRINT FNmontecarlo(10000) PRINT FNmontecarlo(100000) PRINT FNmontecarlo(1000000) PRINT FNmontecarlo(10000000) END   DEF FNmontecarlo(t%) LOCAL i%, n% FOR i% = 1 TO t% IF RND(1)^2 + RND(1)^2 < 1 n% += 1 NEXT = 4 * n% / t%
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.)
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Global All$, nl$ \\ upgrade to document Document All$ Nl$<={ } Function Encode$(Inp$) { Def SymbolTable$="abcdefghijklmnopqrstuvwxyz", Out$="" For i=1 to Len(Inp$) c$=Mid$(Inp$, i, 1) k=Instr(SymbolTable$, c$) Insert k, 1 SymbolTable$="" Out$=If$(Out$="" -> Quote$(k-1),Quote$(Param(Out$), k-1)) Insert 1 SymbolTable$=c$ \\ we use <= for globals All$<=Format$(" {0} {1:30} {2}", c$, Out$, SymbolTable$)+nl$ Next i =Out$ } Function Decode$(Inp$) { Def SymbolTable$="abcdefghijklmnopqrstuvwxyz", Out$="" flush Data Param(Inp$) While not empty { k=Number+1 c$=Mid$(SymbolTable$, k, 1) Out$+=c$ Insert k, 1 SymbolTable$="" ' erase at position k Insert 1 SymbolTable$=c$ All$<=Format$("{0::-2} {1} {2:30} {3}", k-1, c$, Out$, SymbolTable$)+nl$ } =Out$ } TryThis("broood") TryThis("bananaaa") TryThis("hiphophiphop") ClipBoard All$ Sub TryThis(a$) Local Out$=Encode$(a$) Local final$=Decode$(Out$) Print final$, final$=a$ End Sub } CheckIt  
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.)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
mtf[word_]:=Module[{f,f2,p,q}, f[{output_,symList_},next_]:=Module[{index},index=Position[symList,next][[1,1]]-1; {output~Append~index,Prepend[Delete[symList,index+1],next]}]; p=Fold[f,{{},CharacterRange["a","z"]},Characters[ToString[word]]][[1]]; f2[{output_,symList_},next_]:=Module[{index},index=symList[[next+1]]; {output~Append~index,Prepend[DeleteCases[symList,ToString[index]],index]}]; q=Fold[f2,{{},CharacterRange["a","z"]},p][[1]]; Print["'", word,"' encodes to: ",p, " - " ,p," decodes to: '",StringJoin@q,"' - Input equals Output: " ,word===StringJoin@q];]
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).
#AutoHotkey
AutoHotkey
TestString := "Hello World! abcdefg @\;" ;Create a string to be sent with multiple caps and some punctuation MorseBeep(teststring) ;Beeps our string after conversion return ;End Auto-Execute Section     MorseBeep(passedString) { StringLower, passedString, passedString ;Convert to lowercase for simpler checking Loop, Parse, passedString ;This loop stores each character in A_loopField one by one using the more compact form of "if else", by var := x>y ? val1 : val2 which stores val1 in var if x > y, otherwise it stores val2, this can be used together to make a single line of if else morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = ";" ? "-.-.-. " : A_LoopField = "=" ? "-...- " : A_LoopField = "?" ? "..--.. " : A_LoopField = "@" ? ".--.-. " : A_LoopField = "[" ? "-.--. " : A_LoopField = "]" ? "-.--.- " : A_LoopField = "_" ? "..--.- " : "ERROR" ; ---End conversion loop--- Loop, Parse, morse { morsebeep := 120 if (A_LoopField = ".") SoundBeep, 10*morsebeep, morsebeep ;Format: SoundBeep, frequency, duration If (A_LoopField = "-") SoundBeep, 10*morsebeep, 3*morsebeep ;Duration can be an expression If (A_LoopField = " ") Sleep, morsebeep ;Above, each character is followed by a space, and literal } ;Spaces are extended. Sleep pauses the script return morse ;Returns the text in morse code } ; ---End Function Morse---
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it. If both remaining doors have goats behind them, he chooses one randomly. After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door. Imagine that you chose Door 1 and the host opens Door 3, which has a goat. He then asks you "Do you want to switch to Door Number 2?" The question Is it to your advantage to change your choice? Note The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors. Task Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess. Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. References Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3 A YouTube video:   Monty Hall Problem - Numberphile.
#Arturo
Arturo
stay: 0 swit: 0   loop 1..1000 'i [ lst: shuffle new [1 0 0] rand: random 0 2 user: lst\[rand] remove 'lst rand   huh: 0 loop lst 'i [ if zero? i [ remove 'lst huh break ] huh: huh + 1 ]   if user=1 -> stay: stay+1 if and? [0 < size lst] [1 = first lst] -> swit: swit+1 ]   print ["Stay:" stay] print ["Switch:" swit]
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.
#C.23
C#
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } }   public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0);   while (a > 1) { int q = a / m; (a, m) = (m, a % m); (x, y) = (y, x - q * y); } return x < 0 ? x + m0 : x; } }
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#Raku
Raku
# 20200508 Raku programming solution   class Writer { has Numeric $.value ; has Str $.log }   sub Bind (Writer \v, &code) { my \n = v.value.&code; Writer.new: value => n.value, log => v.log ~ n.log };   sub Unit(\v, \s) { Writer.new: value=>v, log=>sprintf "%-17s: %.12f\n",s,v}   sub root(\v) { Unit v.sqrt, "Took square root" }   sub addOne(\v) { Unit v+1, "Added one" }   sub half(\v) { Unit v/2, "Divided by two" }   say Unit(5, "Initial value").&Bind(&root).&Bind(&addOne).&Bind(&half).log;
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#Wren
Wren
import "/fmt" for Fmt   class Mwriter { construct new(value, log) { _value = value _log = log }   value { _value } log {_log} log=(value) { _log = value }   bind(f) { var n = f.call(_value) n.log = _log + n.log return n }   static unit(v, s) { Mwriter.new(v, "  %(Fmt.s(-17, s)): %(v)\n") } }   var root = Fn.new { |v| Mwriter.unit(v.sqrt, "Took square root") } var addOne = Fn.new { |v| Mwriter.unit(v + 1, "Added one") } var half = Fn.new { |v| Mwriter.unit( v / 2, "Divided by two") }   var mw1 = Mwriter.unit(5, "Initial value") var mw2 = mw1.bind(root).bind(addOne).bind(half) System.print("The Golden Ratio is %(mw2.value)") System.print("\nThis was derived as follows:-") System.print(mw2.log)
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Ring
Ring
  # Project : Monads/List monad   func main() str = "[" for x in [3,4,5] y = x+1 z = y*2 str = str + z + ", " next str = left(str, len(str) -2) str = str + "]" see str + nl  
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String Compose the two functions with bind
#Ruby
Ruby
  class Array def bind(f) flat_map(&f) end def self.unit(*args) args end # implementing lift is optional, but is a great helper method for turning # ordinary funcitons into monadic versions of them. def self.lift(f) -> e { self.unit(f[e]) } end end   inc = -> n { n + 1 } str = -> n { n.to_s } listy_inc = Array.lift(inc) listy_str = Array.lift(str)   Array.unit(3,4,5).bind(listy_inc).bind(listy_str) #=> ["4", "5", "6"]   # Note that listy_inc and listy_str cannot be composed directly, # as they don't have compatible type signature. # Due to duck typing (Ruby will happily turn arrays into strings), # in order to show this, a new function will have to be used:   doub = -> n { 2*n } listy_doub = Array.lift(doub) [3,4,5].bind(listy_inc).bind(listy_doub) #=> [8, 10, 12]   # Direct composition will cause a TypeError, as Ruby cannot evaluate 2*[4, 5, 6] # Using bind with the composition is *supposed* to fail, no matter the programming language. comp = -> f, g {-> x {f[g[x]]}} [3,4,5].bind(comp[listy_doub, listy_inc]) #=> TypeError: Array can't be coerced into Fixnum   # Composition needs to be defined in terms of bind class Array def bind_comp(f, g) bind(g).bind(f) end end   [3,4,5].bind_comp(listy_doub, listy_inc) #=> [8, 10, 12]  
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Scala
Scala
object MultiDimensionalArray extends App {   // Create a regular 4 dimensional array and initialize successive elements to the values 1 to 120 val a4 = Array.fill[Int](5, 4, 3, 2) { m += 1; m } var m = 0   println("First element = " + a4(0)(0)(0)(0)) // access and print value of first element println("Last element = " + a4.last.last.last.last) a4(0)(0)(0)(0) = 121 // change value of first element   println(a4.flatten.flatten.flatten.mkString(", "))   }
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.
#ASIC
ASIC
  REM Multiplication tables N = 12 PREDN = N - 1 WDTH = 3 CLS FOR J = 1 TO PREDN INTVAL = J GOSUB PRINTINT: PRINT " "; NEXT J INTVAL = N GOSUB PRINTINT: PRINT FOR J = 0 TO PREDN PRINT "----"; NEXT J PRINT "+" FOR I = 1 TO N WDTH = 3 FOR J = 1 TO N IF J < I THEN PRINT " "; ELSE INTVAL = I * J GOSUB PRINTINT: PRINT " "; ENDIF NEXT J PRINT "| "; INTVAL = I WDTH = 2 GOSUB PRINTINT: PRINT NEXT I END   PRINTINT: REM Writes the value of INTVAL in a field of the given WDTH S2$ = STR$(INTVAL) S2$ = LTRIM$(S2$) SPNUM = LEN(S2$) SPNUM = WDTH - SPNUM S1$ = SPACE$(SPNUM) PRINT S1$; PRINT S2$; RETURN  
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).
#R
R
x <- c(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) y <- c(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)   lm( y ~ x + I(x^2))
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).
#Racket
Racket
  #lang racket (require math) (define T matrix-transpose)   (define (fit X y) (matrix-solve (matrix* (T X) X) (matrix* (T X) y)))  
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Go
Go
package main   import "fmt"   func multiFactorial(n, k int) int { r := 1 for ; n > 1; n -= k { r *= n } return r }   func main() { for k := 1; k <= 5; k++ { fmt.Print("degree ", k, ":") for n := 1; n <= 10; n++ { fmt.Print(" ", multiFactorial(n, k)) } fmt.Println() } }