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/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.
#MiniScript
MiniScript
print mouse.x, mouse.y
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Nanoquery
Nanoquery
import Nanoquery.Util.Windows   // a function to handle the mouse moved event def mouse_moved($caller, $e) println "(" + $e.getX() + ", " + $e.getY() + ")" end   // create a window, set the handler for mouse moved, and show it w = new("Window") w.setSize(500, 500) w.setHandler(w.mouseMoved, mouse_moved) w.show()
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
#IS-BASIC
IS-BASIC
100 PROGRAM "NQueens.bas" 110 TEXT 80 120 DO 130 INPUT PROMPT "Size of board (2-12): ":N$ 140 LET N=VAL(N$) 150 LOOP UNTIL N>1 AND N<13 160 NUMERIC A(1 TO N),X(1 TO N),B(2 TO 2*N),C(-N+1 TO N-1) 170 LET SOL=0 180 CALL INIT(A):CALL INIT(B):CALL INIT(C) 190 CALL TRY(1) 200 PRINT SOL;"solutions." 210 END 220 DEF WRITE 230 LET S$="":LET SOL=SOL+1 240 FOR K=1 TO N 250 LET S$=S$&CHR$(64+K)&STR$(X(K))&" " 260 NEXT 270 PRINT S$ 280 END DEF 290 DEF TRY(I) 300 NUMERIC J 310 FOR J=1 TO N 320 IF A(J) AND B(I+J) AND C(I-J) THEN 330 LET X(I)=J:LET A(J),B(I+J),C(I-J)=0 340 IF I<N THEN 350 CALL TRY(I+1) 360 ELSE 370 CALL WRITE 380 END IF 390 LET A(J),B(I+J),C(I-J)=1 400 END IF 410 NEXT 420 END DEF 430 DEF INIT(REF T) 440 FOR I=LBOUND(T) TO UBOUND(T) 450 LET T(I)=1 460 NEXT 470 END DEF
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.
#Phix
Phix
constant ordinals = {"th","st","nd","rd"} function Nth(integer n, bool apostrophe=false) integer mod10 = mod(n,10)+1 if mod10>4 or mod(n,100)=mod10+9 then mod10 = 1 end if return sprintf("%d%s",{n,repeat('\'',apostrophe)&ordinals[mod10]}) end function constant ranges = {{0,25},{250,265},{1000,1025}} for i=1 to length(ranges) do for j=ranges[i][1] to ranges[i][2] do if mod(j,10)=0 then puts(1,"\n") end if printf(1," %6s",{Nth(j,i=2)}) end for puts(1,"\n") end for
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
#Plain_English
Plain English
To run: Start up. Show the Munchausen numbers up to 5000. Wait for the escape key. Shut down.   To show the Munchausen numbers up to a number: If a counter is past the number, exit. If the counter is Munchausen, convert the counter to a string; write the string to the console. Repeat.   To decide if a number is Munchausen: Privatize the number. Find the sum of the digit self powers of the number. If the number is the original number, say yes. Say no.   To find the sum of the digit self powers of a number: If the number is 0, exit. Put 0 into a sum number. Loop. Divide the number by 10 giving a quotient and a remainder. Put the quotient into the number. Raise the remainder to the remainder. Add the remainder to the sum. If the number is 0, break. Repeat. Put the sum into the number.
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).
#Julia
Julia
F(n) = n < 1 ? one(n) : n - M(F(n - 1)) M(n) = n < 1 ? zero(n) : n - F(M(n - 1))
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.
#Julia
Julia
struct maybe x::Union{Real, Missing}; end   Base.show(io::IO, m::maybe) = print(io, m.x)   unit(x) = maybe(x) bind(f, x) = unit(f(x.x))   f1(x) = 5x f2(x) = x + 4   a = unit(3) b = unit(missing)   println(a, " -> ", bind(f2, bind(f1, a)))   println(b, " -> ", bind(f2, bind(f1, b)))  
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.
#Kotlin
Kotlin
// version 1.2.10   import java.util.Optional   /* doubles 'i' before wrapping it */ fun getOptionalInt(i: Int) = Optional.of(2 * i)   /* returns an 'A' repeated 'i' times wrapped in an Optional<String> */ fun getOptionalString(i: Int) = Optional.of("A".repeat(i))   /* does same as above if i > 0, otherwise returns an empty Optional<String> */ fun getOptionalString2(i: Int) = Optional.ofNullable(if (i > 0) "A".repeat(i) else null)   fun main(args: Array<String>) { /* prints 10 'A's */ println(getOptionalInt(5).flatMap(::getOptionalString).get())   /* prints 4 'A's */ println(getOptionalInt(2).flatMap(::getOptionalString2).get())   /* prints 'false' as there is no value present in the Optional<String> instance */ println(getOptionalInt(0).flatMap(::getOptionalString2).isPresent) }
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   double pi(double tolerance) { double x, y, val, error; unsigned long sampled = 0, hit = 0, i;   do { /* don't check error every turn, make loop tight */ for (i = 1000000; i; i--, sampled++) { x = rand() / (RAND_MAX + 1.0); y = rand() / (RAND_MAX + 1.0); if (x * x + y * y < 1) hit ++; }   val = (double) hit / sampled; error = sqrt(val * (1 - val) / sampled) * 4; val *= 4;   /* some feedback, or user gets bored */ fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples.\r", val, error, sampled/1000000); } while (!hit || error > tolerance); /* !hit is for completeness's sake; if no hit after 1M samples, your rand() is BROKEN */   return val; }   int main() { printf("Pi is %f\n", pi(3e-4)); /* set to 1e-4 for some fun */ return 0; }
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#MATLAB
MATLAB
function testMTF symTable = 'abcdefghijklmnopqrstuvwxyz'; inStr = {'broood' 'bananaaa' 'hiphophiphop'}; for k = 1:length(inStr) outArr = encodeMTF(inStr{k}, symTable); outStr = decodeMTF(outArr, symTable); fprintf('%s: [ %s]\n', inStr{k}, sprintf('%d ', outArr)) fprintf('%scorrectly decoded to %s\n', char('in'.*~strcmp(outStr, inStr{k})), outStr) end end   function arr = encodeMTF(str, symTable) n = length(str); arr = zeros(1, n); for k = 1:n arr(k) = find(str(k) == symTable, 1); symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)]; end arr = arr-1; % Change to zero-indexed array end   function str = decodeMTF(arr, symTable) arr = arr+1; % Change to one-indexed array n = length(arr); str = char(zeros(1, n)); for k = 1:n str(k) = symTable(arr(k)); symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)]; 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).
#AWK
AWK
# usage: awk -f morse.awk [inputfile] BEGIN { FS=""; m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-."; m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. "; }   { for(i=1; i<=NF; i++) { c=toupper($i); n=1; b=".";   while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }   b=substr(m,n,1);   while((b==".")||(b=="-")) { printf("%s",b); n++; b=substr(m,n,1); }   printf("|"); } printf("\n"); }  
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it. If both remaining doors have goats behind them, he chooses one randomly. After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door. Imagine that you chose Door 1 and the host opens Door 3, which has a goat. He then asks you "Do you want to switch to Door Number 2?" The question Is it to your advantage to change your choice? Note The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors. Task Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess. Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. References Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3 A YouTube video:   Monty Hall Problem - Numberphile.
#AutoHotkey
AutoHotkey
#SingleInstance, Force Iterations = 1000 Loop, %Iterations% { If Monty_Hall(1) Correct_Change++ Else Incorrect_Change++ If Monty_Hall(2) Correct_Random++ Else Incorrect_Random++ If Monty_Hall(3) Correct_Stay++ Else Incorrect_Stay++ } Percent_Change := round(Correct_Change / Iterations * 100) Percent_Stay := round(Correct_Stay / Iterations * 100) Percent_Random := round(Correct_Random / Iterations * 100)   MsgBox,, Monty Hall Problem, These are the results:`r`n`r`nWhen I changed my guess, I got %Correct_Change% of %Iterations% (that's %Incorrect_Change% incorrect). That's %Percent_Change%`% correct.`r`n`r`nWhen I randomly changed my guess, I got %Correct_Random% of %Iterations% (that's %Incorrect_Random% incorrect). That's %Percent_Random%`% correct.`r`n`r`nWhen I stayed with my first guess, I got %Correct_Stay% of %Iterations% (that's %Incorrect_Stay% incorrect). That's %Percent_Stay%`% correct. ExitApp   Monty_Hall(Mode) ;Mode is 1 for change, 2 for random, or 3 for stay { Random, guess, 1, 3 Random, actual, 1, 3 Random, rand, 1, 2   show := guess = actual ? guess = 3 ? guess - rand : guess = 1 ? guess+rand : guess + 2*rand - 3 : 6 - guess - actual Mode := Mode = 2 ? 2*rand - 1: Mode Return, Mode = 1 ? 6 - guess - show = actual : guess = actual }
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.2B.2B
C++
#include <iostream>   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) { std::cout << mul_inv(42, 2017) << std::endl; 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.)
#zkl
zkl
class Writer{ fcn init(x){ var X=x, logText=Data(Void," init \U2192; ",x.toString()) } fcn unit(text) { logText.append(text); self } fcn lift(f,name){ unit("\n  %s \U2192; %s".fmt(name,X=f(X))) } fcn bind(f,name){ lift.fp(f,name) } fcn toString{ "Result = %s\n%s".fmt(X,logText.text) }   fcn root{ lift(fcn(x){ x.sqrt() },"root") } fcn half{ lift('/(2),"half") } fcn inc { lift('+(1),"inc") } }
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
#uBasic.2F4tH
uBasic/4tH
s := "[" : Push 5, 4, 3   Do While Used () y = Set (x, Pop ()) + 1 s = Join (s, Str (Set (z, y * 2)), ", " ) Loop   Print Show (Set (s, Join (Clip (s, 2), "]")))  
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
#Wren
Wren
class Mlist { construct new(value) { _value = value }   value { _value }   bind(f) { f.call(_value) }   static unit(lst) { Mlist.new(lst) } }   var increment = Fn.new { |lst| var lst2 = lst.map { |v| v + 1 }.toList return Mlist.unit(lst2) }   var double = Fn.new { |lst| var lst2 = lst.map { |v| v * 2 }.toList return Mlist.unit(lst2) }   var ml1 = Mlist.unit([3, 4, 5]) var ml2 = ml1.bind(increment).bind(double) System.print("%(ml1.value) -> %(ml2.value)")
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).
#Tcl
Tcl
proc multilist {value args} { set res $value foreach dim [lreverse $args] { set res [lrepeat $dim $res] } return $res }
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).
#Vlang
Vlang
smd := [][]string{len: 4, init: []string{len:2, init: 'Hello'}} imd := [][]int{len: 3, init: []int{len:4, init: it}} mut mmd := [][]f64{len: 5, init: []f64{len: 5}} mmd[0][2] = 2.0 mmd[1][3] = 4.2 mmd[2][4] = 1.8 mmd[3][0] = 5.0 mut omd := [][]bool{} // initialize without defining size omd << [true, false, true] println(smd) println(imd) println(mmd) println(omd)
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.
#AutoHotkey
AutoHotkey
Gui, -MinimizeBox Gui, Margin, 0, 0 Gui, Font, s9, Fixedsys Gui, Add, Edit, h0 w0 Gui, Add, Edit, w432 r14 -VScroll Gosub, Table Gui, Show,, Multiplication Table Return   GuiClose: GuiEscape: ExitApp Return   Table: ; top row Table := " x |" Loop, 12 Table .= SubStr(" " A_Index, -3) Table .= "`n"   ; underlines Table .= "----+" Loop, 48 Table .= "-" Table .= "`n"   ; table Loop, 12 { ; rows Table .= SubStr(" " Row := A_Index, -2) " |" Loop, 12 ; columns Table .= SubStr(" " (A_Index >= Row ? A_Index * Row : ""), -3) Table .= "`n" } GuiControl,, Edit2, %Table% 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).
#Raku
Raku
use Clifford; my @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>; my @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>;   my $w = [+] @weight Z* @e;   my $h0 = [+] @e[^@weight]; my $h1 = [+] @height Z* @e; my $h2 = [+] (@height X** 2) Z* @e;   my $I = $h0∧$h1∧$h2; my $I2 = ($I·$I.reversion).Real;   say "α = ", ($w∧$h1∧$h2)·$I.reversion/$I2; say "β = ", ($w∧$h2∧$h0)·$I.reversion/$I2; say "γ = ", ($w∧$h0∧$h1)·$I.reversion/$I2;
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.
#Haskell
Haskell
mulfac :: (Num a, Enum a) => a -> [a] mulfac k = 1 : s where s = [1 .. k] <> zipWith (*) s [k + 1 ..]   -- For single n:   mulfac1 :: (Num a, Enum a) => a -> a -> a mulfac1 k n = product [n, n - k .. 1]   main :: IO () main = mapM_ (print . take 10 . tail . mulfac) [1 .. 5]  
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.
#Nim
Nim
import gintro/[glib, gobject, gtk, gio] import gintro/gdk except Window   #---------------------------------------------------------------------------------------------------   proc onButtonPress(window: ApplicationWindow; event: Event; data: pointer): bool = echo event.getCoords() result = true   #---------------------------------------------------------------------------------------------------   proc activate(app: Application) = ## Activate the application.   let window = app.newApplicationWindow() window.setTitle("Mouse position") window.setSizeRequest(640, 480)   discard window.connect("button-press-event", onButtonPress, pointer(nil))   window.showAll()   #———————————————————————————————————————————————————————————————————————————————————————————————————   let app = newApplication(Application, "Rosetta.MousePosition") discard app.connect("activate", activate) discard app.run()
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.
#OCaml
OCaml
open Xlib   let () = let d = xOpenDisplay "" in   (* ask for active window (no error check); the client must be freedesktop compliant *) let _, _, _, _, props = xGetWindowProperty_window d (xDefaultRootWindow d) (xInternAtom d "_NET_ACTIVE_WINDOW" true) 0 1 false AnyPropertyType in   let _, _, _, child, _ = xQueryPointer d props in begin match child with | Some(_, childx, childy) -> Printf.printf "relative to active window: %d,%d\n%!" childx childy; | None -> print_endline "the pointer is not on the same screen as the specified window" end;   xCloseDisplay d; ;;
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
#J
J
perm =: ! A.&i. ] NB. all permutations of integers 0 to y comb2 =: (, #: I.@,@(</)&i.)~ NB. all size 2 combinations of integers 0 to y mask =: [ */@:~:&(|@-/) { queenst=: comb2 (] #"1~ mask)&.|: perm
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.
#PHP
PHP
function nth($num) { $os = "th"; if ($num % 100 <= 10 or $num % 100 > 20) { switch ($num % 10) { case 1: $os = "st"; break; case 2: $os = "nd"; break; case 3: $os = "rd"; break; } } return $num . $os; }   foreach ([[0,25], [250,265], [1000,1025]] as $i) { while ($i[0] <= $i[1]) { echo nth($i[0]) . " "; $i[0]++; } echo "\n"; }
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL #COMPILER PBCC 6   DECLARE FUNCTION GetTickCount LIB "kernel32.dll" ALIAS "GetTickCount"() AS DWORD   FUNCTION PBMAIN () AS LONG LOCAL i, j, n, sum, ten1, ten2, t AS DWORD LOCAL n0, n1, n2, n3, n4, n5, n6, n7, n8, n9 AS DWORD LOCAL s1, s2, s3, s4, s5, s6, s7, s8 AS DWORD DIM pow(9) AS DWORD, num(9) AS DWORD LOCAL pb AS BYTE PTR LOCAL number AS STRING   t = GetTickCount() ten2 = 10 FOR i = 1 TO 9 pow(i) = i FOR j = 2 TO i pow(i) *= i NEXT j NEXT i FOR n = 1 TO 11 FOR n9 = 0 TO n FOR n8 = 0 TO n - n9 s8 = n9 + n8 FOR n7 = 0 TO n - s8 s7 = s8 + n7 FOR n6 = 0 TO n - s7 s6 = s7 + n6 FOR n5 = 0 TO n - s6 s5 = s6 + n5 FOR n4 = 0 TO n - s5 s4 = s5 + n4 FOR n3 = 0 TO n - s4 s3 = s4 + n3 FOR n2 = 0 TO n - s3 s2 = s3 + n2 FOR n1 = 0 TO n - s2 n0 = n - (s2 + n1) sum = n1 * pow(1) + n2 * pow(2) + n3 * pow(3) + _ n4 * pow(4) + n5 * pow(5) + n6 * pow(6) + _ n7 * pow(7) + n8 * pow(8) + n9 * pow(9) SELECT CASE AS LONG sum CASE ten1 TO ten2 - 1 number = LTRIM$(STR$(sum)) pb = STRPTR(number) MAT num() = ZER FOR i = 0 TO n -1 j = @pb[i] - 48 INCR num(j) NEXT i IF n0 = num(0) AND n1 = num(1) AND n2 = num(2) AND _ n3 = num(3) AND n4 = num(4) AND n5 = num(5) AND _ n6 = num(6) AND n7 = num(7) AND n8 = num(8) AND _ n9 = num(9) THEN CON.PRINT STR$(sum) END SELECT NEXT n1 NEXT n2 NEXT n3 NEXT n4 NEXT n5 NEXT n6 NEXT n7 NEXT n8 NEXT n9 ten1 = ten2 ten2 *= 10 NEXT n t = GetTickCount() - t CON.PRINT "execution time:" & STR$(t) & " ms; hit any key to end program" CON.WAITKEY$ END FUNCTION
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Kotlin
Kotlin
// version 1.0.6   fun f(n: Int): Int = when { n == 0 -> 1 else -> n - m(f(n - 1)) }   fun m(n: Int): Int = when { n == 0 -> 0 else -> n - f(m(n - 1)) }   fun main(args: Array<String>) { val n = 24 print("n :") for (i in 0..n) print("%3d".format(i)) println() println("-".repeat(78)) print("F :") for (i in 0..24) print("%3d".format(f(i))) println() print("M :") for (i in 0..24) print("%3d".format(m(i))) println() }
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.
#Lua
Lua
  -- None is represented by an empty table. Some is represented by any -- array with one element. You SHOULD NOT compare maybe values with the -- Lua operator == because it will give incorrect results. Use the -- functions isMaybe(), isNone(), and isSome().   -- define once for efficiency, to avoid many different empty tables local NONE = {}   local function unit(x) return { x } end local Some = unit local function isNone(mb) return #mb == 0 end local function isSome(mb) return #mb == 1 end local function isMaybe(mb) return isNone(mb) or isSome(mb) end   -- inverse of Some(), extract the value from the maybe; get(Some(x)) === x local function get(mb) return mb[1] end   function maybeToStr(mb) return isNone(mb) and "None" or ("Some " .. tostring(get(mb))) end   local function bind(mb, ...) -- monadic bind for multiple functions local acc = mb for _, fun in ipairs({...}) do -- fun should be a monadic function assert(type(fun) == "function") if isNone(acc) then return NONE else acc = fun(get(acc)) end end return acc end   local function fmap(mb, ...) -- monadic fmap for multiple functions local acc = mb for _, fun in ipairs({...}) do -- fun should be a regular function assert(type(fun) == "function") if isNone(acc) then return NONE else acc = Some(fun(get(acc))) end end return acc end -- ^^^ End of generic maybe monad functionality ^^^   --- vvv Start of example code vvv   local function time2(x) return x * 2 end local function plus1(x) return x + 1 end   local answer answer = fmap(Some(3), time2, plus1, time2) assert(get(answer)==14)   answer = fmap(NONE, time2, plus1, time2) assert(isNone(answer))   local function safeReciprocal(x) if x ~= 0 then return Some(1/x) else return NONE end end local function safeRoot(x) if x >= 0 then return Some(math.sqrt(x)) else return NONE end end local function safeLog(x) if x > 0 then return Some(math.log(x)) else return NONE end end local function safeComputation(x) return bind(safeReciprocal(x), safeRoot, safeLog) end   local function map(func, table) local result = {} for key, val in pairs(table) do result[key] = func(val) end return result end   local inList = {-2, -1, -0.5, 0, math.exp (-1), 1, 2, math.exp (1), 3, 4, 5} print("input:", table.concat(map(tostring, inList), ", "), "\n")   local outList = map(safeComputation, inList) print("output:", table.concat(map(maybeToStr, outList), ", "), "\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
#C.23
C#
using System;   class Program { static double MonteCarloPi(int n) { int inside = 0; Random r = new Random();   for (int i = 0; i < n; i++) { if (Math.Pow(r.NextDouble(), 2)+ Math.Pow(r.NextDouble(), 2) <= 1) { inside++; } }   return 4.0 * inside / n; }   static void Main(string[] args) { int value = 1000; for (int n = 0; n < 5; n++) { value *= 10; Console.WriteLine("{0}:{1}", value.ToString("#,###").PadLeft(11, ' '), MonteCarloPi(value)); } } }
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.)
#Nim
Nim
import algorithm, sequtils, strformat   const SymbolTable = toSeq('a'..'z')   func encode(s: string): seq[int] = var symtable: seq[char] = SymbolTable for c in s: let idx = symtable.find(c) result.add idx symtable.rotateLeft(0..idx, -1)   func decode(s: seq[int]): string = var symtable = SymbolTable for idx in s: result.add symtable[idx] symtable.rotateLeft(0..idx, -1)   for word in ["broood", "babanaaa", "hiphophiphop"]: let encoded = word.encode() let decoded = encoded.decode() let status = if decoded == word: "correctly" else: "incorrectly" echo &"'{word}' encodes to {encoded} which {status} decodes to '{decoded}'."
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow   (e.g. with a different pitch).
#bash
bash
  #!/bin/bash # michaeltd 2019-11-29 https://github.com/michaeltd/dots/blob/master/dot.files/.bashrc.d/.var/morse.sh # https://en.wikipedia.org/wiki/Morse_code # International Morse Code # 1. Length of dot is 1 unit # 2. Length of dash is 3 units # 3. The space between parts of the same letter is 1 unit # 4. The space between letters is 3 units. # 5. The space between words is 7 units. ################################################################################   alpha2morse() { local -A alpha_assoc=( [A]='.-' [B]='-...' [C]='-.-.' [D]='-..' [E]='.' \ [F]='..-.' [G]='--.' [H]='....' [I]='..' [J]='.---' \ [K]='-.-' [L]='.-..' [M]='--' [N]='-.' [O]='---' \ [P]='.--.' [Q]='--.-' [R]='.-.' [S]='...' [T]='-' \ [U]='..-' [V]='...-' [W]='.--' [X]='-..-' [Y]='-.--' [Z]='--..' \ [0]='-----' [1]='.----' [2]='..---' [3]='...--' [4]='....-' \ [5]='.....' [6]='-....' [7]='--...' [8]='----..' [9]='----.' )   if [[ "${#}" -lt "1" ]]; then echo -ne "Usage: ${FUNCNAME[0]} arguments...\n \ ${FUNCNAME[0]} is an IMC transmitter. \n \ It'll transmit your messages to International Morse Code.\n" >&2 return 1 fi   while [[ -n "${1}" ]]; do for (( i = 0; i < ${#1}; i++ )); do local letter="${1:${i}:1}" for (( y = 0; y < ${#alpha_assoc[${letter^^}]}; y++ )); do case "${alpha_assoc[${letter^^}]:${y}:1}" in ".") echo -n "dot "; play -q -n -c2 synth .1 2> /dev/null || sleep .1 ;; "-") echo -n "dash "; play -q -n -c2 synth .3 2> /dev/null || sleep .3 ;; esac sleep .1 done echo sleep .3 done echo sleep .7 shift done }   if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then alpha2morse "${@}" fi    
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.
#AWK
AWK
#!/bin/gawk -f   # Monty Hall problem   BEGIN { srand() doors = 3 iterations = 10000 # Behind a door: EMPTY = "empty"; PRIZE = "prize" # Algorithm used KEEP = "keep"; SWITCH="switch"; RAND="random"; # } function monty_hall( choice, algorithm ) { # Set up doors for ( i=0; i<doors; i++ ) { door[i] = EMPTY } # One door with prize door[int(rand()*doors)] = PRIZE   chosen = door[choice] del door[choice]   #if you didn't choose the prize first time around then # that will be the alternative alternative = (chosen == PRIZE) ? EMPTY : PRIZE   if( algorithm == KEEP) { return chosen } if( algorithm == SWITCH) { return alternative } return rand() <0.5 ? chosen : alternative }   function simulate(algo){ prizecount = 0 for(j=0; j< iterations; j++){ if( monty_hall( int(rand()*doors), algo) == PRIZE) { prizecount ++ } } printf " Algorithm %7s: prize count = %i, = %6.2f%%\n", \ algo, prizecount,prizecount*100/iterations }   BEGIN { print "\nMonty Hall problem simulation:" print doors, "doors,", iterations, "iterations.\n" simulate(KEEP) simulate(SWITCH) simulate(RAND)   }
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.
#Clojure
Clojure
(ns test-p.core (:require [clojure.math.numeric-tower :as math]))   (defn extended-gcd "The extended Euclidean algorithm--using Clojure code from RosettaCode for Extended Eucliean (see http://en.wikipedia.orwiki/Extended_Euclidean_algorithm) Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs with the result: gcd followed by bezout coefficients " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r))))))   (defn mul_inv " Get inverse using extended gcd. Extended GCD returns gcd followed by bezout coefficients. We want the 1st coefficients (i.e. second of extend-gcd result). We compute mod base so result is between 0..(base-1) " [a b] (let [b (if (neg? b) (- b) b) a (if (neg? a) (- b (mod (- a) b)) a) egcd (extended-gcd a b)] (if (= (first egcd) 1) (mod (second egcd) b) (str "No inverse since gcd is: " (first egcd)))))     (println (mul_inv 42 2017)) (println (mul_inv 40 1)) (println (mul_inv 52 -217)) (println (mul_inv -486 217)) (println (mul_inv 40 2018))    
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
#zkl
zkl
class MList{ fcn init(xs){ var list=vm.arglist } fcn bind(f) { list=list.apply(f); self } fcn toString{ list.toString() } }
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).
#Wren
Wren
import "/fmt" for Fmt   // create a 4 dimensional list of the required size and initialize successive elements to the values 1 to 120 var m = 1 var a4 = List.filled(5, null) for (i in 0..4) { a4[i] = List.filled(4, null) for (j in 0..3) { a4[i][j] = List.filled(3, null) for (k in 0..2) { a4[i][j][k] = List.filled(2, 0) for (l in 0..1) { a4[i][j][k][l] = m m = m + 1 } } } }   System.print("First element = %(a4[0][0][0][0])") // access and print value of first element a4[0][0][0][0] = 121 // change value of first element System.print()   // access and print values of all elements for (i in 0..4) { for (j in 0..3) { for (k in 0..2) { for (l in 0..1) { Fmt.write("$4d", a4[i][j][k][l]) } } } }
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.
#AutoIt
AutoIt
#AutoIt Version: 3.2.10.0 $tableupto=12 $table="" for $i = 1 To $tableupto for $j = $i to $tableupto $prod=string($i*$j) if StringLen($prod) == 1 then $prod = " "& $prod EndIf if StringLen($prod) == 2 then $prod = " "& $prod EndIf $table = $table&" "&$prod Next $table = $table&" - "&$i&@CRLF for $k = 1 to $i $table = $table&" " Next Next msgbox(0,"Multiplication Tables",$table)
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).
#Ruby
Ruby
require 'matrix'   def regression_coefficients y, x y = Matrix.column_vector y.map { |i| i.to_f } x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}   (x.t * x).inverse * x.t * y end
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) l := integer(A[1]) | 10 every writeRow(n := !l, [: mf(!10,n) :]) end   procedure writeRow(n, r) writes(right(n,3),": ") every writes(right(!r,8)|"\n") end   procedure mf(n, m) if n <= 0 then return 1 return n*mf(n-m, m) end
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Octave
Octave
[X, Y, BUTTONS] = ginput(N);
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.
#Oz
Oz
declare [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']} WindowClosed = {NewCell false} Label Window = {QTk.build td(action:proc {$} WindowClosed := true {Window close} end label(text:"" handle:Label))} in {Window show}   for while:{Not @WindowClosed} do TopmostWindow = {List.last {String.tokens {Tk.return wm(stackorder '.')} & }} Winfo = {Record.mapInd winfo(rootx:_ rooty:_ pointerx:_ pointery:_) fun {$ I _} {Tk.returnInt winfo(I TopmostWindow)} end} in {Label set(text:"x: "#(Winfo.pointerx - Winfo.rootx) #", y: "#(Winfo.pointery - Winfo.rooty))} {Delay 250} end
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
#Java
Java
public class NQueens {   private static int[] b = new int[8]; private static int s = 0;   static boolean unsafe(int y) { int x = b[y]; for (int i = 1; i <= y; i++) { int t = b[y - i]; if (t == x || t == x - i || t == x + i) { return true; } }   return false; }   public static void putboard() { System.out.println("\n\nSolution " + (++s)); for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { System.out.print((b[y] == x) ? "|Q" : "|_"); } System.out.println("|"); } }   public static void main(String[] args) { int y = 0; b[0] = -1; while (y >= 0) { do { b[y]++; } while ((b[y] < 8) && unsafe(y)); if (b[y] < 8) { if (y < 7) { b[++y] = -1; } else { putboard(); } } else { y--; } } } }
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.
#Picat
Picat
nth2(N) = N.to_string() ++ Th => ( tween(N) -> Th = "th"  ; 1 = N mod 10 -> Th = "st"  ; 2 = N mod 10 -> Th = "nd"  ; 3 = N mod 10 -> Th = "rd"  ; Th = "th" ). tween(N) => Tween = N mod 100, between(11, 13, Tween).
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
#Pure
Pure
// split numer into digits digits n::number = loop n [] with loop n l = loop (n div 10) ((n mod 10):l) if n > 0; = l otherwise; end;   munchausen n::int = (filter isMunchausen list) when list = 1..n; end with isMunchausen n = n == foldl (+) 0 (map (\d -> d^d) (digits n)); end; munchausen 5000;
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Lambdatalk
Lambdatalk
  {def F {lambda {:n} {if {= :n 0} then 1 else {- :n {M {F {- :n 1}}}} }}} {def M {lambda {:n} {if {= :n 0} then 0 else {- :n {F {M {- :n 1}}}} }}}   {map F {serie 0 19}} -> 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 {map M {serie 0 19}} -> 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12  
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String Compose the two functions with bind A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time. A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
#Nim
Nim
import options,math,sugar,strformat template checkAndWrap(x:float,body:typed): untyped = if x.classify in {fcNormal,fcZero,fcNegZero}: some(body) else: none(typeof(body)) func reciprocal(x:float):Option[float] = let res = 1 / x res.checkAndWrap(res) func log(x:float):Option[float] = let res = ln(x) res.checkAndWrap(res) func format(x:float):Option[string] = x.checkAndWrap(&"{x:.2f}")   #our bind function: func `-->`[T,U](input:Option[T], f: T->Option[U]):Option[U] = if input.isSome: f(input.get) else: none(U)   when isMainModule: for i in [0.9,0.0,-0.9,3.0]: echo some(i) --> reciprocal --> log --> format
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.
#Perl
Perl
# 20201101 added Perl programming solution   use strict; use warnings;   use Data::Monad::Maybe;   sub safeReciprocal { ( $_[0] == 0 ) ? nothing : just( 1 / $_[0] ) }   sub safeRoot { ( $_[0] < 0 ) ? nothing : just( sqrt( $_[0] ) ) }   sub safeLog { ( $_[0] <= 0 ) ? nothing : just( log ( $_[0] ) ) }   print join(' ', map { my $safeLogRootReciprocal = just($_)->flat_map( \&safeReciprocal ) ->flat_map( \&safeRoot ) ->flat_map( \&safeLog ); $safeLogRootReciprocal->is_nothing ? "NaN" : $safeLogRootReciprocal->value; } (-2, -1, -0.5, 0, exp (-1), 1, 2, exp(1), 3, 4, 5) ), "\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
#C.2B.2B
C++
  #include<iostream> #include<math.h> #include<stdlib.h> #include<time.h>   using namespace std; int main(){ int jmax=1000; // maximum value of HIT number. (Length of output file) int imax=1000; // maximum value of random numbers for producing HITs. double x,y; // Coordinates int hit; // storage variable of number of HITs srand(time(0)); for (int j=0;j<jmax;j++){ hit=0; x=0; y=0; for(int i=0;i<imax;i++){ x=double(rand())/double(RAND_MAX); y=double(rand())/double(RAND_MAX); if(y<=sqrt(1-pow(x,2))) hit+=1; } //Choosing HITs according to analytic formula of circle cout<<""<<4*double(hit)/double(imax)<<endl; } // Print out Pi number }  
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.)
#Perl
Perl
use strict; use warnings; sub encode { my ($str) = @_; my $table = join '', 'a' .. 'z'; map { $table =~ s/(.*?)$_/$_$1/ or die; length($1); } split //, $str; }   sub decode { my $table = join '', 'a' .. 'z'; join "", map { $table =~ s/(.{$_})(.)/$2$1/ or die; $2; } @_; }   for my $test ( qw(broood bananaaa hiphophiphop) ) { my @encoded = encode($test); print "$test: @encoded\n"; my $decoded = decode(@encoded); print "in" x ( $decoded ne $test ); print "correctly decoded to $decoded\n"; }  
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow   (e.g. with a different pitch).
#BASIC
BASIC
DECLARE SUB player (what AS STRING)   'this determines the length of the notes 'lower number = longer duration CONST noteLen = 16   DIM tones(62) AS STRING   FOR n% = 0 TO 62 READ tones(n%) NEXT n%   'set up the playing system PLAY "t255o4l" + LTRIM$(STR$(noteLen))   LINE INPUT "String to convert to Morse code: "; x$   FOR n% = 1 TO LEN(x$) c$ = UCASE$(MID$(x$, n%, 1)) PLAY "p" + LTRIM$(STR$(noteLen / 2)) + "." SELECT CASE UCASE$(c$) CASE " " 'since each char is effectively wrapped with 6 p's, we only need to add 1: PLAY "p" + LTRIM$(STR$(noteLen)) PRINT " "; CASE "!" TO "_" PRINT tones(ASC(c$) - 33); " "; player tones(ASC(c$) - 33) CASE ELSE PRINT "# "; player "#" END SELECT PLAY "p" + LTRIM$(STR$(noteLen / 2)) + "." NEXT n% PRINT   'all the Morse codes in ASCII order, from "!" to "_" DATA "-.-.--", ".-..-.", "#", "...-..-", "#", ".-...", ".----.", "-.--." DATA "-.--.-", "#", ".-.-.", "--..--", "-....-", ".-.-.-", "-..-.", "-----" DATA ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---.." DATA "----.", "---...", "-.-.-.", "#", "-...-", "#", "..--..", ".--.-.", ".-" DATA "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-" DATA ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-" DATA "...-", ".--", "-..-", "-.--", "--..", "#", "#", "#", "#", "..--.-"   SUB player (what AS STRING) FOR i% = 1 TO LEN(what) z$ = MID$(what, i%, 1) SELECT CASE z$ CASE "." o$ = "g" CASE "-" o$ = "g" + LTRIM$(STR$(noteLen / 2)) + "." CASE ELSE o$ = "<<<<c>>>>" END SELECT PLAY o$ PLAY "p" + LTRIM$(STR$(noteLen)) NEXT i% END SUB
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.
#BASIC
BASIC
RANDOMIZE TIMER DIM doors(3) '0 is a goat, 1 is a car CLS switchWins = 0 stayWins = 0 FOR plays = 0 TO 32767 winner = INT(RND * 3) + 1 doors(winner) = 1'put a winner in a random door choice = INT(RND * 3) + 1'pick a door, any door DO shown = INT(RND * 3) + 1 'don't show the winner or the choice LOOP WHILE doors(shown) = 1 OR shown = choice stayWins = stayWins + doors(choice) 'if you won by staying, count it switchWins = switchWins + doors(3 - choice - shown) 'could have switched to win doors(winner) = 0 'clear the doors for the next test NEXT plays PRINT "Switching wins"; switchWins; "times." PRINT "Staying wins"; stayWins; "times."
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m} It can be shown that such an inverse exists   if and only if   a   and   m   are coprime,   but we will ignore this for this task. Task Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language,   compute the modular inverse of   42 modulo 2017.
#CLU
CLU
mul_inv = proc (a, b: int) returns (int) signals (no_inverse) if b<0 then b := -b end if a<0 then a := b - (-a // b) end t: int := 0 nt: int := 1 r: int := b nr: int := a // b while nr ~= 0 do q: int := r / nr t, nt := nt, t - q*nt r, nr := nr, r - q*nr end if r>1 then signal no_inverse end if t<0 then t := t+b end return(t) end mul_inv   start_up = proc () pair = struct[a, b: int] tests: sequence[pair] := sequence[pair]$ [pair${a: 42, b: 2017}, pair${a: 40, b: 1}, pair${a: 52, b: -217}, pair${a: -486, b: 217}, pair${a: 40, b: 2018}]   po: stream := stream$primary_output() for test: pair in sequence[pair]$elements(tests) do stream$puts(po, int$unparse(test.a) || ", " || int$unparse(test.b) || " -> ") stream$putl(po, int$unparse(mul_inv(test.a, test.b))) except when no_inverse: stream$putl(po, "no modular inverse") end end end start_up
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.
#Comal
Comal
0010 FUNC mulinv#(a#,b#) CLOSED 0020 IF b#<0 THEN b#:=-b# 0030 IF a#<0 THEN a#:=b#-(-a# MOD b#) 0040 t#:=0;nt#:=1;r#:=b#;nr#:=a# MOD b# 0050 WHILE nr#<>0 DO 0060 q#:=r# DIV nr# 0070 tmp#:=nt#;nt#:=t#-q#*nt#;t#:=tmp# 0080 tmp#:=nr#;nr#:=r#-q#*nr#;r#:=tmp# 0090 ENDWHILE 0100 IF r#>1 THEN RETURN -1 0110 IF t#<0 THEN t#:+b# 0120 RETURN t# 0130 ENDFUNC mulinv# 0140 // 0150 WHILE NOT EOD DO 0160 READ a#,b# 0170 PRINT a#,", ",b#," -> ",mulinv#(a#,b#) 0180 ENDWHILE 0190 END 0200 // 0210 DATA 42,2017,40,1,52,-217,-486,217,40,2018
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).
#X86-64_Assembly
X86-64 Assembly
  option casemap:none   printf proto :qword, :vararg exit proto :dword   ROW_LEN equ (4*4) MEM_SIZE equ 4   .data ;; A 2d array - 2 rows, 4 columns ;; int twodimen[2][4] = { {0,1,2,3}, ;; {4,5,6,7}}; twodimen db 48 dup (0) tpl db "%d",13,10,0   .code main proc local cols:qword   lea rbx, twodimen mov cols, 0 ;; Forgive me for the multiple loops, I'm just to lazy to ;; do the conditional jumps required for 2 for loops. -.- @1: mov rcx, cols mov dword ptr [rbx+0*ROW_LEN + rcx*MEM_SIZE], ecx ;; first row, rcx column inc cols cmp cols, 3 jle @1   mov cols, 0 mov rdx, 4 @2: mov rcx, cols mov dword ptr [rbx+1*ROW_LEN + rcx*MEM_SIZE], edx ;; second row, rcx column inc cols inc edx cmp cols, 3 jle @2   invoke printf, CSTR("--> Printing columns in row 1",10) mov cols, 0 @3: mov rcx, cols mov esi, dword ptr [rbx+0*ROW_LEN + rcx*MEM_SIZE] lea rdi, tpl call printf inc cols cmp cols, 3 jle @3   invoke printf, CSTR("--> Printing columns in row 2",10) mov cols, 0 @4: mov rcx, cols mov esi, dword ptr [rbx+1*ROW_LEN + rcx*MEM_SIZE] lea rdi, tpl call printf inc cols cmp cols, 3 jle @4     mov rax, 0 xor edi, edi call exit leave ret main endp  
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.
#AWK
AWK
  BEGIN { for(i=1;i<=12;i++){ for(j=1;j<=12;j++){ if(j>=i||j==1){printf "%4d",i*j} else {printf " "} } print } }
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).
#SPSS
SPSS
set rng=mc seed=17760704. new file. input program. vector x(4). loop #i=1 to 200. loop #j=1 to 4. compute x(#j)=rv.normal(0,1). end loop. end case. end loop. end file. end input program. compute y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rv.normal(0,1). execute.
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).
#Stata
Stata
clear set seed 17760704 set obs 200 forv i=1/4 { gen x`i'=rnormal() } gen y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rnormal()
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.
#IS-BASIC
IS-BASIC
100 PROGRAM "Multifac.bas" 110 FOR I=1 TO 5 120 PRINT "Degree";I;":"; 130 FOR N=1 TO 10 140 PRINT MFACT(N,I); 150 NEXT 160 PRINT 170 NEXT 180 DEF MFACT(N,D) 190 NUMERIC I,RES 200 IF N<2 THEN LET MFACT=1:EXIT DEF 210 LET RES=N 220 FOR I=N-D TO 2 STEP-D 230 LET RES=RES*I 240 NEXT 250 LET MFACT=RES 260 END DEF
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.
#Perl
Perl
use SDL; use SDL::Events; use SDLx::App;   my $app = SDLx::App->new; $app->add_event_handler( sub { my $event = shift; if( $event->type == SDL_MOUSEMOTION ) { printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y ); $app->stop } } ); $app->run;  
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.
#Phix
Phix
-- demo\rosetta\Mouse_position.exw include pGUI.e   Ihandle global_lbl, canvas_lbl, timer_lbl   function globalmotion_cb(integer x, integer y, atom /*pStatus*/) IupSetStrAttribute(global_lbl,"TITLE","globalmotion_cb %d, %d",{x,y}) return IUP_DEFAULT end function   function canvas_motion_cb(Ihandle /*canvas*/, integer x, integer y, atom pStatus) IupSetStrAttribute(canvas_lbl,"TITLE","canvasmotion_cb %d, %d",{x,y}) return IUP_DEFAULT; end function   function OnTimer(Ihandle /*ih*/) integer {x,y} = IupGetIntInt(NULL,"CURSORPOS") IupSetStrAttribute(timer_lbl,"TITLE","timer %d, %d",{x,y}) return IUP_IGNORE end function   procedure main() Ihandle separator1, separator2, canvas, frame_1, frame_2, dialog   IupOpen()   global_lbl = IupLabel("Move the mouse anywhere on the window","EXPAND=HORIZONTAL") separator1 = IupLabel(NULL,"SEPARATOR=HORIZONTAL") canvas_lbl = IupLabel("Move the mouse anywhere on the canvas","EXPAND=HORIZONTAL") separator2 = IupLabel(NULL,"SEPARATOR=HORIZONTAL") timer_lbl = IupLabel("This one runs on a three second timer","EXPAND=HORIZONTAL")   frame_1 = IupFrame(IupVbox({global_lbl, separator1, canvas_lbl, separator2, timer_lbl}), "TITLE=IupLabel, SIZE=200x")   canvas = IupCanvas("MOTION_CB", Icallback("canvas_motion_cb"), "EXPAND=HORIZONTAL, RASTERSIZE=200x200") frame_2 = IupFrame(canvas, "TITLE=IupCanvas")   dialog = IupDialog(IupHbox({frame_1,frame_2}, "MARGIN=5x5, GAP=5")) IupSetAttribute(dialog,"TITLE","Mouse motion");   IupSetGlobal("INPUTCALLBACKS", "Yes"); IupSetGlobalFunction("GLOBALMOTION_CB", Icallback("globalmotion_cb"));   Ihandle hTimer = IupTimer(Icallback("OnTimer"), 3000)   IupShow(dialog)   IupMainLoop() IupClose() end procedure main()
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
#JavaScript
JavaScript
function queenPuzzle(rows, columns) { if (rows <= 0) { return [[]]; } else { return addQueen(rows - 1, columns); } }   function addQueen(newRow, columns, prevSolution) { var newSolutions = []; var prev = queenPuzzle(newRow, columns); for (var i = 0; i < prev.length; i++) { var solution = prev[i]; for (var newColumn = 0; newColumn < columns; newColumn++) { if (!hasConflict(newRow, newColumn, solution)) newSolutions.push(solution.concat([newColumn])) } } return newSolutions; }   function hasConflict(newRow, newColumn, solution) { for (var i = 0; i < newRow; i++) { if (solution[i] == newColumn || solution[i] + i == newColumn + newRow || solution[i] - i == newColumn - newRow) { return true; } } return false; }   console.log(queenPuzzle(8,8));
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.
#PicoLisp
PicoLisp
(de rangeth (A B) (mapcar '((I) (pack I (if (member (% I 100) (11 12 13)) 'th (case (% I 10) (1 'st) (2 'nd) (3 'rd) (T 'th) ) ) ) ) (range A B) ) )   (prinl (glue " " (rangeth 0 25))) (prinl (glue " " (rangeth 250 265))) (prinl (glue " " (rangeth 1000 1025)))   (bye)
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
#PureBasic
PureBasic
EnableExplicit Declare main()   If OpenConsole("Munchausen_numbers") main() : Input() : End EndIf   Procedure main() Define i.i, sum.i, number.i, digit.i For i = 1 To 5000 sum = 0 number = i While number > 0 digit = number % 10 sum + Pow(digit, digit) number / 10 Wend If sum = i PrintN(Str(i)) EndIf Next EndProcedure
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).
#Liberty_BASIC
Liberty BASIC
  print "F sequence." for i = 0 to 20 print f(i);" "; next print print "M sequence." for i = 0 to 20 print m(i);" "; next   end   function f(n) if n = 0 then f = 1 else f = n - m(f(n - 1)) end if end function   function m(n) if n = 0 then m = 0 else m = n - f(m(n - 1)) end if end function  
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.
#Phix
Phix
function bindf(object m, integer f) return f(m) end function function unit(object m) return m end function function times_five(object l) return iff(integer(l)?l*5:l) end function function plus_four(object l) return iff(integer(l)?l+4:l) end function procedure test(object l) printf(1,"%v -> %v\n", {l, bindf(bindf(l,times_five),plus_four)}) end procedure test(3) test("none")
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.
#Python
Python
"""A Maybe Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations   from typing import Any from typing import Callable from typing import Generic from typing import Optional from typing import TypeVar from typing import Union     T = TypeVar("T")     class Maybe(Generic[T]): def __init__(self, value: Union[Optional[T], Maybe[T]] = None): if isinstance(value, Maybe): self.value: Optional[T] = value.value else: self.value = value   def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]): return self.bind(func)   def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]: return func(self.value)   def __str__(self): return f"{self.__class__.__name__}({self.value!r})"     def plus_one(value: Optional[int]) -> Maybe[int]: if value is not None: return Maybe[int](value + 1) return Maybe[int](None)     def currency(value: Optional[int]) -> Maybe[str]: if value is not None: return Maybe[str](f"${value}.00") return Maybe[str](None)     if __name__ == "__main__": test_cases = [1, 99, None, 4]   for case in test_cases: m_int = Maybe[int](case) result = m_int >> plus_one >> currency # or.. # result = m_int.bind(plus_one).bind(currency) print(f"{str(case):<4} -> {result}")  
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
#Clojure
Clojure
(defn calc-pi [iterations] (loop [x (rand) y (rand) in 0 total 1] (if (< total iterations) (recur (rand) (rand) (if (<= (+ (* x x) (* y y)) 1) (inc in) in) (inc total)) (double (* (/ in total) 4)))))   (doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi x))))
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\displaystyle \pi } . If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π / 4 {\displaystyle \pi /4} . So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π / 4 {\displaystyle \pi /4} . Task Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number π {\displaystyle \pi } is not built-in, we give π {\displaystyle \pi } as a number of digits: 3.141592653589793238462643383280
#Common_Lisp
Common Lisp
(defun approximate-pi (n) (/ (loop repeat n count (<= (abs (complex (random 1.0) (random 1.0))) 1.0)) n 0.25))   (dolist (n (loop repeat 5 for n = 1000 then (* n 10) collect n)) (format t "~%~8d -> ~f" n (approximate-pi 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.)
#Phix
Phix
with javascript_semantics function encode(string s) string symtab = "abcdefghijklmnopqrstuvwxyz" sequence res = {} for i=1 to length(s) do integer ch = s[i], k = find(ch,symtab) res &= k-1 -- for j=k to 2 by -1 do -- symtab[j] = symtab[j-1] -- end for -- symtab[1] = ch symtab[1..k] = ch&symtab[1..k-1] end for return res end function function decode(sequence s) string symtab = "abcdefghijklmnopqrstuvwxyz" string res = "" for i=1 to length(s) do integer k = s[i]+1 integer ch = symtab[k] res &= ch -- for j=k to 2 by -1 do -- symtab[j] = symtab[j-1] -- end for -- symtab[1] = ch symtab[1..k] = ch&symtab[1..k-1] end for return res end function procedure test(string s) sequence e = encode(s) string d = decode(e) ?{s,e,d,{"**ERROR**","ok"}[(s=d)+1]} end procedure test("broood") test("bananaaa") test("hiphophiphop")
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow   (e.g. with a different pitch).
#Befunge
Befunge
>~>48*-:0\`#@_2*::"!"%\"!"/3+g75v ^v('_')v!:-*57g+3/"!"\%"!":+1\-*< ^$$,*84_\#!:#:2#-%#15#\9#/*#2+#,< ##X)P)##Z*##3(D)5);(##8(/)A)8)9(# ($(&(*(2(B(A(?(;(3([)M)##1(##V)L) $%1'-')&$$.''&2'&%$'%&0'#%%%#&,'' '(&*&#$&&*'$&)'%'/'########6)##$% 1'-')&$$.''&2'&%$'%&0'#%%%#&,'''( &*&#$&&*'$&)'%'/'################
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.
#BBC_BASIC
BBC BASIC
total% = 10000 FOR trial% = 1 TO total% prize_door% = RND(3) : REM. The prize is behind this door guess_door% = RND(3) : REM. The contestant guesses this door IF prize_door% = guess_door% THEN REM. The contestant guessed right, reveal either of the others reveal_door% = RND(2) IF prize_door% = 1 reveal_door% += 1 IF prize_door% = 2 AND reveal_door% = 2 reveal_door% = 3 ELSE REM. The contestant guessed wrong, so reveal the non-prize door reveal_door% = prize_door% EOR guess_door% ENDIF stick_door% = guess_door% : REM. The sticker doesn't change his mind swap_door% = guess_door% EOR reveal_door% : REM. but the swapper does IF stick_door% = prize_door% sticker% += 1 IF swap_door% = prize_door% swapper% += 1 NEXT trial% PRINT "After a total of ";total%;" trials," PRINT "The 'sticker' won ";sticker%;" times (";INT(sticker%/total%*100);"%)" PRINT "The 'swapper' won ";swapper%;" times (";INT(swapper%/total%*100);"%)"
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m} It can be shown that such an inverse exists   if and only if   a   and   m   are coprime,   but we will ignore this for this task. Task Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language,   compute the modular inverse of   42 modulo 2017.
#Common_Lisp
Common Lisp
  ;; ;; Calculates the GCD of a and b based on the Extended Euclidean Algorithm. The function also returns ;; the Bézout coefficients s and t, such that gcd(a, b) = as + bt. ;; ;; The algorithm is described on page http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 ;; (defun egcd (a b) (do ((r (cons b a) (cons (- (cdr r) (* (car r) q)) (car r))) ; (r+1 r) i.e. the latest is first. (s (cons 0 1) (cons (- (cdr s) (* (car s) q)) (car s))) ; (s+1 s) (u (cons 1 0) (cons (- (cdr u) (* (car u) q)) (car u))) ; (t+1 t) (q nil)) ((zerop (car r)) (values (cdr r) (cdr s) (cdr u))) ; exit when r+1 = 0 and return r s t (setq q (floor (/ (cdr r) (car r)))))) ; inside loop; calculate the q   ;; ;; Calculates the inverse module for a = 1 (mod m). ;; ;; Note: The inverse is only defined when a and m are coprimes, i.e. gcd(a, m) = 1.” ;; (defun invmod (a m) (multiple-value-bind (r s k) (egcd a m) (unless (= 1 r) (error "invmod: Values ~a and ~a are not coprimes." a m)) s))  
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).
#XPL0
XPL0
  int A(5,4,3,2); [A(3,1,0,1):= 3100; A(3,1,0,1):= A(3,1,0,1)+1; IntOut(0, A(3,1,0,1)); ]
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.
#Axe
Axe
Fix 5 ClrDraw For(I,1,10) Text(I-1*9,0,I▶Dec) Text(91,I*7+1,I▶Dec) End   For(J,1,8) For(I,J,10) Text(I-1*9,J*7+1,I*J▶Dec) End End   HLine(7) VLine(89) DispGraph getKeyʳ Fix 4
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).
#Tcl
Tcl
package require math::linearalgebra namespace eval multipleRegression { namespace export regressionCoefficients namespace import ::math::linearalgebra::*   # Matrix inversion is defined in terms of Gaussian elimination # Note that we assume (correctly) that we have a square matrix proc invert {matrix} { solveGauss $matrix [mkIdentity [lindex [shape $matrix] 0]] } # Implement the Ordinary Least Squares method proc regressionCoefficients {y x} { matmul [matmul [invert [matmul $x [transpose $x]]] $x] $y } } namespace import multipleRegression::regressionCoefficients
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).
#TI-83_BASIC
TI-83 BASIC
{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}→L₁ {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}→L₂ QuadReg L₁,L₂
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#J
J
  NB. tacit implementation of the recursive c function NB. int multifact(int n,int deg){return n<=deg?n:n*multifact(n-deg,deg);}   multifact=: [`([ * - $: ])@.(<~) (a:,<' degree'),multifact table >:i.10 ┌─────────┬──────────────────────────────────────┐ │ │ degree │ ├─────────┼──────────────────────────────────────┤ │multifact│ 1 2 3 4 5 6 7 8 9 10│ ├─────────┼──────────────────────────────────────┤ │ 1 │ 1 1 1 1 1 1 1 1 1 1│ │ 2 │ 2 2 2 2 2 2 2 2 2 2│ │ 3 │ 6 3 3 3 3 3 3 3 3 3│ │ 4 │ 24 8 4 4 4 4 4 4 4 4│ │ 5 │ 120 15 10 5 5 5 5 5 5 5│ │ 6 │ 720 48 18 12 6 6 6 6 6 6│ │ 7 │ 5040 105 28 21 14 7 7 7 7 7│ │ 8 │ 40320 384 80 32 24 16 8 8 8 8│ │ 9 │ 362880 945 162 45 36 27 18 9 9 9│ │10 │3628800 3840 280 120 50 40 30 20 10 10│ └─────────┴──────────────────────────────────────┘  
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.
#PicoLisp
PicoLisp
(de mousePosition () (prog2 (prin "^[[?9h") # Mouse reporting on (and (= "^[" (key)) (key 200) (key 200) (key) (cons (- (char (key)) 32) (- (char (key)) 32) ) ) (prin "^[[?9l") ) ) # Mouse reporting off
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.
#PureBasic
PureBasic
x = WindowMouseX(#MyWindow) y = WindowMouseY(#MyWindow)
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.
#Processing
Processing
void setup(){ size(640, 480); }   void draw(){ // mouseX and mouseY provide the current mouse position ellipse(mouseX, mouseY, 5, 5); // graphic output example println("x:" + mouseX + " y:" + mouseY); }
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
#jq
jq
def single_solution_queens(n): def q: "♛"; def init(k): reduce range(0;k) as $i ([]; . + ["."]); def matrix(k): init(k) as $row | reduce range(0;k) as $i ([]; . + [$row]); def place(stream; i; j): # jq indexing is based on offsets but we are using the 1-based formulae: reduce stream as $s (.; setpath([-1+($s|i), -1+($s|j)]; q) ); def even(k): if ((k-2) % 6) != 0 then place( range(1; 1+(k/2)); .; 2*. ) | place( range(1; 1+(k/2)); (k/2) + .; 2*. -1 ) else place( range(1; 1+(k/2)); .; 1 + ((2*. + (k/2) - 3) % k)) | place( range(1; 1+(n/2)); n + 1 - .; n - ((2*. + (n/2) - 3) % n)) end;   matrix(n) # the chess board | if (n % 2) == 0 then even(n) else even(n-1) | .[n-1][n-1] = q end;   # Example: def pp: reduce .[] as $row (""; reduce $row[] as $x (.; . + $x) + "\n");   single_solution_queens(8) | pp
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.
#PL.2FI
PL/I
Nth: procedure options (main); /* 1 June 2014 */ declare i fixed (10);   do i = 0 to 25, 250 to 265, 1000 to 1025; if i = 250 | i = 1000 then put skip (2); put edit (enth(i)) (x(1), a); end;   enth: procedure (i) returns (character (25) varying); declare i fixed (10); declare suffix character (2);   select (mod(i, 10)); when (1) suffix = 'st'; when (2) suffix = 'nd'; when (3) suffix = 'rd'; otherwise suffix = 'th'; end; select (mod(i, 100)); when (11, 12, 13) suffix = 'th'; otherwise ; end; return ( trim(i) || suffix ); end enth;   end Nth;
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.
#PowerShell
PowerShell
function nth($inp){ $suffix = "th"   switch($inp % 10){ 1{$suffix="st"} 2{$suffix="nd"} 3{$suffix="rd"} } return "$inp$suffix " }   0..25 | %{Write-host -nonewline (nth "$_")};"" 250..265 | %{Write-host -nonewline (nth "$_")};"" 1000..1025 | %{Write-host -nonewline (nth "$_")};""
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Python
Python
for i in range(5000): if i == sum(int(x) ** int(x) for x in str(i)): print(i)
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#LibreOffice_Basic
LibreOffice Basic
'// LibreOffice Basic Implementation of Hofstadter Female-Male sequences   '// Utility functions sub setfont(strfont) ThisComponent.getCurrentController.getViewCursor.charFontName = strfont end sub   sub newline oVC = thisComponent.getCurrentController.getViewCursor oText = oVC.text oText.insertControlCharacter(oVC, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False) end sub   sub out(sString) oVC = ThisComponent.getCurrentController.getViewCursor oText = oVC.text oText.insertString(oVC, sString, false) end sub   sub outln(optional sString) if not ismissing (sString) then out(sString) newline end sub   function intformat(n as integer,nlen as integer) as string dim nstr as string nstr = CStr(n) while len(nstr) < nlen nstr = " " & nstr wend intformat = nstr end function   '// Hofstadter Female-Male function definitions function F(n as long) as long if n = 0 Then F = 1 elseif n > 0 Then F = n - M(F(n - 1)) endif end function   function M(n) if n = 0 Then M = 0 elseif n > 0 Then M = n - F(M(n - 1)) endif end function   '// Hofstadter Female Male sequence demo routine sub Hofstadter_Female_Male_Demo '// Introductory Text setfont("LM Roman 10") outln("Rosetta Code Hofstadter Female and Male Sequence Challenge") outln out("Two functions are said to be mutually recursive if the first calls the second,") outln(" and in turn the second calls the first.") out("Write two mutually recursive functions that compute members of the Hofstadter") outln(" Female and Male sequences defined as:") outln setfont("LM Mono Slanted 10") outln(chr(9)+"F(0) = 1 ; M(0)=0") outln(chr(9)+"F(n) = n - M(F(n-1)), n > 0") outln(chr(9)+"M(n) = n - F(M(n-1)), n > 0") outln '// Sequence Generation const nmax as long = 20 dim n as long setfont("LM Mono 10") out("n = " for n = 0 to nmax out(" " + intformat(n, 2)) next n outln out("F(n) = " for n = 0 to nmax out(" " + intformat(F(n),2)) next n outln out("M(n) = " for n = 0 to nmax out(" " + intformat(M(n), 2)) next n outln   end sub   ------------------------------ Output ------------------------------ n = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 F(n) = 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13 M(n) = 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12  
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String Compose the two functions with bind A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time. A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
#Racket
Racket
#lang racket   (require syntax/parse/define)   (define (bind x f) (and x (f x))) (define return identity)   ;; error when arg = 0 (define reciprocal (curry / 1)) ;; error when arg < 0 (define (root x) (if (< x 0) (error 'bad) (sqrt x))) ;; error whe arg <= 0 (define (ln x) (if (<= x 0) (error 'bad) (log x)))   (define (lift f check) (λ (x) (and (check x) (f x))))   (define safe-reciprocal (lift reciprocal (negate (curry equal? 0)))) (define safe-root (lift root (curry <= 0))) (define safe-ln (lift ln (curry < 0)))   (define (safe-log-root-reciprocal x) (bind (bind (bind x safe-reciprocal) safe-root) safe-ln))   (define tests `(-2 -1 -0.5 0 1 ,(exp -1) 1 2 ,(exp 1) 3 4 5))   (map safe-log-root-reciprocal tests)   (define-syntax-parser do-macro [(_ [x {~datum <-} y] . the-rest) #'(bind y (λ (x) (do-macro . the-rest)))] [(_ e) #'e])   (define (safe-log-root-reciprocal* x) (do-macro [x <- (safe-reciprocal x)] [x <- (safe-root x)] [x <- (safe-ln x)] (return x)))   (map safe-log-root-reciprocal* tests)
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.
#Raku
Raku
my $monad = <42>; say 'Is $monad an Int?: ', $monad ~~ Int; say 'Is $monad a Str?: ', $monad ~~ Str; say 'Wait, what? What exactly is $monad?: ', $monad.^name;
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
#Crystal
Crystal
def approx_pi(throws) times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0} 4.0 * times_inside / throws end   [1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n| puts "%8d samples: PI = %s" % [n, approx_pi(n)] end
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\displaystyle \pi } . If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π / 4 {\displaystyle \pi /4} . So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π / 4 {\displaystyle \pi /4} . Task Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number π {\displaystyle \pi } is not built-in, we give π {\displaystyle \pi } as a number of digits: 3.141592653589793238462643383280
#D
D
import std.stdio, std.random, std.math;   double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ { uint inside; foreach (immutable i; 0 .. nthrows) if (hypot(uniform01, uniform01) <= 1) inside++; return 4.0 * inside / nthrows; }   void main() { foreach (immutable p; 1 .. 8) writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p)); }
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.)
#PHP
PHP
<?php   function symbolTable() { $symbol = array(); for ($c = ord('a') ; $c <= ord('z') ; $c++) { $symbol[$c - ord('a')] = chr($c); } return $symbol; }   function mtfEncode($original, $symbol) { $encoded = array(); for ($i = 0 ; $i < strlen($original) ; $i++) { $char = $original[$i]; $position = array_search($char, $symbol); $encoded[] = $position; $mtf = $symbol[$position]; unset($symbol[$position]); array_unshift($symbol, $mtf); } return $encoded; }   function mtfDecode($encoded, $symbol) { $decoded = ''; foreach ($encoded AS $position) { $char = $symbol[$position]; $decoded .= $char; unset($symbol[$position]); array_unshift($symbol, $char); } return $decoded; }   foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) { $encoded = mtfEncode($original, symbolTable()); $decoded = mtfDecode($encoded, symbolTable()); echo $original, ' -> [', implode(',', $encoded), ']', ' -> ', $decoded, ' : ', ($original === $decoded ? 'OK' : 'Error'), PHP_EOL; }
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow   (e.g. with a different pitch).
#C
C
  /*   David Lambert, 2010-Dec-09   filter producing morse beep commands.   build: make morse   use: $ echo tie a. | ./morse beep -n -f 440 -l 300 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -f 440 -l 100 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -D 200 -n -D 400 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -D 200 -n -D 400 -n -D 400   bugs: What is the space between letter and punctuation? Demo truncates input lines at 71 characters or so.   */   #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   #define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) /* BIND(-1,0,9) is 0 BIND( 7,0,9) is 7 BIND(77,0,9) is 9 */   char /* beep args for */ /* dit dah extra space */ dih[50],dah[50],medium[30],word[30], *dd[2] = {dih,dah}; const char *ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!/()&:;=+-_\"$@", *itu[] = { "13","3111","3131","311","1","1131","331","1111","11","1333","313","1311","33","31","333","1331","3313","131","111","3","113","1113","133","3113","3133","3311","33333","13333","11333","11133","11113","11111","31111","33111","33311","33331","131313","331133","113311","133331","313133","31131","31331","313313","13111","333111","313131","31113","13131","311113","113313","131131","1113113","133131" };   void append(char*s,const char*morse) { for (; *morse; ++morse) strcat(s,dd['3'==*morse]); strcat(s,medium); }   char*translate(const char*i,char*o) { const char*pc; sprintf(o,"beep"); for (; *i; ++i) if (NULL == (pc = strchr(ascii,toupper(*i)))) strcat(o,word); else append(o,itu[pc-ascii]); strcat(o,word); return o; }   int main(int ac,char*av[]) { char sin[73],sout[100000]; int dit = 100; if (1 < ac) { if (strlen(av[1]) != strspn(av[1],"0123456789")) return 0*fprintf(stderr,"use: %s [duration] dit in ms, default %d\n",*av,dit); dit = BIND(atoi(av[1]),1,1000); } sprintf(dah," -n -f 440 -l %d -D %d",3*dit,dit); sprintf(dih," -n -f 440 -l %d -D %d",dit,dit); sprintf(medium," -n -D %d",(3-1)*dit); sprintf(word," -n -D %d",(7-(3-1)-1)*dit); while (NULL != fgets(sin,72,stdin)) puts(translate(sin,sout)); return 0; }  
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it. If both remaining doors have goats behind them, he chooses one randomly. After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door. Imagine that you chose Door 1 and the host opens Door 3, which has a goat. He then asks you "Do you want to switch to Door Number 2?" The question Is it to your advantage to change your choice? Note The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors. Task Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess. Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. References Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3 A YouTube video:   Monty Hall Problem - Numberphile.
#C
C
//Evidence of the Monty Hall solution.   #include <stdio.h> #include <stdlib.h> #include <time.h>   #define GAMES 3000000   int main(void){ unsigned i, j, k, choice, winsbyswitch=0, door[3];   srand(time(NULL)); //initialize random seed. for(i=0; i<GAMES; i++){ door[0] = (!(rand()%2)) ? 1: 0; //give door 1 either a car or a goat randomly. if(door[0]) door[1]=door[2]=0; //if 1st door has car, give other doors goats. else{ door[1] = (!(rand()%2)) ? 1: 0; door[2] = (!door[1]) ? 1: 0; } //else, give 2nd door car or goat, give 3rd door what's left. choice = rand()%3; //choose a random door.   //if the next door has a goat, and the following door has a car, or vice versa, you'd win if you switch. if(((!(door[((choice+1)%3)])) && (door[((choice+2)%3)])) || (!(door[((choice+2)%3)]) && (door[((choice+1)%3)]))) winsbyswitch++; } printf("\nAfter %u games, I won %u by switching. That is %f%%. ", GAMES, winsbyswitch, (float)winsbyswitch*100.0/(float)i); }  
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m} It can be shown that such an inverse exists   if and only if   a   and   m   are coprime,   but we will ignore this for this task. Task Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language,   compute the modular inverse of   42 modulo 2017.
#Cowgol
Cowgol
include "cowgol.coh";   sub mulinv(a: int32, b: int32): (t: int32) is if b<0 then b := -b; end if; if a<0 then a := b - (-a % b); end if; t := 0; var nt: int32 := 1; var r := b; var nr := a % b; while nr != 0 loop var q := r / nr; var tmp := nt; nt := t - q*nt; t := tmp; tmp := nr; nr := r - q*nr; r := tmp; end loop; if r>1 then t := -1; elseif t<0 then t := t + b; end if; end sub;   record Pair is a: int32; b: int32; end record;   var data: Pair[] := { {42, 2017}, {40, 1}, {52, -217}, {-486, 217}, {40, 2018} };   var i: @indexof data := 0; while i < @sizeof data loop print_i32(data[i].a as uint32); print(", "); print_i32(data[i].b as uint32); print(" -> "); var mi := mulinv(data[i].a, data[i].b); if mi<0 then print("no inverse"); else print_i32(mi as uint32); end if; print_nl(); i := i + 1; end loop;
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.
#Crystal
Crystal
def modinv(a0, m0) return 1 if m0 == 1 a, m = a0, m0 x0, inv = 0, 1 while a > 1 inv -= (a // m) * x0 a, m = m, a % m x0, inv = inv, x0 end inv += m0 if inv < 0 inv end
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#BASIC
BASIC
CLS   'header row PRINT " "; FOR n = 1 TO 12 'do it this way for alignment purposes o$ = " " MID$(o$, LEN(o$) - LEN(STR$(n)) + 1) = STR$(n) PRINT o$; NEXT PRINT : PRINT " "; STRING$(49, "-");   FOR n = 1 TO 12 PRINT IF n < 10 THEN PRINT " "; PRINT n; "|"; 'row labels FOR m = 1 TO n - 1 PRINT " "; NEXT FOR m = n TO 12 'alignment again o$ = " " MID$(o$, LEN(o$) - LEN(STR$(m * n)) + 1) = STR$(m * n) PRINT o$; NEXT NEXT
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).
#Ursala
Ursala
regression_coefficients = lapack..dgelsd
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).
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Swap(Of T)(ByRef x As T, ByRef y As T) Dim temp = x x = y y = temp End Sub   Sub Require(condition As Boolean, message As String) If condition Then Return End If Throw New ArgumentException(message) End Sub   Class Matrix Private data As Double(,) Private rowCount As Integer Private colCount As Integer   Public Sub New(rows As Integer, cols As Integer) Require(rows > 0, "Need at least one row") rowCount = rows   Require(cols > 0, "Need at least one column") colCount = cols   data = New Double(rows - 1, cols - 1) {} End Sub   Public Sub New(source As Double(,)) Dim rows = source.GetLength(0) Require(rows > 0, "Need at least one row") rowCount = rows   Dim cols = source.GetLength(1) Require(cols > 0, "Need at least one column") colCount = cols   data = New Double(rows - 1, cols - 1) {} For i = 1 To rows For j = 1 To cols data(i - 1, j - 1) = source(i - 1, j - 1) Next Next End Sub   Default Public Property Index(i As Integer, j As Integer) As Double Get Return data(i, j) End Get Set(value As Double) data(i, j) = value End Set End Property   Public Property Slice(i As Integer) As Double() Get Dim m(colCount - 1) As Double For j = 1 To colCount m(j - 1) = Index(i, j - 1) Next Return m End Get Set(value As Double()) Require(colCount = value.Length, "Slice must match the number of columns") For j = 1 To colCount Index(i, j - 1) = value(j - 1) Next End Set End Property   Public Shared Operator *(m1 As Matrix, m2 As Matrix) As Matrix Dim rc1 = m1.rowCount Dim cc1 = m1.colCount Dim rc2 = m2.rowCount Dim cc2 = m2.colCount Require(cc1 = rc2, "Cannot multiply if the first columns does not equal the second rows") Dim result As New Matrix(rc1, cc2) For i = 1 To rc1 For j = 1 To cc2 For k = 1 To rc2 result(i - 1, j - 1) += m1(i - 1, k - 1) * m2(k - 1, j - 1) Next Next Next Return result End Operator   Public Function Transpose() As Matrix Dim rc = rowCount Dim cc = colCount   Dim trans As New Matrix(cc, rc) For i = 1 To cc For j = 1 To rc trans(i - 1, j - 1) = Index(j - 1, i - 1) Next Next Return trans End Function   Public Sub ToReducedRowEchelonForm() Dim lead = 0 Dim rc = rowCount Dim cc = colCount For r = 1 To rc If cc <= lead Then Return End If Dim i = r   While Index(i - 1, lead) = 0.0 i += 1 If rc = i Then i = r lead += 1 If cc = lead Then Return End If End If End While   Dim temp = Slice(i - 1) Slice(i - 1) = Slice(r - 1) Slice(r - 1) = temp   If Index(r - 1, lead) <> 0.0 Then Dim div = Index(r - 1, lead) For j = 1 To cc Index(r - 1, j - 1) /= div Next End If   For k = 1 To rc If k <> r Then Dim mult = Index(k - 1, lead) For j = 1 To cc Index(k - 1, j - 1) -= Index(r - 1, j - 1) * mult Next End If Next   lead += 1 Next End Sub   Public Function Inverse() As Matrix Require(rowCount = colCount, "Not a square matrix") Dim len = rowCount Dim aug As New Matrix(len, 2 * len) For i = 1 To len For j = 1 To len aug(i - 1, j - 1) = Index(i - 1, j - 1) Next REM augment identity matrix to right aug(i - 1, i + len - 1) = 1.0 Next aug.ToReducedRowEchelonForm() Dim inv As New Matrix(len, len) For i = 1 To len For j = len + 1 To 2 * len inv(i - 1, j - len - 1) = aug(i - 1, j - 1) Next Next Return inv End Function End Class   Function ConvertArray(source As Double()) As Double(,) Dim dest(0, source.Length - 1) As Double For i = 1 To source.Length dest(0, i - 1) = source(i - 1) Next Return dest End Function   Function MultipleRegression(y As Double(), x As Matrix) As Double() Dim tm As New Matrix(ConvertArray(y)) Dim cy = tm.Transpose Dim cx = x.Transpose Return ((x * cx).Inverse * x * cy).Transpose.Slice(0) End Function   Sub Print(v As Double()) Dim it = v.GetEnumerator()   Console.Write("[") If it.MoveNext() Then Console.Write(it.Current) End If While it.MoveNext Console.Write(", ") Console.Write(it.Current) End While Console.Write("]") End Sub   Sub Main() Dim y() = {1.0, 2.0, 3.0, 4.0, 5.0} Dim x As New Matrix({{2.0, 1.0, 3.0, 4.0, 5.0}}) Dim v = MultipleRegression(y, x) Print(v) Console.WriteLine()   y = {3.0, 4.0, 5.0} x = New Matrix({ {1.0, 2.0, 1.0}, {1.0, 1.0, 2.0} }) v = MultipleRegression(y, x) Print(v) Console.WriteLine()   y = {52.21, 53.12, 54.48, 55.84, 57.2, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.1, 69.92, 72.19, 74.46} Dim a = {1.47, 1.5, 1.52, 1.55, 1.57, 1.6, 1.63, 1.65, 1.68, 1.7, 1.73, 1.75, 1.78, 1.8, 1.83}   Dim xs(2, a.Length - 1) As Double For i = 1 To a.Length xs(0, i - 1) = 1.0 xs(1, i - 1) = a(i - 1) xs(2, i - 1) = a(i - 1) * a(i - 1) Next x = New Matrix(xs) v = MultipleRegression(y, x) Print(v) Console.WriteLine() End Sub   End Module
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.
#Java
Java
public class MultiFact { private static long multiFact(long n, int deg){ long ans = 1; for(long i = n; i > 0; i -= deg){ ans *= i; } return ans; }   public static void main(String[] args){ for(int deg = 1; deg <= 5; deg++){ System.out.print("degree " + deg + ":"); for(long n = 1; n <= 10; n++){ System.out.print(" " + multiFact(n, deg)); } System.out.println(); } } }
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Python
Python
  import Tkinter as tk   def showxy(event): xm, ym = event.x, event.y str1 = "mouse at x=%d y=%d" % (xm, ym) # show cordinates in title root.title(str1) # switch color to red if mouse enters a set location range x,y, delta = 100, 100, 10 frame.config(bg='red' if abs(xm - x) < delta and abs(ym - y) < delta else 'yellow')   root = tk.Tk() frame = tk.Frame(root, bg= 'yellow', width=300, height=200) frame.bind("<Motion>", showxy) frame.pack()   root.mainloop()  
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.
#Racket
Racket
  #lang racket/gui (define-values [point _] (get-current-mouse-state)) (send point get-x) (send point get-y)  
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
#Julia
Julia
""" # EightQueensPuzzle   Ported to **Julia** from examples in several languages from here: https://hbfs.wordpress.com/2009/11/10/is-python-slow """ module EightQueensPuzzle   export Board, solve!   mutable struct Board cols::Int nodes::Int diag45::Int diag135::Int solutions::Int   Board() = new(0, 0, 0, 0, 0) end   "Marks occupancy." function mark!(b::Board, k::Int, j::Int) b.cols ⊻= (1 << j) b.diag135 ⊻= (1 << (j+k)) b.diag45 ⊻= (1 << (32+j-k)) end   "Tests if a square is menaced." function test(b::Board, k::Int, j::Int) b.cols & (1 << j) + b.diag135 & (1 << (j+k)) + b.diag45 & (1 << (32+j-k)) == 0 end   "Backtracking solver." function solve!(b::Board, niv::Int, dx::Int) if niv > 0 for i in 0:dx-1 if test(b, niv, i) == true mark!(b, niv, i) solve!(b, niv-1, dx) mark!(b, niv, i) end end else for i in 0:dx-1 if test(b, 0, i) == true b.solutions += 1 end end end b.nodes += 1 b.solutions end   end # module   using .EightQueensPuzzle   for n = 1:17 b = Board() @show n print("elapsed:") solutions = @time solve!(b, n-1, n) @show solutions println() end