task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Python
Python
>>> from pprint import pprint as pp # Pretty printer >>> from itertools import product >>> >>> def dict_as_mdarray(dimensions=(2, 3), init=0.0): ... return {indices: init for indices in product(*(range(i) for i in dimensions))} ... >>> >>> mdarray = dict_as_mdarray((2, 3, 4, 5)) >>> pp(mdarray) {(0, 0, 0, 0): ...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#ALGOL_W
ALGOL W
begin  % print a school style multiplication table  % i_w := 3; s_w := 0; % set output formating  % write( " " ); for i := 1 until 12 do writeon( " ", i ); write( " +" ); for i := 1 until 12 do writeon( "----" ); for i := 1 until 1...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#PARI.2FGP
PARI/GP
pseudoinv(M)=my(sz=matsize(M),T=conj(M))~;if(sz[1]<sz[2],T/(M*T),(T*M)^-1*T) addhelp(pseudoinv, "pseudoinv(M): Moore pseudoinverse of the matrix M.");   y*pseudoinv(X)
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Factor
Factor
USING: formatting io kernel math math.ranges prettyprint sequences ; IN: rosetta-code.multifactorial   : multifactorial ( n degree -- m ) neg 1 swap <range> product ;   : mf-row ( degree -- ) dup "Degree %d: " printf 10 [1,b] [ swap multifactorial pprint bl ] with each ;   : main ( -- ) 5 [1,b] [ mf-row...
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)(...
#Forth
Forth
: !n negate swap 1 dup rot do i * over +loop nip ; : test cr 6 1 ?do 11 1 ?do i j !n . loop cr loop ;
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Lingo
Lingo
put _mouse.mouseLoc -- point(310, 199)
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#xTalk
xTalk
  -- Method 1: -- this script in either the stack script or the card script to get position relative to the current stack window on mouseMove pMouseH,pMouseV put pMouseH,pMouse end mouseMove   -- Method 2: -- this script can go anywhere to get current position relative to the current stack window put mouseLoc()   -...
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 armie...
#Groovy
Groovy
def listOrder = { a, b -> def k = [a.size(), b.size()].min() def i = (0..<k).find { a[it] != b[it] } (i != null) ? a[i] <=> b[i] : a.size() <=> b.size() }   def orderedPermutations = { list -> def n = list.size() (0..<n).permutations().sort(listOrder) }   def diagonalSafe = { list -> def n = lis...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#VBA
VBA
Private Function nth_root(y As Double, n As Double) Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy Dim x As Variant: x = 1 Do While True d = (y / x ^ (n - 1) - x) / n x = x + d e = eps * x '-- absolute accuracy If d > -e And d < e Then Exit Do ...
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 t...
#Oforth
Oforth
: nth(n) | r | n "th" over 10 mod ->r r 1 == ifTrue: [ n 100 mod 11 == ifFalse: [ drop "st" ] ] r 2 == ifTrue: [ n 100 mod 12 == ifFalse: [ drop "nd" ] ] r 3 == ifTrue: [ n 100 mod 13 == ifFalse: [ drop "rd" ] ] + ;
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#PHP
PHP
  <?php   $pwr = array_fill(0, 10, 0);   function isMunchhausen($n) { global $pwr; $sm = 0; $temp = $n; while ($temp) { $sm= $sm + $pwr[($temp % 10)]; $temp = (int)($temp / 10); } return $sm == $n; }   for ($i = 0; $i < 10; $i++) { $pwr[$i] = pow((float)($i), (float)($i)); }...
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 ) ) , ...
#Java
Java
  import java.util.HashMap; import java.util.Map;   public class MutualRecursion {   public static void main(final String args[]) { int max = 20; System.out.printf("First %d values of the Female sequence:  %n", max); for (int i = 0; i < max; i++) { System.out.printf(" f(%d) = %d...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#zkl
zkl
n:=3; n.pump(List) //-->L(0,1,2)   n.pump(List,List) //-->L(0,1,2), not expected because the second list can be used to describe a calculation n.pump(List,List(Void,List)) //--> L(L(),L(),L()) all same List(Void,List) means returns List, which is a "known" value n.pump(List,List.fpM("-")) //--> L(L(),L(),L()) all ...
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 ...
#F.23
F#
  // We can use Some as return, Option.bind and the pipeline operator in order to have a very concise code     let f1 (v:int) = Some v // int -> Option<int> let f2 (v:int) = Some(string v) // int -> Option<sting>   f1 4 |> Option.bind f2 |> printfn "Value is %A" // bind when option (maybe) has data None |> Option.bin...
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 ...
#Factor
Factor
USING: monads ; FROM: monads => do ;   ! Prints "T{ just { value 7 } }" 3 maybe-monad return >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call .   ! Prints "nothing" nothing >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call .
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Arturo
Arturo
Pi: function [throws][ inside: new 0.0 do.times: throws [ if 1 > hypot random 0 1.0 random 0 1.0 -> inc 'inside ] return 4 * inside / throws ]   loop [100 1000 10000 100000 1000000] 'n -> print [pad to :string n 8 "=>" Pi n]
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#AutoHotkey
AutoHotkey
  MsgBox % MontePi(10000) ; 3.154400 MsgBox % MontePi(100000) ; 3.142040 MsgBox % MontePi(1000000) ; 3.142096   MontePi(n) { Loop %n% { Random x, -1, 1.0 Random y, -1, 1.0 p += x*x+y*y < 1 } Return 4*p/n }  
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#jq
jq
# Input is the string to be encoded, st is the initial symbol table (an array) # Output: the encoded string (an array) def m2f_encode(st): reduce explode[] as $ch ( [ [], st]; # state: [ans, st] (.[1]|index($ch)) as $ix | .[1] as $st | [ (.[0] + [ $ix ]), [$st[$ix]] + $st[0:$i...
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...
#Julia
Julia
function encodeMTF(str::AbstractString, symtable::Vector{Char}=collect('a':'z')) function encode(ch::Char) r = findfirst(symtable, ch) deleteat!(symtable, r) prepend!(symtable, ch) return r end collect(encode(ch) for ch in str) end   function decodeMTF(arr::Vector{Int}, symta...
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...
#Ada
Ada
package Morse is   type Symbols is (Nul, '-', '.', ' '); -- Nul is the letter separator, space the word separator; Dash : constant Symbols := '-'; Dot : constant Symbols := '.'; type Morse_Str is array (Positive range <>) of Symbols; pragma Pack (Morse_Str);   function Convert (Input : String) retu...
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 hos...
#Ada
Ada
-- Monty Hall Game   with Ada.Text_Io; use Ada.Text_Io; with Ada.Float_Text_Io; use Ada.Float_Text_Io; with ada.Numerics.Discrete_Random;   procedure Monty_Stats is Num_Iterations : Positive := 100000; type Action_Type is (Stay, Switch); type Prize_Type is (Goat, Pig, Car); type Door_Index is range 1..3; ...
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 \math...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion %== Calls the "function" ==% call :ModInv 42 2017 result echo !result! call :ModInv 40 1 result echo !result! call :ModInv 52 -217 result echo !result! call :ModInv -486 217 result echo !result! call :ModInv 40 2018 result echo !result! pause>nul exit /b 0   %== The "function...
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...
#Phix
Phix
with javascript_semantics function bind(object m, integer f) return f(m) end function function unit(object m) return m end function function root(sequence al) {atom a, string lg} = al atom res = sqrt(a) return {res,lg&sprintf("took root: %f -> %f\n",{a,res})} end function function addOne(seque...
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...
#Perl
Perl
use strict; use feature 'say'; use Data::Monad::List;   # Cartesian product to 'count' in binary my @cartesian = [( list_flat_map_multi { scalar_list(join '', @_) } scalar_list(0..1), scalar_list(0..1), scalar_list(0..1) )->scalars]; say join "\n", @{shift @cartesian};   say '';   # Pythagor...
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. ...
#Racket
Racket
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly commo...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#AppleScript
AppleScript
set n to 12 -- Size of table. repeat with x from 0 to n if x = 0 then set {table, x} to {{return}, -1} repeat with y from 0 to n if y's contents = 0 then if x > 0 then set row to {f(x)} if x = -1 then set {row, x} to {{f("x")}, 1} else if y ≥ x then set end of...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Perl
Perl
use strict; use warnings; use Statistics::Regression;   my @y = (52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46); my @x = ( 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83);   my @model = ('const', 'X', 'X*...
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)(...
#Fortran
Fortran
program test implicit none integer :: i, j, n   do i = 1, 5 write(*, "(a, i0, a)", advance = "no") "Degree ", i, ": " do j = 1, 10 n = multifactorial(j, i) write(*, "(i0, 1x)", advance = "no") n end do write(*,*) end do   contains   function multifactorial (range, degree) integer :...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#LiveCode_Builder
LiveCode Builder
  LiveCode Builder (LCB) is a slightly lower level, strictly typed variant of LiveCode Script (LCS) used for making add-on extensions to LiveCode Script   -- results will be a point array struct like [117.0000,394.0000] relative to the current widget's view port use com.livecode.widget -- include the required module --...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Logo
Logo
show mousepos  ; [-250 250]
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Haskell
Haskell
import Control.Monad import Data.List   -- given n, "queens n" solves the n-queens problem, returning a list of all the -- safe arrangements. each solution is a list of the columns where the queens are -- located for each row queens :: Int -> [[Int]] queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where   ...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Wren
Wren
var nthRoot = Fn.new { |x, n| if (n < 2) Fiber.abort("n must be more than 1") if (x <= 0) Fiber.abort("x must be positive") var np = n - 1 var iter = Fn.new { |g| (np*g + x/g.pow(np))/n } var g1 = x var g2 = iter.call(g1) while (g1 != g2) { g1 = iter.call(g1) g2 = iter.call(i...
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 t...
#PARI.2FGP
PARI/GP
ordinal(n)=my(k=n%10,m=n%100); Str(n,if(m<21&&m>3,"th",k==1,"st",k==2,"nd",k==3,"rd","th")); apply(ordinal, [0..25]) apply(ordinal, [250..265]) apply(ordinal, [1000..1025]) apply(ordinal, [111, 1012])
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Picat
Picat
go => println([N : N in 1..5000, munchhausen_number(N)]).   munchhausen_number(N) => N == sum([T : I in N.to_string(),II = I.to_int(), T = II**II]).
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#JavaScript
JavaScript
function f(num) { return (num === 0) ? 1 : num - m(f(num - 1)); }   function m(num) { return (num === 0) ? 0 : num - f(m(num - 1)); }   function range(m, n) { return Array.apply(null, Array(n - m + 1)).map( function (x, i) { return m + i; } ); }   var a = range(0, 19);   //return a new array of the results an...
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 ...
#Go
Go
package main   import ( "fmt" "strconv" )   type maybe struct{ value *int }   func (m maybe) bind(f func(p *int) maybe) maybe { return f(m.value) }   func unit(p *int) maybe { return maybe{p} }   func decrement(p *int) maybe { if p == nil { return unit(nil) } else { q := *p - 1 ...
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 π {\...
#AWK
AWK
  # --- with command line argument "throws" ---   BEGIN{ th=ARGV[1]; for(i=0; i<th; i++) cin += (rand()^2 + rand()^2) < 1 printf("Pi = %8.5f\n",4*cin/th) }   usage: awk -f pi 2300   Pi = 3.14333    
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Kotlin
Kotlin
// version 1.1.2   fun encode(s: String): IntArray { if (s.isEmpty()) return intArrayOf() val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray() val result = IntArray(s.length) for ((i, c) in s.withIndex()) { val index = symbols.indexOf(c) if (index == -1) throw IllegalArg...
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...
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation" use framework "AppKit"   on morseCode(msg) script morse -- Unit duration in seconds and sounds used. property units : 0.075 property morseSound : current application's class "NSSound"'s soundNamed:("Gl...
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 hos...
#ALGOL_68
ALGOL 68
INT trials=100 000;   PROC brand = (INT n)INT: 1 + ENTIER (n * random);   PROC percent = (REAL x)STRING: fixed(100.0*x/trials,0,2)+"%";   main: ( INT prize, choice, show, not shown, new choice; INT stay winning:=0, change winning:=0, random winning:=0; INT doors = 3; [doors-1]INT other door;   TO trials DO ...
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 \math...
#BCPL
BCPL
get "libhdr"   let mulinv(a, b) = b<0 -> mulinv(a, -b), a<0 -> mulinv(b - (-a rem b), b), valof $( let t, nt, r, nr = 0, 1, b, a rem b until nr = 0 $( let tmp, q = ?, r / nr tmp := nt ; nt := t - q*nt ; t := tmp tmp := nr ; nr := r - q*nr ; r := tmp $) ...
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 \math...
#Bracmat
Bracmat
( ( mod-inv = a b b0 x0 x1 q .  !arg:(?a.?b) & ( !b:1 | (!b.0.1):(?b0.?x0.?x1) & whl ' ( !a:>1 & div$(!a.!b):?q & (!b.mod$(!a.!b)):(?a.?b) & (!x1+-1*!q*!x0.!x0):(?x0.?x1) ) & (!x:>0|!x1+!b0) ) ) ...
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...
#PHP
PHP
class WriterMonad {   /** @var mixed */ private $value; /** @var string[] */ private $logs;   private function __construct($value, array $logs = []) { $this->value = $value; $this->logs = $logs; }   public static function unit($value, string $log): WriterMonad { return new WriterMonad($value, ["{$log}: {$v...
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...
#Phix
Phix
function bindf(sequence m, integer f) return f(m) end function function unit(sequence m) return m end function function increment(sequence l) return unit(sq_add(l,1)) end function function double(sequence l) return unit(sq_mul(l,2)) end function sequence m1 = unit({3, 4, 5}), m2 = bindf...
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...
#Python
Python
"""A List Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations from itertools import chain   from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar     T = TypeVar("T")     class MList(List[T]): @classmethod ...
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. ...
#Raku
Raku
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly commo...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program multtable.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall .equ MAXI, 12 /******...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Phix
Phix
with javascript_semantics constant N = 15, M=3 sequence x = {1.47,1.50,1.52,1.55,1.57, 1.60,1.63,1.65,1.68,1.70, 1.73,1.75,1.78,1.80,1.83}, y = {52.21,53.12,54.48,55.84,57.20, 58.57,59.93,61.29,63.11,64.47, 66.28,68.10,69.92,72.19,74.46}, s = rep...
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)(...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function multiFactorial (n As UInteger, degree As Integer) As UInteger If n < 2 Then Return 1 Var result = n For i As Integer = n - degree To 2 Step -degree result *= i Next Return result End Function   For degree As Integer = 1 To 5 Print "Degree"; degree; " => "; For n As Intege...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ works when console is the active window \\ pressing right mouse button exit the loop While mouse<>2 Print mouse.x, mouse.y End While \\ end of part one, now we make a form with title Form1 (same name as the variable name) Declare Form1 Form Layer Form1 { window 16, 10000,8000 ' 16pt fo...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MousePosition["WindowAbsolute"]
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Heron
Heron
module NQueens { inherits { Heron.Windows.Console; } fields { n : Int = 4; sols : List = new List(); } methods { PosToString(row : Int, col : Int) : String { return "row " + row.ToString() + ", col " + col.ToString(); } AddQueen(b : Board, ...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#XBS
XBS
func nthRoot(x,a){ send x^(1/a); }{a=2}; log(nthRoot(8,3));
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#XPL0
XPL0
include c:\cxpl\stdlib;   func real NRoot(A, N); \Return the Nth root of A real A, N; real X, X0, Y; int I; [X:= 1.0; \initial guess repeat X0:= X; Y:= 1.0; for I:= 1 to fix(N)-1 do Y:= Y*X0; X:= ((N-1.0)*X0 + A/Y) / N; until abs(X-X0) < 1.0E-15; \(until X=X0 doesn'...
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 t...
#Pascal
Pascal
Program n_th;   function Suffix(N: NativeInt):AnsiString; var res: AnsiString; begin res:= 'th'; case N mod 10 of 1:IF N mod 100 <> 11 then res:= 'st'; 2:IF N mod 100 <> 12 then res:= 'nd'; 3:IF N mod 100 <> 13 then res:= 'rd'; else end; Suffix := res; end;   procedure Print_Images(l...
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 ...
#PicoLisp
PicoLisp
(for N 5000 (and (= N (sum '((N) (** N N)) (mapcar format (chop N)) ) ) (println N) ) )
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#jq
jq
  def M: def F: if . == 0 then 1 else . - ((. - 1) | F | M) end; if . == 0 then 0 else . - ((. - 1) | M | F) end;   def F: if . == 0 then 1 else . - ((. - 1) | F | M) end;
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Haskell
Haskell
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1)) -- prints "Just 7" print $ Nothing >>= (return . (*2)) >>= (return . (+1)) -- prints "Nothing"
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Hoon
Hoon
  :-  %say |= [^ [[txt=(unit ,@tas) ~] ~]] :-  %noun |^  %+ biff txt  ;~ biff m-parse m-double == ++ m-parse |= a=@tas ^- (unit ,@ud) (rust (trip a) dem)  :: ++ m-double |= a=@ud ^- (unit ,@ud) (some (mul a 2)) --  
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#BASIC
BASIC
DECLARE FUNCTION getPi! (throws!) CLS PRINT getPi(10000) PRINT getPi(100000) PRINT getPi(1000000) PRINT getPi(10000000)   FUNCTION getPi (throws) inCircle = 0 FOR i = 1 TO throws 'a square with a side of length 2 centered at 0 has 'x and y range of -1 to 1 randX = (RND * 2) - 1'range -1 to 1 randY = (RND...
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...
#Lua
Lua
-- Return table of the alphabet in lower case function getAlphabet () local letters = {} for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end return letters end   -- Move the table value at ind to the front of tab function moveToFront (tab, ind) local toMove = tab[ind] for i = ind - ...
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...
#Arturo
Arturo
; set the morse code   code: #[ ; letters a: ".-" b: "-..." c: "-.-." d: "-.." e: "." f: "..-." g: "--." h: "...." i: ".." j: ".---" k: "-.-" l: ".-.." m: "--" n: "-." o: "---" p: ".--." q: "--.-" r: ".-." s: "..." t: "-" u: "..-" v: "...-" w: "....
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 hos...
#APL
APL
∇ Run runs;doors;i;chosen;cars;goats;swap;stay;ix;prices [1] ⍝0: Monthy Hall problem [2] ⍝1: http://rosettacode.org/wiki/Monty_Hall_problem [3] [4] (⎕IO ⎕ML)←0 1 [5] prices←0 0 1 ⍝ 0=Goat, 1=Car [6] [7] ix←⊃,/{3?3}¨⍳runs ⍝ random indexes of doors (placement of car) [8] doors←...
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 \math...
#C
C
#include <stdio.h>   int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; }   int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#Python
Python
"""A Writer Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations   import functools import math import os   from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union     T = TypeVar("T")     cl...
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...
#Racket
Racket
#lang racket   (define (bind x f) (append-map f x)) (define return list) (define ((lift f) x) (list (f x)))   (define listy-inc (lift add1)) (define listy-double (lift (λ (x) (* 2 x))))   (bind (bind '(3 4 5) listy-inc) listy-double) ;; => '(8 10 12)   (define (pythagorean-triples n) (bind (range 1 n) (λ (x) ...
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...
#Raku
Raku
multi bind (@list, &code) { @list.map: &code };   multi bind ($item, &code) { $item.&code };   sub divisors (Int $int) { gather for 1 .. $int { .take if $int %% $_ } }   put (^10).&bind(* + 3).&bind(&divisors)».&bind(*.base: 2).join: "\n";
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#REXX
REXX
g = antenna.2.0
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Ring
Ring
# Project : Multi-dimensional array   a4 = newlist4(5,4,3,2)   func main() m = 1 for i = 1 to 5 for j = 1 to 4 for k = 1 to 3 for l = 1 to 2 a4[i][j][k][l] = m m = m + 1 ...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Arturo
Arturo
mulTable: function [n][ print [" |"] ++ map 1..n => [pad to :string & 3] print "----+" ++ join map 1..n => "----" loop 1..n 'x [ prints (pad to :string x 3) ++ " |" if x>1 -> loop 1..x-1 'y [prints " "] loop x..n 'y [prints " " ++ pad to :string x*y 3] print "" ] ] ...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#PicoLisp
PicoLisp
(scl 20)   # Matrix transposition (de matTrans (Mat) (apply mapcar Mat list) )   # Matrix multiplication (de matMul (Mat1 Mat2) (mapcar '((Row) (apply mapcar Mat2 '(@ (sum */ Row (rest) (1.0 .))) ) ) Mat1 ) )   # Matrix identity (de matIdent (N) (let L (need N (1.0) 0) (m...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Python
Python
import numpy as np   height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83] weight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46]   X = np.mat(height**np.arange(3)[:, None]) y = np.mat(weight)   print(y * X...
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)(...
#FunL
FunL
def multifactorial( n, d ) = product( n..1 by -d )   for d <- 1..5 println( d, [multifactorial(i, d) | i <- 1..10] ))
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#GAP
GAP
MultiFactorial := function(n, k) local r; r := 1; while n > 1 do r := r*n; n := n - k; od; return r; end;   PrintArray(List([1 .. 10], n -> List([1 .. 5], k -> MultiFactorial(n, k)))); [ [ 1, 1, 1, 1, 1 ], [ 2, 2, 2, 2,...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#MATLAB
MATLAB
get(0,'PointerLocation')
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#MAXScript
MAXScript
  try destroydialog mousePos catch ()   rollout mousePos "Mouse position" width:200 ( label mousePosText "Current mouse position:" pos:[0,0] label mousePosX "" pos:[130,0] label mousePosSep "x" pos:[143,0] label mousePosY "" pos:[160,0]   timer updateTimer interval:50 active:true   on updateTimer tick do ( mou...
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 armie...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(q(1), " ", q(2), " ", q(3), " ", q(4), " ", q(5), " ", q(6), " ", q(7), " ", q(8)) end   procedure q(c) static udiag, ddiag, row   initial { udiag := list(15, 0) ddiag := list(15, 0) row := list(8, 0) }   every 0 = row[r := 1 to 8] = ddiag[r + c - 1] = ...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Yabasic
Yabasic
data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0   do read e, b if e = 0 break print "The ", e, "th root of ", b, " is ", b^(1/e), " (", nthroot(b, e), ")" loop     sub nthroot(y, n) local eps, x, d, e   eps = 1e-15 // relative accuracy x = 1 repeat d = ( y / ( x^(n-1) ) - x...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#zkl
zkl
fcn nthroot(nth,a,precision=1.0e-5){ x:=prev:=a=a.toFloat(); n1:=nth-1; do{ prev=x; x=( prev*n1 + a/prev.pow(n1) ) / nth; } while( not prev.closeTo(x,precision) ); x }   nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Perl
Perl
use 5.10.0; my %irregulars = ( 1 => 'st', 2 => 'nd', 3 => 'rd', 11 => 'th', 12 => 'th', 13 => 'th'); sub nth { my $n = shift; $n . # q(') . # Uncomment this to add apostrophes to output ($irregulars{$n % 100} // $irr...
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 ...
#PL.2FI
PL/I
munchausen: procedure options(main); /* precalculate powers */ declare (pows(0:5), i) fixed; pows(0) = 0; /* 0^0=0 for Munchausen numbers */ do i=1 to 5; pows(i) = i**i; end;   declare (d1, d2, d3, d4, num, dpow) fixed; do d1=0 to 5; do d2=0 to 5; do d3=0 to 5; ...
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 ) ) , ...
#Jsish
Jsish
/* Mutual recursion, is jsish */ function f(num):number { return (num === 0) ? 1 : num - m(f(num - 1)); } function m(num):number { return (num === 0) ? 0 : num - f(m(num - 1)); }   function range(n=10, start=0, step=1):array { var a = Array(n).fill(0); for (var i in a) a[i] = start+i*step; return a; }   var a ...
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 ...
#J
J
  NB. monad implementation: unit=: < bind=: (@>)( :: ])   NB. monad utility safeVersion=: (<@) ( ::((<_.)"_)) safeCompose=:dyad define dyad def 'x`:6 bind y'/x,unit y )   NB. unsafe functions (fail with infinite arguments) subtractFromSelf=: -~ divideBySelf=: %~   NB. wrapped functions: safeSubtractFromSelf=: subtrac...
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 ...
#JavaScript
JavaScript
(function () { 'use strict';   // START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS:   // Returns Infinity if n === 0 function reciprocal(n) { return 1 / n; }   // Returns NaN if n < 0 function root(n) { return Math.sqrt(n); }   // Returns -Infinity if n === 0 // ...
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 π {\...
#BASIC256
BASIC256
  # Monte Carlo Simulator # Determine value of pi # 21010513     tosses = 1000 in_c = 0 i = 0   for i = 1 to tosses x = rand y = rand x2 = x * x y2 = y * y xy = x2 + y2 d_xy = sqr(xy) if d_xy <= 1 then in_c += 1 endif next i   print float(4*in_c/tosses)
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#BBC_BASIC
BBC BASIC
PRINT FNmontecarlo(1000) PRINT FNmontecarlo(10000) PRINT FNmontecarlo(100000) PRINT FNmontecarlo(1000000) PRINT FNmontecarlo(10000000) END   DEF FNmontecarlo(t%) LOCAL i%, n% FOR i% = 1 TO t% IF RND(1)^2 + RND(1)^2 < 1 n% += 1 NEXT = 4 * n% / t%
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Global All$, nl$ \\ upgrade to document Document All$ Nl$<={ } Function Encode$(Inp$) { Def SymbolTable$="abcdefghijklmnopqrstuvwxyz", Out$="" For i=1 to Len(Inp$) c$=Mid$(Inp$, i, 1) k=Instr(SymbolTable$, ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
mtf[word_]:=Module[{f,f2,p,q}, f[{output_,symList_},next_]:=Module[{index},index=Position[symList,next][[1,1]]-1; {output~Append~index,Prepend[Delete[symList,index+1],next]}]; p=Fold[f,{{},CharacterRange["a","z"]},Characters[ToString[word]]][[1]]; f2[{output_,symList_},next_]:=Module[{index},index=symLi...
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...
#AutoHotkey
AutoHotkey
TestString := "Hello World! abcdefg @\;" ;Create a string to be sent with multiple caps and some punctuation MorseBeep(teststring) ;Beeps our string after conversion return ;End Auto-Execute Section     MorseBeep(passedString) { StringLower, passedString, passedString ;Convert to lowercase for simpler...
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 hos...
#Arturo
Arturo
stay: 0 swit: 0   loop 1..1000 'i [ lst: shuffle new [1 0 0] rand: random 0 2 user: lst\[rand] remove 'lst rand   huh: 0 loop lst 'i [ if zero? i [ remove 'lst huh break ] huh: huh + 1 ]   if user=1 -> stay: stay+1 if and? [0 < size lst...
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 \math...
#C.23
C#
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } }   public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0);   while (a > 1) { ...
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...
#Raku
Raku
# 20200508 Raku programming solution   class Writer { has Numeric $.value ; has Str $.log }   sub Bind (Writer \v, &code) { my \n = v.value.&code; Writer.new: value => n.value, log => v.log ~ n.log };   sub Unit(\v, \s) { Writer.new: value=>v, log=>sprintf "%-17s: %.12f\n",s,v}   sub root(\v) { Unit v.sqrt, "Took...
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...
#Wren
Wren
import "/fmt" for Fmt   class Mwriter { construct new(value, log) { _value = value _log = log }   value { _value } log {_log} log=(value) { _log = value }   bind(f) { var n = f.call(_value) n.log = _log + n.log return n }   static unit(v, s) { Mwri...
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...
#Ring
Ring
  # Project : Monads/List monad   func main() str = "[" for x in [3,4,5] y = x+1 z = y*2 str = str + z + ", " next str = left(str, len(str) -2) str = str + "]" see str + nl  
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Ruby
Ruby
  class Array def bind(f) flat_map(&f) end def self.unit(*args) args end # implementing lift is optional, but is a great helper method for turning # ordinary funcitons into monadic versions of them. def self.lift(f) -> e { self.unit(f[e]) } end end   inc = -> n { n + 1 } str = -> n { n.to_s ...
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. ...
#Scala
Scala
object MultiDimensionalArray extends App {   // Create a regular 4 dimensional array and initialize successive elements to the values 1 to 120 val a4 = Array.fill[Int](5, 4, 3, 2) { m += 1; m } var m = 0   println("First element = " + a4(0)(0)(0)(0)) // access and print value of first element println("Last el...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#ASIC
ASIC
  REM Multiplication tables N = 12 PREDN = N - 1 WDTH = 3 CLS FOR J = 1 TO PREDN INTVAL = J GOSUB PRINTINT: PRINT " "; NEXT J INTVAL = N GOSUB PRINTINT: PRINT FOR J = 0 TO PREDN PRINT "----"; NEXT J PRINT "+" FOR I = 1 TO N WDTH = 3 FOR J = 1 TO N IF J < I THEN PRINT " "; ELSE INT...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#R
R
x <- c(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83) y <- c(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46)   lm( y ~ x + I(x^2))
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Racket
Racket
  #lang racket (require math) (define T matrix-transpose)   (define (fit X y) (matrix-solve (matrix* (T X) X) (matrix* (T X) y)))  
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Go
Go
package main   import "fmt"   func multiFactorial(n, k int) int { r := 1 for ; n > 1; n -= k { r *= n } return r }   func main() { for k := 1; k <= 5; k++ { fmt.Print("degree ", k, ":") for n := 1; n <= 10; n++ { fmt.Print(" ", multiFactorial(n, k)) } ...