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/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#jq
jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def motzkin: . as $n | reduce range(2; $n+1) as $i ( {m: [1,1]}; .m[$i] = (.m[$i-1] * (2*$i + 1) + .m[$i-2] * (3*$i -3))/($i + 2)) | .m ;     " n M[n] Prime?", "------------------------------",   (41 | motzkin | range(0;length) as $i |"\($i|lpad(2)) \(.[$i]|lpad(20)) \(.[$i]|if is_prime then "prime" else "" end)")
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Julia
Julia
using Primes   function motzkin(N) m = zeros(Int, N) m[1] = m[2] = 1 for i in 3:N m[i] = (m[i - 1] * (2i - 1) + m[i - 2] * (3i - 6)) ÷ (i + 1) end return m end   println(" n M[n] Prime?\n-----------------------------------") for (i, m) in enumerate(motzkin(42)) println(lpad(i - 1, 2), lpad(m, 20), lpad(isprime(m), 8)) end  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Table[With[{o = Hypergeometric2F1[(1 - n)/2, -n/2, 2, 4]}, {n, o, PrimeQ[o]}], {n, 0, 41}] // Grid
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.)
#Elixir
Elixir
defmodule MoveToFront do @table Enum.to_list(?a..?z)   def encode(text), do: encode(to_char_list(text), @table, [])   defp encode([], _, output), do: Enum.reverse(output) defp encode([h|t], table, output) do i = Enum.find_index(table, &(&1 == h)) encode(t, move2front(table, i), [i | output]) end   def decode(indices), do: decode(indices, @table, [])   defp decode([], _, output), do: Enum.reverse(output) |> to_string defp decode([h|t], table, output) do decode(t, move2front(table, h), [Enum.at(table, h) | output]) end   def move2front(table, i), do: [Enum.at(table,i) | List.delete_at(table, i)] end   Enum.each(["broood", "bananaaa", "hiphophiphop"], fn word -> IO.inspect word IO.inspect enc = MoveToFront.encode(word) IO.puts "#{word == MoveToFront.decode(enc)}\n" end)
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#F.23
F#
  // Move-to-front algorithm . Nigel Galloway: March 1st., 2021 let fN g=List.permute(fun n->match compare n g with 0->0 |1->n |_->n+1) let decode n=let rec fG n g=[|match n with n::t->yield List.item n g; yield! fG t (fN n g)|_->()|] in fG n ['a'..'z']|>System.String let encode n=let rec fG n g=[match n with n::t->let n=g|>List.findIndex((=)n) in yield n; yield! fG t (fN n g)|_->()] fG ((string n).ToCharArray()|>List.ofArray) ['a'..'z'] ["broood";"bananaaa";"hiphophiphop"]|>List.iter(fun n->let i=encode n in let g=decode i in printfn "%s->%A->%s check=%A" n i g (n=g))  
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.)
#C.2B.2B
C++
#include <cmath> #include <iostream> #include <string>   using namespace std;   // Use a struct as the monad struct LoggingMonad { double Value; string Log; };   // Use the >> operator as the bind function auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingMonad{result.Value, monad.Log + "\n" + result.Log}; }   // Define the three simple functions auto Root = [](double x){ return sqrt(x); }; auto AddOne = [](double x){ return x + 1; }; auto Half = [](double x){ return x / 2.0; };   // Define a function to create writer monads from the simple functions auto MakeWriter = [](auto f, string message) { return [=](double x){return LoggingMonad(f(x), message);}; };   // Derive writer versions of the simple functions auto writerRoot = MakeWriter(Root, "Taking square root"); auto writerAddOne = MakeWriter(AddOne, "Adding 1"); auto writerHalf = MakeWriter(Half, "Dividing by 2");     int main() { // Compose the writers to compute the golden ratio auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf; cout << result.Log << "\nResult: " << result.Value; }  
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
#C.2B.2B
C++
#include <iostream> #include <vector>   using namespace std;   // std::vector can be a list monad. Use the >> operator as the bind function template <typename T> auto operator>>(const vector<T>& monad, auto f) { // Declare a vector of the same type that the function f returns vector<remove_reference_t<decltype(f(monad.front()).front())>> result; for(auto& item : monad) { // Apply the function f to each item in the monad. f will return a // new list monad containing 0 or more items. const auto r = f(item); // Concatenate the results of f with previous results result.insert(result.end(), begin(r), end(r)); }   return result; }   // The Pure function returns a vector containing one item, t auto Pure(auto t) { return vector{t}; }   // A function to double items in the list monad auto Double(int i) { return Pure(2 * i); }   // A function to increment items auto Increment(int i) { return Pure(i + 1); }   // A function to convert items to a string auto NiceNumber(int i) { return Pure(to_string(i) + " is a nice number\n"); }   // A function to map an item to a sequence ending at max value // for example: 497 -> {497, 498, 499, 500} auto UpperSequence = [](auto startingVal) { const int MaxValue = 500; vector<decltype(startingVal)> sequence; while(startingVal <= MaxValue) sequence.push_back(startingVal++); return sequence; };   // Print contents of a vector void PrintVector(const auto& vec) { cout << " "; for(auto value : vec) { cout << value << " "; } cout << "\n"; }   // Print the Pythagorean triples void PrintTriples(const auto& vec) { cout << "Pythagorean triples:\n"; for(auto it = vec.begin(); it != vec.end();) { auto x = *it++; auto y = *it++; auto z = *it++;   cout << x << ", " << y << ", " << z << "\n"; } cout << "\n"; }   int main() { // Apply Increment, Double, and NiceNumber to {2, 3, 4} using the monadic bind auto listMonad = vector<int> {2, 3, 4} >> Increment >> Double >> NiceNumber;   PrintVector(listMonad);   // Find Pythagorean triples using the list monad. The 'x' monad list goes // from 1 to the max; the 'y' goes from the current 'x' to the max; and 'z' // goes from the current 'y' to the max. The last bind returns the triplet // if it is Pythagorean, otherwise it returns an empty list monad. auto pythagoreanTriples = UpperSequence(1) >> [](int x){return UpperSequence(x) >> [x](int y){return UpperSequence(y) >> [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};   PrintTriples(pythagoreanTriples); }  
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).
#jq
jq
# The input is used to initialize the elements of the # multi-dimensional array: def multiarray(d): . as $in | if (d|length) == 1 then [range(0;d[0]) | $in] else multiarray(d[1:]) | multiarray( d[0:1] ) end;
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).
#Julia
Julia
  julia> a4d = rand(Int, 5, 4, 3, 2) 5×4×3×2 Array{Int64,4}: [:, :, 1, 1] = -4071410509370082480 -361121233222804742 6884099527706004770 -3207257047234122321 8613938183523990915 -6284413064884272355 2092274063225757339 2883192477194384468 8063489472918692884 7817079491035828713 4371491775271354348 276862286105940437 -1772662642291072402 4809985701129914416 8281858591045636672 8406920023376702651 5149318914785292575 -1515076735924485336 -3446939844768424035 1325012392213218275   [:, :, 2, 1] = 6880114761106392524 6088903043766771621 3427296371455723937 -3871156425725741320 -9056731070343072262 -6900689642579036552 6428097039068264082 -8965404397337530418 -1972367399165031500 -2213273885576423725 -5169665910043775523 4625836493333597033 -2599106204536686594 8110110151332124377 2213007499408257641 -8439992945948333993 -5582801554832553928 7198533994867969144 -5086532281938936871 -5785587643130395544   [:, :, 3, 1] = -17294958981345227 -3894742251505912349 5910938929594406050 -1362996293154965701 3987219021607448038 6324367415515825846 3745581879541731998 2844758786713062315 -6091449020940608221 4456121461951632195 -2584728255467516797 -3497659495227813242 -5928873932509420551 -3918487907573141316 5830965509944713914 8236501134345492283 -8221039525025311485 -1377489816166018715 3331466694873878620 -6251825104964406539   [:, :, 1, 2] = -3457374235750853577 5435555757951424162 -2045941319469405317 7328458353379957791 1713055171323579940 7991986037097235116 -7241088987591638401 1660634030535548686 4673394669827656364 5361350944786403116 -3165400775730699962 -2786870864776919360 -936605780936708362 -8663743677584705168 2854140834792323092 -8335310793071345837 -3681644266158007140 -725263380984390472 -3882196050441743539 3104333567303051945   [:, :, 2, 2] = 6571168566735939900 -2962119128748096 -6995171731724009568 -3311757615633004375 -2337587211780934167 -4326286389873661148 4350714846343974202 7735721289399158250 -8213453299747381553 -8821356424402127712 -6240807297203610060 -4705744555934991961 5320110310888142259 -767643622294485330 -3059460131766056283 -7562911883833519677 -7578327835336665804 -1125154035165505958 7801099686760373595 -7212481716316687824   [:, :, 3, 2] = 4758459841719113041 -2608915613406792656 -4400228941420712011 8931157241145543293 7349481815101847836 -1609425280933983575 -4442082290554782826 -7044337833155803104 -4991211814494456720 6358355341301107435 -7486441622913196485 -1654445042306345503 -2789599665862904090 2753632931032283690 -1580743162155175963 -5070035295183713618 6026427076366641381 -2363816652576128818 -7282095369321808360 9097339410999816372   julia> a4d[1,1,1,1] = 10 10   julia> a4d 5×4×3×2 Array{Int64,4}: [:, :, 1, 1] = 10 -361121233222804742 6884099527706004770 -3207257047234122321 8613938183523990915 -6284413064884272355 2092274063225757339 2883192477194384468 8063489472918692884 7817079491035828713 4371491775271354348 276862286105940437 -1772662642291072402 4809985701129914416 8281858591045636672 8406920023376702651 5149318914785292575 -1515076735924485336 -3446939844768424035 1325012392213218275   [:, :, 2, 1] = 6880114761106392524 6088903043766771621 3427296371455723937 -3871156425725741320 -9056731070343072262 -6900689642579036552 6428097039068264082 -8965404397337530418 -1972367399165031500 -2213273885576423725 -5169665910043775523 4625836493333597033 -2599106204536686594 8110110151332124377 2213007499408257641 -8439992945948333993 -5582801554832553928 7198533994867969144 -5086532281938936871 -5785587643130395544   [:, :, 3, 1] = -17294958981345227 -3894742251505912349 5910938929594406050 -1362996293154965701 3987219021607448038 6324367415515825846 3745581879541731998 2844758786713062315 -6091449020940608221 4456121461951632195 -2584728255467516797 -3497659495227813242 -5928873932509420551 -3918487907573141316 5830965509944713914 8236501134345492283 -8221039525025311485 -1377489816166018715 3331466694873878620 -6251825104964406539   [:, :, 1, 2] = -3457374235750853577 5435555757951424162 -2045941319469405317 7328458353379957791 1713055171323579940 7991986037097235116 -7241088987591638401 1660634030535548686 4673394669827656364 5361350944786403116 -3165400775730699962 -2786870864776919360 -936605780936708362 -8663743677584705168 2854140834792323092 -8335310793071345837 -3681644266158007140 -725263380984390472 -3882196050441743539 3104333567303051945   [:, :, 2, 2] = 6571168566735939900 -2962119128748096 -6995171731724009568 -3311757615633004375 -2337587211780934167 -4326286389873661148 4350714846343974202 7735721289399158250 -8213453299747381553 -8821356424402127712 -6240807297203610060 -4705744555934991961 5320110310888142259 -767643622294485330 -3059460131766056283 -7562911883833519677 -7578327835336665804 -1125154035165505958 7801099686760373595 -7212481716316687824   [:, :, 3, 2] = 4758459841719113041 -2608915613406792656 -4400228941420712011 8931157241145543293 7349481815101847836 -1609425280933983575 -4442082290554782826 -7044337833155803104 -4991211814494456720 6358355341301107435 -7486441622913196485 -1654445042306345503 -2789599665862904090 2753632931032283690 -1580743162155175963 -5070035295183713618 6026427076366641381 -2363816652576128818 -7282095369321808360 9097339410999816372   julia> a4d[4,3,2,1] 2213007499408257641  
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.
#8080_Assembly
8080 Assembly
org 100h lxi h,output ;;; Make the header call skip ; Four spaces, mvi m,'|' ; separator, inx h lxi d,0C01h ; 12 fields starting at 1 fnum: mov a,e ; Field number call num inr e dcr d ; If not 12 yet, next field number jnz fnum call nl ; Newline mvi a,'-' ; Four dashes, mvi b,4 call bchr mvi m,'+' ; Plus, inx h mvi b,12*4 ; and 12*4 more dashes call bchr call nl ; Newline ;;; Write the 12 lines mvi d,1 ; Start at line 1, line: mov a,d ; Add the line number call num mvi m,'|' ; separator inx h mvi e,1 ; Start at column 1 mvi c,0 ; Cumulative sum at C field: mov a,c ; Add line number giving next column add d mov c,a mov a,e ; If column >= line, we need to print cmp d mov a,c ; the current total cc skip ; skip field if column >= line cnc num ; print field if column < line inr e ; next column mov a,e cpi 13 ; column 13? jnz field ; If not, next field on line call nl ; But if so, add newline inr d ; next line mov a,d cpi 13 ; line 13? jnz line ; If not, next line mvi m,'$' ; Write a CP/M string terminator, mvi c,9 ; And use CP/M to print the string lxi d,output jmp 5 ;;; Add the character in A to the string at HL, B times bchr: mov m,a inx h dcr b jnz bchr ret ;;; Add newline to string at HL nl: mvi m,13 ; CR inx h mvi m,10 ; LF inx h ret ;;; Add four spaces to string at HL (skip field) skip: mvi b,' ' mov m,b inx h mov m,b inx h mov m,b inx h mov m,b inx h ret ;;; Add 3-digit number in A to string at HL num: mvi m,' ' ; Separator space inx h ana a ; Clear carry mvi b,100 ; 100s digit call dspc mvi b,10 ; 10s digit call dspc mvi b,1 ; 1s digit dspc: jc dgt ; If carry, we need a digit cmp b ; >= digit? jnc dgt ; If not, we need a digit mvi m,' ' ; Otherwise, fill with space inx h cmc ; Return with carry off ret dgt: mvi m,'0'-1 ; Calculate digit dloop: inr m ; Increment digit sub b ; while B can be subtracted jnc dloop add b inx h ret output: equ $
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).
#Hy
Hy
(import [numpy [ones column-stack]] [numpy.random [randn]] [numpy.linalg [lstsq]])   (setv n 1000) (setv x1 (randn n)) (setv x2 (randn n)) (setv y (+ 3 (* 1 x1) (* -2 x2) (* .25 x1 x2) (randn n)))   (print (first (lstsq (column-stack (, (ones n) x1 x2 (* x1 x2))) y)))
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).
#J
J
NB. Wikipedia data 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   y %. x ^/ i.3 NB. calculate coefficients b1, b2 and b3 for 2nd degree polynomial 128.813 _143.162 61.9603
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.
#CLU
CLU
multifactorial = proc (n, degree: int) returns (int) result: int := 1 for i: int in int$from_to_by(n, 1, -degree) do result := result * i end return (result) end multifactorial   start_up = proc () po: stream := stream$primary_output() for n: int in int$from_to(1, 10) do for d: int in int$from_to(1, 5) do stream$putright(po, int$unparse(multifactorial(n,d)), 10) end stream$putc(po, '\n') end end start_up
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.
#Emacs_Lisp
Emacs Lisp
(mouse-pixel-position) ;; => (FRAME . (X . 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.
#ERRE
ERRE
  ! ! MOUSE WITH 'MOUSE.LIB' LIBRARY !   PROGRAM MOUSE   !$KEY   !$INCLUDE="PC.LIB"   !$INCLUDE="MOUSE.LIB"   PROCEDURE GETMONITORTYPE(->MONITOR$)  !$RCODE="DEF SEG=0" STATUS=PEEK($463)  !$RCODE="DEF SEG" MONITOR$="" IF STATUS=$B4 THEN  !$RCODE="STATUS=(INP(&H3BA) AND &H80)" FOR DELAYLOOP=1 TO 30000 DO  !$RCODE="XX=((INP(&H3BA) AND &H80)<>STATUS)" IF XX THEN MONITOR$="HERC" END IF END FOR IF MONITOR$="" THEN MONITOR$="MONO" END IF ELSE REGAX%=$1A00 EXECUTEASM($10) IF (REGAX% AND $FF)=$1A THEN MONITOR$="VGA" ELSE REGAX%=$1200 REGBX%=$10 EXECUTEASM($10) IF (REGBX% AND $FF)=$10 THEN MONITOR$="CGA" ELSE MONITOR$="EGA" END IF END IF END IF END PROCEDURE   BEGIN INITASM GETMONITORTYPE(->MONITOR$) COLOR(7,0) CLS LOCATE(1,50) PRINT("MONITOR TYPE ";MONITOR$) MOUSE_RESETANDSTATUS(->STATUS,BUTTONS) IF STATUS<>-1 THEN BEEP CLS PRINT("MOUSE DRIVER NOT INSTALLED OR MOUSE NOT FOUND") REPEAT GET(IN$) UNTIL IN$<>"" ELSE MOUSE_SETEXTCURSOR MOUSE_SETCURSORLIMITS(8,199,0,639) MOUSE_SETSENSITIVITY(30,30,50) MOUSE_SHOWCURSOR REPEAT OLDX=X OLDY=Y MOUSE_GETCURSORPOSITION(->X,Y,LEFT%,RIGHT%,BOTH%,MIDDLE%) GET(IN$) COLOR(15,0) LOCATE(1,2) PRINT("X =";INT(X/8)+1;" Y =";INT(Y/8)+1;" ";) IF LEFT% THEN LOCATE(1,37) COLOR(10,0) PRINT("LEFT";) END IF IF RIGHT% THEN LOCATE(1,37) COLOR(12,0) PRINT("RIGHT";) END IF IF MIDDLE% THEN LOCATE(1,37) COLOR(14,0) PRINT("MIDDLE";) END IF IF NOT RIGHT% AND NOT LEFT% AND NOT MIDDLE% THEN LOCATE(1,37) PRINT(" ";) END IF IF NOT (X=OLDX AND Y=OLDY) THEN MOUSE_SHOWCURSOR END IF UNTIL IN$=CHR$(27) END IF MOUSE_HIDECURSOR CLS END PROGRAM  
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.
#F.23
F#
open System.Windows.Forms open System.Runtime.InteropServices   #nowarn "9" [<Struct; StructLayout(LayoutKind.Sequential)>] type POINT = new (x, y) = { X = x; Y = y } val X : int val Y : int   [<DllImport("user32.dll")>] extern nativeint GetForegroundWindow(); [<DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)>] extern int ScreenToClient(nativeint hWnd, POINT &pt);   let GetMousePosition() = let hwnd = GetForegroundWindow() let pt = Cursor.Position let mutable ptFs = new POINT(pt.X, pt.Y) ScreenToClient(hwnd, &ptFs) |> ignore ptFs  
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
#Forth
Forth
variable solutions variable nodes   : bits ( n -- mask ) 1 swap lshift 1- ; : lowBit ( mask -- bit ) dup negate and ; : lowBit- ( mask -- bits ) dup 1- and ;   : next3 ( dl dr f files -- dl dr f dl' dr' f' ) invert >r 2 pick r@ and 2* 1+ 2 pick r@ and 2/ 2 pick r> and ;   : try ( dl dr f -- ) dup if 1 nodes +! dup 2over and and begin ?dup while dup >r lowBit next3 recurse r> lowBit- repeat else 1 solutions +! then drop 2drop ;   : queens ( n -- ) 0 solutions ! 0 nodes ! -1 -1 rot bits try solutions @ . ." solutions, " nodes @ . ." nodes" ;   8 queens \ 92 solutions, 1965 nodes
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc multOrder {a m} { assert {[gcd $a $m] == 1} set mofs [list] dict for {p e} [factor_num $m] { lappend mofs [multOrdr1 $a $p $e] } return [struct::list fold $mofs 1 lcm] }   proc multOrdr1 {a p e} { set m [expr {$p ** $e}] set t [expr {($p - 1) * ($p ** ($e - 1))}] set qs [dict create 1 ""]   dict for {f0 f1} [factor_num $t] { dict for {q -} $qs { foreach j [range [expr {1 + $f1}]] { dict set qs [expr {$q * $f0 ** $j}] "" } } }   dict for {q -} $qs { if {pypow($a, $q, $m) == 1} break } return $q }   #################################################### # utility procs proc assert {condition {message "Assertion failed!"}} { if { ! [uplevel 1 [list expr $condition]]} { return -code error $message } }   proc gcd {a b} { while {$b != 0} { lassign [list $b [expr {$a % $b}]] a b } return $a }   proc lcm {a b} { expr {$a * $b / [gcd $a $b]} }   proc factor_num {num} { primes::restart set factors [dict create] for {set i [primes::get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [primes::get_next_prime] } } return $factors }   #################################################### # a range command akin to Python's proc range args { foreach {start stop step} [switch -exact -- [llength $args] { 1 {concat 0 $args 1} 2 {concat $args 1} 3 {concat $args } default {error {wrong # of args: should be "range ?start? stop ?step?"}} }] break if {$step == 0} {error "cannot create a range when step == 0"} set range [list] while {$step > 0 ? $start < $stop : $stop < $start} { lappend range $start incr start $step } return $range }   # python's pow() proc ::tcl::mathfunc::pypow {x y {z ""}} { expr {$z eq "" ? $x ** $y : ($x ** $y) % $z} }   #################################################### # prime number generator # ref http://wiki.tcl.tk/5996 #################################################### namespace eval primes {}   proc primes::reset {} { variable list [list] variable current_index end }   namespace eval primes {reset}   proc primes::restart {} { variable list variable current_index if {[llength $list] > 0} { set current_index 0 } }   proc primes::is_prime {candidate} { variable list   foreach prime $list { if {$candidate % $prime == 0} { return false } if {$prime * $prime > $candidate} { return true } } while true { set largest [get_next_prime] if {$largest * $largest >= $candidate} { return [is_prime $candidate] } } }   proc primes::get_next_prime {} { variable list variable current_index   if {$current_index ne "end"} { set p [lindex $list $current_index] if {[incr current_index] == [llength $list]} { set current_index end } return $p }   switch -exact -- [llength $list] { 0 {set candidate 2} 1 {set candidate 3} default { set candidate [lindex $list end] while true { incr candidate 2 if {[is_prime $candidate]} break } } } lappend list $candidate return $candidate }   #################################################### puts [multOrder 37 1000] ;# 100   set b [expr {10**20 - 1}] puts [multOrder 2 $b] ;# 3748806900 puts [multOrder 17 $b] ;# 1499522760   set a 54 set m 100001 puts [set n [multOrder $a $m]] ;# 9090 puts [expr {pypow($a, $n, $m)}] ;# 1   set lambda {{a n m} {expr {pypow($a, $n, $m) == 1}}} foreach r [lreverse [range 1 $n]] { if {[apply $lambda $a $r $m]} { error "Oops, $n is not the smallest: {$a $r $m} satisfies $lambda" } if {$r % 1000 == 0} {puts "$r ..."} } puts "OK, $n is the smallest n such that {$a $n $m} satisfies $lambda"
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.
#Scheme
Scheme
(define (root number degree tolerance) (define (good-enough? next guess) (< (abs (- next guess)) tolerance)) (define (improve guess) (/ (+ (* (- degree 1) guess) (/ number (expt guess (- degree 1)))) degree)) (define (*root guess) (let ((next (improve guess))) (if (good-enough? next guess) guess (*root next)))) (*root 1.0))   (display (root (expt 2 10) 10 0.1)) (newline) (display (root (expt 2 10) 10 0.01)) (newline) (display (root (expt 2 10) 10 0.001)) (newline)
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.
#Microsoft_Small_Basic
Microsoft Small Basic
  loLim = 0 hiLim = 25 PrintImages() loLim = 250 hiLim = 265 PrintImages() loLim = 1000 hiLim = 1025 PrintImages()   Sub PrintImages For i = loLim To hiLim nr = i GetSuffix() TextWindow.Write(i + suffix + " ") EndFor TextWindow.WriteLine("") EndSub   Sub GetSuffix rem10 = Math.Remainder(nr, 10) rem100 = Math.Remainder(nr, 100) If rem10 = 1 And rem100 <> 11 Then suffix = "st" ElseIf rem10 = 2 And rem100 <> 12 Then suffix = "nd" ElseIf rem10 = 3 And rem100 <> 13 Then suffix = "rd" Else suffix = "th" EndIf EndSub  
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
#Maple
Maple
isMunchausen := proc(n::posint) local num_digits; num_digits := map(x -> StringTools:-Ord(x) - 48, StringTools:-Explode(convert(n, string))); return evalb(n = convert(map(x -> x^x, num_digits), `+`)); end proc;   Munchausen_upto := proc(n::posint) local k, count, list_num; list_num := []; for k to n do if isMunchausen(k) then list_num := [op(list_num), k]; end if; end do; return list_num; end proc;   Munchausen_upto(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).
#Go
Go
package main import "fmt"   func F(n int) int { if n == 0 { return 1 } return n - M(F(n-1)) }   func M(n int) int { if n == 0 { return 0 } return n - F(M(n-1)) }   func main() { for i := 0; i < 20; i++ { fmt.Printf("%2d ", F(i)) } fmt.Println() for i := 0; i < 20; i++ { fmt.Printf("%2d ", M(i)) } fmt.Println() }
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Phix
Phix
with javascript_semantics sequence s = repeat("x",6) ?s s[$] = 5 ?s s[1] &= 'y' ?s -- s[2] = s  ?s s[2] = deep_copy(s) ?s
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#PicoLisp
PicoLisp
: (make (do 5 (link (new)))) -> ($384717187 $384717189 $384717191 $384717193 $384717195)
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#PowerShell
PowerShell
  1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} | Select-Object -Unique | ForEach-Object {$_.ToString()}  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Nim
Nim
import strformat, strutils   func isPrime(n: Positive): bool = if n == 1: return false if (n and 1) == 0: return n == 2 if n mod 3 == 0: return n == 3 var d = 5 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 result = true   func motzkin(n: Positive): seq[int64] = result.setLen(n + 1) result[0] = 1 result[1] = 1 for i in 2..n: result[i] = (result[i-1] * (2 * i + 1) + result[i-2] * (3 * i - 3)) div (i + 2)   echo " n M[n] Prime?" echo "-----------------------------------" var m = motzkin(41) for i, val in m: echo &"{i:2} {insertSep($val):>23} {val.isPrime}"
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#PARI.2FGP
PARI/GP
  M=vector(41) M[1]=1 M[2]=2 for(n=3, 41, M[n]=(M[n-1]*(2*n+1) + M[n-2]*(3*n-3))/(n+2)) M=concat([1], M) for(n=1, 42, print(M[n]," ",isprime(M[n])))  
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.
#ALGOL_68
ALGOL 68
BEGIN   # This is a translation of the Javascript sample, main differences are because Algol 68 # # is strongly typed and "on-the-fly" constructon of functions is not really possible - # # we need to define a STRUCT where Javascript would just construct a new function. # # As Algol 68 does not allow procedure overloading, we use custom operators (which do # # allow overloading) so the techniques used here could be extended to procedures with # # signatures other than PROC(REAL)REAL # # The comments are generally the same as in the javascript original, changed as necessary # # to reflect Algol 68... #   # START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS: #   # error in n < 0 # PROC unsafe reciprocal = (REAL n)REAL: 1 / n; # error if n < 0 # PROC unsafe root = (REAL n)REAL: sqrt(n); # error if n <= 0 # PROC unsafe log = (REAL n)REAL: ln(n);     # NOW DERIVE SAFE VERSIONS OF THESE SIMPLE FUNCTIONS: # # These versions use a validity test, and return a wrapped value # # with a boolean is valid property as well as a value property #   MODE SAFEFUNCTION = STRUCT( PROC(REAL)REAL fn, PROC(REAL)BOOL fn safety check ); MODE MAYBE = STRUCT( BOOL is valid, REAL value );   SAFEFUNCTION safe reciprocal = ( unsafe reciprocal, ( REAL n )BOOL: n /= 0 ); SAFEFUNCTION safe root = ( unsafe root, ( REAL n )BOOL: n >= 0 ); SAFEFUNCTION safe log = ( unsafe log, ( REAL n )BOOL: n > 0 );   COMMENT the original Javascript contains this:   // THE DERIVATION OF THE SAFE VERSIONS USED THE 'UNIT' OR 'RETURN' // FUNCTION OF THE MAYBE MONAD   // Named maybe() here, the unit function of the Maybe monad wraps a raw value // in a datatype with two elements: .isValid (Bool) and .value (Number)   // a -> Ma function maybe(n) { return { isValid: (typeof n !== 'undefined'), value: n }; }   However Algol 68 is strongly typed, so the type (MODE) of the function parameters cannot be anything other than REAL. We therefore use "MAYBE( TRUE, n )" instead. COMMENT   # THE PROBLEM FOR FUNCTION NESTING (COMPOSITION) OF THE SAFE FUNCTIONS # # IS THAT THEIR INPUT AND OUTPUT TYPES ARE DIFFERENT #   # Our safe versions of the functions take simple numeric arguments (i.e. REAL), but return # # wrapped results. If we feed a wrapped result as an input to another safe function, the # # compiler will object. The solution is to write a higher order # # function (sometimes called 'bind' or 'chain') which handles composition, taking a # # a safe function and a wrapped value as arguments, #   # The 'bind' function of the Maybe monad: # # 1. Applies a 'safe' function directly to the raw unwrapped value, and # # 2. returns the wrapped result. #   # Ma -> (a -> Mb) -> Mb # # defined as an operator to allow overloading to other PROC modes # PRIO BIND = 1; OP BIND = (MAYBE maybe n, SAFEFUNCTION mf )MAYBE: IF is valid OF maybe n THEN mf CALL ( value OF maybe n ) ELSE maybe n FI; # we need an operator to call the wrapped function # PRIO CALL = 1; OP CALL = ( SAFEFUNCTION f, REAL value )MAYBE: BEGIN BOOL is valid = ( fn safety check OF f )( value ); MAYBE( is valid, IF is valid THEN ( fn OF f )( value ) ELSE value FI ) END; # CALL #   # Using the bind function, we can nest applications of safe functions, # # without the compiler choking on unexpectedly wrapped values returned from # # other functions of the same kind. # REAL root one over four = value OF ( MAYBE( TRUE, 4 ) BIND safe reciprocal BIND safe root );   # print( ( root one over four, newline ) ); # # -> 0.5 #   # We can compose a chain of safe functions (of any length) with a simple foldr/reduceRight # # which starts by 'lifting' the numeric argument into a Maybe wrapping, # # and then nests function applications (working from right to left) # # again, defined as an operator here to allow extension to other PROC modes # # also, as Algol 68 doesn't have builtin foldr/reduceRight, we need a loop... # PRIO SAFECOMPOSE = 1; OP SAFECOMPOSE = ( []SAFEFUNCTION lst functions, REAL value )MAYBE: BEGIN MAYBE result := MAYBE( TRUE, value ); FOR fn pos FROM UPB lst functions BY -1 TO LWB lst functions DO result := result BIND lst functions[ fn pos ] OD; result END; # SAFECOMPOSE #   # TEST INPUT VALUES WITH A SAFELY COMPOSED VERSION OF LOG(SQRT(1/X)) #   PROC safe log root reciprocal = ( REAL n )MAYBE: BEGIN # this declaration is requied for Algol 68G 2.8 # []SAFEFUNCTION function list = ( safe log, safe root, safe reciprocal ); function list SAFECOMPOSE n END; # safe log root reciprocal #   # Algol 68 doesn't have a builtin map operator, we could define one here but we can just # # use a loop for the purposes of this task... # REAL e = exp( 1 ); []REAL test values = ( -2, -1, -0.5, 0, 1 / e, 1, 2, e, 3, 4, 5 );   STRING prefix := "["; FOR test pos FROM LWB test values TO UPB test values DO MAYBE result = safe log root reciprocal( test values[ test pos ] ); print( ( prefix, IF is valid OF result THEN fixed( value OF result, -12, 8 ) ELSE "undefined" FI ) ); IF test pos MOD 4 = 0 THEN print( ( newline ) ) FI; prefix := ", " OD; print( ( "]", newline ) )   END
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#Factor
Factor
USING: formatting kernel locals make sequences ;   : to-front ( elt seq -- seq' ) over [ remove ] dip prefix ;   : encode ( symbols msg -- indices ) [ [ swap 2dup index , to-front ] each ] { } make nip ;   : decode ( symbols indices -- msg ) [ [ swap [ nth ] keep over , to-front ] each ] "" make nip ;   :: round-trip ( msg symbols -- ) symbols msg encode :> encoded symbols encoded decode :> decoded msg decoded assert= msg encoded decoded "%s -> %u -> %s\n" printf ;   "broood" "bananaaa" "hiphophiphop" [ "abcdefghijklmnopqrstuvwxyz" round-trip ] tri@
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.)
#FreeBASIC
FreeBASIC
#define FAIL -1   sub mtf( s() as string, i as uinteger ) 'moves the symbol at index i to the front and shifts preceding ones back dim as string*1 t = s(i) for j as uinteger = i to 1 step -1 s(j) = s(j-1) next j s(0)=t end sub   sub make_symbols( s() as string ) 'populates an array of strings with the lowercase alphabet for i as uinteger = 97 to 122 s(i-97) = chr(i) next i end sub   function find( s() as string, l as string ) as integer 'returns the index of the first occurrence of the symbol l in s() for i as uinteger = 0 to ubound(s) if s(i) = l then return i next i return FAIL end function   sub encode( s() as string, ind() as uinteger ) dim as integer n = ubound(s), i redim as uinteger ind(0 to n) dim as string a(0 to 25) make_symbols(a()) for z as uinteger = 0 to n i = find( a(), s(z) ) if i = FAIL then print "Uh oh! Couldn't find ";s(z);" in alphabet." end end if mtf( a(), i ) ind(z) = i next z end sub   sub decode( s() as string, ind() as uinteger ) dim as integer n = ubound(ind), i redim as string s(0 to n) dim as string a(0 to 25) make_symbols(a()) for z as uinteger = 0 to n s(z) = a(ind(z)) mtf(a(), ind(z)) next z end sub   sub printarr( s() as string ) for i as uinteger = 0 to ubound(s) print s(i); next i print end sub   sub printind( ind() as integer ) for i as uinteger = 0 to ubound(ind) print ind(i);" "; next i print end sub   sub compose( s() as string, b as string ) 'turns a string into a zero-indexed array of single letters 'The reason we use such arrays is to get them zero-indexed 'and to make the point that we could work with multi-char 'symbol tables if we wanted to dim as integer n = len(b), i redim as string s(0 to n-1) for i = 0 to n-1 s(i) = mid(b, 1+i, 1) next i end sub   '-----------now the tests------------- redim as string s(0) redim as integer ind(0)   compose( s(), "broood" ) encode( s(), ind() ) printind( ind() ) decode( s(), ind() ) printarr( s() ) : print   compose( s(), "bananaaa" ) encode( s(), ind() ) printind( ind() ) decode( s(), ind() ) printarr( s() ) : print   compose( s(), "hiphophiphop" ) encode( s(), ind() ) printind( ind() ) decode( s(), ind() ) printarr( s() )
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.)
#EchoLisp
EchoLisp
  (define (Writer.unit x (log #f)) (if log (cons log x) (cons (format "init → %d" x) x)))   ;; f is a lisp function ;; (Writer.lift f) returns a Writer function which returns a Writer element   (define (Writer.lift f name) (lambda(elem) (Writer.unit (f (rest elem)) (format "%a \n %a → %a" (first elem) name (f (rest elem))))))   ;; lifts and applies (define (Writer.bind f elem) ((Writer.lift f (string f)) elem))   (define (Writer.print elem) (writeln 'result (rest elem)) (writeln (first elem)))   ;; Writer monad versions (define w-root (Writer.lift sqrt "root")) (define w-half (Writer.lift (lambda(x) (// x 2)) "half")) (define w-inc ( Writer.lift add1 "add-one"))     ;; no binding required, as we use Writer lifted functions (-> 5 Writer.unit w-root w-inc w-half Writer.print)   result 1.618033988749895 init → 5 root → 2.23606797749979 add-one → 3.23606797749979 half → 1.618033988749895   ;; binding (->> 0 Writer.unit (Writer.bind sin) (Writer.bind cos) w-inc w-half Writer.print)   result 1 init → 0 sin → 0 cos → 1 add-one → 2 half → 1  
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
#Clojure
Clojure
  (defn bind [coll f] (apply vector (mapcat f coll))) (defn unit [val] (vector val))   (defn doubler [n] [(* 2 n)]) ; takes a number and returns a List number (def vecstr (comp vector str)) ; takes a number and returns a List string   (bind (bind (vector 3 4 5) doubler) vecstr) ; evaluates to ["6" "8" "10"] (-> [3 4 5] (bind doubler) (bind vecstr)) ; also evaluates to ["6" "8" "10"]  
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
#Delphi
Delphi
  program List_monad;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TmList = record Value: TArray<Integer>; function ToString: string; function Bind(f: TFunc<TArray<Integer>, TmList>): TmList; end;   function Create(aValue: TArray<Integer>): TmList; begin Result.Value := copy(aValue, 0, length(aValue)); end;   { TmList }   function TmList.Bind(f: TFunc<TArray<Integer>, TmList>): TmList; begin Result := f(self.Value); end;   function TmList.ToString: string; var i: Integer; begin Result := '[ '; for i := 0 to length(value) - 1 do begin if i > 0 then Result := Result + ', '; Result := Result + value[i].toString; end; Result := Result + ']'; end;   function Increment(aValue: TArray<Integer>): TmList; var i: integer; begin SetLength(Result.Value, length(aValue)); for i := 0 to High(aValue) do Result.Value[i] := aValue[i] + 1; end;   function Double(aValue: TArray<Integer>): TmList; var i: integer; begin SetLength(Result.Value, length(aValue)); for i := 0 to High(aValue) do Result.Value[i] := aValue[i] * 2; end;   var ml1, ml2: TmList;   begin ml1 := Create([3, 4, 5]); ml2 := ml1.Bind(Increment).Bind(double); Writeln(ml1.ToString, ' -> ', ml2.ToString); readln; end.
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).
#Klingphix
Klingphix
include ..\Utilitys.tlhy   0 ( 4 3 2 ) dim pstack   5432 ( 4 3 2 ) set pstack   ( 4 3 2 ) get ?   ( 4 3 ) get %row !row $row ?   $row 1 2 set !row $row ?   $row ( 4 3 ) set 0 4 repeat ( 4 2 ) set   pstack   "End " input
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).
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { // create a regular 4 dimensional array and initialize successive elements to the values 1 to 120 var m = 1 val a4 = Array<Array<Array<Array<Int>>>>(5) { Array<Array<Array<Int>>>(4) { Array<Array<Int>>(3) { Array<Int>(2) { m++ } } } }   println("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 println()   // access and print values of all elements val f = "%4d" for (i in 0..4) for (j in 0..3) for (k in 0..2) for (l in 0..1) print(f.format(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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program multtable64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" .equ MAXI, 12 /*********************************/ /* Initialized data */ /*********************************/ .data sMessValeur: .fill 11, 1, ' ' // size => 11 szCarriageReturn: .asciz "\n" sBlanc1: .asciz " " sBlanc2: .asciz " " sBlanc3: .asciz " " /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x6,qAdrsBlanc1 ldr x7,qAdrsBlanc2 ldr x8,qAdrsBlanc3 // display first line mov x4,#0 1: // begin loop mov x0,x4 ldr x1,qAdrsMessValeur // display value bl conversion10 // call function strb wzr,[x1,x0] // final zéro on display value ldr x0,qAdrsMessValeur bl affichageMess // display message cmp x4,#10 // one or two digit in résult csel x0,x7,x8,ge // display 2 or 3 spaces bl affichageMess // display message add x4,x4,1 // increment counter cmp x4,MAXI ble 1b // loop ldr x0,qAdrszCarriageReturn bl affichageMess // display carriage return   mov x5,#1 // line counter 2: // begin loop lines mov x0,x5 // display column 1 with N° line ldr x1,qAdrsMessValeur // display value bl conversion10 // call function strb wzr,[x1,x0] // final zéro ldr x0,qAdrsMessValeur bl affichageMess // display message cmp x5,#10 // one or two digit in N° line csel x0,x7,x8,ge // display 2 or 3 spaces bl affichageMess mov x4,#1 // counter column 3: // begin loop columns mul x0,x4,x5 // multiplication mov x3,x0 // save résult ldr x1,qAdrsMessValeur // display value bl conversion10 // call function strb wzr,[x1,x0] ldr x0,qAdrsMessValeur bl affichageMess // display message cmp x3,100 // 3 digits in résult ? csel x0,x6,x0,ge // display 1 spaces bge 4f cmp x3,10 // 2 digits in result csel x0,x7,x8,ge // display 2 or 3 spaces   4: bl affichageMess // display message add x4,x4,1 // increment counter column cmp x4,x5 // < counter lines ble 3b // loop ldr x0,qAdrszCarriageReturn bl affichageMess // display carriage return add x5,x5,1 // increment line counter cmp x5,MAXI // MAXI ? ble 2b // loop   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsMessValeur: .quad sMessValeur qAdrszCarriageReturn: .quad szCarriageReturn qAdrsBlanc1: .quad sBlanc1 qAdrsBlanc2: .quad sBlanc2 qAdrsBlanc3: .quad sBlanc3   /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* x0 contains value and x1 address area */ /* x0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x3,x1 mov x2,#LGZONECAL mov x4,10 1: // start loop mov x5,x0 udiv x0,x5,x4 msub x1,x0,x4,x5 // x5 <- dividende. quotient ->x0 reste -> x1 add x1,x1,48 // digit strb w1,[x3,x2] // store digit on area cbz x0,2f // stop if quotient = 0 sub x2,x2,1 // else previous position b 1b // and loop // and move digit from left of area 2: mov x4,0 3: ldrb w1,[x3,x2] strb w1,[x3,x4] add x2,x2,1 add x4,x4,1 cmp x2,LGZONECAL ble 3b // and move spaces in end on area mov x0,x4 // result length mov x1,' ' // space 4: strb w1,[x3,x4] // store space in area add x4,x4,1 // next position cmp x4,LGZONECAL ble 4b // loop if x4 <= area size   100: ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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).
#Java
Java
import java.util.Arrays; import java.util.Objects;   public class MultipleRegression { public static void require(boolean condition, String message) { if (condition) { return; } throw new IllegalArgumentException(message); }   public static class Matrix { private final double[][] data; private final int rowCount; private final int colCount;   public Matrix(int rows, int cols) { require(rows > 0, "Need at least one row"); this.rowCount = rows;   require(cols > 0, "Need at least one column"); this.colCount = cols;   this.data = new double[rows][cols]; for (double[] row : this.data) { Arrays.fill(row, 0.0); } }   public Matrix(double[][] source) { require(source.length > 0, "Need at least one row"); this.rowCount = source.length;   require(source[0].length > 0, "Need at least one column"); this.colCount = source[0].length;   this.data = new double[this.rowCount][this.colCount]; for (int i = 0; i < this.rowCount; i++) { set(i, source[i]); } }   public double[] get(int row) { Objects.checkIndex(row, this.rowCount); return this.data[row]; }   public void set(int row, double[] data) { Objects.checkIndex(row, this.rowCount); require(data.length == this.colCount, "The column in the row must match the number of columns in the matrix"); System.arraycopy(data, 0, this.data[row], 0, this.colCount); }   public double get(int row, int col) { Objects.checkIndex(row, this.rowCount); Objects.checkIndex(col, this.colCount); return this.data[row][col]; }   public void set(int row, int col, double value) { Objects.checkIndex(row, this.rowCount); Objects.checkIndex(col, this.colCount); this.data[row][col] = value; }   @SuppressWarnings("UnnecessaryLocalVariable") public Matrix times(Matrix that) { var rc1 = this.rowCount; var cc1 = this.colCount; var rc2 = that.rowCount; var cc2 = that.colCount; require(cc1 == rc2, "Cannot multiply if the first columns does not equal the second rows"); var result = new Matrix(rc1, cc2); for (int i = 0; i < rc1; i++) { for (int j = 0; j < cc2; j++) { for (int k = 0; k < rc2; k++) { var prod = get(i, k) * that.get(k, j); result.set(i, j, result.get(i, j) + prod); } } } return result; }   public Matrix transpose() { var rc = this.rowCount; var cc = this.colCount; var trans = new Matrix(cc, rc); for (int i = 0; i < cc; i++) { for (int j = 0; j < rc; j++) { trans.set(i, j, get(j, i)); } } return trans; }   public void toReducedRowEchelonForm() { int lead = 0; var rc = this.rowCount; var cc = this.colCount; for (int r = 0; r < rc; r++) { if (cc <= lead) { return; } var i = r;   while (get(i, lead) == 0.0) { i++; if (rc == i) { i = r; lead++; if (cc == lead) { return; } } }   var temp = get(i); set(i, get(r)); set(r, temp);   if (get(r, lead) != 0.0) { var div = get(r, lead); for (int j = 0; j < cc; j++) { set(r, j, get(r, j) / div); } }   for (int k = 0; k < rc; k++) { if (k != r) { var mult = get(k, lead); for (int j = 0; j < cc; j++) { var prod = get(r, j) * mult; set(k, j, get(k, j) - prod); } } }   lead++; } }   public Matrix inverse() { require(this.rowCount == this.colCount, "Not a square matrix"); var len = this.rowCount; var aug = new Matrix(len, 2 * len); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { aug.set(i, j, get(i, j)); } // augment identity matrix to right aug.set(i, i + len, 1.0); } aug.toReducedRowEchelonForm(); var inv = new Matrix(len, len); // remove identity matrix to left for (int i = 0; i < len; i++) { for (int j = len; j < 2 * len; j++) { inv.set(i, j - len, aug.get(i, j)); } } return inv; } }   public static double[] multipleRegression(double[] y, Matrix x) { var tm = new Matrix(new double[][]{y}); var cy = tm.transpose(); var cx = x.transpose(); return x.times(cx).inverse().times(x).times(cy).transpose().get(0); }   public static void printVector(double[] v) { System.out.println(Arrays.toString(v)); System.out.println(); }   public static double[] repeat(int size, double value) { var a = new double[size]; Arrays.fill(a, value); return a; }   public static void main(String[] args) { double[] y = new double[]{1.0, 2.0, 3.0, 4.0, 5.0}; var x = new Matrix(new double[][]{{2.0, 1.0, 3.0, 4.0, 5.0}}); var v = multipleRegression(y, x); printVector(v);   y = new double[]{3.0, 4.0, 5.0}; x = new Matrix(new double[][]{ {1.0, 2.0, 1.0}, {1.0, 1.0, 2.0} }); v = multipleRegression(y, x); printVector(v);   y = new double[]{52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46}; var a = new double[]{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}; x = new Matrix(new double[][]{ repeat(a.length, 1.0), a, Arrays.stream(a).map(it -> it * it).toArray() });   v = multipleRegression(y, x); printVector(v); } }
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.
#Common_Lisp
Common Lisp
  (defun mfac (n m) (reduce #'* (loop for i from n downto 1 by m collect i)))   (loop for i from 1 to 10 do (format t "~2@a: ~{~a~^ ~}~%" i (loop for j from 1 to 10 collect (mfac j i))))  
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Factor
Factor
: replace-text ( button text -- ) [ drop children>> pop drop ] [ >label add-gadget drop ] 2bi ; : present-locations ( loc1 loc2 -- string ) [ first2 [ number>string ] bi@ "," glue ] bi@ ";" glue ; : example ( -- ) "click me" [ dup hand-rel ! location relative to the button hand-loc get ! location relative to the window present-locations replace-text ] <border-button> gadget. ;  
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.
#FreeBASIC
FreeBASIC
  type MOUSE 'mouse position, button state, wheel state x as integer y as integer buttons as integer wheel as integer end type   screen 12   dim as MOUSE mouse   while inkey="" locate 1,1 getmouse(mouse.x, mouse.y, mouse.wheel, mouse.buttons) if mouse.x < 0 then print "Mouse out of window. " print " " print " " else print "Mouse position : ", mouse.x, mouse.y, " " print "Buttons clicked: "; print Iif( mouse.buttons and 1, "Left ", " " ); print Iif( mouse.buttons and 2, "Right ", " " ); print Iif( mouse.buttons and 4, "Middle ", " " ) print "Wheel scrolls: ", mouse.wheel," " end if wend
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
#Fortran
Fortran
program Nqueens implicit none   integer, parameter :: n = 8 ! size of board integer :: file = 1, rank = 1, queens = 0 integer :: i logical :: board(n,n) = .false.   do while (queens < n) board(file, rank) = .true. if(is_safe(board, file, rank)) then queens = queens + 1 file = 1 rank = rank + 1 else board(file, rank) = .false. file = file + 1 do while(file > n) rank = rank - 1 if (rank < 1) then write(*, "(a,i0)") "No solution for n = ", n stop end if do i = 1, n if (board(i, rank)) then file = i board(file, rank) = .false. queens = queens - 1 file = i + 1 exit end if end do end do end if end do   call Printboard(board)   contains   function is_safe(board, file, rank) logical :: is_safe logical, intent(in) :: board(:,:) integer, intent(in) :: file, rank integer :: i, f, r   is_safe = .true. do i = rank-1, 1, -1 if(board(file, i)) then is_safe = .false. return end if end do   f = file - 1 r = rank - 1 do while(f > 0 .and. r > 0) if(board(f, r)) then is_safe = .false. return end if f = f - 1 r = r - 1 end do   f = file + 1 r = rank - 1 do while(f <= n .and. r > 0) if(board(f, r)) then is_safe = .false. return end if f = f + 1 r = r - 1 end do end function   subroutine Printboard(board) logical, intent(in) :: board(:,:) character(n*4+1) :: line integer :: f, r   write(*, "(a, i0)") "n = ", n line = repeat("+---", n) // "+" do r = 1, n write(*, "(a)") line do f = 1, n write(*, "(a)", advance="no") "|" if(board(f, r)) then write(*, "(a)", advance="no") " Q " else if(mod(f+r, 2) == 0) then write(*, "(a)", advance="no") " " else write(*, "(a)", advance="no") "###" end if end do write(*, "(a)") "|" end do write(*, "(a)") line end subroutine end program
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Runtime.CompilerServices Imports System.Threading   Module Module1 Private s_gen As New ThreadLocal(Of Random)(Function() New Random())   Private Function Gen() Return s_gen.Value End Function   <Extension()> Public Function IsProbablyPrime(value As BigInteger, Optional witnesses As Integer = 10) As Boolean If value <= 1 Then Return False End If   If witnesses <= 0 Then witnesses = 10 End If   Dim d = value - 1 Dim s = 0   While d Mod 2 = 0 d /= 2 s += 1 End While   Dim bytes(value.ToByteArray.LongLength - 1) As Byte Dim a As BigInteger   For i = 1 To witnesses Do Gen.NextBytes(bytes)   a = New BigInteger(bytes) Loop While a < 2 OrElse a >= value - 2   Dim x = BigInteger.ModPow(a, d, value) If x = 1 OrElse x = value - 1 Then Continue For End If   For r = 1 To s - 1 x = BigInteger.ModPow(x, 2, value)   If x = 1 Then Return False End If If x = value - 1 Then Exit For End If Next   If x <> value - 1 Then Return False End If Next   Return True End Function   <Extension()> Function Sqrt(self As BigInteger) As BigInteger Dim b = self While True Dim a = b b = self / a + a >> 1 If b >= a Then Return a End If End While Throw New Exception("Should not have happened") End Function   <Extension()> Function BitLength(self As BigInteger) As Long Dim bi = self Dim len = 0L While bi <> 0 len += 1 bi >>= 1 End While Return len End Function   <Extension()> Function BitTest(self As BigInteger, pos As Integer) As Boolean Dim arr = self.ToByteArray Dim i = pos \ 8 Dim m = pos Mod 8 If i >= arr.Length Then Return False End If Return (arr(i) And (1 << m)) > 0 End Function   Class PExp Sub New(p As BigInteger, e As Integer) Prime = p Exp = e End Sub   Public ReadOnly Property Prime As BigInteger Public ReadOnly Property Exp As Integer End Class   Function MoBachShallit58(a As BigInteger, n As BigInteger, pf As List(Of PExp)) As BigInteger Dim n1 = n - 1 Dim mo As BigInteger = 1 For Each pe In pf Dim y = n1 / BigInteger.Pow(pe.Prime, pe.Exp) Dim o = 0 Dim x = BigInteger.ModPow(a, y, BigInteger.Abs(n)) While x > 1 x = BigInteger.ModPow(x, pe.Prime, BigInteger.Abs(n)) o += 1 End While Dim o1 = BigInteger.Pow(pe.Prime, o) o1 /= BigInteger.GreatestCommonDivisor(mo, o1) mo *= o1 Next Return mo End Function   Function Factor(n As BigInteger) As List(Of PExp) Dim pf As New List(Of PExp) Dim nn = n Dim e = 0 While Not nn.BitTest(e) e += 1 End While If e > 0 Then nn >>= e pf.Add(New PExp(2, e)) End If Dim s = nn.Sqrt Dim d As BigInteger = 3 While nn > 1 If d > s Then d = nn End If e = 0 While True Dim remainder As New BigInteger Dim div = BigInteger.DivRem(nn, d, remainder) If remainder.BitLength > 0 Then Exit While End If nn = div e += 1 End While If e > 0 Then pf.Add(New PExp(d, e)) s = nn.Sqrt End If d += 2 End While Return pf End Function   Sub MoTest(a As BigInteger, n As BigInteger) If Not n.IsProbablyPrime(20) Then Console.WriteLine("Not computed. Modulus must be prime for this algorithm.") Return End If If a.BitLength < 100 Then Console.Write("ord({0})", a) Else Console.Write("ord([big])") End If If n.BitLength < 100 Then Console.Write(" mod {0}", n) Else Console.Write(" mod [big]") End If Dim mob = MoBachShallit58(a, n, Factor(n - 1)) Console.WriteLine(" = {0}", mob) End Sub   Sub Main() MoTest(37, 3343) MoTest(BigInteger.Pow(10, 100) + 1, 7919) MoTest(BigInteger.Pow(10, 1000) + 1, 15485863) MoTest(BigInteger.Pow(10, 10000) - 1, 22801763489) MoTest(1511678068, 7379191741) MoTest(3047753288, 2257683301) End Sub   End Module
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.
#Seed7
Seed7
const func float: nthRoot (in integer: n, in float: a) is func result var float: x1 is 0.0; local var float: x0 is 0.0; begin x0 := a; x1 := a / flt(n); while abs(x1 - x0) >= abs(x0 * 1.0E-9) do x0 := x1; x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n); end while; end func;
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.
#Sidef
Sidef
func nthroot(n, a, precision=1e-5) { var x = 1.float var prev = 0.float while ((prev-x).abs > precision) { prev = x; x = (((n-1)*prev + a/(prev**(n-1))) / n) } return x }   say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204
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.
#MiniScript
MiniScript
ordinal = function(n) if n > 3 and n < 20 then return n + "th" if n % 10 == 1 then return n + "st" if n % 10 == 2 then return n + "nd" if n % 10 == 3 then return n + "rd" return n + "th" end function   out = [] test = function(from, to) for i in range(from, to) out.push ordinal(i) end for end function   test 0, 25 test 250, 265 test 1000, 1025 print out.join
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Off[Power::indet];(*Supress 0^0 warnings*) Select[Range[5000], Total[IntegerDigits[#]^IntegerDigits[#]] == # &]
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
#min
min
(dup string "" split (int dup pow) (+) map-reduce ==) :munchausen? 1 :i (i 5000 <=) ((i munchausen?) (i puts!) when i succ @i) while
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).
#Groovy
Groovy
def f, m // recursive closures must be declared before they are defined f = { n -> n == 0 ? 1 : n - m(f(n-1)) } m = { n -> n == 0 ? 0 : n - f(m(n-1)) }
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#PureBasic
PureBasic
n=Random(50)+25 Dim A.i(n) ; Creates a Array of n [25-75] elements depending on the outcome of Random(). ; Each element will be initiated to zero.   For i=0 To ArraySize(A()) A(i)=2*i Next i ; Set each individual element at a wanted (here 2*i) value and ; automatically adjust accordingly to the unknown length of the Array.   NewList *PointersToA() For i=0 To ArraySize(A()) AddElement(*PointersToA()) *PointersToA()=@A(i) Next ; Create a linked list of the same length as A() above. ; Each element is then set to point to the Array element ; of the same order.   ForEach *PointersToA() Debug PeekI(*PointersToA()) Next ; Verify by sending each value of A() via *PointersToA() ; to the debugger's output.
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Python
Python
[Foo()] * n # here Foo() can be any expression that returns a new object
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Motzkin_numbers use warnings; use ntheory qw( is_prime );   sub motzkin { my $N = shift; my @m = ( 0, 1, 1 ); for my $i ( 3 .. $N ) { $m[$i] = ($m[$i - 1] * (2 * $i - 1) + $m[$i - 2] * (3 * $i - 6)) / ($i + 1); } return splice @m, 1; }   print " n M[n]\n"; my $count = 0; for ( motzkin(42) ) { printf "%3d%25s  %s\n", $count++, s/\B(?=(\d\d\d)+$)/,/gr, is_prime($_) ? 'prime' : ''; }
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Phix
Phix
with javascript_semantics include mpfr.e function motzkin(integer n) sequence m = mpz_inits(2,1) -- {1,1} mpz m2 = mpz_init() -- (scratch) for i=3 to n do mpz m1 = mpz_init() -- (a new mpz rqd for every m[i]) mpz_mul_si(m1,m[i-1],2*i-1) -- (nb i is 1-based) mpz_mul_si(m2,m[i-2],3*i-6) -- "" mpz_add(m1,m1,m2) assert(mpz_fdiv_q_ui(m1,m1,i+1)==0) -- (verify rmdr==0) m &= m1 end for return m end function printf(1," n M[n]\n") printf(1,"---------------------------\n") sequence m = motzkin(42) for i=1 to 42 do string mi = mpz_get_str(m[i],comma_fill:=true), pi = iff(mpz_prime(m[i])?"prime":"") printf(1,"%2d  %23s  %s\n", {i-1, mi, pi}) end for
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.
#AppleScript
AppleScript
property e : 2.71828182846   on run {}   -- Derive safe versions of three simple functions set sfReciprocal to safeVersion(reciprocal, notZero) set sfRoot to safeVersion(root, isPositive) set sfLog to safeVersion(ln, aboveZero)     -- Test a composition of these function with a range of invalid and valid arguments   -- (The safe composition returns missing value (without error) for invalid arguments)   map([-2, -1, -0.5, 0, 1 / e, 1, 2, e, 3, 4, 5], safeLogRootReciprocal)   -- 'missing value' is returned by a safe function (and threaded up through the monad) when the input argument is out of range --> {missing value, missing value, missing value, missing value, 0.5, 0.0, -0.346573590279, -0.499999999999, -0.549306144333, -0.69314718056, -0.804718956217} end run     -- START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS:   -- Returns ERROR 'Script Error: Can’t divide 1.0 by zero.' if n = 0 on reciprocal(n) 1 / n end reciprocal   -- Returns ERROR 'error "The result of a numeric operation was too large." number -2702' -- for all values below 0 on root(n) n ^ (1 / 2) end root   -- Returns -1.0E+20 for all values of zero and below on ln(n) (do shell script ("echo 'l(" & (n as string) & ")' | bc -l")) as real end ln   -- DERIVE A SAFE VERSION OF EACH FUNCTION -- (SEE on Run() handler)   on safeVersion(f, fnSafetyCheck) script on call(x) if sReturn(fnSafetyCheck)'s call(x) then sReturn(f)'s call(x) else missing value end if end call end script end safeVersion   on notZero(n) n is not 0 end notZero   on isPositive(n) n ≥ 0 end isPositive   on aboveZero(n) n > 0 end aboveZero     -- DEFINE A FUNCTION WHICH CALLS A COMPOSITION OF THE SAFE VERSIONS on safeLogRootReciprocal(x)   value of mbCompose([my sfLog, my sfRoot, my sfReciprocal], x)   end safeLogRootReciprocal     -- UNIT/RETURN and BIND functions for the Maybe monad   -- Unit / Return for maybe on maybe(n) {isValid:n is not missing value, value:n} end maybe   -- BIND maybe on mbBind(recMaybe, mfSafe) if isValid of recMaybe then maybe(mfSafe's call(value of recMaybe)) else recMaybe end if end mbBind   -- lift 2nd class function into 1st class wrapper -- handler function --> first class script object on sReturn(f) script property call : f end script end sReturn   -- return a new script in which function g is composed -- with the f (call()) of the Mf script -- Mf -> (f -> Mg) -> Mg on sBind(mf, g) script on call(x) sReturn(g)'s call(mf's call(x)) end call end script end sBind   on mbCompose(lstFunctions, value) reduceRight(lstFunctions, mbBind, maybe(value)) end mbCompose   -- xs: list, f: function, a: initial accumulator value -- the arguments available to the function f(a, x, i, l) are -- v: current accumulator value -- x: current item in list -- i: [ 1-based index in list ] optional -- l: [ a reference to the list itself ] optional on reduceRight(xs, f, a) set mf to sReturn(f)   repeat with i from length of xs to 1 by -1 set a to mf's call(a, item i of xs, i, xs) end repeat end reduceRight   -- [a] -> (a -> b) -> [b] on map(xs, f) set mf to sReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set end of lst to mf's call(item i of xs, i, xs) end repeat return lst end map  
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.)
#Gambas
Gambas
Public Sub Main() Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"] 'Samples to process Dim sHold As New String[] 'To store results Dim siCount, siCounter, siPos As Short 'Various variables Dim sOutput, sCode, sWork, sEach As String 'Various variables   For siCounter = 0 To sToCode.Max 'To loop through each 'Sample' sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting For siCount = 1 To Len(sToCode[siCounter]) 'Loop through each letter in 'Sample' sWork = Mid(sToCode[siCounter], siCount, 1) 'sWork to store the Letter siPos = InStr(scode, sWork) - 1 'Find the position of the letter in sCode, -1 for '0' based array sOutput &= Str(siPos) & " " 'Add the postion to sOutput sCode = Mid(sCode, siPos + 1, 1) & Replace(sCode, sWork, "") 'sCode = the letter + the rest of sCode except the letter Next Print sToCode[siCounter] & " = " & sOutput 'Print the 'Sample' and the coded version sHold.Add(Trim(sOutput)) 'Add the code to the sHold array sOutput = "" 'Clear sOutput Next   Print 'Print a blank line   For siCounter = 0 To sHold.Max 'To loop through each coded 'Sample' sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting For Each sEach In Split(sHold[siCounter], " ") 'For each 'code' in coded 'Sample' sWork = Mid(sCode, Val(sEach) + 1, 1) 'sWork = the decoded letter sOutput &= sWork 'Add the decoded letter to sOutput sCode = sWork & Replace(sCode, sWork, "") 'sCode = the decoded letter + the rest of sCode except the letter Next Print sHold[siCounter] & " = " & sOutput 'Print the coded and decoded result sOutput = "" 'Clear sOutput Next   End
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m} It can be shown that such an inverse exists   if and only if   a   and   m   are coprime,   but we will ignore this for this task. Task Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language,   compute the modular inverse of   42 modulo 2017.
#11l
11l
F mul_inv(=a, =b) V b0 = b V x0 = 0 V x1 = 1 I b == 1 {R 1}   L a > 1 V q = a I/ b (a, b) = (b, a % b) (x0, x1) = (x1 - q * x0, x0)   I x1 < 0 {x1 += b0} R x1   print(mul_inv(42, 2017))
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) Write three simple functions: root, addOne, and half Derive Writer monad versions of each of these functions Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#Factor
Factor
USING: kernel math math.functions monads prettyprint ; FROM: monads => do ;   { [ 5 "Started with five, " <writer> ] [ sqrt "took square root, " <writer> ] [ 1 + "added one, " <writer> ] [ 2 / "divided by two." <writer> ] } do .
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.)
#Go
Go
package main   import ( "fmt" "math" )   type mwriter struct { value float64 log string }   func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n }   func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)} }   func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") }   func addOne(v float64) mwriter { return unit(v+1, "Added one") }   func half(v float64) mwriter { return unit(v/2, "Divided by two") }   func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String Compose the two functions with bind
#EchoLisp
EchoLisp
  ;; -> and ->> are the pipeline operators ;; (-> x f g h) = (h (g ( f x))) ;; (->> x f (g a) h) = (h (g a ( f x)))   (define (List.unit elem) (append '(List) elem)) (define (List.bind xs f) (List.unit (->> xs rest (map f) (map rest) (apply append)))) (define (List.lift f) (lambda(elem) (List.unit (f elem))))   (define List.square (List.lift (lambda(x) (* x x)))) (define List.cube (List.lift (lambda(x) (* x x x)))) (define List.tostr (List.lift number->string))   ;; composition   (-> '(List 1 -2 3 -5) (List.bind List.cube) (List.bind List.tostr)) → (List "1" "-8" "27" "-125") ;; or (-> '(1 -2 3 -5) List.unit (List.bind List.cube) (List.bind List.tostr)) → (List "1" "-8" "27" "-125")  
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).
#Lingo
Lingo
on array () cnt = paramCount() if cnt=0 then return arr = [] arr[param(cnt)] = 0 repeat with d = cnt-1 down to 1 newArr = [] repeat with i = 1 to param(d) newArr[i] = arr.duplicate() -- duplicate does a deep copy end repeat arr = newArr.duplicate() end repeat return arr end
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).
#Lua
Lua
-- Variadic, first argument is the value with which to populate the array. function multiArray (initVal, ...) local function copy (t) local new = {} for k, v in pairs(t) do if type(v) == "table" then new[k] = copy(v) else new[k] = v end end return new end local dimensions, arr, newArr = {...}, {} for i = 1, dimensions[#dimensions] do table.insert(arr, initVal) end for d = #dimensions - 1, 1, -1 do newArr = {} for i = 1, dimensions[d] do table.insert(newArr, copy(arr)) end arr = copy(newArr) end return arr end   -- Function to print out the specific example created here function show4dArray (a) print("\nPrinting 4D array in 2D...") for k, v in ipairs(a) do print(k) for l, w in ipairs(v) do print("\t" .. l) for m, x in ipairs(w) do print("\t", m, unpack(x)) end end end end   -- Main procedure local t = multiArray("a", 2, 3, 4, 5) show4dArray(t) t[1][1][1][1] = true show4dArray(t)
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.
#Action.21
Action!
PROC PrintRight(BYTE num,size) BYTE i   IF num<10 THEN size==-1 ELSEIF num<100 THEN size==-2 ELSE size==-3 FI FOR i=1 TO size DO Put(' ) OD PrintB(num) RETURN   PROC Main() BYTE ARRAY colw=[1 1 1 2 2 2 2 2 2 3 3 3] BYTE i,j,x,w    ;clear screen Put(125)    ;draw frame Position(1,3) FOR i=1 TO 38 DO Put($12) OD   FOR j=2 TO 15 DO Position(36,j) Put($7C) OD   Position(36,3) Put($13)    ;draw numbers FOR j=1 TO 12 DO x=1 FOR i=1 TO 12 DO w=colw(i-1) IF i>=j THEN IF j=1 THEN Position(x,j+1) PrintRight(i*j,w) FI IF i=12 THEN Position(37,j+3) PrintRight(j,2) FI Position(x,j+3) PrintRight(i*j,w) FI x==+w+1 OD OD 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).
#JavaScript
JavaScript
// modifies the matrix "in place" Matrix.prototype.inverse = function() { if (this.height != this.width) { throw "can't invert a non-square matrix"; }   var I = new IdentityMatrix(this.height); for (var i = 0; i < this.height; i++) this.mtx[i] = this.mtx[i].concat(I.mtx[i]) this.width *= 2;   this.toReducedRowEchelonForm();   for (var i = 0; i < this.height; i++) this.mtx[i].splice(0, this.height); this.width /= 2;   return this; }   function ColumnVector(ary) { return new Matrix(ary.map(function(v) {return [v]})) } ColumnVector.prototype = Matrix.prototype   Matrix.prototype.regression_coefficients = function(x) { var x_t = x.transpose(); return x_t.mult(x).inverse().mult(x_t).mult(this); }   // the Ruby example var y = new ColumnVector([1,2,3,4,5]); var x = new ColumnVector([2,1,3,4,5]); print(y.regression_coefficients(x)); print();   // the Tcl example y = new ColumnVector([ 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 = new Matrix( [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].map( function(v) {return [Math.pow(v,0), Math.pow(v,1), Math.pow(v,2)]} ) ); print(y.regression_coefficients(x));
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#Crystal
Crystal
def multifact(n, d) n.step(to: 1, by: -d).product end   (1..5).each {|d| puts "Degree #{d}: #{(1..10).map{|n| multifact(n, d)}.join "\t"}"}
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.
#Gambas
Gambas
  PUBLIC SUB Form1_MouseMove() PRINT mouse.X PRINT Mouse.Y 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.
#Go
Go
package main   import ( "fmt" "github.com/go-vgo/robotgo" )   func isInside(x, y, w, h, mx, my int) bool { rx := x + w - 1 ry := y + h - 1 return mx >= x && mx <= rx && my >= y && my <= ry }   func main() { name := "gedit" // say fpid, err := robotgo.FindIds(name) if err == nil && len(fpid) > 0 { pid := fpid[0] robotgo.ActivePID(pid) // make gedit active window x, y, w, h := robotgo.GetBounds(pid) fmt.Printf("The active window's top left corner is at (%d, %d)\n", x, y) fmt.Printf("Its width is %d and its height is %d\n", w, h) mx, my := robotgo.GetMousePos() fmt.Printf("The screen location of the mouse cursor is (%d, %d)\n", mx, my) if !isInside(x, y, w, h, mx, my) { fmt.Println("The mouse cursor is outside the active window") } else { wx := mx - x wy := my - y fmt.Printf("The window location of the mouse cursor is (%d, %d)\n", wx, wy) } } else { fmt.Println("Problem when finding PID(s) of", name) } }
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
#FreeBASIC
FreeBASIC
' version 13-04-2017 ' compile with: fbc -s console Dim Shared As ULong count, c()   Sub n_queens(row As ULong, n As ULong, show As ULong = 0)   Dim As ULong x, y   For x = 1 To n   For y = 1 To row -1 If c(y) = x OrElse ((row - y) - Abs(x - c(y))) = 0 Then Continue For, For End If Next   c(row) = x If row < n Then n_queens(row +1 , n, show) Else count += 1   If show <> 0 Then For y = 1 To n Print Using "###"; c(y); Next Print End If   End If   Next   End Sub   ' ------=< MAIN >=------   Dim As ULong n = 5 ReDim c(n) ' n_queens(1, n, show = 0 only show total | show <> 0 show every solution n_queens(1, n, 1) Print Using "## x ## board, ##### solutions"; n; n; count Print   For n = 1 To 14 ReDim c(n) count = 0 n_queens(1, n) Print Using "A ## x ## board has ######## solutions"; n; n; count Next   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#Wren
Wren
import "/big" for BigInt   class PExp { construct new(prime, exp) { _prime = prime _exp = exp } prime { _prime } exp { _exp } }   var moBachShallit58 = Fn.new { |a, n, pf| var n1 = n - BigInt.one var mo = BigInt.one for (pe in pf) { var y = n1 / pe.prime.pow(pe.exp) var o = 0 var x = a.modPow(y, n.abs) while (x > BigInt.one) { x = x.modPow(pe.prime, n.abs) o = o + 1 } var o1 = BigInt.new(o) o1 = pe.prime.pow(o1) o1 = o1 / BigInt.gcd(mo, o1) mo = mo * o1 } return mo }   var factor = Fn.new { |n| var pf = [] var nn = n.copy() var e = 0 while (!nn.testBit(e)) e = e + 1 if (e > 0) { nn = nn >> e pf.add(PExp.new(BigInt.two, e)) } var s = nn.isqrt var d = BigInt.three while (nn > BigInt.one) { if (d > s) d = nn e = 0 while (true) { var dm = nn.divMod(d) if (dm[1].bitLength > 0) break nn = dm[0] e = e + 1 } if (e > 0) { pf.add(PExp.new(d, e)) s = nn.isqrt } d = d + BigInt.two } return pf }   var moTest = Fn.new { |a, n| if (!n.isProbablePrime(10)) { System.print("Not computed. Modulus must be prime for this algorithm.") return } System.write((a.bitLength < 100) ? "ord(%(a))" : "ord([big])") System.write((n.bitLength < 100) ? " mod %(n) " : "mod([big])") var mob = moBachShallit58.call(a, n, factor.call(n - BigInt.one)) System.print("= %(mob)") }   moTest.call(BigInt.new(37), BigInt.new(3343))   var b = BigInt.ten.pow(100) + BigInt.one moTest.call(b, BigInt.new(7919))   b = BigInt.ten.pow(1000) + BigInt.one moTest.call(b, BigInt.new(15485863))   b = BigInt.ten.pow(10000) - BigInt.one moTest.call(b, BigInt.new(22801763489))   moTest.call(BigInt.new(1511678068), BigInt.new(7379191741)) moTest.call(BigInt.new(3047753288), BigInt.new(2257683301))
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.
#Smalltalk
Smalltalk
Number extend [ nthRoot: n [ |x0 m x1| x0 := (self / n) asFloatD. m := n - 1. [true] whileTrue: [ x1 := ( (m * x0) + (self/(x0 raisedTo: m))) / n. ((x1 - x0) abs) < ((x0 * 1e-9) abs) ifTrue: [ ^ x1 ]. x0 := x1 ] ] ].
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.
#Modula-2
Modula-2
  MODULE Nth;   FROM STextIO IMPORT WriteString, WriteLn; FROM WholeStr IMPORT IntToStr;   PROCEDURE Suffix(N: CARDINAL; VAR OUT Destination: ARRAY OF CHAR); VAR NMod10, NMod100: CARDINAL; BEGIN NMod10 := N MOD 10; NMod100 := N MOD 100; IF (NMod10 = 1) AND (NMod100 <> 11) THEN Destination := "st"; ELSIF (NMod10 = 2) AND (NMod100 <> 12) THEN Destination := "nd"; ELSIF (NMod10 = 3) AND (NMod100 <> 13) THEN Destination := "rd"; ELSE Destination := "th"; END; END Suffix;   PROCEDURE PrintImages(LoLim, HiLim: CARDINAL); VAR I: CARDINAL; IString: ARRAY [0 .. 15] OF CHAR; ISuff: ARRAY [0 .. 1] OF CHAR; BEGIN FOR I := LoLim TO HiLim DO IntToStr(I, IString); Suffix(I, ISuff); WriteString(IString); WriteString(ISuff); WriteString(" "); END; WriteLn; END PrintImages;   BEGIN PrintImages( 0, 25); PrintImages( 250, 265); PrintImages(1000, 1025); END 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
#Modula-2
Modula-2
MODULE MunchausenNumbers; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   (* Simple power function, does not handle negatives *) PROCEDURE Pow(b,e : INTEGER) : INTEGER; VAR result : INTEGER; BEGIN IF e=0 THEN RETURN 1; END; IF b=0 THEN RETURN 0; END;   result := b; DEC(e); WHILE e>0 DO result := result * b; DEC(e); END; RETURN result; END Pow;   VAR buf : ARRAY[0..31] OF CHAR; i,sum,number,digit : INTEGER; BEGIN FOR i:=1 TO 5000 DO (* Loop through each digit in i e.g. for 1000 we get 0, 0, 0, 1. *) sum := 0; number := i; WHILE number>0 DO digit := number MOD 10; sum := sum + Pow(digit, digit); number := number DIV 10; END; IF sum=i THEN FormatString("%i\n", buf, i); WriteString(buf); END; END;   ReadChar; END MunchausenNumbers.
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).
#Haskell
Haskell
f 0 = 1 f n | n > 0 = n - m (f $ n-1)   m 0 = 0 m n | n > 0 = n - f (m $ n-1)   main = do print $ map f [0..19] print $ map m [0..19]
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#R
R
rep(foo(), n) # foo() is any code returning a value
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Racket
Racket
  #lang racket   ;; a list of 10 references to the same vector (make-list 10 (make-vector 10 0))   ;; a list of 10 distinct vectors (build-list 10 (λ (n) (make-vector 10 0)))  
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#Raku
Raku
my @a = Foo.new xx $n;
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: Closures/Value capture
#REXX
REXX
/*REXX program does a list comprehension that will create N random integers, all unique.*/ parse arg n lim . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/ if lim=='' | lim=="," then lim= 100000 /* " " " " " " */ lim= min(lim, 1e5) /*limit the random range if necessary. */ randoms= /*will contain random list of integers.*/ $= . do j=1 for n /*gen a unique random integer for list.*/   do until wordpos($, randoms)==0 /*ensure " " " " " */ $= random(0, lim) /*Not unique? Then obtain another int.*/ end /*until*/ /*100K is the maximum range for RANDOM.*/   randoms= $ randoms /*add an unique random integer to list.*/ end /*j*/   say words(randoms) ' unique numbers generated.' /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Quackery
Quackery
' [ 1 1 ] 41 times [ dup -2 split nip do i^ 2 + 2 * 1 - * swap i^ 2 + 3 * 6 - * + i^ 3 + / join ] behead drop witheach [ i^ echo sp dup echo isprime if [ say " prime" ] cr ]
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime. See also oeis:A001006 Motzkin numbers
#Raku
Raku
use Lingua::EN::Numbers;   constant \C = 1, |[\×] (2, 6 … ∞) Z/ 2 .. *;   sub binomial { [×] ($^n … 0) Z/ 1 .. $^p }   my \𝐌 = 1, |(1..∞).map: -> \𝐧 { sum ^𝐧 .map( -> \𝐤 { C[𝐤] × binomial 𝐧, 2×𝐤 } ) };   say " 𝐧 𝐌[𝐧] Prime?"; 𝐌[^42].kv.map: { printf "%2d %24s  %s\n", $^k, $^v.&comma, $v.is-prime };
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.
#C
C
  #include <stdio.h> #include <stdlib.h> #include <stdbool.h>   typedef enum type { INT, STRING } Type;   typedef struct maybe { int i; char *s; Type t; _Bool is_something; } Maybe;   void print_Maybe(Maybe *m) { if (m->t == INT) printf("Just %d : INT\n", m->i);   else if (m->t == STRING) printf("Just \"%s\" : STRING\n", m->s);   else printf("Nothing\n");   }   Maybe *return_maybe(void *data, Type t) { Maybe *m = malloc(sizeof(Maybe)); if (t == INT) { m->i = *(int *) data; m->s = NULL; m->t = INT; m->is_something = true; }   else if (t == STRING) { m->i = 0; m->s = data; m->t = STRING; m->is_something = true; }   else { m->i = 0; m->s = NULL; m->t = 0; m->is_something = false; }   return m; }   Maybe *bind_maybe(Maybe *m, Maybe *(*f)(void *)) { Maybe *n = malloc(sizeof(Maybe));   if (f(&(m->i))->is_something) { n->i = f(&(m->i))->i; n->s = f(&(m->i))->s; n->t = f(&(m->i))->t; n->is_something = true; }   else { n->i = 0; n->s = NULL; n->t = 0; n->is_something = false; } return n; }   Maybe *f_1(void *v) // Int -> Maybe Int { Maybe *m = malloc(sizeof(Maybe)); m->i = (*(int *) v) * (*(int *) v); m->s = NULL; m->t = INT; m->is_something = true; return m; }   Maybe *f_2(void *v) // :: Int -> Maybe String { Maybe *m = malloc(sizeof(Maybe)); m->i = 0; m->s = malloc(*(int *) v * sizeof(char) + 1); for (int i = 0; i < *(int *) v; i++) { m->s[i] = 'x'; } m->s[*(int *) v + 1] = '\0'; m->t = STRING; m->is_something = true; return m; }   int main() { int i = 7; char *s = "lorem ipsum dolor sit amet";   Maybe *m_1 = return_maybe(&i, INT); Maybe *m_2 = return_maybe(s, STRING);   print_Maybe(m_1); // print value of m_1: Just 49 print_Maybe(m_2); // print value of m_2 : Just "lorem ipsum dolor sit amet"   print_Maybe(bind_maybe(m_1, f_1)); // m_1 `bind` f_1 :: Maybe Int print_Maybe(bind_maybe(m_1, f_2)); // m_1 `bind` f_2 :: Maybe String   print_Maybe(bind_maybe(bind_maybe(m_1, f_1), f_2)); // (m_1 `bind` f_1) `bind` f_2 :: Maybe String -- it prints 49 'x' characters in a row }  
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.)
#Go
Go
package main   import ( "bytes" "fmt" )   type symbolTable string   func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq }   func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) }   func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
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.
#8th
8th
  \ return "extended gcd" of a and b; The result satisfies the equation: \ a*x + b*y = gcd(a,b) : n:xgcd \ a b -- gcd x y dup 0 n:= if 1 swap \ -- a 1 0 else tuck n:/mod -rot recurse tuck 4 roll n:* n:neg n:+ then ;   \ Return modular inverse of n modulo mod, or null if it doesn't exist (n and mod \ not coprime): : n:invmod \ n mod -- invmod dup >r n:xgcd rot 1 n:= not if 2drop null else drop dup 0 n:< if r@ n:+ then then rdrop ;   42 2017 n:invmod . cr bye  
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.
#Action.21
Action!
INT FUNC ModInverse(INT a,b) INT t,nt,r,nr,q,tmp   IF b<0 THEN b=-b FI IF a<0 THEN a=b-(-a MOD b) FI t=0 nt=1 r=b nr=a MOD b WHILE nr#0 DO q=r/nr tmp=nt nt=t-q*nt t=tmp tmp=nr nr=r-q*nr r=tmp OD IF r>1 THEN RETURN (-1) FI IF t<0 THEN t==+b FI RETURN (t)   PROC Test(INT a,b) INT res   res=ModInverse(a,b) IF res>=0 THEN PrintF("%I MODINV %I=%I%E",a,b,res) ELSE PrintF("%I MODINV %I has no result%E",a,b) FI RETURN   PROC Main() Test(42,2017) Test(40,1) Test(52,-217) Test(-486,217) Test(40,2018) RETURN
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.)
#Haskell
Haskell
import Control.Monad.Trans.Writer import Control.Monad ((>=>))   loggingVersion :: (a -> b) -> c -> a -> Writer c b loggingVersion f log x = writer (f x, log)   logRoot = loggingVersion sqrt "obtained square root, " logAddOne = loggingVersion (+1) "added 1, " logHalf = loggingVersion (/2) "divided by 2, "   halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf   main = print $ runWriter (halfOfAddOneOfRoot 5)
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.)
#J
J
root=: %: incr=: >: half=: -:   tostr=: ,@":   loggingVersion=: conjunction define n;~u )   Lroot=: root loggingVersion 'obtained square root' Lincr=: incr loggingVersion 'added 1' Lhalf=: half loggingVersion 'divided by 2'   loggingUnit=: verb define y;'Initial value: ',tostr y )   loggingBind=: adverb define r=. u 0{::y v=. 0{:: r v;(1{::y),LF,(1{::r),' -> ',tostr v )   loggingCompose=: dyad define  ;(dyad def '<x`:6 loggingBind;y')/x,<loggingUnit y )
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
#F.23
F#
  type ListMonad() = member o.Bind( (m:'a list), (f: 'a -> 'b list) ) = List.concat( List.map f m ) member o.Return(x) = [x] member o.Zero() = []   let list = ListMonad()   let pyth_triples n = list { let! x = [1..n] let! y = [x..n] let! z = [y..n] if x*x + y*y = z*z then return (x,y,z) }   printf "%A" (pyth_triples 100)
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
#Factor
Factor
USING: kernel math monads prettyprint ; FROM: monads => do ;   { 3 4 5 } >>= [ 1 + array-monad return ] swap call >>= [ 2 * array-monad return ] swap call .
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).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a = ConstantArray[0, {2, 3, 4, 5}] a[[1, 2, 3, 4]] = 15; a[[1, 2, 3, 4]] a a[[2, 2]] = 8; a
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).
#Nim
Nim
import arraymancer   let c = [ [ [1,2,3], [4,5,6] ], [ [11,22,33], [44,55,66] ], [ [111,222,333], [444,555,666] ], [ [1111,2222,3333], [4444,5555,6666] ] ].toTensor()   echo c # Tensor of shape 4x2x3 of type "int" on backend "Cpu" # | 1 2 3 | 11 22 33 | 111 222 333 | 1111 2222 3333| # | 4 5 6 | 44 55 66 | 444 555 666 | 4444 5555 6666|   let e = newTensor[bool]([2, 3])   echo e # Tensor of shape 2x3 of type "bool" on backend "Cpu" # |false false false| # |false false false|   let f = zeros[float]([4, 3])   echo f # Tensor of shape 4x3 of type "float" on backend "Cpu" # |0.0 0.0 0.0| # |0.0 0.0 0.0| # |0.0 0.0 0.0| # |0.0 0.0 0.0|   let g = ones[float]([4, 3])   echo g # Tensor of shape 4x3 of type "float" on backend "Cpu" # |1.0 1.0 1.0| # |1.0 1.0 1.0| # |1.0 1.0 1.0| # |1.0 1.0 1.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.
#ActionScript
ActionScript
  package {   import flash.display.Sprite; import flash.events.Event; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat;   [SWF (width = 550, height = 550)] public class MultiplicationTable extends Sprite {   public function MultiplicationTable() { if ( stage ) _init(); else addEventListener(Event.ADDED_TO_STAGE, _init); }   private function _init(e:Event = null):void {   removeEventListener(Event.ADDED_TO_STAGE, _init);   var format:TextFormat = new TextFormat(); format.size = 15; var blockSize:uint = 40; var max:uint = 12;   var i:uint, j:uint; var tf:TextField;   for ( i = 1; i <= max; i++ ) { tf = new TextField(); tf.defaultTextFormat = format; tf.x = blockSize * i; tf.y = 0; tf.width = tf.height = blockSize; tf.autoSize = TextFieldAutoSize.CENTER; tf.text = String(i); addChild(tf);   tf = new TextField(); tf.defaultTextFormat = format; tf.x = 0; tf.y = blockSize * i; tf.width = tf.height = blockSize; tf.autoSize = TextFieldAutoSize.CENTER; tf.text = String(i); addChild(tf); }   var yOffset:Number = tf.textHeight / 2; y += yOffset;   graphics.lineStyle(1, 0x000000); graphics.moveTo(blockSize, -yOffset); graphics.lineTo(blockSize, (blockSize * (max + 1)) - yOffset); graphics.moveTo(0, blockSize - yOffset); graphics.lineTo(blockSize * (max + 1), blockSize - yOffset);     for ( i = 1; i <= max; i++ ) { for ( j = 1; j <= max; j++ ) { if ( j > i ) continue;   tf = new TextField(); tf.defaultTextFormat = format; tf.x = blockSize * i; tf.y = blockSize * j; tf.width = tf.height = blockSize; tf.autoSize = TextFieldAutoSize.CENTER; tf.text = String(i * j); addChild(tf); } }   }   }   }  
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).
#jq
jq
def dot_product(a; b): reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );   # A and B should both be numeric matrices, A being m by n, and B being n by p. def multiply(A; B): (B[0]|length) as $p | (B|transpose) as $BT | reduce range(0; A|length) as $i ([]; reduce range(0; $p) as $j (.; .[$i][$j] = dot_product( A[$i]; $BT[$j] ) ));
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).
#Julia
Julia
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] X = [x.^0 x.^1 x.^2]; b = X \ y
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#D
D
import std.stdio, std.algorithm, std.range;   T multifactorial(T=long)(in int n, in int m) pure /*nothrow*/ { T one = 1; return reduce!q{a * b}(one, iota(n, 0, -m)); }   void main() { foreach (immutable m; 1 .. 11) writefln("%2d: %s", m, iota(1, 11) .map!(n => multifactorial(n, m))); }
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.
#Groovy
Groovy
1.upto(5) { Thread.sleep(1000) def p = java.awt.MouseInfo.pointerInfo.location println "${it}: x=${p.@x} y=${p.@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.
#HicEst
HicEst
WINDOW(WINdowhandle=handle) AXIS(WINdowhandle=handle, MouSeCall=Mouse_Callback, MouSeX=X, MouSeY=Y) END   SUBROUTINE Mouse_Callback() WRITE(Messagebox, Name) X, Y 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
#Frink
Frink
solution[board] := { for q = 0 to length[board] - 1 for c = q+1 to length[board] - 1 if board@q == board@c + (c - q) or board@q == board@c - (c - q) return false return true }   for b = array[1 to 8].permute[] if solution[b] println[b]
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and combine the results with the least common multiple operation. Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent. Task Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library. An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996: Exercise 5.8, page 115: Suppose you are given a prime p and a complete factorization of p-1.   Show how to compute the order of an element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit operations. Solution, page 337: Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation: if x^((p-1)/qifi) = 1 (mod p) , and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.) Hence it suffices to find, for each i , the exponent fi such that the condition above holds. This can be done as follows: first compute q1e1, q2e2, ... , qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek . This can be done using O((lg p)2) bit operations. Now, using the binary method, compute x1=ay1(mod p), ... , xk=ayk(mod p) . This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10. Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained. This can be done using O((lg p)3) steps. The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
#zkl
zkl
var BN =Import("zklBigNum"); var Sieve=Import("sieve");   // factor n into powers of primes // eg 9090 == 2^1 * 3^2 * 5^1 * 101^1 fcn factor2PP(n){ // lazy factors using lazy primes --> (prime,power) ... Utils.Generator(fcn(a){ primes:=Utils.Generator(Sieve.postponed_sieve); foreach p in (primes){ e:=0; while(a%p == 0){ a /= p; e+=1; } if (e) vm.yield(p,e); if (a<p*p) break; } if (a>1) vm.yield(a,1); },n) }   fcn _multOrdr1(a,p,e){ m:=p.pow(e); t:=m/p*(p - 1); qs:=L(BN(1)); foreach p2,e2 in (factor2PP(t)){ qs=[[(e,q); [0..e2]; qs; '{ q*BN(p2).pow(e) }]]; } qs.filter1('wrap(q){ a.powm(q,m)==1 }); }   fcn multiOrder(a,m){ if (m.gcd(a)!=1) throw(Exception.ValueError("Not co-prime")); res:=BN(1); foreach p,e in (factor2PP(m)){ res = res.lcm(_multOrdr1(BN(a),BN(p),e)); } return(res); }
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.
#SPL
SPL
nthr(n,r) <= n^(1/r)   nthroot(n,r)= a = n/r g = n > g!=a g = a a = (1/r)*(((r-1)*g)+(n/(g^(r-1)))) < <= a .   #.output(nthr(2,2)) #.output(nthroot(2,2))
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.
#Swift
Swift
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1)   for _ in 0..<e { res *= self }   return res }   @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) var res = Self(1)   guard self != 0 else { return 0 }   guard n >= 1 else { return .nan }   repeat { d = (self / res.power(n - 1) - res) / Self(n) res += d } while d >= epsilon * 10 || d <= -epsilon * 10   return res } }   print(81.root(n: 4)) print(13.root(n: 5))
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.
#Nanoquery
Nanoquery
def ordinalAbbrev(n) if int(n % 100 / 10) = 1 return "th" end   if n % 10 = 1 return "st" else if n % 10 = 2 return "nd" else if n % 10 = 3 return "rd" else return "th" end end   for i in range(0, 25) print (i + "'" + ordinalAbbrev(i) + " ") end println   for i in range(250, 265) print (i + "'" + ordinalAbbrev(i) + " ") end println   for i in range(1000, 1025) print (i + "'" + ordinalAbbrev(i) + " ") end println
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Nim
Nim
import math   for i in 1..<5000: var sum: int64 = 0 var number = i while number > 0: var digit = number mod 10 sum += digit ^ digit number = number div 10 if sum == i: echo 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).
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) every write(F(!arglist)) # F of all arguments end   procedure F(n) if integer(n) >= 0 then return (n = 0, 1) | n - M(F(n-1)) end   procedure M(n) if integer(n) >= 0 then return (0 = n) | n - F(M(n-1)) end