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/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).
#Euphoria
Euphoria
integer idM, idF   function F(integer n) if n = 0 then return 1 else return n - call_func(idM,{F(n-1)}) end if end function   idF = routine_id("F")   function M(integer n) if n = 0 then return 0 else return n - call_func(idF,{M(n-1)}) end if end function   idM = routine_id("M")
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Sidef
Sidef
func multisplit(sep, str, keep_sep=false) { sep = sep.map{.escape}.join('|'); var re = Regex.new(keep_sep ? "(#{sep})" : sep); str.split(re, -1); }   [false, true].each { |bool| say multisplit(%w(== != =), 'a!===b=!=c', keep_sep: bool); }
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Swift
Swift
extension String { func multiSplit(on seps: [String]) -> ([Substring], [(String, (start: String.Index, end: String.Index))]) { var matches = [Substring]() var matched = [(String, (String.Index, String.Index))]() var i = startIndex var lastMatch = startIndex   main: while i != endIndex { for sep in seps where self[i...].hasPrefix(sep) { if i > lastMatch { matches.append(self[lastMatch..<i]) } else { matches.append("") }   lastMatch = index(i, offsetBy: sep.count) matched.append((sep, (i, lastMatch))) i = lastMatch   continue main }   i = index(i, offsetBy: 1) }   if i > lastMatch { matches.append(self[lastMatch..<i]) }   return (matches, matched) } }   let (matches, matchedSeps) = "a!===b=!=c".multiSplit(on: ["==", "!=", "="])   print(matches, matchedSeps.map({ $0.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
#Factor
Factor
1000 [ { 1 } clone ] replicate
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
#FreeBASIC
FreeBASIC
dim as foo array(1 to 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
#Forth
Forth
include FMS-SI.f include FMS-SILib.f     \ create a list of VAR objects the right way \ each: returns a unique object reference o{ 0 0 0 } dup p: o{ 0 0 0 } dup each: drop . 10774016 dup each: drop . 10786896 dup each: drop . 10786912     \ create a list of VAR objects the wrong way \ each: returns the same object reference var x object-list2 list x list add: x list add: x list add: list p: o{ 0 0 0 } list each: drop . 1301600 list each: drop . 1301600 list each: drop . 1301600  
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.)
#Ada
Ada
with Ada.Text_IO;   procedure Move_To_Front is   subtype Lower_Case is Character range 'a' .. 'z'; subtype Index is Integer range 0 .. 25; type Table is array (Index) of Lower_Case; Alphabet: constant Table := "abcdefghijklmnopqrstuvwxyz"; type Number_String is array(Positive range <>) of Natural;   function Encode(S: String) return Number_String is Key: Table := Alphabet;   function Encode(S: String; Tab: in out Table) return Number_String is   procedure Look_Up(A: in out Table; Ch: Lower_Case; Pos: out Index) is begin for I in A'Range loop if A(I) = Ch then Pos := I; A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last); return; end if; end loop; raise Program_Error with "unknown character"; end Look_Up;   Empty: Number_String(1 .. 0); Result: Natural; begin if S'Length = 0 then return Empty; else Look_Up(Tab, S(S'First), Result); return Result & Encode(S(S'First+1 .. S'Last), Tab); end if; end Encode;   begin return Encode(S, Key); end Encode;   function Decode(N: Number_String) return String is Key: Table := Alphabet;   function Decode(N: Number_String; Tab: in out Table) return String is   procedure Look_Up(A: in out Table; Pos: Index; Ch: out Lower_Case) is begin Ch := A(Pos); A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last); end Look_Up;   Result: String(N'Range); begin for I in N'Range loop Look_Up(Tab, N(I), Result(I)); end loop; return Result; end Decode;   begin return Decode(N, Key); end Decode;   procedure Encode_Write_Check(S: String) is N: Number_String := Encode(S); T: String := Decode(N); Check: String := (if S=T then "Correct!" else "*WRONG*!"); begin Ada.Text_IO.Put("'" & S & "' encodes to"); for Num of N loop Ada.Text_IO.Put(Integer'Image(Num)); end loop; Ada.Text_IO.Put_Line(". This decodes to '" & T & "'. " & Check); end Encode_Write_Check;   begin Encode_Write_Check("broood"); Encode_Write_Check("bananaaa"); Encode_Write_Check("hiphophiphop"); end Move_To_Front;
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).
#ALGOL_W
ALGOL W
integer array a ( 1 :: 5, 1 :: 4, 1 :: 3, 1 :: 2 );
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).
#C
C
/*Single dimensional array of integers*/ int a[10];   /*2-dimensional array, also called matrix of floating point numbers. This matrix has 3 rows and 2 columns.*/   float b[3][2];   /*3-dimensional array ( Cube ? Cuboid ? Lattice ?) of characters*/   char c[4][5][6];   /*4-dimensional array (Hypercube ?) of doubles*/   double d[6][7][8][9];   /*Note that the right most number in the [] is required, all the others may be omitted. Thus this is ok : */   int e[][3];   /*But this is not*/   float f[5][4][];   /*But why bother with all those numbers ? You can also write :*/ int *g;   /*And for a matrix*/ float **h;   /*or if you want to show off*/ double **i[];   /*you get the idea*/   char **j[][5];
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).
#C
C
#include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_multifit.h>   double w[] = { 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 }; double h[] = { 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 };   int main() { int n = sizeof(h)/sizeof(double); gsl_matrix *X = gsl_matrix_calloc(n, 3); gsl_vector *Y = gsl_vector_alloc(n); gsl_vector *beta = gsl_vector_alloc(3);   for (int i = 0; i < n; i++) { gsl_vector_set(Y, i, w[i]);   gsl_matrix_set(X, i, 0, 1); gsl_matrix_set(X, i, 1, h[i]); gsl_matrix_set(X, i, 2, h[i] * h[i]); }   double chisq; gsl_matrix *cov = gsl_matrix_alloc(3, 3); gsl_multifit_linear_workspace * wspc = gsl_multifit_linear_alloc(n, 3); gsl_multifit_linear(X, Y, beta, cov, &chisq, wspc);   printf("Beta:"); for (int i = 0; i < 3; i++) printf("  %g", gsl_vector_get(beta, i)); printf("\n");   gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(Y); gsl_vector_free(beta); gsl_multifit_linear_free(wspc);   }
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.
#ALGOL_W
ALGOL W
begin  % returns the multifactorial of n with the specified degree % integer procedure multifactorial ( integer value n, degree ) ; begin integer mf, v; mf := v := n; while begin v := v - degree; v > 1 end do mf := mf * v; mf end multifactorial ;    % tests as per task % for degree := 1 until 5 do begin i_w := 1; s_w := 0; % output formatting % write( "Degree: ", degree, ":" ); for v := 1 until 10 do begin writeon( " ", multifactorial( v, degree ) ) end for_v end for_degree end.
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} n ! ! = n ( n − 2 ) ( n − 4 ) . . . {\displaystyle n!!=n(n-2)(n-4)...} n ! ! ! = n ( n − 3 ) ( n − 6 ) . . . {\displaystyle n!!!=n(n-3)(n-6)...} n ! ! ! ! = n ( n − 4 ) ( n − 8 ) . . . {\displaystyle n!!!!=n(n-4)(n-8)...} n ! ! ! ! ! = n ( n − 5 ) ( n − 10 ) . . . {\displaystyle n!!!!!=n(n-5)(n-10)...} In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: Write a function that given n and the degree, calculates the multifactorial. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 FUNCTION multiFactorial (n, degree) 110 IF n < 2 THEN 120 LET multiFactorial = 1 130 EXIT FUNCTION 140 END IF 150 LET result = n 160 FOR i = n - degree TO 2 STEP -degree 170 LET result = result * i 180 NEXT i 190 LET multiFactorial = result 200 END FUNCTION 210 220 FOR degree = 1 TO 5 230 PRINT "Degree"; degree; " => "; 240 FOR n = 1 TO 10 250 PRINT multiFactorial(n, degree); " "; 260 NEXT n 270 PRINT 280 NEXT degree 290 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.
#ActionScript
ActionScript
  package {   import flash.display.Sprite; import flash.events.Event; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat;   public class MousePosition extends Sprite {   private var _textField:TextField = new TextField();   public function MousePosition() { if ( stage ) init(); else addEventListener(Event.ADDED_TO_STAGE, init); }   private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init);   _textField.autoSize = TextFieldAutoSize.RIGHT; _textField.x = stage.stageWidth - 10; _textField.defaultTextFormat = new TextFormat(null, 15); _textField.text = "Mouse position: X = 0, Y = 0"; _textField.y = stage.stageHeight - _textField.textHeight - 14; addChild(_textField);   addEventListener(Event.ENTER_FRAME, _onEnterFrame); }   private function _onEnterFrame(e:Event):void { _textField.text = "Mouse position: X = " + stage.mouseX + ", Y = " + stage.mouseY; }   }   }  
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Nim
Nim
import math, sequtils, strutils   const MaxDepth = 6 Max = 36^MaxDepth - 1 # Max value for MaxDepth digits in base 36. Digits = "0123456789abcdefghijklmnopqrstuvwxyz"   # Sieve of Erathostenes. var composite: array[1..(Max div 2), bool] # Only odd numbers. for i in 1..composite.high: let n = 2 * i + 1 let n2 = n * n if n2 > Max: break if not composite[i]: for k in countup(n2, Max, 2 * n): composite[k shr 1] = true   template isPrime(n: int): bool = if n <= 1: false elif (n and 1) == 0: n == 2 else: not composite[n shr 1]   type Context = object indices: seq[int] mostBases: int maxStrings: seq[tuple[indices, bases: seq[int]]]   func initContext(depth: int): Context = result.indices.setLen(depth) result.mostBases = -1     proc process(ctx: var Context) = let minBase = max(2, max(ctx.indices) + 1) if 37 - minBase < ctx.mostBases: return   var bases: seq[int] for b in minBase..36: var n = 0 for i in ctx.indices: n = n * b + i if n.isPrime: bases.add b   var count = bases.len if count > ctx.mostBases: ctx.mostBases = count ctx.maxStrings = @{ctx.indices: bases} elif count == ctx.mostBases: ctx.maxStrings.add (ctx.indices, bases)     proc nestedFor(ctx: var Context; length, level: int) = if level == ctx.indices.len: ctx.process() else: ctx.indices[level] = if level == 0: 1 else: 0 while ctx.indices[level] < length: ctx.nestedFor(length, level + 1) inc ctx.indices[level]     for depth in 1..MaxDepth: var ctx = initContext(depth) ctx.nestedFor(Digits.len, 0) echo depth, " character strings which are prime in most bases: ", ctx.maxStrings[0].bases.len for m in ctx.maxStrings: echo m.indices.mapIt(Digits[it]).join(), " → ", m[1].join(" ") echo()
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Pascal
Pascal
program MAXBaseStringIsPrimeInBase; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils; const CharOfBase= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; MINBASE = 2; MAXBASE = 62;//36;//62; MAXDIGITCOUNT = 5;//6; type tdigits = packed record dgtDgts : array [0..13] of byte; dgtMaxIdx, dgtMaxDgtVal :byte; dgtNum : Uint64; end; tSol = array of Uint64; var BoolPrimes: array of boolean;   function BuildWheel(primeLimit:Int64):NativeUint; var myPrimes : pBoolean; wheelprimes :array[0..31] of byte; wheelSize,wpno, pr,pw,i, k: NativeUint; begin myPrimes := @BoolPrimes[0]; pr := 1; myPrimes[1]:= true; WheelSize := 1; wpno := 0; repeat inc(pr); pw := pr; if pw > wheelsize then dec(pw,wheelsize); If myPrimes[pw] then begin k := WheelSize+1; for i := 1 to pr-1 do begin inc(k,WheelSize); if k<primeLimit then move(myPrimes[1],myPrimes[k-WheelSize],WheelSize) else begin move(myPrimes[1],myPrimes[k-WheelSize],PrimeLimit-WheelSize*i); break; end; end; dec(k); IF k > primeLimit then k := primeLimit; wheelPrimes[wpno] := pr; myPrimes[pr] := false; inc(wpno); WheelSize := k; i:= pr; i := i*i; while i <= k do begin myPrimes[i] := false; inc(i,pr); end; end; until WheelSize >= PrimeLimit;   while wpno > 0 do begin dec(wpno); myPrimes[wheelPrimes[wpno]] := true; end; myPrimes[0] := false; myPrimes[1] := false; BuildWheel := pr+1; end;   procedure Sieve(PrimeLimit:Uint64); var myPrimes : pBoolean; sieveprime, fakt : NativeUint; begin setlength(BoolPrimes,PrimeLimit+1);   myPrimes := @BoolPrimes[0]; sieveprime := BuildWheel(PrimeLimit); repeat if myPrimes[sieveprime] then begin fakt := PrimeLimit DIV sieveprime; IF fakt < sieveprime then BREAK; repeat myPrimes[sieveprime*fakt] := false; repeat dec(fakt); until myPrimes[fakt]; until fakt < sieveprime; end; inc(sieveprime); until false; myPrimes[1] := false; end;   procedure CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint); var q,r: Uint64; i : Int32; Begin i := 0; with dgt do Begin fillchar(dgtDgts,SizeOf(dgtDgts),#0); dgtNum:= n; repeat r := n; q := n div base; r -= q*base; n := q; dgtDgts[i] := r; inc(i); until (q = 0); dec(i); dgtMaxIdx := i;   r := 1; repeat q := dgtDgts[i]; if r < q then r := q; dec(i); until i <0 ; dgtMaxDgtVal := r; end; end;   function CnvDgtAsInBase(const dgt:tDigits;base:NativeUint):Uint64; var tmpDgt,i: NativeInt; Begin result := 0; with dgt do Begin i:= dgtMaxIdx; repeat tmpDgt := dgtDgts[i]; result *= base; dec(i); result +=tmpDgt; until (i< 0); end; end;   procedure IncInBaseDigits(var dgt:tDigits;base:NativeInt); var i,q,tmp :NativeInt; Begin with dgt do Begin tmp := dgtMaxIdx; i := 0; repeat q := dgtDgts[i]+1; q -= (-ORD(q >=base) AND base); dgtDgts[i] := q; inc(i); until q <> 0; dec(i); if tmp < i then begin tmp := i; dgtMaxIdx := i; end; i := tmp; repeat tmp := dgtDgts[i]; if q< tmp then q := tmp; dec(i); until i <0; inc(dgtNum); dgtMaxDgtVal := q; end; end;   function CntPrimeInBases(var Digits :tdigits;max:Int32):Uint32; var pr : Uint64; base: Uint32; begin result := 0; IncInBaseDigits(Digits,MAXBASE); base := Digits.dgtMaxDgtVal+1; //divisible by every base IF Digits.dgtDgts[0] = 0 then EXIT; IF base < MINBASE then base := MINBASE; // if (MAXBASE - Base) <= (max-result) then BREAK; max := (max+Base-MAXBASE); if (max>=0) then EXIT; for base := base TO MAXBASE do begin pr := CnvDgtAsInBase(Digits,base); inc(result,Ord(boolprimes[pr])); //no chance to reach max then exit if result<max then break; inc(max); end; end;   function GetMaxBaseCnt(var dgt:tDigits;MinLmt,MaxLmt:Uint32):tSol; var i : Uint32; baseCnt,max,Idx: Int32; Begin setlength(result,0); max :=-1; Idx:= 0; For i := MinLmt to MaxLmt do Begin baseCnt := CntPrimeInBases(dgt,max); if baseCnt = 0 then continue; if max<=baseCnt then begin if max = baseCnt then begin inc(Idx); if Idx > High(result) then setlength(result,Idx); result[idx-1] := i; end else begin Idx:= 1; setlength(result,1); result[0] := i; max := baseCnt; end; end; end; end;   function Out_String(n:Uint64;var s: AnsiString):Uint32; //out-sourced for debugging purpose var dgt:tDigits; sl : string[15]; base,i: Int32; Begin result := 0; CnvtoBASE(dgt,n,MaxBase); sl := ''; with dgt do begin base:= dgtMaxDgtVal+1; IF base < MINBASE then base := MINBASE; i := dgtMaxIdx; while (i>=0)do Begin sl += CharOfBase[dgtDgts[i]+1]; dec(i); end; s := sl+' -> ['; end; For base := base to MAXBASE do if boolprimes[CnvDgtAsInBase(dgt,base)] then begin inc(result); str(base,sl); s := s+sl+','; end; s[length(s)] := ']'; end;   procedure Out_Sol(sol:tSol); var s : AnsiString; i,cnt : Int32; begin if length(Sol) = 0 then EXIT; for i := 0 to High(Sol) do begin cnt := Out_String(sol[i],s); if i = 0 then writeln(cnt); writeln(s); end; writeln; setlength(Sol,0); end;   var dgt:tDigits; T0 : Int64; i : NativeInt; lmt,minLmt : UInt64; begin T0 := GetTickCount64; lmt := 0; //maxvalue in Maxbase for i := 1 to MAXDIGITCOUNT do lmt :=lmt*MAXBASE+MAXBASE-1; writeln('max prime limit ',lmt); Sieve(lmt); writeln('Prime sieving ',(GetTickCount64-T0)/1000:6:3,' s');   T0 := GetTickCount64; CnvtoBASE(dgt,0,MAXBASE); i := 1; minLmt := 1; repeat write(i:2,' character strings which are prime in count bases = '); Out_Sol(GetMaxBaseCnt(dgt,minLmt,MAXBASE*minLmt-1)); minLmt *= MAXBASE; inc(i); until i>MAXDIGITCOUNT; writeln(' Converting ',(GetTickCount64-T0)/1000:6:3,' s'); {$IFDEF WINDOWS} readln; {$ENDIF} 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
#Draco
Draco
byte SIZE = 8; word count;   proc solve([*] int hist; int col) void: int i, j, n; n := dim(hist, 1); if col = n then count := count + 1; writeln(); writeln("No. ", count); writeln("-----"); for i from 0 upto n-1 do for j from 0 upto n-1 do write(if j=hist[i] then 'Q' elif (i+j)&1 /= 0 then ' ' else '.' fi) od; writeln() od else for i from 0 upto n-1 do j := 0; while j<col and not (hist[j]=i or |(hist[j]-i) = col-j) do j := j + 1 od; if j >= col then hist[col] := i; solve(hist, col+1) fi od fi corp   proc nonrec main() void: [SIZE] int hist; count := 0; solve(hist, 0) corp
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)).
#Maple
Maple
numtheory:-order( a, n )
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)).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MultiplicativeOrder[37, 1000] MultiplicativeOrder[10^100 + 1, 7919] (*10^3th prime number Prime[1000]*) MultiplicativeOrder[10^1000 + 1, 15485863] (*10^6th prime number*) MultiplicativeOrder[10^10000 - 1, 22801763489] (*10^9th prime number*) MultiplicativeOrder[13, 1 + 10^80] MultiplicativeOrder[11, 1 + 10^100]
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.
#Prolog
Prolog
  iroot(_, 0, 0) :- !. iroot(M, N, R) :- M > 1, (N > 0 -> irootpos(M, N, R) ; N /\ 1 =:= 1, NegN is -N, irootpos(M, NegN, R0), R is -R0).   irootpos(N, A, R) :- X0 is 1 << (msb(A) div N), % initial guess is 2^(log2(A) / N) newton(N, A, X0, X1), iroot_loop(A, X1, N, A, R).   iroot_loop(X1, X2, _, _, X1) :- X1 =< X2, !. iroot_loop(_, X1, N, A, R) :- newton(N, A, X1, X2), iroot_loop(X1, X2, N, A, R).   newton(2, A, X0, X1) :- X1 is (X0 + A div X0) >> 1, !. % fast special case newton(N, A, X0, X1) :- X1 is ((N - 1)*X0 + A div X0**(N - 1)) div N.  
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.
#jq
jq
  # ordinalize an integer input, positive or negative def ordinalize: (if . < 0 then -(.) else . end) as $num | ($num % 100) as $small | (if 11 <= $small and $small <= 13 then "th" else ( $num % 10) | (if . == 1 then "st" elif . == 2 then "nd" elif . == 3 then "rd" else "th" end) end) as $ordinal | "\(.)\($ordinal)" ;   ([range(-5; -1)], [range(0;26)], [range(250;266)], [range(1000;1026)]) | map(ordinalize)  
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#zkl
zkl
(26).toString(16) //--> "1a" "1a".toInt(16) //-->26
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Sidef
Sidef
func is_narcissistic(n) { n.digits »**» n.len -> sum == n }   var count = 0 for i in ^Inf { if (is_narcissistic(i)) { say "#{++count}\t#{i}" break if (count == 25) } }
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Swift
Swift
extension BinaryInteger { @inlinable public var isNarcissistic: Bool { let digits = String(self).map({ Int(String($0))! }) let m = digits.count   guard m != 1 else { return true }   return digits.map({ $0.power(m) }).reduce(0, +) == self }   @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) }   }   let narcs = Array((0...).lazy.filter({ $0.isNarcissistic }).prefix(25))   print("First 25 narcissistic numbers are \(narcs)")
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
#JavaScript
JavaScript
for (let i of [...Array(5000).keys()] .filter(n => n == n.toString().split('') .reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0))) console.log(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).
#F.23
F#
let rec f n = match n with | 0 -> 1 | _ -> n - (m (f (n-1))) and m n = match n with | 0 -> 0 | _ -> n - (f (m (n-1)))
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Tcl
Tcl
proc simplemultisplit {text sep} { set map {}; foreach s $sep {lappend map $s "\uffff"} return [split [string map $map $text] "\uffff"] } puts [simplemultisplit "a!===b=!=c" {"==" "!=" "="}]
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#TXR
TXR
@(next :args) @(coll :gap 0)@(choose :shortest tok)@\ @tok@{sep /==/}@\ @(or)@\ @tok@{sep /!=/}@\ @(or)@\ @tok@{sep /=/}@\ @(end)@(end)@tail @(output) @(rep)"@tok" {@sep} @(end)"@tail" @(end)
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
#Fortran
Fortran
  program multiple ! Define a simple type type T integer :: a = 3 end type T   ! Define a type containing a pointer type S integer, pointer :: a end type S   type(T), allocatable :: T_array(:) type(S), allocatable :: S_same(:) integer :: i integer, target :: v integer, parameter :: N = 10   ! Create 10 allocate(T_array(N))   ! Set the fifth one to b something different T_array(5)%a = 1   ! Print them out to show they are distinct write(*,'(10i2)') (T_array(i),i=1,N)   ! Create 10 references to the same object allocate(S_same(N)) v = 5 do i=1, N allocate(S_same(i)%a) S_same(i)%a => v end do   ! Print them out - should all be 5 write(*,'(10i2)') (S_same(i)%a,i=1,N)   ! Change the referenced object and reprint - should all be 3 v = 3 write(*,'(10i2)') (S_same(i)%a,i=1,N)   end program multiple  
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
#Go
Go
func nxm(n, m int) [][]int { d2 := make([][]int, n) for i := range d2 { d2[i] = make([]int, m) } return d2 }
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
#ALGOL_68
ALGOL 68
BEGIN # find some Motzkin numbers # PR read "primes.incl.a68" PR # returns a table of the Motzkin numbers 0 .. n # OP MOTZKIN = ( INT n )[]LONG LONG INT: BEGIN [ 0 : n ]LONG LONG INT m; IF n >= 0 THEN m[ 0 ] := 1; IF n >= 1 THEN m[ 1 ] := 1; FOR i FROM 2 TO UPB m DO m[ i ] := ( ( m[ i - 1 ] * ( ( 2 * i ) + 1 ) ) + ( m[ i - 2 ] * ( ( 3 * i ) - 3 ) ) ) OVER ( i + 2 ) OD FI FI; m END # MOTZKIN # ; # returns a string representation of n with commas # PROC commatise = ( LONG LONG INT n )STRING: BEGIN STRING result := ""; STRING unformatted = whole( n, 0 ); INT ch count := 0; FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO IF ch count <= 2 THEN ch count +:= 1 ELSE ch count := 1; "," +=: result FI; unformatted[ c ] +=: result OD; result END; # commatise # # left-pads a string to at least n characters # PROC pad left = ( STRING s, INT n )STRING: BEGIN STRING result := s; WHILE ( UPB result - LWB result ) + 1 < n DO " " +=: result OD; result END; # pad left #   # show the Motzkin numbers # print( ( " n M[n] Prime?", newline ) ); print( ( "-----------------------------------", newline ) ); []LONG LONG INT m = MOTZKIN 41; FOR i FROM LWB m TO UPB m DO print( ( whole( i, -2 ) , pad left( commatise( m[ i ] ), 26 ) , IF is probably prime( m[ i ] ) THEN " prime" ELSE "" FI , newline ) ) OD 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.)
#Aime
Aime
decode(list l) { integer c, e; data al, s;   al = "abcdefghijklmnopqrstuvwxyz"; for (, e in l) { s.append(c = al[e]); al.delete(e).insert(0, c); }   s; }   encode(data s) { integer c, e; data al; list l;   al = "abcdefghijklmnopqrstuvwxyz"; for (, c in s) { l.append(e = al.place(c)); al.delete(e).insert(0, c); }   l; }   main(void) { for (, text s in list("broood", "bananaaa", "hiphophiphop")) { list l;   l = encode(s); l.ucall(o_, 1, " "); o_(": ", decode(l), "\n"); }   0; }
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#ALGOL_68
ALGOL 68
# move the character at text pos to the front of text # # note text pos is based from 0 # PROC move to front = ( STRING text, INT text pos )STRING: IF text pos < 1 THEN # the character is already at the front (or not in the string) # text ELSE # the character isn't already at the front - construct the new string #   INT char pos = LWB text + text pos;   ( text[ char pos : char pos ] + text[ : char pos - 1 ] + text[ char pos + 1 : ] )   FI;     # encode the string "text", using "initial table" as the starting symbol table# PROC encode = ( STRING text, STRING initial table )[]INT: BEGIN   [ 1 : ( UPB text - LWB text ) + 1 ]INT result;   STRING symbol table := initial table;   FOR text pos FROM LWB text TO UPB text DO INT symbol pos := 0;   result[ text pos ] := IF char in string( text[ text pos ], symbol pos, symbol table ) THEN # the character is in the symbol table at symbol pos # # (indexed from LWB text) - we store the positions # # indexed from 0 # symbol pos - LWB text ELSE # the character isn't in the symbol table # -1 FI;   # modify the symbol table so the latest character is at the front # symbol table := move to front( symbol table, result[ text pos ] )   OD;   result END; # encode #       # decode "encoded", using "initial table" as the starting symbol table # PROC decode = ( []INT encoded, STRING initial table )STRING: BEGIN   STRING result := ""; STRING symbol table := initial table;   FOR text pos FROM LWB encoded TO UPB encoded DO result +:= IF encoded[ text pos ] < 0 THEN # the encoded character wasn't in the string # "?" ELSE # the character is in the symbol table # symbol table[ encoded[ text pos ] + LWB symbol table ] FI;   # modify the symbol table so the latest character is at the front # symbol table := move to front( symbol table, encoded[ text pos ] )   OD;   result END; # decode #       # routine to test the encode and decode routines # PROC test encode and decode = ( STRING text )VOID: BEGIN   # initial value for the symbol table # []CHAR initial table = "abcdefghijklmnopqrstuvwxyz";   # procedure to format the encoded value # PROC format encoded value = ( []INT values )STRING: BEGIN STRING result := ""; FOR value pos FROM LWB values TO UPB values DO result +:= ( " " + whole( values[ value pos ], 0 ) ) OD;   result END; # format encoded value #   []INT encoded = encode( text, initial table ); STRING decoded = decode( encoded, initial table );   print( ( ( text + " encodes to [" + format encoded value( encoded ) + " ] which " + IF text = decoded THEN "correctly" ELSE "INCORRECTLY" FI + " decodes to """ + decoded + """" ) , newline ) )   END; # test encode and decode #       main: (   test encode and decode( "broood" ) ; test encode and decode( "bananaaa" ) ; test encode and decode( "hiphophiphop" )   # ; test encode and decode( "abcdefghijklmnopqrstuvwxyz" ) # # ; test encode and decode( "zyxwvutsrqponmlkjihgfedcba" ) #   )
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).
#C.23
C#
var array = new int[,] { //Dimensions are inferred { 1, 2, 3 }, { 4, 5, 6} } //Accessing a single element: array[0, 0] = 999;   //To create a 4-dimensional array with all zeroes: var array = new int[5, 4, 3, 2];
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).
#C.2B.2B
C++
#include <iostream> #include <vector>   // convienince for printing the contents of a collection template<typename T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) { auto it = c.cbegin(); auto end = c.cend();   out << '['; if (it != end) { out << *it; it = std::next(it); } while (it != end) { out << ", " << *it; it = std::next(it); } return out << ']'; }   void fourDim() { using namespace std;   // create a 4d jagged array, with bounds checking etc... vector<vector<vector<vector<int>>>> arr; int cnt = 0;   arr.push_back(vector<vector<vector<int>>>{}); arr[0].push_back(vector<vector<int>>{}); arr[0][0].push_back(vector<int>{}); arr[0][0][0].push_back(cnt++); arr[0][0][0].push_back(cnt++); arr[0][0][0].push_back(cnt++); arr[0][0][0].push_back(cnt++); arr[0].push_back(vector<vector<int>>{}); arr[0][1].push_back(vector<int>{}); arr[0][1][0].push_back(cnt++); arr[0][1][0].push_back(cnt++); arr[0][1][0].push_back(cnt++); arr[0][1][0].push_back(cnt++); arr[0][1].push_back(vector<int>{}); arr[0][1][1].push_back(cnt++); arr[0][1][1].push_back(cnt++); arr[0][1][1].push_back(cnt++); arr[0][1][1].push_back(cnt++);   arr.push_back(vector<vector<vector<int>>>{}); arr[1].push_back(vector<vector<int>>{}); arr[1][0].push_back(vector<int>{}); arr[1][0][0].push_back(cnt++); arr[1][0][0].push_back(cnt++); arr[1][0][0].push_back(cnt++); arr[1][0][0].push_back(cnt++);   cout << arr << '\n'; }   int main() { /* C++ does not have native support for multi-dimensional arrays, * but classes could be written to make things easier to work with. * There are standard library classes which can be used for single dimension arrays. * Also raw access is supported through pointers as in C. */   fourDim();   return 0; }
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).
#C.2B.2B
C++
#include <array> #include <iostream>   void require(bool condition, const std::string &message) { if (condition) { return; } throw std::runtime_error(message); }   template<typename T, size_t N> std::ostream &operator<<(std::ostream &os, const std::array<T, N> &a) { auto it = a.cbegin(); auto end = a.cend();   os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; }   template <size_t RC, size_t CC> class Matrix { std::array<std::array<double, CC>, RC> data;   public: Matrix() : data{} { // empty }   Matrix(std::initializer_list<std::initializer_list<double>> values) { size_t rp = 0; for (auto row : values) { size_t cp = 0; for (auto col : row) { data[rp][cp] = col; cp++; } rp++; } }   double get(size_t row, size_t col) const { return data[row][col]; }   void set(size_t row, size_t col, double value) { data[row][col] = value; }   std::array<double, CC> get(size_t row) { return data[row]; }   void set(size_t row, const std::array<double, CC> &values) { std::copy(values.begin(), values.end(), data[row].begin()); }   template <size_t D> Matrix<RC, D> operator*(const Matrix<CC, D> &rhs) const { Matrix<RC, D> result; for (size_t i = 0; i < RC; i++) { for (size_t j = 0; j < D; j++) { for (size_t k = 0; k < CC; k++) { double prod = get(i, k) * rhs.get(k, j); result.set(i, j, result.get(i, j) + prod); } } } return result; }   Matrix<CC, RC> transpose() const { Matrix<CC, RC> trans; for (size_t i = 0; i < RC; i++) { for (size_t j = 0; j < CC; j++) { trans.set(j, i, data[i][j]); } } return trans; }   void toReducedRowEchelonForm() { size_t lead = 0; for (size_t r = 0; r < RC; r++) { if (CC <= lead) { return; } auto i = r;   while (get(i, lead) == 0.0) { i++; if (RC == i) { i = r; lead++; if (CC == lead) { return; } } }   auto temp = get(i); set(i, get(r)); set(r, temp);   if (get(r, lead) != 0.0) { auto div = get(r, lead); for (size_t j = 0; j < CC; j++) { set(r, j, get(r, j) / div); } }   for (size_t k = 0; k < RC; k++) { if (k != r) { auto mult = get(k, lead); for (size_t j = 0; j < CC; j++) { auto prod = get(r, j) * mult; set(k, j, get(k, j) - prod); } } }   lead++; } }   Matrix<RC, RC> inverse() { require(RC == CC, "Not a square matrix");   Matrix<RC, 2 * RC> aug; for (size_t i = 0; i < RC; i++) { for (size_t j = 0; j < RC; j++) { aug.set(i, j, get(i, j)); } // augment identify matrix to right aug.set(i, i + RC, 1.0); }   aug.toReducedRowEchelonForm();   // remove identity matrix to left Matrix<RC, RC> inv; for (size_t i = 0; i < RC; i++) { for (size_t j = RC; j < 2 * RC; j++) { inv.set(i, j - RC, aug.get(i, j)); } } return inv; }   template <size_t RC, size_t CC> friend std::ostream &operator<<(std::ostream &, const Matrix<RC, CC> &); };   template <size_t RC, size_t CC> std::ostream &operator<<(std::ostream &os, const Matrix<RC, CC> &m) { for (size_t i = 0; i < RC; i++) { os << '['; for (size_t j = 0; j < CC; j++) { if (j > 0) { os << ", "; } os << m.get(i, j); } os << "]\n"; }   return os; }   template <size_t RC, size_t CC> std::array<double, RC> multiple_regression(const std::array<double, CC> &y, const Matrix<RC, CC> &x) { Matrix<1, CC> tm; tm.set(0, y);   auto cy = tm.transpose(); auto cx = x.transpose(); return ((x * cx).inverse() * x * cy).transpose().get(0); }   void case1() { std::array<double, 5> y{ 1.0, 2.0, 3.0, 4.0, 5.0 }; Matrix<1, 5> x{ {2.0, 1.0, 3.0, 4.0, 5.0} }; auto v = multiple_regression(y, x); std::cout << v << '\n'; }   void case2() { std::array<double, 3> y{ 3.0, 4.0, 5.0 }; Matrix<2, 3> x{ {1.0, 2.0, 1.0}, {1.0, 1.0, 2.0} }; auto v = multiple_regression(y, x); std::cout << v << '\n'; }   void case3() { std::array<double, 15> 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 }; std::array<double, 15> a{ 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83 };   Matrix<3, 15> x; for (size_t i = 0; i < 15; i++) { x.set(0, i, 1.0); } x.set(1, a); for (size_t i = 0; i < 15; i++) { x.set(2, i, a[i] * a[i]); }   auto v = multiple_regression(y, x); std::cout << v << '\n'; }   int main() { case1(); case2(); case3();   return 0; }
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.
#Arturo
Arturo
multifact: function [n deg][ if? n =< deg -> n else -> n * multifact n-deg deg ]   loop 1..5 'i [ prints ["Degree" i ":"] loop 1..10 'j [ prints [multifact j i " "] ] print "" ]
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.
#Ada
Ada
with GLib; use GLib; with Gtk.Button; use Gtk.Button; with Gtk.Label; use Gtk.Label; with Gtk.Window; use Gtk.Window; with Gtk.Widget; use Gtk.Widget; with Gtk.Table; use Gtk.Table;   with Gtk.Handlers; with Gtk.Main;   procedure Tell_Mouse is Window : Gtk_Window; Grid  : Gtk_Table; Button : Gtk_Button; Label  : Gtk_Label;   package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); package Return_Handlers is new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);   function Delete_Event (Widget : access Gtk_Widget_Record'Class) return Boolean is begin return False; end Delete_Event;   procedure Destroy (Widget : access Gtk_Widget_Record'Class) is begin Gtk.Main.Main_Quit; end Destroy;   procedure Clicked (Widget : access Gtk_Widget_Record'Class) is X, Y : GInt; begin Get_Pointer (Window, X, Y); Set_Text (Label, "At" & GInt'Image (X) & GInt'Image (Y)); end Clicked;   begin Gtk.Main.Init; Gtk.Window.Gtk_New (Window); Gtk_New (Grid, 1, 2, False); Add (Window, Grid); Gtk_New (Label); Attach (Grid, Label, 0, 1, 0, 1); Gtk_New (Button, "Click me"); Attach (Grid, Button, 0, 1, 1, 2); Return_Handlers.Connect ( Window, "delete_event", Return_Handlers.To_Marshaller (Delete_Event'Access) ); Handlers.Connect ( Window, "destroy", Handlers.To_Marshaller (Destroy'Access) ); Handlers.Connect ( Button, "clicked", Handlers.To_Marshaller (Clicked'Access) ); Show_All (Grid); Show (Window);   Gtk.Main.Main; end Tell_Mouse;
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::AllUtils <firstidx max>; use ntheory qw/fromdigits todigitstring primes/;   my(%prime_base, %max_bases, $l);   my $chars = 5; my $upto = fromdigits( '1' . 'Z' x $chars, 36); my @primes = @{primes( $upto )};   for my $base (2..36) { my $n = todigitstring($base-1, $base) x $chars; my $threshold = fromdigits($n, $base); my $i = firstidx { $_ > $threshold } @primes; map { push @{$prime_base{ todigitstring($primes[$_],$base) }}, $base } 0..$i-1; }   $l = length and $max_bases{$l} = max( $#{$prime_base{$_}}, $max_bases{$l} // 0 ) for keys %prime_base;   for my $m (1 .. $chars) { say "$m character strings that are prime in maximum bases: ", 1+$max_bases{$m}; for (sort grep { length($_) == $m } keys %prime_base) { my @bases = @{($prime_base{$_})[0]}; say "$_: " . join ' ', @bases if $max_bases{$m} eq $#bases; } say '' }
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
#EasyLang
EasyLang
subr show_sol print "Solution " & n_sol print "" for i range n write " " for j range n if j = x[i] write "Q " else write ". " . . print "" . print "" . subr test ok = 1 for i range y if x[y] = x[i] or abs (x[i] - x[y]) = abs (y - i) ok = 0 . . . n = 8 len x[] n y = 0 x[0] = 0 while y >= 0 call test if ok = 1 and y + 1 <> n y += 1 x[y] = 0 else if ok = 1 n_sol += 1 if n_sol <= 1 call show_sol . . while y >= 0 and x[y] = n - 1 y -= 1 . if y >= 0 x[y] += 1 . . . print n_sol & " solutions"
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)).
#Maxima
Maxima
zn_order(37, 1000); /* 100 */   zn_order(10^100 + 1, 7919); /* 3959 */   zn_order(10^1000 + 1, 15485863); /* 15485862 */   zn_order(10^10000 - 1, 22801763489); /* 22801763488 */   zn_order(13, 1 + 10^80); /* 109609547199756140150989321269669269476675495992554276140800 */   zn_order(11, 1 + 10^100); /* 2583496112724752500580158969425549088007844580826869433740066152289289764829816356800 */
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)).
#Nim
Nim
import strformat import bignum   type PExp = tuple[prime: Int; exp: uint]   let one = newInt(1) two = newInt(2) ten = newInt(10)     func sqrt(n: Int): Int = var s = n while true: result = s s = (n div result + result) shr 1 if s >= result: break     proc factor(n: Int): seq[PExp] = var n = n var e = 0u while n.bit(e) == 0: inc e if e != 0: n = n shr e result.add (two, e) var s = sqrt(n) var d = newInt(3) while n > one: if d > s: d = n e = 0u while true: let (q, r) = divMod(n, d) if not r.isZero: break n = q inc e if e != 0: result.add (d.clone, e) s = sqrt(n) inc d, two     proc moBachShallit58(a, n: Int; pf: seq[PExp]): Int = let n = abs(n) let n1 = n - one result = newInt(1) for pe in pf: let y = n1 div pe.prime.pow(pe.exp) var o = 0u var x = a.exp(y.toInt.uint, n) while x > one: x = x.exp(pe.prime.toInt.uint, n) inc o var o1 = pe.prime.pow(o) o1 = o1 div gcd(result, o1) result *= o1     proc moTest(a, n: Int) = if n.probablyPrime(25) == 0: echo "Not computed. Modulus must be prime for this algorithm." return   stdout.write if a.bitLen < 100: &"ord({a})" else: "ord([big])" stdout.write if n.bitlen < 100: &" mod {n}" else: " mod [big]" let mob = moBachShallit58(a, n, factor(n - one)) echo &" = {mob}"     when isMainModule: moTest(newInt(37), newInt(3343))   var b = ten.pow(100) + one motest(b, newInt(7919))   b = ten.pow(1000) + one moTest(b, newInt("15485863"))   b = ten.pow(10000) - one moTest(b, newInt("22801763489"))   moTest(newInt("1511678068"), newInt("7379191741"))   moTest(newInt("3047753288"), newInt("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.
#PureBasic
PureBasic
#Def_p=0.001   Procedure.d Nth_root(n.i, A.d, p.d=#Def_p) Protected Dim x.d(1) x(0)=A: x(1)=A/n While Abs(x(1)-x(0))>p x(0)=x(1) x(1)=((n-1.0)*x(1)+A/Pow(x(1),n-1.0))/n Wend ProcedureReturn x(1) EndProcedure   ;////////////////////////////// Debug "125'th root of 5642 is" Debug Pow(5642,1/125) Debug "First estimate is:" Debug Nth_root(125,5642) Debug "And better:" Debug Nth_root(125,5642,0.00001)
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.
#Julia
Julia
using Printf
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Tcl
Tcl
proc isNarcissistic {n} { set m [string length $n] for {set t 0; set N $n} {$N} {set N [expr {$N / 10}]} { incr t [expr {($N%10) ** $m}] } return [expr {$n == $t}] }   proc firstNarcissists {target} { for {set n 0; set count 0} {$count < $target} {incr n} { if {[isNarcissistic $n]} { incr count lappend narcissists $n } } return $narcissists }   puts [join [firstNarcissists 25] ","]
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#jq
jq
def sigma( stream ): reduce stream as $x (0; . + $x ) ;   def ismunchausen: def digits: tostring | split("")[] | tonumber; . == sigma(digits | pow(.;.));   # Munchausen numbers from 1 to 5000 inclusive: range(1;5001) | select(ismunchausen)
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).
#Factor
Factor
DEFER: F : M ( n -- n' ) dup 0 = [ dup 1 - M F - ] unless ; : F ( n -- n' ) dup 0 = [ drop 1 ] [ dup 1 - F M - ] if ;
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#UNIX_Shell
UNIX Shell
multisplit() { local str=$1 shift local regex=$( IFS='|'; echo "$*" ) local sep while [[ $str =~ $regex ]]; do sep=${BASH_REMATCH[0]} words+=( "${str%%${sep}*}" ) seps+=( "$sep" ) str=${str#*$sep} done words+=( "$str" ) }   words=() seps=()   original="a!===b=!=c" recreated=""   multisplit "$original" "==" "!=" "="   for ((i=0; i<${#words[@]}; i++)); do printf 'w:"%s"\ts:"%s"\n' "${words[i]}" "${seps[i]}" recreated+="${words[i]}${seps[i]}" done   if [[ $original == $recreated ]]; then echo "successfully able to recreate original string" fi
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
#Groovy
Groovy
def createFoos1 = { n -> (0..<n).collect { new Foo() } }
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
#Haskell
Haskell
replicateM n makeTheDistinctThing
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
#Icon_and_Unicon
Icon and Unicon
  items_wrong := list (10, []) # prints '0' for size of each item every item := !items_wrong do write (*item) # after trying to add an item to one of the lists push (items_wrong[1], 2) # now prints '1' for size of each item every item := !items_wrong do write (*item)  
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
#AWK
AWK
  # syntax: GAWK --bignum -f MOTZKIN_NUMBERS.AWK BEGIN { print(" n Motzkin[n] prime") limit = 41 m[0] = m[1] = 1 for (i=2; i<=limit; i++) { m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2) } for (i=0; i<=limit; i++) { printf("%2d %18d %3d\n",i,m[i],is_prime(m[i])) } exit(0) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }  
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
#BASIC256
BASIC256
dim M(42) M[0] = 1 : M[1] = 1 print rjust("1",18) : print rjust("1",18)   for n = 2 to 41 M[n] = M[n-1] for i = 0 to n-2 M[n] += M[i]*M[n-2-i] next i print rjust(string(M[n]),18); chr(9); if isPrime(M[n]) then print "is a prime" else print next n end   function isPrime(v) if v <= 1 then return False for i = 2 to int(sqr(v)) if v % i = 0 then return False next i return True end function
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#AutoHotkey
AutoHotkey
MTF_Encode(string){ str := "abcdefghijklmnopqrstuvwxyz" loop, parse, string code .= (A_Index>1 ? ",":"") . InStr(str, A_LoopField) - 1 , str := A_LoopField . StrReplace(str, A_LoopField) return code }   MTF_Decode(code){ str := "abcdefghijklmnopqrstuvwxyz" loop, parse, code, `, string .= (letter := SubStr(str, A_LoopField+1, 1)) , str := letter . StrReplace(str, letter) return string }  
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).
#D
D
import std.stdio;   /* * Using just what is built-in, D only supports single dimension arrays. Like other languages, arrays can be built up as jagged arrays. * Arrays can either be created with a fixed size, or dynamically with support for resizing. */ void nativeExample() { int[3] staticArray; // Statically allocated array. Will only contain three elements, accessed from 0 to 2 inclusive. staticArray[0] = 1; staticArray[1] = 2; staticArray[2] = 3; writeln("Static array: ", staticArray);   int[] dynamicArray; // Dynamically allocated array. dynamicArray.length = 3; // The array can be resized at runtime. If the number elements exceeds the allocated memory, new memory will be given from the heap. dynamicArray[0] = 4; dynamicArray[1] = 5; dynamicArray[2] = 6; dynamicArray ~= 7; // New elements can be concatenated. writeln("Dynamic array: ", dynamicArray); }   /* * Multi-dimensional arrays can be created as custom types (classes or structs). They can have as many dimensions as are written for support. * The indexes can either be standard 0-n, or arbitrary m-n as needed. This example shows just a two dimensional example with standard indexes. * As few or as many of these pieces can be implemented as desired (compile-time error is given if a feature is not supported). */ struct Matrix(T) { // A dynamic array for the actual storage. private: T[] source; uint rows, cols; // dimensions   public: this(uint m, uint n) { rows = m; cols = n; source.length = m*n; }   /// Allow for short access to limits, e.g. a[$-1,$-1] int opDollar(size_t pos : 0)() const { return rows; } int opDollar(size_t pos : 1)() const { return cols; }   /// Allow for indexing to read a value, e.g. a[0,0] T opIndex(int i, int j) const in { assert(0 <= i && i <= rows, "Row index out of bounds"); assert(0 <= j && j <= cols, "Col index out of bounds"); } body { return source[i*rows + j]; }   /// Allow for assigning elements, e.g. a[0,0] = c T opIndexAssign(T elem, int i, int j) in { assert(0 <= i && i <= rows, "Row index out of bounds"); assert(0 <= j && j <= cols, "Col index out of bounds"); } body { auto index = rows*i + j; T prev = source[index]; source[index] = elem; return prev; }   /// Allow for applying operations and assigning elements, e.g. a[0,0] += c T opIndexOpAssign(string op)(T elem, int i, int j) { auto index = rows*i + j; T prev = source[index]; mixin("source[index] " ~ op ~ "= elem;"); return prev; }   /// Support slicing, shown below auto opSlice(size_t pos)(int a, int b) in { assert(0 <= a && a <= opDollar!pos); assert(0 <= b && b <= opDollar!pos); } body { if (pos == 0) { } else { assert(0 <= a && a <= cols, "Col slice out of bounds"); assert(0 <= b && b <= cols, "Col slice out of bounds"); } return [a, b]; }   /// Allow for getting a sub-portion of the matrix, e.g. [0..2, 2..4] auto opIndex(int[] a, int[] b) const { auto t = Matrix!T(a.length, b.length); foreach(i, ia; a) { foreach(j, jb; b) { t[i, j] = this[ia, jb]; } } return t; } auto opIndex(int[] a, int b) const { return opIndex(a, [b,b+1]); } auto opIndex(int a, int[] b) const { return opIndex([a,a+1], b); }   /// Assign a single value to every element void opAssign(T value) { source[0..$] = value; }   /// Assign a single element to a subset of the Matrix void opIndexAssign(T elem, int[] a, int[] b) { for (int i=a[0]; i<a[1]; i++) { auto start = rows * i; source[start+b[0]..start+b[1]] = elem; } } void opIndexAssign(T elem, int[] a, int b) { opIndexAssign(elem, a, [b, b+1]); } void opIndexAssign(T elem, int a, int[] b) { opIndexAssign(elem, [a, a+1], b); }   /// Define how to write Matrix values as a string. Only does a simple string representation void toString(scope void delegate(const(char)[]) sink) const { import std.format;   sink("["); foreach (i; 0..opDollar!0) { sink("["); foreach (j; 0..opDollar!1) { formattedWrite(sink, "%s", opIndex(i,j)); if (j < cols-1) sink(", "); } if (i < rows-1) sink("]\n "); else sink("]"); } sink("]"); } }   void customArray() { auto multi = Matrix!int(3, 3); writeln("Create a multidimensional object:\n", multi); writeln("Access an element: ", multi[0,0]); multi[0,0] = 1; writeln("Assign an element: ", multi[0,0]); multi[0,0] += 2; writeln("Arithmetic on an element: ", multi[0,0]); writeln("Slice a matrix:\n", multi[0..2, 0..2]); multi = 5; writeln("Assign all elements:\n", multi); multi[0..2,1..3] = 4; writeln("Assign some elements:\n", multi); }   void main() { nativeExample(); customArray(); }
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).
#C.23
C#
using System; using MathNet.Numerics.LinearRegression; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double;   class Program { static void Main(string[] args) { var col = DenseVector.OfArray(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 }); var X = DenseMatrix.OfColumns(new Vector<double>[] { col.PointwisePower(0), col, col.PointwisePower(2) }); var y = DenseVector.OfArray(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 β = MultipleRegression.QR(X, y); Console.WriteLine(β); } }
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.
#AutoHotkey
AutoHotkey
Loop, 5 { Output .= "Degree " (i := A_Index) ": " Loop, 10 Output .= MultiFact(A_Index, i) (A_Index = 10 ? "`n" : ", ") } MsgBox, % Output   MultiFact(n, d) { Result := n while 1 < n -= d Result *= n return, Result }
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.
#AmigaBASIC
AmigaBASIC
MOUSE ON   WHILE 1 m=MOUSE(0) PRINT MOUSE(1),MOUSE(2) WEND
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.
#AppleScript
AppleScript
use framework "AppKit"   tell application id "com.apple.SystemEvents" to tell ¬ (the first process where it is frontmost) to ¬ set {x, y} to the front window's position   tell the current application set H to NSHeight(its NSScreen's mainScreen's frame) tell [] & its NSEvent's mouseLocation set item 1 to (item 1) - x set item 2 to H - (item 2) - y set coords to it as point end tell end tell   log coords
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Phix
Phix
with javascript_semantics constant maxbase=36 -- or 62 function evalpoly(integer x, sequence p) integer result = 0 for y=1 to length(p) do result = result*x + p[y] end for return result end function function stringify(sequence digits) string res = repeat('0',length(digits)) for i=1 to length(digits) do integer di = digits[i] res[i] = di + iff(di<=9?'0':iff(di<36?'A'-10:'a'-36)) end for return res end function procedure max_prime_bases(integer ndig, maxbase) atom t0 = time(), t1 = time()+1 sequence maxprimebases = {}, digits = repeat(0,ndig) integer maxlen = 0, limit = power(10,ndig), maxdigit = maxbase if ndig>1 then digits[1] = 1 end if while true do for i=length(digits) to 1 by -1 do integer di = digits[i]+1 if di<maxdigit then -- (or 9, see below) digits[i] = di exit else di = 0 digits[i] = 0 end if end for integer minbase = max(digits)+1, maxposs = maxbase-minbase+1 if minbase=1 then exit end if -- (ie we just wrapped round to all 0s) sequence bases = {} for base=minbase to maxbase do if is_prime(evalpoly(base,digits)) then bases &= base else maxposs -= 1 if maxposs<maxlen then exit end if -- (a 5-fold speedup) end if end for integer l = length(bases) if l>maxlen then maxlen = l maxdigit = maxbase-maxlen -- (around 20-fold speedup) maxprimebases = {} end if if l=maxlen then maxprimebases &= {{stringify(digits), bases}} end if if platform()!=JS and time()>t1 then progress("%V\r",{digits}) t1 = time()+1 end if end while string e = elapsed(time()-t0) printf(1,"%d character numeric strings that are prime in %d bases (%s):\n",{ndig,maxlen,e}) for i=1 to length(maxprimebases) do printf(1," %s => %V\n", maxprimebases[i]) end for printf(1,"\n") end procedure for n=1 to iff(platform()=JS or maxbase>36?4:6) do max_prime_bases(n, maxbase) end for
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
#EchoLisp
EchoLisp
  ;; square num is i + j*N (define-syntax-rule (sq i j) (+ i (* j N)))   ;; compute diag number for each square (define (do-diag1 i0 j0 dnum into: dnum1 N) ;; ++i and ++j diags (for [(i (in-range i0 N)) (j (in-range j0 N))] ;;(writeln i j 'diag1 dnum) (vector-set! dnum1 (sq i j) dnum)))   (define (do-diag2 i0 j0 dnum into: dnum2 N) ;; --i and ++j diags (for [(i (in-range i0 -1 -1)) (j (in-range j0 N))] ;; (writeln i j 'diag2 dnum) (vector-set! dnum2 (sq i j) dnum)))   (define (init-diags dnum1 dnum2 N) (define dnum 0) (for ((j N)) (do-diag1 0 j dnum dnum1 N) (++ dnum)) (for ((i (in-range 1 N))) (do-diag1 i 0 dnum dnum1 N) (++ dnum)) (set! dnum 0) (for ((j N)) (do-diag2 (1- N) j dnum dnum2 N) (++ dnum)) (for ((i (1- N))) (do-diag2 i 0 dnum dnum2 N) (++ dnum))) ;; end boring diags part   (define (q-search i N col diag1 diag2 dnum1 dnum2 &hits (ns)) (cond [(= i N) (set-box! &hits (1+ (unbox &hits))) ] ;; (writeln 'HIT col) [else   (for ((j N)) (set! ns (sq i j)) #:continue (or [col j] [diag1 [dnum1 ns]] [diag2 [dnum2 ns]]) (vector-set! col j i) ;; move (vector-set! diag1 [dnum1 ns] #t) ;; flag busy diagonal (vector-set! diag2 [dnum2 ns] #t) (q-search (1+ i) N col diag1 diag2 dnum1 dnum2 &hits) (vector-set! col j #f) ;; unmove (vector-set! diag1 [dnum1 ns] #f) (vector-set! diag2 [dnum2 ns] #f)) ]))   (define (q-count (N 8)) (define dnum1 (make-vector (* N N))) (define dnum2 (make-vector (* N N ))) (init-diags dnum1 dnum2 N)   (define diag1 (make-vector (* 2 N) #f)) ; busy diag's (define diag2 (make-vector (* 2 N) #f)) (define col (make-vector N #f)) (define &hits (box 0))     (q-search 0 N col diag1 diag2 dnum1 dnum2 &hits) (unbox &hits))   (define (task up-to-n) (for ((i up-to-n)) (writeln i ' ♕ (q-count i) 'solutions)))  
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)).
#PARI.2FGP
PARI/GP
znorder(Mod(a,n))
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)).
#Perl
Perl
use ntheory qw/znorder/; say znorder(54, 100001); use bigint; say znorder(11, 1 + 10**100);
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.
#Python
Python
from decimal import Decimal, getcontext   def nthroot (n, A, precision): getcontext().prec = precision   n = Decimal(n) x_0 = A / n #step 1: make a while guess. x_1 = 1 #need it to exist before step 2 while True: #step 2: x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1)))) if x_0 == x_1: return x_1
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Kotlin
Kotlin
fun Int.ordinalAbbrev() = if (this % 100 / 10 == 1) "th" else when (this % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" }   fun IntRange.ordinalAbbrev() = map { "$it" + it.ordinalAbbrev() }.joinToString(" ")   fun main(args: Array<String>) { listOf((0..25), (250..265), (1000..1025)).forEach { println(it.ordinalAbbrev()) } }
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#UNIX_Shell
UNIX Shell
function narcissistic { integer n=$1 len=${#n} sum=0 i for ((i=0; i<len; i++)); do (( sum += pow(${n:i:1}, len) )) done (( sum == n )) }   nums=() for ((n=0; ${#nums[@]} < 25; n++)); do narcissistic $n && nums+=($n) done echo "${nums[*]}" echo "elapsed: $SECONDS"
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
#Julia
Julia
println([n for n = 1:5000 if sum(d^d for d in digits(n)) == n])
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#FALSE
FALSE
[$[$1-f;!m;!-1-]?1+]f: [$[$1-m;!f;!- ]? ]m: [0[$20\>][\$@$@!." "1+]#%%]t: f; t;!" "m; t;!
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#VBScript
VBScript
  Function multisplit(s,sep) arr_sep = Split(sep,"|") For i = 0 To UBound(arr_sep) arr_s = Split(s,arr_sep(i)) s = Join(arr_s,",") Next multisplit = s End Function   Function multisplit_extra(s,sep) Set dict_sep = CreateObject("Scripting.Dictionary") arr_sep = Split(sep,"|") For i = 0 To UBound(arr_sep) dict_sep.Add i,"(" & arr_sep(i) & ")" arr_s = Split(s,arr_sep(i)) s = Join(arr_s,i) Next For Each key In dict_sep.Keys s = Replace(s,key,dict_sep.Item(key)) Next multisplit_extra = s End Function   WScript.StdOut.Write "Standard: " & multisplit("a!===b=!=c","!=|==|=") WScript.StdOut.WriteLine WScript.StdOut.Write "Extra Credit: " & multisplit_extra("a!===b=!=c","!=|==|=") WScript.StdOut.WriteLine
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Wren
Wren
import "/pattern" for Pattern import "/fmt" for Fmt   var input = "a!===b=!=c" var p = Pattern.new("[/=/=|!/=|/=]") var separators = p.findAll(input) System.print("The separators matched and their starting/ending indices are:") for (sep in separators) { System.print("  %(Fmt.s(-4, Fmt.q(sep.text))) between %(sep.span)") } var parts = p.splitAll(input) System.print("\nThe substrings between the separators are:") System.print(parts.map { |p| (p != "") ? Fmt.q(p) : "empty string" }.toList)
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
#J
J
i.
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
#Java
Java
Foo[] foos = new Foo[n]; // all elements initialized to null for (int i = 0; i < foos.length; i++) foos[i] = new Foo();   // incorrect version: Foo[] foos_WRONG = new Foo[n]; Arrays.fill(foos, new Foo()); // new Foo() only evaluated once
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
#JavaScript
JavaScript
var a = new Array(n); for (var i = 0; i < n; i++) a[i] = new Foo();
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
#Burlesque
Burlesque
41rz{{2./}c!rz2?*{nr}c!\/2?/{JJ2.*J#Rnr#r\/+.nr.-}m[?*++it+.}m[Jp^#R{~]}5E!{fCL[1==}f[#r
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
#C
C
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; }   int main() { setlocale(LC_ALL, ""); printf(" n M(n) Prime?\n"); printf("-----------------------------------\n"); uint64_t m0 = 1, m1 = 1; for (uint64_t i = 0; i < 42; ++i) { uint64_t m = i > 1 ? (m1 * (2 * i + 1) + m0 * (3 * i - 3)) / (i + 2) : 1; printf("%2llu%'25llu  %s\n", i, m, is_prime(m) ? "true" : "false"); m0 = m1; m1 = m; } }
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.)
#Bracmat
Bracmat
( encode = string symboltable .  !arg:(?string.?symboltable) & vap $ ( ( = A Z i .  !symboltable:?A [?i !arg ?Z & !arg !A !Z:?symboltable & !i ) . !string ) ) & ( decode = indices symboltable .  !arg:(?indices.?symboltable) & str $ ( map $ ( ( = A Z symbol .  !symboltable:?A [!arg %?symbol ?Z & !symbol !A !Z:?symboltable & !symbol ) . !indices ) ) ) & ( test = string symboltable encoded decoded .  !arg:(?string.?symboltable) & put$str$("input:" !string ", ") & encode$(!string.!symboltable):?encoded & put$("encoded:" !encoded ", ") & decode$(!encoded.!symboltable):?decoded & put$str$("decoded:" !decoded ", ") & (  !string:!decoded & out$OK | out$WRONG ) ) & a b c d e f g h i j k l m n o p q r s t y v w x y z  : ?symboltable & test$(broood.!symboltable) & test$(bananaaa.!symboltable) & test$(hiphophiphop.!symboltable)
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. 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.)
#C
C
#include<stdio.h> #include<stdlib.h> #include<string.h>   #define MAX_SIZE 100   int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); //returns pointer to location of char c in string str shift=q-p; // no of characters from 0 to position of c in str strncpy(str+1,p,shift); str[0]=c; free(p); // printf("\n%s\n",str); return shift; }   void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf("there is an error"); sym[i]=c; } sym[size]='\0'; }   void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } }   int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1;   encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0;   decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0;   free(sym2); free(pass2);   return val; }   int main() { char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf("%s : [",sym[i]); for(j=0;j<len;j++) printf("%d ",pass[j]); printf("]\n"); if(check(sym[i],len,pass)) printf("Correct :)\n"); else printf("Incorrect :(\n"); } return 0; }
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#EchoLisp
EchoLisp
(require 'math) ;; dot-product   ;; dims = vector #(d1 d2 .....) ;; allocates a new m-array (define (make-m-array dims (init 0)) ;; allocate 2 + d1*d2*d3... consecutive cells (define msize (apply * (vector->list dims))) (define m-array (make-vector (+ 2 msize) init))   ;; compute displacements vector once for all ;; m-array[0] = [1 d1 d1*d2 d1*d2*d3 ...] (define disps (vector-rotate! (vector-dup dims) 1)) (vector-set! disps 0 1) (for [(i(in-range 1 (vector-length disps)) )] (vector-set! disps i (* [disps i] [disps (1- i)]))) (vector-set! m-array 0 disps)   (vector-set! m-array 1 dims) ;; remember dims m-array)   ;; from indices = #(i j k ...) to displacement (define-syntax-rule (m-array-index ma indices) (+ 2 (dot-product (ma 0) indices)))   ;; check i < d1, j < d2, ... (define (m-array-check ma indices) (for [(dim [ma 1]) (idx indices)] #:break (>= idx dim) => (error 'm-array:bad-index (list idx '>= dim))))   ;; -------------------- ;; A P I ;; -------------------- ;; indices is a vector #[i j k ...] ;; (make-m-array (dims) [init])   (define (m-array-dims ma) [ma 1])   ; return ma[indices] (define (m-array-ref ma indices) (m-array-check ma indices) [ma (m-array-index ma indices)]) ; sets ma[indices] (define (m-array-set! ma indices value ) (m-array-check ma indices) (vector-set! ma (m-array-index ma indices) value))
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).
#Common_Lisp
Common Lisp
  ;; Solve a linear system AX=B where A is symmetric and positive definite, so it can be Cholesky decomposed. (defun linsys (A B) (let* ((n (car (array-dimensions A))) (m (cadr (array-dimensions B))) (y (make-array n :element-type 'long-float :initial-element 0.0L0)) (X (make-array `(,n ,m) :element-type 'long-float :initial-element 0.0L0)) (L (chol A))) ; A=LL'   (loop for col from 0 to (- m 1) do ;; Forward substitution: y = L\B (loop for k from 0 to (- n 1) do (setf (aref y k) (/ (- (aref B k col) (loop for j from 0 to (- k 1) sum (* (aref L k j) (aref y j)))) (aref L k k))))   ;; Back substitution. x=L'\y (loop for k from (- n 1) downto 0 do (setf (aref X k col) (/ (- (aref y k) (loop for j from (+ k 1) to (- n 1) sum (* (aref L j k) (aref X j col)))) (aref L k k))))) X))   ;; Solve a linear least squares problem. Ax=b, with A being mxn, with m>n. ;; Solves the linear system A'Ax=A'b. (defun lsqr (A b) (linsys (mmul (mtp A) A) (mmul (mtp A) b)))  
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.
#AWK
AWK
  # syntax: GAWK -f MULTIFACTORIAL.AWK # converted from Go BEGIN { for (k=1; k<=5; k++) { printf("degree %d:",k) for (n=1; n<=10; n++) { printf(" %d",multi_factorial(n,k)) } printf("\n") } exit(0) } function multi_factorial(n,k, r) { r = 1 for (; n>1; n-=k) { r *= n } return(r) }  
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.
#AutoHotkey
AutoHotkey
#i:: ; (Optional) Assigns a hotkey to display window info, Windows+i MouseGetPos, x, y ; Gets x/y pos relative to active window WinGetActiveTitle, WinTitle ; Gets active window title Traytip, Mouse position, x: %x%`ny: %y%`rWindow: %WinTitle%, 4 ; Displays the info as a Traytip for 4 seconds return
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.
#BBC_BASIC
BBC BASIC
MOUSE xmouse%, ymouse%, buttons% PRINT xmouse%, ymouse%
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted to base 6 == 255 173 base 10 converted to base 8 == 255 353 base 10 converted to base 12 == 255 467 base 10 converted to base 14 == 255 743 base 10 converted to base 18 == 255 1277 base 10 converted to base 24 == 255 1487 base 10 converted to base 26 == 255 2213 base 10 converted to base 32 == 255 Task Restricted to bases 2 through 36; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base. Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string. Display here, on this page, the string, the count and the list for all of the: 1 character, 2 character, 3 character, and 4 character strings that have the maximum base count that evaluate to that string. Should be no surprise, the string '2' has the largest base count for single character strings. Stretch goal Do the same for the maximum 5 character string.
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   my %prime-base;   my $chars = 4; # for demonstration purposes. Change to 5 for the whole shmegegge.   my $threshold = ('1' ~ 'Z' x $chars).parse-base(36);   my @primes = $sieve.primes($threshold);   %prime-base.push: $_ for (2..36).map: -> $base { $threshold = (($base - 1).base($base) x $chars).parse-base($base); @primes[^(@primes.first: * > $threshold, :k)].race.map: { .base($base) => $base } }   %prime-base.=grep: +*.value.elems > 10;   for 1 .. $chars -> $m { say "$m character strings that are prime in maximum bases: " ~ (my $e = ((%prime-base.grep( *.key.chars == $m )).max: +*.value.elems).value.elems); .say for %prime-base.grep( +*.value.elems == $e ).grep(*.key.chars == $m).sort: *.key; say ''; }
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
#Eiffel
Eiffel
  class QUEENS   create make   feature {NONE} counter: INTEGER   place_queens(board: ARRAY[INTEGER]; level: INTEGER) local i, j: INTEGER safe: BOOLEAN do if level > board.count then counter := counter + 1 else from i := 1 until i > board.count loop safe := True from j := 1 until j = level or not safe loop if (board[j] = i) or (j - level = i - board[j]) or (j - level = board[j] - i) then safe := False end j := j + 1 end if safe then board[level] := i place_queens(board, level + 1) end i := i + 1 end end end   feature possible_positions_of_n_queens(n: INTEGER): INTEGER local board: ARRAY[INTEGER] do create board.make_filled (0, 1, n) counter := 0 place_queens(board, 1) Result := counter end   make local n: INTEGER do io.put_string ("Please enter the number of queens: ") io.read_integer n := io.last_integer print("%NPossible number of placings: " + possible_positions_of_n_queens(n).out + "%N") end 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)).
#Phix
Phix
with javascript_semantics include mpfr.e procedure multi_order(mpz res, a, sequence p_and_k) mpz {pk,t,x,q,pz} = mpz_inits(5) mpz_set_si(res,1) if length(p_and_k)=1 then string {ps} = p_and_k mpz_set_str(pk,ps) mpz_sub_ui(t,pk,1) else atom {p, k} = p_and_k mpz_set_d(pz,p) mpz_pow_ui(pk,pz,k) mpz_pow_ui(t,pz,k-1) mpz_sub_ui(pz,pz,1) mpz_mul(t,t,pz) end if sequence pf = mpz_prime_factors(t) for i=1 to length(pf) do if length(pf[i])=1 then string {fs} = pf[i] mpz_set_str(q,fs) mpz_set(x,q) else {integer qi, integer ei} = pf[i] mpz_set_si(q,qi) mpz_pow_ui(x,q,ei) end if mpz_fdiv_q(x, t, x) mpz_powm(x,a,x,pk) integer guard = 0 while mpz_cmp_si(x,1)!=0 do mpz_mul(res,res,q) mpz_powm(x,x,q,pk) guard += 1 if guard>100 then ?9/0 end if -- (increase if rqd) end while end for x = mpz_free(x) end procedure function multiplicative_order(mpz a, m) mpz res = mpz_init(1), ri = mpz_init() mpz_gcd(ri,a,m) if mpz_cmp_si(ri,1)!=0 then return "(a,m) not coprime" end if sequence pf = mpz_prime_factors(m,10000) -- (increase if rqd) for i=1 to length(pf) do multi_order(ri,a,pf[i]) mpz_lcm(res,res,ri) end for return mpz_get_str(res) end function function shorta(mpz n) string res = mpz_get_str(n) integer lr = length(res) if lr>80 then res[6..-6] = "..." res &= sprintf(" (%d digits)",lr) end if return res end function procedure mo_test(mpz a, n) string res = multiplicative_order(a, n) printf(1,"ord(%s) mod %s = %s\n",{shorta(a),shorta(n),res}) end procedure function i(atom i) return mpz_init(i) end function -- (ugh) function p10(integer e,i) -- init to 10^e+i mpz res = mpz_init() mpz_ui_pow_ui(res,10,e) mpz_add_si(res,res,i) return res end function atom t = time() mo_test(i(3), i(10)) mo_test(i(37), i(1000)) mo_test(i(37), i(10000)) mo_test(i(37), i(3343)) mo_test(i(37), i(3344)) mo_test(i(2), i(1000)) mo_test(p10(100,+1), i(7919)) mo_test(p10(1000,+1), i(15485863)) mo_test(p10(10000,-1), i(22801763489)) mo_test(i(1511678068), i(7379191741)) mo_test(i(3047753288), i(2257683301)) ?"===" mpz b = p10(20,-1) mo_test(i(2), b) mo_test(i(17),b) mo_test(i(54),i(100001)) string s9090 = multiplicative_order(mpz_init(54),mpz_init(100001)) if s9090!="9090" then ?9/0 end if mpz m54 = mpz_init(54), m100001 = mpz_init(100001) mpz_powm_ui(b,m54,9090,m100001) printf(1,"%s\n",mpz_get_str(b)) bool error = false for r=1 to 9090-1 do mpz_powm_ui(b,m54,r,m100001) if mpz_cmp_si(b,1)=0 then printf(1,"mpz_powm_ui(54,%d,100001) gives 1!\n",r) error = true exit end if end for if not error then printf(1,"Everything checks. (%s)\n",{elapsed(time()-t)}) end if
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.
#R
R
nthroot <- function(A, n, tol=sqrt(.Machine$double.eps)) { ifelse(A < 1, x0 <- A * n, x0 <- A / n) repeat { x1 <- ((n-1)*x0 + A / x0^(n-1))/n if(abs(x1 - x0) > tol) x0 <- x1 else break } x1 } nthroot(7131.5^10, 10) # 7131.5 nthroot(7, 0.5) # 49
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.
#Racket
Racket
#lang racket   (define (nth-root number root (tolerance 0.001)) (define (acceptable? next current) (< (abs (- next current)) tolerance))   (define (improve current) (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root))   (define (loop current) (define next-guess (improve current)) (if (acceptable? next-guess current) next-guess (loop next-guess))) (loop 1.0))
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Lambdatalk
Lambdatalk
  {def fnOrdinalForm {lambda {:n} {if {and {<= 11 {% :n 100}} {>= 13 {% :n 100}}} then :nth else :n{A.get {% :n 10} th st nd rd th th th th th th}}}} -> fnOrdinalForm   {S.map fnOrdinalForm {S.serie 0 25}} -> 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th   {S.map fnOrdinalForm {S.serie 250 265}} -> 250th 251st 252nd 253rd 254th 255th 256th 257th 258th 259th 260th 261st 262nd 263rd 264th 265th   {S.map fnOrdinalForm {S.serie 1000 1025}} -> 1000th 1001st 1002nd 1003rd 1004th 1005th 1006th 1007th 1008th 1009th 1010th 1011th 1012th 1013th 1014th 1015th 1016th 1017th 1018th 1019th 1020th 1021st 1022nd 1023rd 1024th 1025th  
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#VBA
VBA
Private Function narcissistic(n As Long) As Boolean Dim d As String: d = CStr(n) Dim l As Integer: l = Len(d) Dim sumn As Long: sumn = 0 For i = 1 To l sumn = sumn + (Mid(d, i, 1) - "0") ^ l Next i narcissistic = sumn = n End Function   Public Sub main() Dim s(24) As String Dim n As Long: n = 0 Dim found As Integer: found = 0 Do While found < 25 If narcissistic(n) Then s(found) = CStr(n) found = found + 1 End If n = n + 1 Loop Debug.Print Join(s, ", ") End Sub
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
#Kotlin
Kotlin
// version 1.0.6   val powers = IntArray(10)   fun isMunchausen(n: Int): Boolean { if (n < 0) return false var sum = 0L var nn = n while (nn > 0) { sum += powers[nn % 10] if (sum > n.toLong()) return false nn /= 10 } return sum == n.toLong() }   fun main(args: Array<String>) { // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose for (i in 1..9) powers[i] = Math.pow(i.toDouble(), i.toDouble()).toInt()   // check numbers 0 to 500 million println("The Munchausen numbers between 0 and 500 million are:") for (i in 0..500000000) if (isMunchausen(i))print ("$i ") println() }
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).
#Fantom
Fantom
  class Main { static Int f (Int n) { if (n <= 0) // ensure n > 0 return 1 else return n - m(f(n-1)) }   static Int m (Int n) { if (n <= 0) // ensure n > 0 return 0 else return n - f(m(n-1)) }   public static Void main () { 50.times |Int n| { echo (f(n)) } } }  
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Yabasic
Yabasic
t$ = "a!===b=!=c" s$ = "==,!=,="   dim n$(1)   n = token(s$, n$(), ",") dim p(n)   do l = len(t$) j = 0 for i = 1 to n p(i) = instr(t$, n$(i)) if p(i) and p(i) < l then l = p(i) : j = i end if next if not j print t$ : break print left$(t$, l - 1), " with separator ", n$(j) t$ = right$(t$, len(t$) - (l + len(n$(j))) + 1) loop
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#zkl
zkl
fcn multisplit(text, sep){ lastmatch := i := 0; matches := List(); while(i < text.len()){ foreach j,s in ([0..].zip(sep)){ if(i == text.find(s,i)){ if(i > lastmatch) matches.append(text[lastmatch,i-lastmatch]); matches.append(T(j,i)); # Replace the string containing the matched separator with a tuple of which separator and where in the string the match occured lastmatch = i + s.len(); i += s.len()-1; break; } } i += 1; } if(i > lastmatch) matches.append(text[lastmatch,i-lastmatch]); return(matches); }
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
#jq
jq
  def Array(atype; n): if atype == "number" then [ range(0;n) ] elif atype == "object" then [ range(0;n)| {"value": . } ] elif atype == "array" then [ range(0;n)| [.] ] elif atype == "string" then [ range(0;n)| tostring ] elif atype == "boolean" then if n == 0 then [] elif n == 1 then [false] elif n==2 then [false, true] else error("there are only two boolean values") end elif atype == "null" then if n == 0 then [] elif n == 1 then [null] else error("there is only one null value") end else error("\(atype) is not a jq type") end;   # Example:   Array("object"; 4)
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
#Julia
Julia
  foo() = rand() # repeated calls change the result with each call repeat([foo()], outer=5) # but this only calls foo() once, clones that first 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
#Kotlin
Kotlin
// version 1.1.2   class Foo { val id: Int   init { id = ++numCreated // creates a distict id for each object }   companion object { private var numCreated = 0 } }   fun main(args: Array<String>) { val n = 3 // say   /* correct approach - creates references to distinct objects */ val fooList = List(n) { Foo() } for (foo in fooList) println(foo.id)   /* incorrect approach - creates references to same object */ val f = Foo() val fooList2 = List(n) { f } for (foo in fooList2) println(foo.id) }
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
#C.23
C#
using System; using BI = System.Numerics.BigInteger;   class Program {   // has multiple factors (other than 1 and x) static bool hmf(BI x) { if (x < 4) return x == 1; if ((x & 1) == 0 || x % 3 == 0) return true; int l = (int)Math.Sqrt((double)x); // this limit works because the 40th to 80th Motzkin numbers have factors of 2 or 3 for (int j = 5, d = 4; j <= l; j += d = 6 - d) if (x % j == 0) return x > j; return false; }   static void Main(string[] args) { BI a = 0, b = 1, t; int n = 1, s = 0, d = 1, c = 0, f = 1; while (n <= 80) Console.WriteLine("{0,46:n0} {1}", t = b / n++, hmf(t) ? "" : "is prime.", t = b, b = ((c += d * 3 + 3) * a + (f += d * 2 + 3) * b) / (s += d += 2), a = t); } }
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. Encoding algorithm for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table Decoding algorithm # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table Example Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   a-to-z Input Output SymbolTable broood 1 'abcdefghijklmnopqrstuvwxyz' broood 1 17 'bacdefghijklmnopqrstuvwxyz' broood 1 17 15 'rbacdefghijklmnopqstuvwxyz' broood 1 17 15 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 'orbacdefghijklmnpqstuvwxyz' broood 1 17 15 0 0 5 'orbacdefghijklmnpqstuvwxyz' Decoding the indices back to the original symbol order: Input Output SymbolTable 1 17 15 0 0 5 b 'abcdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 br 'bacdefghijklmnopqrstuvwxyz' 1 17 15 0 0 5 bro 'rbacdefghijklmnopqstuvwxyz' 1 17 15 0 0 5 broo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 brooo 'orbacdefghijklmnpqstuvwxyz' 1 17 15 0 0 5 broood 'orbacdefghijklmnpqstuvwxyz' Task   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   a-to-z   as above.   Show the strings and their encoding here.   Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#C.23
C#
  using System; using System.Collections.Generic; using System.Text;   namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); }   private static void moveToFront(int charIndex) { char toFront = symbolTable[charIndex]; for (int j = charIndex; j > 0; j--) { symbolTable[j] = symbolTable[j - 1]; } symbolTable[0] = toFront; }   public static int[] Encode(string input) { setSymbolTable(); var output = new List<int>(); foreach (char c in input) { for (int i = 0; i < 26; i++) { if (symbolTable[i] == c) { output.Add(i); moveToFront(i); break; } } } return output.ToArray(); }   public static string Decode(int[] input) { setSymbolTable(); var output = new StringBuilder(input.Length); foreach (int n in input) { output.Append(symbolTable[n]); moveToFront(n); } return output.ToString(); }   static void Main(string[] args) { string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" }; int[] encoding; foreach (string s in testInputs) { Console.WriteLine($"Encoding for '{s}':"); encoding = Encode(s); foreach (int i in encoding) { Console.Write($"{i} "); } Console.WriteLine($"\nDecoding for '{s}':"); Console.WriteLine($"{Decode(encoding)}\n"); } } } }  
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. Task State if the language supports multi-dimensional arrays in its syntax and usual implementation. State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#Factor
Factor
USING: accessors arrays.shaped io kernel prettyprint sequences ;   ! Create a 4-dimensional array with increasing elements. { 2 3 4 5 } increasing   ! Check if an index is in bounds. { 0 0 0 0 } over shaped-bounds-check   ! Access and print the first element. "First element: " write get-shaped-row-major .   ! Set the first element and show the array. "With first element set to 999:" print 999 { 0 0 0 0 } pick set-shaped-row-major dup .   ! Reshape and show the array. "Reshaped: " print { 5 4 3 2 } reshape .
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).
#Forth
Forth
  4 5 6 7 8 CELL 5 darray test5d \ Creates the array i j k l m test5d \ Returns the address of test5d[ i, j, k, l, m ]   100 i j k l m test5d ! \ Sets contents of test5d[ i, j, k, l, m ] to 100 i j k l m test5d @ \ Gets contents of test5d[ i, j, k, l, m ]  
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , 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).
#D
D
import std.algorithm; import std.array; import std.exception; import std.range; import std.stdio;   public class Matrix { private double[][] data; private size_t rowCount; private size_t colCount;   public this(size_t size) in(size > 0, "Must have at least one element") { this(size, size); }   public this(size_t rows, size_t cols) in(rows > 0, "Must have at least one row") in(cols > 0, "Must have at least one column") { rowCount = rows; colCount = cols;   data = uninitializedArray!(double[][])(rows, cols); foreach (ref row; data) { row[] = 0.0; } }   public this(const double[][] source) { enforce(source.length > 0, "Must have at least one row"); rowCount = source.length;   enforce(source[0].length > 0, "Must have at least one column"); colCount = source[0].length;   data = uninitializedArray!(double[][])(rowCount, colCount); foreach (i; 0 .. rowCount) { enforce(source[i].length == colCount, "All rows must have equal columns"); data[i] = source[i].dup; } }   public auto opIndex(size_t r, size_t c) const { return data[r][c]; }   public auto opIndex(size_t r) const { return data[r]; }   public auto opBinary(string op)(const Matrix rhs) const { static if (op == "*") { auto rc1 = rowCount; auto cc1 = colCount; auto rc2 = rhs.rowCount; auto cc2 = rhs.colCount; enforce(cc1 == rc2, "Cannot multiply if the first columns does not equal the second rows"); auto result = new Matrix(rc1, cc2); foreach (i; 0 .. rc1) { foreach (j; 0 .. cc2) { foreach (k; 0 .. rc2) { result[i, j] += this[i, k] * rhs[k, j]; } } } return result; } else { assert(false, "Not implemented"); } }   public void opIndexAssign(double value, size_t r, size_t c) { data[r][c] = value; }   public void opIndexAssign(const double[] value, size_t r) { enforce(colCount == value.length, "Slice size must match column size"); data[r] = value.dup; }   public void opIndexOpAssign(string op)(double value, size_t r, size_t c) { mixin("data[r][c] " ~ op ~ "= value;"); }   public auto transpose() const { auto rc = rowCount; auto cc = colCount; auto t = new Matrix(cc, rc); foreach (i; 0 .. cc) { foreach (j; 0 .. rc) { t[i, j] = this[j, i]; } } return t; }   public void toReducedRowEchelonForm() { auto lead = 0; auto rc = rowCount; auto cc = colCount; foreach (r; 0 .. rc) { if (cc <= lead) { return; } auto i = r;   while (this[i, lead] == 0.0) { i++; if (rc == i) { i = r; lead++; if (cc == lead) { return; } } }   auto temp = this[i]; this[i] = this[r]; this[r] = temp;   if (this[r, lead] != 0.0) { auto div = this[r, lead]; foreach (j; 0 .. cc) { this[r, j] = this[r, j] / div; } }   foreach (k; 0 .. rc) { if (k != r) { auto mult = this[k, lead]; foreach (j; 0 .. cc) { this[k, j] -= this[r, j] * mult; } } }   lead++; } }   public auto inverse() const { enforce(rowCount == colCount, "Not a square matrix"); auto len = rowCount; auto aug = new Matrix(len, 2 * len); foreach (i; 0 .. len) { foreach (j; 0 .. len) { aug[i, j] = this[i, j]; } // augment identity matrix to right aug[i, i + len] = 1.0; } aug.toReducedRowEchelonForm; auto inv = new Matrix(len); // remove identify matrix to left foreach (i; 0 .. len) { foreach (j; len .. 2 * len) { inv[i, j - len] = aug[i, j]; } } return inv; }   void toString(scope void delegate(const(char)[]) sink) const { import std.format; auto fmt = FormatSpec!char("%s");   put(sink, "["); foreach (i; 0 .. rowCount) { if (i > 0) { put(sink, " ["); } else { put(sink, "["); }   formatValue(sink, this[i, 0], fmt); foreach (j; 1 .. colCount) { put(sink, ", "); formatValue(sink, this[i, j], fmt); }   if (i + 1 < rowCount) { put(sink, "]\n"); } else { put(sink, "]"); } } put(sink, "]"); } }   auto multipleRegression(double[] y, Matrix x) { auto tm = new Matrix([y]); auto cy = tm.transpose; auto cx = x.transpose; return ((x * cx).inverse * x * cy).transpose[0].dup; }   void main() { auto y = [1.0, 2.0, 3.0, 4.0, 5.0]; auto x = new Matrix([[2.0, 1.0, 3.0, 4.0, 5.0]]); auto v = multipleRegression(y, x); v.writeln;   y = [3.0, 4.0, 5.0]; x = new Matrix([ [1.0, 2.0, 1.0], [1.0, 1.0, 2.0] ]); v = multipleRegression(y, x); v.writeln;   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]; auto a = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83]; x = new Matrix([ repeat(1.0, a.length).array, a, a.map!"a * a".array ]); v = multipleRegression(y, x); v.writeln; }