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/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#REXX
REXX
/*REXX program finds the maximum sum of a path of numbers in a pyramid of numbers. */ @.=.; @.1 = 55 @.2 = 94 48 @.3 = 95 30 96 @.4 = 77 71 26 67 @.5 = 97 13 76 38 45 @.6 = 07 36 79 16 37 68 @.7 = 48 07 09 18 70 26 06 @.8 = 18 72 79 46 59 79 29 90 @.9 = 20 76 87 11 32 07 07 49 18 @.10 = 27 83 58 35 71 11 25 57 29 85 @.11 = 14 64 36 96 27 11 58 56 92 18 55 @.12 = 02 90 03 60 48 49 41 46 33 36 47 23 @.13 = 92 50 48 02 36 59 42 79 72 20 82 77 42 @.14 = 56 78 38 80 39 75 02 71 66 66 01 03 55 72 @.15 = 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 @.16 = 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 @.17 = 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 @.18 = 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 #.=0 do r=1 while @.r\==. /*build another version of the pyramid.*/ do k=1 for r; #.r.k=word(@.r, k) /*assign a number to an array number. */ end /*k*/ end /*r*/   do r=r-1 by -1 to 2; p=r-1 /*traipse through the pyramid rows. */ do k=1 for p; _=k+1 /*re─calculate the previous pyramid row*/ #.p.k=max(#.r.k, #.r._) + #.p.k /*replace the previous number. */ end /*k*/ end /*r*/ /*stick a fork in it, we're all done. */ say 'maximum path sum: ' #.1.1 /*show the top (row 1) pyramid number. */
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Lingo
Lingo
put cx_md5_string(str)
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#C.23
C#
using System; using System.Drawing; using System.Drawing.Imaging; using System.Threading; using System.Windows.Forms;   /// <summary> /// Generates bitmap of Mandelbrot Set and display it on the form. /// </summary> public class MandelbrotSetForm : Form { const double MaxValueExtent = 2.0; Thread thread;   static double CalcMandelbrotSetColor(ComplexNumber c) { // from http://en.wikipedia.org/w/index.php?title=Mandelbrot_set const int MaxIterations = 1000; const double MaxNorm = MaxValueExtent * MaxValueExtent;   int iteration = 0; ComplexNumber z = new ComplexNumber(); do { z = z * z + c; iteration++; } while (z.Norm() < MaxNorm && iteration < MaxIterations); if (iteration < MaxIterations) return (double)iteration / MaxIterations; else return 0; // black }   static void GenerateBitmap(Bitmap bitmap) { double scale = 2 * MaxValueExtent / Math.Min(bitmap.Width, bitmap.Height); for (int i = 0; i < bitmap.Height; i++) { double y = (bitmap.Height / 2 - i) * scale; for (int j = 0; j < bitmap.Width; j++) { double x = (j - bitmap.Width / 2) * scale; double color = CalcMandelbrotSetColor(new ComplexNumber(x, y)); bitmap.SetPixel(j, i, GetColor(color)); } } }   static Color GetColor(double value) { const double MaxColor = 256; const double ContrastValue = 0.2; return Color.FromArgb(0, 0, (int)(MaxColor * Math.Pow(value, ContrastValue))); }   public MandelbrotSetForm() { // form creation this.Text = "Mandelbrot Set Drawing"; this.BackColor = System.Drawing.Color.Black; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.MaximizeBox = false; this.StartPosition = FormStartPosition.CenterScreen; this.FormBorderStyle = FormBorderStyle.FixedDialog; this.ClientSize = new Size(640, 640); this.Load += new System.EventHandler(this.MainForm_Load); }   void MainForm_Load(object sender, EventArgs e) { thread = new Thread(thread_Proc); thread.IsBackground = true; thread.Start(this.ClientSize); }   void thread_Proc(object args) { // start from small image to provide instant display for user Size size = (Size)args; int width = 16; while (width * 2 < size.Width) { int height = width * size.Height / size.Width; Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb); GenerateBitmap(bitmap); this.BeginInvoke(new SetNewBitmapDelegate(SetNewBitmap), bitmap); width *= 2; Thread.Sleep(200); } // then generate final image Bitmap finalBitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb); GenerateBitmap(finalBitmap); this.BeginInvoke(new SetNewBitmapDelegate(SetNewBitmap), finalBitmap); }   void SetNewBitmap(Bitmap image) { if (this.BackgroundImage != null) this.BackgroundImage.Dispose(); this.BackgroundImage = image; }   delegate void SetNewBitmapDelegate(Bitmap image);   static void Main() { Application.Run(new MandelbrotSetForm()); } }   struct ComplexNumber { public double Re; public double Im;   public ComplexNumber(double re, double im) { this.Re = re; this.Im = im; }   public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y) { return new ComplexNumber(x.Re + y.Re, x.Im + y.Im); }   public static ComplexNumber operator *(ComplexNumber x, ComplexNumber y) { return new ComplexNumber(x.Re * y.Re - x.Im * y.Im, x.Re * y.Im + x.Im * y.Re); }   public double Norm() { return Re * Re + Im * Im; } }
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Delphi
Delphi
proc inc(word n, order) word: if n=order-1 then 0 else n+1 fi corp proc dec(word n, order) word: if n=0 then order-1 else n-1 fi corp   proc odd_magic_square([*,*]word square) void: word order, x, nx, y, ny, i; order := dim(square,1);   for x from 0 upto order-1 do for y from 0 upto order-1 do square[x,y] := 0 od od;   x := order/2; y := 0; for i from 1 upto order*order do square[x,y] := i; nx := inc(x,order); ny := dec(y,order); if square[nx,ny] = 0 then x := nx; y := ny else y := inc(y,order) fi od corp   proc digit_count(word n) word: word count; count := 0; while n > 0 do count := count + 1; n := n / 10 od; count corp   proc print_magic_square([*,*]word square) void: word order, max, col_size, magic, x, y; order := dim(square,1); max := order*order; col_size := digit_count(max) + 1;   magic := 0; for x from 0 upto order-1 do magic := magic + square[x,0] od;   writeln("Magic square of order ",order," with magic number ",magic,":"); for y from 0 upto order-1 do for x from 0 upto order-1 do write(square[x,y]:col_size) od; writeln() od; writeln() corp   proc main() void: [1,1]word sq1; [3,3]word sq3; [5,5]word sq5; [7,7]word sq7;   odd_magic_square(sq1); odd_magic_square(sq3); odd_magic_square(sq5); odd_magic_square(sq7);   print_magic_square(sq1); print_magic_square(sq3); print_magic_square(sq5); print_magic_square(sq7) corp
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Draco
Draco
proc inc(word n, order) word: if n=order-1 then 0 else n+1 fi corp proc dec(word n, order) word: if n=0 then order-1 else n-1 fi corp   proc odd_magic_square([*,*]word square) void: word order, x, nx, y, ny, i; order := dim(square,1);   for x from 0 upto order-1 do for y from 0 upto order-1 do square[x,y] := 0 od od;   x := order/2; y := 0; for i from 1 upto order*order do square[x,y] := i; nx := inc(x,order); ny := dec(y,order); if square[nx,ny] = 0 then x := nx; y := ny else y := inc(y,order) fi od corp   proc digit_count(word n) word: word count; count := 0; while n > 0 do count := count + 1; n := n / 10 od; count corp   proc print_magic_square([*,*]word square) void: word order, max, col_size, magic, x, y; order := dim(square,1); max := order*order; col_size := digit_count(max) + 1;   magic := 0; for x from 0 upto order-1 do magic := magic + square[x,0] od;   writeln("Magic square of order ",order," with magic number ",magic,":"); for y from 0 upto order-1 do for x from 0 upto order-1 do write(square[x,y]:col_size) od; writeln() od; writeln() corp   proc main() void: [1,1]word sq1; [3,3]word sq3; [5,5]word sq5; [7,7]word sq7;   odd_magic_square(sq1); odd_magic_square(sq3); odd_magic_square(sq5); odd_magic_square(sq7);   print_magic_square(sq1); print_magic_square(sq3); print_magic_square(sq5); print_magic_square(sq7) corp
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#EGL
EGL
  program Matrix_multiplication type BasicProgram {}   function main() a float[][] = [[1,2,3],[4,5,6]]; b float[][] = [[1,2],[3,4],[5,6]]; c float[][] = mult(a, b); end   function mult(a float[][], b float[][]) returns(float[][]) if(a.getSize() == 0) return (new float[0][0]); end if(a[1].getSize() != b.getSize()) return (null); //invalid dims end   n int = a[1].getSize(); m int = a.getSize(); p int = b[1].getSize();   ans float[0][0]; ans.resizeAll([m, p]);   // Calculate dot product. for(i int from 1 to m) for(j int from 1 to p) for(k int from 1 to n) ans[i][j] += a[i][k] * b[k][j]; end end end return (ans); end end  
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Lua
Lua
import bitops, sequtils, strutils   type Square = seq[seq[int]]   func magicSquareDoublyEven(n: int): Square = ## Build a magic square of doubly even order.   assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4." result = newSeqWith(n, newSeq[int](n))   const bits = 0b1001_0110_0110_1001 # Pattern of count-up vs count-down zones. let size = n * n let mult = n div 4 # How many multiples of 4.   var i = 0 for r in 0..<n: for c in 0..<n: let bitPos = c div mult + r div mult * 4 result[r][c] = if bits.testBit(bitPos): i + 1 else: size - i inc i     func `$`(square: Square): string = ## Return the string representation of a magic square. let length = len($(square.len * square.len)) for row in square: result.add row.mapIt(($it).align(length)).join(" ") & '\n'     when isMainModule: let n = 8 echo magicSquareDoublyEven(n) echo "Magic constant = ", n * (n * n + 1) div 2
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Nim
Nim
import bitops, sequtils, strutils   type Square = seq[seq[int]]   func magicSquareDoublyEven(n: int): Square = ## Build a magic square of doubly even order.   assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4." result = newSeqWith(n, newSeq[int](n))   const bits = 0b1001_0110_0110_1001 # Pattern of count-up vs count-down zones. let size = n * n let mult = n div 4 # How many multiples of 4.   var i = 0 for r in 0..<n: for c in 0..<n: let bitPos = c div mult + r div mult * 4 result[r][c] = if bits.testBit(bitPos): i + 1 else: size - i inc i     func `$`(square: Square): string = ## Return the string representation of a magic square. let length = len($(square.len * square.len)) for row in square: result.add row.mapIt(($it).align(length)).join(" ") & '\n'     when isMainModule: let n = 8 echo magicSquareDoublyEven(n) echo "Magic constant = ", n * (n * n + 1) div 2
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Gosu
Gosu
function A(in_k: int, x1(): int, x2(): int, x3(): int, x4(): int, x5(): int): int { var k = in_k var B(): int // B is a function variable B = \ -> { k = k-1; return A(k, B, x1, x2, x3, x4) } return k<=0 ? x4()+x5() : B() } print(A(10, \ -> 1, \ -> -1, \ -> -1, \ -> 1, \ -> 0))
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Groovy
Groovy
def a; a = { k, x1, x2, x3, x4, x5 -> def b; b = { a (--k, b, x1, x2, x3, x4) } k <= 0 ? x4() + x5() : b() }   def x = { n -> { it -> n } }
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Delphi
Delphi
  (lib 'matrix)   (define M (list->array (iota 6) 3 2)) (array-print M) 0 1 2 3 4 5 (array-print (matrix-transpose M)) 0 2 4 1 3 5  
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#Huginn
Huginn
import Algorithms as algo; import Mathematics as math; import Terminal as term;   class Maze { _rows = none; _cols = none; _data = none; constructor( rows_, cols_ ) { _rows = ( rows_ / 2 ) * 2 - 1; _cols = ( cols_ / 2 ) * 2 - 1; _data = [].resize( _rows + 2, [].resize( _cols + 2, false ) ); x = 0; y = 0; path = []; rng = math.Randomizer( math.Randomizer.DISTRIBUTION.DISCRETE, 0, integer( $2 ^ $63 - $1 ) ); for ( _ : algo.range( _rows * _cols / 3 ) ) { _data[y + 1][x + 1] = true; while ( true ) { n = neighbours( y, x ); ns = size( n ); if ( ns == 0 ) { if ( size( path ) == 0 ) { break; } y, x = path[-1]; path.pop(); continue; } oy, ox = ( y, x ); y, x = n[rng.next() % ns]; _data[(y + oy) / 2 + 1][(x + ox) / 2 + 1] = true; path.push( ( y, x ) ); break; } } _data[0][1] = true; _data[-1][-2] = true; } neighbours( y_, x_ ) { n = []; if ( ( x_ > 1 ) && ! _data[y_ + 1][x_ - 1] ) { n.push( ( y_, x_ - 2 ) ); } if ( ( y_ > 1 ) && ! _data[y_ - 1][x_ + 1] ) { n.push( ( y_ - 2, x_ ) ); } if ( ( x_ < ( _cols - 2 ) ) && ! _data[y_ + 1][x_ + 3] ) { n.push( ( y_, x_ + 2 ) ); } if ( ( y_ < ( _rows - 2 ) ) && ! _data[y_ + 3][x_ + 1] ) { n.push( ( y_ + 2, x_ ) ); } return ( n ); } to_string() { s = ""; for ( r : _data ) { s += ∑( algo.map( r, @( b ) { b ? " " : "#"; } ) ); s += "\n"; } return ( s ); } }   main() { rows = term.lines() - 2; cols = term.columns() - 1; maze = Maze( rows, cols ); print( "{}".format( maze ) ); }
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Scala
Scala
class Matrix[T](matrix:Array[Array[T]])(implicit n: Numeric[T], m: ClassManifest[T]) { import n._ val rows=matrix.size val cols=matrix(0).size def row(i:Int)=matrix(i) def col(i:Int)=matrix map (_(i))   def *(other: Matrix[T]):Matrix[T] = new Matrix( Array.tabulate(rows, other.cols)((row, col) => (this.row(row), other.col(col)).zipped.map(_*_) reduceLeft (_+_) ))   def **(x: Int)=x match { case 0 => createIdentityMatrix case 1 => this case 2 => this * this case _ => List.fill(x)(this) reduceLeft (_*_) }   def createIdentityMatrix=new Matrix(Array.tabulate(rows, cols)((row,col) => if (row == col) one else zero) )   override def toString = matrix map (_.mkString("[", ", ", "]")) mkString "\n" }   object MatrixTest { def main(args:Array[String])={ val m=new Matrix[BigInt](Array(Array(3,2), Array(2,1))) println("-- m --\n"+m)   Seq(0,1,2,3,4,10,20,50) foreach {x => println("-- m**"+x+" --") println(m**x) } } }
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Groovy
Groovy
  def mapRange(a1, a2, b1, b2, s) { b1 + ((s - a1) * (b2 - b1)) / (a2 - a1) }   (0..10).each { s -> println(s + " in [0, 10] maps to " + mapRange(0, 10, -1, 0, s) + " in [-1, 0].") }  
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Haskell
Haskell
import Data.Ratio import Text.Printf (PrintfType, printf)   -- Map a value from the range [a1,a2] to the range [b1,b2]. We don't check -- for empty ranges. mapRange :: Fractional a => (a, a) -> (a, a) -> a -> a mapRange (a1, a2) (b1, b2) s = b1 + (s - a1) * (b2 - b1) / (a2 - a1)   main :: IO () main -- Perform the mapping over floating point numbers. = do putStrLn "---------- Floating point ----------" mapM_ (\n -> prtD n . mapRange (0, 10) (-1, 0) $ fromIntegral n) [0 .. 10] -- Perform the same mapping over exact rationals. putStrLn "---------- Rationals ----------" mapM_ (\n -> prtR n . mapRange (0, 10) (-1, 0) $ n % 1) [0 .. 10] where prtD :: PrintfType r => Integer -> Double -> r prtD = printf "%2d -> %6.3f\n" prtR :: PrintfType r => Integer -> Rational -> r prtR n x = printf "%2d -> %s\n" n (show x)
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Ring
Ring
  # Project : Maximum triangle path sum   load "stdlib.ring" ln = list(19) ln[1] = " 55" ln[2] = " 94 48" ln[3] = " 95 30 96" ln[4] = " 77 71 26 67" ln[5] = " 97 13 76 38 45" ln[6] = " 07 36 79 16 37 68" ln[7] = " 48 07 09 18 70 26 06" ln[8] = " 18 72 79 46 59 79 29 90" ln[9] = " 20 76 87 11 32 07 07 49 18" ln[10] = " 27 83 58 35 71 11 25 57 29 85" ln[11] = " 14 64 36 96 27 11 58 56 92 18 55" ln[12] = " 02 90 03 60 48 49 41 46 33 36 47 23" ln[13] = " 92 50 48 02 36 59 42 79 72 20 82 77 42" ln[14] = " 56 78 38 80 39 75 02 71 66 66 01 03 55 72" ln[15] = " 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36" ln[16] = " 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52" ln[17] = " 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15" ln[18] = " 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93" ln[19] = "end"   matrix = newlist(20,20) x = 1 size = 0   for n = 1 to len(ln) - 1 ln2 = ln[n] ln2 = trim(ln2) for y = 1 to x matrix[x][y] = number(left(ln2,2)) if len(ln2) > 4 ln2 = substr(ln2,4,len(ln2)-4) ok next x = x + 1 size = size + 1 next   for x = size - 1 to 1 step - 1 for y = 1 to x s1 = matrix[x+1][y] s2 = matrix[x+1][y+1] if s1 > s2 matrix[x][y] = matrix[x][y] + s1 else matrix[x][y] = matrix[x][y] + s2 ok next next   see "maximum triangle path sum = " + matrix[1][1]  
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#LiveCode
LiveCode
function md5sum hashtext local md5, mdhex put md5Digest(hashtext) into md5 get binaryDecode("H*",md5,mdhex) return mdhex end md5sum
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#C.2B.2B
C++
#include <cstdlib> #include <complex>   // get dimensions for arrays template<typename ElementType, std::size_t dim1, std::size_t dim2> std::size_t get_first_dimension(ElementType (&a)[dim1][dim2]) { return dim1; }   template<typename ElementType, std::size_t dim1, std::size_t dim2> std::size_t get_second_dimension(ElementType (&a)[dim1][dim2]) { return dim2; }     template<typename ColorType, typename ImageType> void draw_Mandelbrot(ImageType& image, //where to draw the image ColorType set_color, ColorType non_set_color, //which colors to use for set/non-set points double cxmin, double cxmax, double cymin, double cymax,//the rect to draw in the complex plane unsigned int max_iterations) //the maximum number of iterations { std::size_t const ixsize = get_first_dimension(image); std::size_t const iysize = get_first_dimension(image); for (std::size_t ix = 0; ix < ixsize; ++ix) for (std::size_t iy = 0; iy < iysize; ++iy) { std::complex<double> c(cxmin + ix/(ixsize-1.0)*(cxmax-cxmin), cymin + iy/(iysize-1.0)*(cymax-cymin)); std::complex<double> z = 0; unsigned int iterations;   for (iterations = 0; iterations < max_iterations && std::abs(z) < 2.0; ++iterations) z = z*z + c;   image[ix][iy] = (iterations == max_iterations) ? set_color : non_set_color;   } }
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#EchoLisp
EchoLisp
  (lib 'matrix)   ;; compute next i,j = f(move,i,j) (define-syntax-rule (path imove jmove) (begin (set! i (imove i n)) (set! j (jmove j n))))   ;; We define the ordinary and break moves ;; (1 , -1), (0, 1) King's move (define (inext i n) (modulo (1+ i) n)) (define (jnext j n) (modulo (1- j) n)) (define (ibreak i n) i) (define (jbreak j n) (modulo (1+ j) n))   (define (make-ms n) (define n2+1 (1+ (* n n))) (define ms (make-array n n)) (define i (quotient n 2)) (define j 0) (array-set! ms i j 1)   (for ((ns (in-range 2 n2+1))) (if (zero? (array-ref ms (inext i n ) (jnext j n ))) (path inext jnext) ;; ordinary move if empty target (path ibreak jbreak)) ;; else break move   (if (zero? (array-ref ms i j)) (array-set! ms i j ns) (error ns "illegal path")) ) (writeln 'order n 'magic-number (/ ( * n n2+1) 2)) (array-print ms))    
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ela
Ela
open list   mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]   [[1, 2], [3, 4]] `mmult` [[-3, -8, 3], [-2, 1, 4]]
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#PARI.2FGP
PARI/GP
magicsquare(n)=matrix(n,n,i,j,k=i+j*n-n;if(bitand(38505,2^((j-1)%4*4+(i-1)%4)),k,n*n+1-k))
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Perl
Perl
 
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Haskell
Haskell
import Data.IORef (modifyIORef, newIORef, readIORef)   a :: (Enum a, Num b, Num a, Ord a) => a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b a k x1 x2 x3 x4 x5 = do r <- newIORef k let b = do k <- pred ! r a k b x1 x2 x3 x4 if k <= 0 then (+) <$> x4 <*> x5 else b where f !r = modifyIORef r f >> readIORef r   main :: IO () main = a 10 # 1 # (-1) # (-1) # 1 # 0 >>= print where ( # ) f = f . return
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#EchoLisp
EchoLisp
  (lib 'matrix)   (define M (list->array (iota 6) 3 2)) (array-print M) 0 1 2 3 4 5 (array-print (matrix-transpose M)) 0 2 4 1 3 5  
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main(A) # generate rows x col maze /mh := \A[1] | 12 # or take defaults 12 x 16 /mw := \A[2] | 16 mz := DisplayMaze(GenerateMaze(mh,mw)) WriteImage(mz.filename) # save file WAttrib(mz.window,"canvas=normal") # show maze in hidden window until Event() == &lpress # wait for left mouse press close(mz.window) end   $define FINISH 64 # exit $define START 32 # entrance $define PATH 128 $define SEEN 16 # bread crumbs for generator $define NORTH 8 # sides ... $define EAST 4 $define SOUTH 2 $define WEST 1 $define EMPTY 0 # like new   procedure GenerateMaze(r,c) #: Depth First Maze Generation static maze,h,w,rd if /maze then { # BEGING - No maze yet /h := integer(1 < r) | runerr(r,205) # valid size 2x2 or better /w := integer(1 < c) | runerr(r,205) every !(maze := list(h)) := list(w,EMPTY) # shinny new empty maze start := [?h,?w,?4-1,START] # random [r,c] start & finish finish := [?h,?w,(start[3]+2)%4,FINISH] # w/ opposite side exponent every x := start | finish do { case x[3] := 2 ^ x[3] of { # get side from exponent and NORTH : x[1] := 1 # project r,c to selected edge EAST : x[2] := w SOUTH : x[1] := h WEST : x[2] := 1 } maze[x[1],x[2]] +:= x[3] + x[4] # transcribe s/f to maze } rd := [NORTH, EAST, SOUTH, WEST] # initial list of directions GenerateMaze(start[1],start[2]) # recurse through maze return 1(.maze,maze := &null) # return maze, reset for next } else { # ----------------------- recursed to clear insize of maze if iand(maze[r,c],SEEN) = 0 then { # in bounds and not SEEN yet? maze[r,c] +:= SEEN # Mark current cell as visited every !rd :=: ?rd # randomize list of directions every d := !rd do case d of { # try all, succeed & clear wall NORTH : maze[r,c] +:= ( GenerateMaze(r-1,c), NORTH) EAST : maze[r,c] +:= ( GenerateMaze(r,c+1), EAST) SOUTH : maze[r,c] +:= ( GenerateMaze(r+1,c), SOUTH) WEST : maze[r,c] +:= ( GenerateMaze(r,c-1), WEST) } return # signal success to caller } } end   $define CELL 20 # cell size in pixels $define BORDER 30 # border size in pixels   record mazeinfo(window,maze,filename) # keepers   procedure DisplayMaze(maze) #: show it off if CELL < 8 then runerr(205,CELL) # too small   wh := (ch := (mh := *maze ) * CELL) + 2 * BORDER # win, cell, maze height ww := (cw := (mw := *maze[1]) * CELL) + 2 * BORDER # win, cell, maze width   wparms := [ sprintf("Maze %dx%d",*maze,*maze[1]), # window parameters "g","bg=white","canvas=hidden", sprintf("size=%d,%d",ww,wh), sprintf("dx=%d",BORDER), sprintf("dy=%d",BORDER)]   &window := open!wparms | stop("Unable to open Window")   Fg("black") # Draw full grid every DrawLine(x := 0 to cw by CELL,0,x,ch+1) # . verticals every DrawLine(0,y := 0 to ch by CELL,cw+1,y) # . horizontals   Fg("white") # Set to erase lines every y := CELL*((r := 1 to mh)-1) & x := CELL*((c := 1 to mw)-1) do { WAttrib("dx="||x+BORDER,"dy="||y+BORDER) # position @ cell r,c if iand(maze[r,c],NORTH) > 0 then DrawLine(2,0,CELL-1,0) if iand(maze[r,c],EAST) > 0 then DrawLine(CELL,2,CELL,CELL-1) if iand(maze[r,c],SOUTH) > 0 then DrawLine(2,CELL,CELL-1,CELL) if iand(maze[r,c],WEST) > 0 then DrawLine(0,2,0,CELL-1) }   return mazeinfo(&window,maze,sprintf("maze-%dx%d-%d.gif",r,c,&now)) end
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Scheme
Scheme
  (define (dec x) (- x 1))   (define (halve x) (/ x 2))   (define (row*col row col) (apply + (map * row col)))   (define (matrix-multiply m1 m2) (map (lambda (row) (apply map (lambda col (row*col row col)) m2)) m1))   (define (matrix-exp mat exp) (cond ((= exp 1) mat) ((even? exp) (square-matrix (matrix-exp mat (halve exp)))) (else (matrix-multiply mat (matrix-exp mat (dec exp))))))   (define (square-matrix mat) (matrix-multiply mat mat))  
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Icon_and_Unicon
Icon and Unicon
  record Range(a, b)   # note, we force 'n' to be real, which means recalculation will # be using real numbers, not integers procedure remap (range1, range2, n : real) if n < range2.a | n > range2.b then fail # n out of given range return range1.a + (n - range2.a) * (range1.b - range1.a) / (range2.b - range2.a) end   procedure range_string (range) return "[" || range.a || ", " || range.b || "]" end   procedure main () range1 := Range (0, 10) range2 := Range (-1, 0) # if i is out of range1, then 'remap' fails, so only valid changes are written every i := -2 to 12 do { if m := remap (range2, range1, i) then write ("Value " || i || " in " || range_string (range1) || " maps to " || m || " in " || range_string (range2)) } end  
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Ruby
Ruby
triangle = " 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"   ar = triangle.each_line.map{|line| line.split.map(&:to_i)} puts ar.inject([]){|res,x| maxes = [0, *res, 0].each_cons(2).map(&:max) x.zip(maxes).map{|a,b| a+b} }.max # => 1320
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Lua
Lua
require "md5"   --printing a sum: print(md5.sumhexa"The quick brown fox jumps over the lazy dog")   --running the test suite:   local function test(msg,sum) assert(md5.sumhexa(msg)==sum) end   test("","d41d8cd98f00b204e9800998ecf8427e") test("a","0cc175b9c0f1b6a831c399e269772661") test("abc","900150983cd24fb0d6963f7d28e17f72") test("message digest","f96b697d7cb7938d525a2f31aaf161d0") test("abcdefghijklmnopqrstuvwxyz","c3fcd3d76192e4007dfb496cca67e13b") test("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789","d174ab98d277d9f5a5611c2c9f419d9f") test("12345678901234567890123456789012345678901234567890123456789012345678901234567890","57edf4a22be3c955ac49da2e2107b67a")
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#C3
C3
module mandelbrot;   extern fn int atoi(char *s); extern fn int printf(char *s, ...); extern fn void putchar(int c);   fn void main(int argc, char **argv) { int w = atoi(argv[1]); int h = w;   const LIMIT = 2.0; const SQUARE_LIMIT = LIMIT * LIMIT;   printf("P4\n%d %d\n", w, h);   int iter = 50; int bit_num = 0; char byte_acc = 0; for (double y = 0; y < h; y++) { for (double x = 0; x < w; x++) { double zr; double zi; double ti; double tr; double cr = (2.0 * x / w - 1.5); double ci = (2.0 * y / h - 1.0); for (int i = 0; i < iter && (tr + ti <= SQUARE_LIMIT); i++) { zi = 2.0 * zr * zi + ci; zr = tr - ti + cr; tr = zr * zr; ti = zi * zi; }   byte_acc <<= 1; if (tr + ti <= SQUARE_LIMIT) byte_acc |= 0x01;   ++bit_num;   if (bit_num == 8) { putchar(byte_acc); byte_acc = 0; bit_num = 0; } else if (x == w - 1) { byte_acc <<= (8 - w % 8); putchar(byte_acc); byte_acc = 0; bit_num = 0; } } } }
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Elixir
Elixir
defmodule RC do def odd_magic_square(n) when rem(n,2)==1 do for i <- 0..n-1 do for j <- 0..n-1, do: n * rem(i+j+1+div(n,2),n) + rem(i+2*j+2*n-5,n) + 1 end end   def print_square(sq) do width = List.flatten(sq) |> Enum.max |> to_char_list |> length fmt = String.duplicate(" ~#{width}w", length(sq)) <> "~n" Enum.each(sq, fn row -> :io.format fmt, row end) end end   Enum.each([3,5,11], fn n -> IO.puts "\nSize #{n}, magic sum #{div(n*n+1,2)*n}" RC.odd_magic_square(n) |> RC.print_square end)
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Elixir
Elixir
  def mult(m1, m2) do Enum.map m1, fn (x) -> Enum.map t(m2), fn (y) -> Enum.zip(x, y) |> Enum.map(fn {x, y} -> x * y end) |> Enum.sum end end end   def t(m) do # transpose List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end      
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Phix
Phix
with javascript_semantics constant t = {{1,1,0,0}, {1,1,0,0}, {0,0,1,1}, {0,0,1,1}} function magic_square(integer n) if n<4 or mod(n,4)!=0 then return false end if sequence square = repeat(repeat(0,n),n) integer i = 0 for r=1 to n do for c=1 to n do square[r,c] = iff(t[mod(r,4)+1,mod(c,4)+1]?i+1:n*n-i) i += 1 end for end for return square end function procedure check(sequence sq) integer n = length(sq) integer magic = n*(n*n+1)/2 integer bd = 0, fd = 0 for i=1 to length(sq) do if sum(sq[i])!=magic then ?9/0 end if if sum(columnize(sq,i))!=magic then ?9/0 end if bd += sq[i,i] fd += sq[n-i+1,n-i+1] end for if bd!=magic or fd!=magic then ?9/0 end if end procedure --for i=4 to 16 by 4 do for i=8 to 8 by 4 do sequence square = magic_square(i) printf(1,"maqic square of order %d, sum: %d\n", {i,sum(square[i])}) string fmt = sprintf("%%%dd",length(sprintf("%d",i*i))) pp(square,{pp_Nest,1,pp_IntFmt,fmt,pp_StrFmt,3,pp_IntCh,false,pp_Pause,0}) check(square) end for
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Icon_and_Unicon
Icon and Unicon
record mutable(value) # we need mutable integers # ... be obvious when we break normal scope rules procedure main(arglist) # supply the initial k value k := integer(arglist[1])|10 # .. or default to 10=default write("Man or Boy = ", A( k, 1, -1, -1, 1, 0 ) ) end   procedure eval(ref) # evaluator to distinguish between a simple value and a code reference return if type(ref) == "co-expression" then @ref else ref end   procedure A(k,x1,x2,x3,x4,x5) # Knuth's A k := mutable(k) # make k mutable for B return if k.value <= 0 then # -> boy compilers may recurse and die here eval(x4) + eval(x5) # the crux of separating man .v. boy compilers else # -> boy compilers can run into trouble at k=5+ B(k,x1,x2,x3,x4,x5) end   procedure B(k,x1,x2,x3,x4,x5) # Knuth's B k.value -:= 1 # diddle A's copy of k return A(k.value, create |B(k,x1,x2,x3,x4,x5),x1,x2,x3,x4) # call A with a new k and 5 x's end
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#EDSAC_order_code
EDSAC order code
  [Demo of matrix transposition. Not in place, creates a new matrix. EDSAC, Initial Orders 2.] ..PZ [blank tape and terminator] T 50 K [to call matrix transpose subroutine with 'G X'] P 200 F [address of matrix transpose subroutine] T 47 K [to call matrix print subroutine with 'G M'] P 100 F [address of matrix print subroutine] T 46 K [to call print subroutine with 'G N'] P 56 F [address of print subroutine (EDSAC library P1)]   [Subroutine to transpose a matrix of 17-bit real numbers, not in place. Caller must ensure original and transpose don't overlap. Parameters, all in the address field (i.e. denote n by P n F) 10F = width (number of columns) 11F = height (number of rows) 12F = start address of input matrix 13F = start address of output matrix] E25K TX GK   [The subroutine loads elements by working down each column in turn. Elements are stored at consecutive locations in the transposed matrix.] A3F T31@ [set up return to caller] A13F A33@ T14@ [initialize T order for storing transpose] A12F A32@ U13@ [initialize A order for loading original] T36@ [also save as A order for top of current column] S10 F [negative of width] [10] T35@ [initialize negative counter] S11 F [negative of height] [12] T34@ [initialize negative counter] [13] AF [maunfactured order; load matrix element] [14] TF [maunfactured order; store matrix element] A14@ A2F T14@ [update address in T order] A13@ A10F T13@ [update address in A order] A34@ A2F G12@ [inner loop till finished this column] A36@ A2F U36@ T13@ [update address for start of column] A35@ A2F G10@ [outer loop till finished all columns] [31] ZF [exit] [32] AF [added to an address to make A order for that address] [33] TF [added to an address to make T order for that address] [34] PF [negative counter for rows] [35] PF [negative counter for columns] [36] AF [load order for first element in current column]   [Subroutine to print a matrix of 17-bit real numbers. Straightforward, so given in condensed form. Parameters (in the address field, i.e. pass n as PnF): 10F = width (number of columns) 11F = height (number of rows) 12F = start address of matrix 13F = number of decimals] E25K TM GKA3FT30@A13FT18@A12FA31@T14@S11FT36@S10FT37@O34@O35@TDAFT1FA16@ GN [call library subroutine P1] PFA14@A2FT14@A37@A2FG10@O32@O33@A36@A2FG8@ZFAF@F&F!FMFPFPF   [Library subroutine P1. Prints number in 0D to n places of decimals, where n is specified by 'P n F' pseudo-order after subroutine call.] E25K TN GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F   [Main routine] PK T300K GK [Constants] [0] #F [figures shift on teleprinter] [1] @F [carriage return] [2] &F [line feed] [3] P3F [number of columns (in address field)] [4] P5F [number of rows (in address field)] [5] P400F [address of matrix] [6] P500F [address of transposed matrix] [7] P2F [number of decimals when printing matrix] [8] TF [add to address to make T order] [9] P328F [0.0100097...., matrix elements are multiples of this] [Variables] [10] PF [matrix element, initialized to 0.00] [11] PF [negative counter]   [Enter with acc = 0] [12] O@ [set figures mode on teleprinter] A5@ [address of matrix] A8@ [make T order to store first elememt] T24@ [plant in code] H4@ N3@ L64F L32F [acc := negative number of entries] [20] T11@ [initialize negative counter] A10@ A9@ U10@ [increment matrix element] [24] TF [store in matrix] A24@ A2F T24@ [inc store address] A11@ A2F G20@ [inc negative counter, loop till zero]   [Matrix is set up, now print it] A3@ T10F [10F := width] A4@ T11F [11F := height] A5@ T12F [12F := address of matrix] A7@ T13F [13F := number of decimals] [39] A39@ GM [call print subroutine] O1@ O2@ [add CR LF]   [Transpose matrix: 10F, 11F, 12F stay the same] A6@ T13F [13F := address of transpose] [45] A45@ GX [call transpose routine]   [Print transpose] A10F TF A11F T10F AF T11F [swap width and height] A13F T12F [12F := address of transpose] A7@ T13F [13F := number of decimals] [57] A57@ GM [call print subroutine]   O@ [figures mode, dummy to flush teleprinter buffer] ZF [stop] E12Z [enter at 12 (relative)] PF [accumulator = 0 on entry]  
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#J
J
maze=:4 :0 assert.0<:n=.<:x*y horiz=. 0$~x,y-1 verti=. 0$~(x-1),y path=.,:here=. ?x,y unvisited=.0 (<here+1)} 0,0,~|:0,0,~1$~y,x while.n do. neighbors=. here+"1 (,-)=0 1 neighbors=. neighbors #~ (<"1 neighbors+1) {unvisited if.#neighbors do. n=.n-1 next=. ({~ ?@#) neighbors unvisited=.0 (<next+1)} unvisited if.{.next=here do. horiz=.1 (<-:here+next-0 1)} horiz else. verti=. 1 (<-:here+next-1 0)} verti end. path=.path,here=.next else. here=.{:path path=.}:path end. end. horiz;verti )   display=:3 :0 size=. >.&$&>/y text=. (}:1 3$~2*1+{:size)#"1":size$<' ' 'hdoor vdoor'=. 2 4&*&.>&.> (#&,{@;&i./@$)&.> y ' ' (a:-.~0 1;0 2; 0 3;(2 1-~$text);(1 4&+&.> hdoor),,vdoor+&.>"0/2 1;2 2;2 3)} text )
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const type: matrix is array array float;   const func string: str (in matrix: mat) is func result var string: stri is ""; local var integer: row is 0; var integer: column is 0; begin for row range 1 to length(mat) do for column range 1 to length(mat[row]) do stri &:= str(mat[row][column]); if column < length(mat[row]) then stri &:= ", "; end if; end for; if row < length(mat) then stri &:= "\n"; end if; end for; end func;   enable_output(matrix);   const func matrix: (in matrix: mat1) * (in matrix: mat2) is func result var matrix: product is matrix.value; local var integer: row is 0; var integer: column is 0; var integer: k is 0; begin product := length(mat1) times length(mat1) times 0.0; for row range 1 to length(mat1) do for column range 1 to length(mat1) do product[row][column] := 0.0; for k range 1 to length(mat1) do product[row][column] +:= mat1[row][k] * mat2[k][column]; end for; end for; end for; end func;   const func matrix: (in var matrix: base) ** (in var integer: exponent) is func result var matrix: power is matrix.value; local var integer: row is 0; var integer: column is 0; begin if exponent < 0 then raise NUMERIC_ERROR; else if odd(exponent) then power := base; else # Create identity matrix power := length(base) times length(base) times 0.0; for row range 1 to length(base) do for column range 1 to length(base) do if row = column then power[row][column] := 1.0; end if; end for; end for; end if; exponent := exponent div 2; while exponent > 0 do base := base * base; if odd(exponent) then power := power * base; end if; exponent := exponent div 2; end while; end if; end func;   const proc: main is func local var matrix: m is [] ( [] (4.0, 3.0), [] (2.0, 1.0)); var integer: exponent is 0; begin for exponent range [] (0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23) do writeln("m ** " <& exponent <& " ="); writeln(m ** exponent); end for; end func;
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Sidef
Sidef
class Array { method ** (Number n { .>= 0 }) { var tmp = self var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} loop { out = (out `mmul` tmp) if n.is_odd n >>= 1 || break tmp = (tmp `mmul` tmp) } return out } }   var m = [[1, 2, 0], [0, 3, 1], [1, 0, 0]]   for order in (0..5) { say "### Order #{order}" var t = (m ** order) say (' ', t.join("\n ")) }
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#J
J
maprange=:2 :0 'a1 a2'=.m 'b1 b2'=.n b1+((y-a1)*b2-b1)%a2-a1 ) NB. this version defers all calculations to runtime, but mirrors exactly the task formulation
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Java
Java
public class Range { public static void main(String[] args){ for(float s = 0;s <= 10; s++){ System.out.println(s + " in [0, 10] maps to "+ mapRange(0, 10, -1, 0, s)+" in [-1, 0]."); } }   public static double mapRange(double a1, double a2, double b1, double b2, double s){ return b1 + ((s - a1)*(b2 - b1))/(a2 - a1); } }
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Rust
Rust
use std::cmp::max;   fn max_path(vector: &mut Vec<Vec<u32>>) -> u32 {   while vector.len() > 1 {   let last = vector.pop().unwrap(); let ante = vector.pop().unwrap();   let mut new: Vec<u32> = Vec::new();   for (i, value) in ante.iter().enumerate() { new.push(max(last[i], last[i+1]) + value); };   vector.push(new); };   vector[0][0] }   fn main() { let mut data = "55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93";   let mut vector = data.split("\n").map(|x| x.split(" ").map(|s: &str| s.parse::<u32>().unwrap()) .collect::<Vec<u32>>()).collect::<Vec<Vec<u32>>>();   let max_value = max_path(&mut vector);   println!("{}", max_value); //=> 7273 }
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Maple
Maple
  > with( StringTools ): > Hash( "" ); "d41d8cd98f00b204e9800998ecf8427e"   > Hash( "a" ); "0cc175b9c0f1b6a831c399e269772661"   > Hash( "abc" ); "900150983cd24fb0d6963f7d28e17f72"   > Hash( "message digest" ); "f96b697d7cb7938d525a2f31aaf161d0"   > Hash( "abcdefghijklmnopqrstuvwxyz" ); "c3fcd3d76192e4007dfb496cca67e13b"   > Hash( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ); "d174ab98d277d9f5a5611c2c9f419d9f"   > Hash( "12345678901234567890123456789012345678901234567890123456789012345678901234567890" ); "57edf4a22be3c955ac49da2e2107b67a"  
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Cixl
Cixl
  use: cx;   define: max 4.0; define: max-iter 570;   let: (max-x max-y) screen-size; let: max-cx $max-x 2.0 /; let: max-cy $max-y 2.0 /; let: rows Stack<Str> new; let: buf Buf new; let: zoom 0 ref;   func: render()() $rows clear   $max-y 2 / { let: y; $buf 0 seek   $max-x { let: x; let: (zx zy) 0.0 ref %%; let: cx $x $max-cx - $zoom deref /; let: cy $y $max-cy - $zoom deref /; let: i #max-iter ref;   { let: nzx $zx deref ** $zy deref ** - $cx +; $zy $zx deref *2 $zy deref * $cy + set $zx $nzx set $i &-- set-call $nzx ** $zy deref ** + #max < $i deref and } while   let: c $i deref % -7 bsh bor 256 mod; $c {$x 256 mod $y 256 mod} {0 0} if-else $c new-rgb $buf set-bg @@s $buf print } for   $rows $buf str push } for   1 1 #out move-to $rows {#out print} for $rows riter {#out print} for;   #out hide-cursor raw-mode   let: poll Poll new; let: is-done #f ref;   $poll #in { #in read-char _ $is-done #t set } on-read   { $zoom &++ set-call render $poll 0 wait _ $is-done deref ! } while   #out reset-style #out clear-screen 1 1 #out move-to #out show-cursor normal-mode  
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#ERRE
ERRE
  PROGRAM MAGIC_SQUARE   !$INTEGER   PROCEDURE Magicsq(size,filename$)   LOCAL DIM sq[25,25] ! array to hold square   IF (size AND 1)=0 OR size<3 THEN PRINT PRINT(CHR$(7)) ! beep PRINT("error: size is not odd or size is smaller then 3") PAUSE(3) EXIT PROCEDURE END IF   ! filename$ <> "" then save magic square in a file ! filename$ can contain directory name ! if filename$ exist it will be overwriten, no error checking   ! start in the middle of the first row nr=1 x=size-(size DIV 2) y=1 max=size*size   ! create format string for using frmt$=STRING$(LEN(STR$(max)),"#")   ! main loop for creating magic square REPEAT IF sq[x,y]=0 THEN sq[x,y]=nr IF nr MOD size=0 THEN y=y+1 ELSE x=x+1 y=y-1 END IF nr=nr+1 END IF IF x>size THEN x=1 WHILE sq[x,y]<>0 DO x=x+1 END WHILE END IF IF y<1 THEN y=size WHILE sq[x,y]<>0 DO y=y-1 END WHILE END IF UNTIL nr>max   ! printing square's bigger than 19 result in a wrapping of the line PRINT("Odd magic square size:";size;"*";size) PRINT("The magic sum =";((max+1) DIV 2)*size) PRINT   FOR y=1 TO size DO FOR x=1 TO size DO WRITE(frmt$;sq[x,y];) END FOR PRINT END FOR    ! output magic square to a file with the name provided IF filename$<>"" THEN OPEN("O",1,filename$) PRINT(#1,"Odd magic square size:";size;" *";size) PRINT(#1,"The magic sum =";((max+1) DIV 2)*size) PRINT(#1,)   FOR y=1 TO size DO FOR x=1 TO size DO WRITE(#1,frmt$;sq[x,y];) END FOR PRINT(#1,) END FOR END IF CLOSE(1)   END PROCEDURE   BEGIN PRINT(CHR$(12);)  ! CLS Magicsq(5,"") Magicsq(11,"") !---------------------------------------------------- ! the next line will also print the square to a file ! called 'magic_square_19txt' !---------------------------------------------------- Magicsq(19,"msq_19.txt")   END PROGRAM  
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Factor
Factor
USING: formatting io kernel math math.matrices math.ranges sequences sequences.extras ; IN: rosetta-code.magic-squares-odd   : inc-matrix ( n -- matrix ) [ 0 ] dip dup [ 1 + dup ] make-matrix nip ;   : rotator ( n -- seq ) 2/ dup [ neg ] dip [a,b] ;   : odd-magic-square ( n -- matrix ) [ inc-matrix ] [ rotator [ rotate ] 2map flip ] dup tri ;   : show-square ( n -- ) dup "Order: %d\n" printf odd-magic-square dup [ [ "%4d" printf ] each nl ] each first sum "Magic number: %d\n\n" printf ;   3 5 11 [ show-square ] tri@
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#ELLA
ELLA
MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t: [INT k = 1..n](vector1[k], vector2[k]).   MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t: [INT i = 1..m] [INT j = 1..n] matrix[j][i].   MAC INNER_PRODUCT{FN * = [2]TYPE t -> TYPE s, FN + = [2]s -> s} = ([INT n][2]t: vector) -> s: IF n = 1 THEN *vector[1] ELSE *vector[1] + INNER_PRODUCT {*,+} vector[2..n] FI.   MAC MATRIX_MULT {FN * = [2]TYPE t->TYPE s, FN + = [2]s->s} = ([INT n][INT m]t: matrix1, [m][INT p]t: matrix2) -> [n][p]s: BEGIN LET transposed_matrix2 = TRANSPOSE matrix2. OUTPUT [INT i = 1..n][INT j = 1..p] INNER_PRODUCT{*,+}ZIP(matrix1[i],transposed_matrix2[j]) END.     TYPE element = NEW elt/(1..20), product = NEW prd/(1..1200).   FN PLUS = (product: integer1 integer2) -> product: ARITH integer1 + integer2.   FN MULT = (element: integer1 integer2) -> product: ARITH integer1 * integer2.   FN MULT_234 = ([2][3]element:matrix1, [3][4]element:matrix2) -> [2][4]product: MATRIX_MULT{MULT,PLUS}(matrix1, matrix2).   FN TEST = () -> [2][4]product: ( LET m1 = ((elt/2, elt/1, elt/1), (elt/3, elt/6, elt/9)), m2 = ((elt/6, elt/1, elt/3, elt/4), (elt/9, elt/2, elt/8, elt/3), (elt/6, elt/4, elt/1, elt/2)). OUTPUT MULT_234 (m1, m2) ).   COM test: just displaysignal MOC
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#PureBasic
PureBasic
Procedure.i MagicN(n.i) ProcedureReturn n*(n*n+1)/2 EndProcedure   Procedure.i MaxN(mx.i,n.i) If mx>n : ProcedureReturn mx : Else : ProcedureReturn n : EndIf EndProcedure   Procedure.i MaxL(mx.i) Define.i i While mx mx/10 : i+1 Wend ProcedureReturn i EndProcedure   Procedure.b DblEvenMagicSquare(n.i) Define.i q=n/4, nr=1, x, y, max, spc Dim sq.i(n,n)   For y=1 To n For x=q+1 To n-q sq(x,y)=1 Next Next   For x=1 To n For y=q+1 To n-q sq(x,y) ! 1 Next Next   q=n*n+1 For y=1 To n For x=1 To n If sq(x,y)=0 sq(x,y)=q-nr Else sq(x,y)=nr EndIf nr+1 max=MaxN(max,sq(x,y)) Next Next   spc=MaxL(max)+1 For y=n To 1 Step -1 For x=n To 1 Step -1 Print(RSet(Str(sq(x,y)),spc," ")) Next PrintN("") Next   EndProcedure   OpenConsole("Magic-Square-Doubly-Even") Define.i n   Repeat PrintN("Input [4,8,12..n] (0=Exit)") While (n<4) Or (n%4) Print(">") : n=Val(Input()) If n=0 : End : EndIf Wend PrintN("The magic sum = "+Str(MagicN(n))) DblEvenMagicSquare(n) n=0 ForEver
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Io
Io
Range   a := method(k, xs, b := block( k = k -1 a(k, list(b, xs slice(0,4)) flatten)) if(k <= 0, (xs at(3) call) + (xs at(4) call), b call))   f := method(x, block(x)) 1 to(500) foreach(k, (k .. " ") print a(k, list(1, -1, -1, 1, 0) map (x, f(x))) println)
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Elixir
Elixir
m = [[1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], [5, 25,125, 625]]   transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end   IO.inspect transpose.(m)
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#Java
Java
package org.rosettacode;   import java.util.Collections; import java.util.Arrays;   /* * recursive backtracking algorithm * shamelessly borrowed from the ruby at * http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking */ public class MazeGenerator { private final int x; private final int y; private final int[][] maze;   public MazeGenerator(int x, int y) { this.x = x; this.y = y; maze = new int[this.x][this.y]; generateMaze(0, 0); }   public void display() { for (int i = 0; i < y; i++) { // draw the north edge for (int j = 0; j < x; j++) { System.out.print((maze[j][i] & 1) == 0 ? "+---" : "+ "); } System.out.println("+"); // draw the west edge for (int j = 0; j < x; j++) { System.out.print((maze[j][i] & 8) == 0 ? "| " : " "); } System.out.println("|"); } // draw the bottom line for (int j = 0; j < x; j++) { System.out.print("+---"); } System.out.println("+"); }   private void generateMaze(int cx, int cy) { DIR[] dirs = DIR.values(); Collections.shuffle(Arrays.asList(dirs)); for (DIR dir : dirs) { int nx = cx + dir.dx; int ny = cy + dir.dy; if (between(nx, x) && between(ny, y) && (maze[nx][ny] == 0)) { maze[cx][cy] |= dir.bit; maze[nx][ny] |= dir.opposite.bit; generateMaze(nx, ny); } } }   private static boolean between(int v, int upper) { return (v >= 0) && (v < upper); }   private enum DIR { N(1, 0, -1), S(2, 0, 1), E(4, 1, 0), W(8, -1, 0); private final int bit; private final int dx; private final int dy; private DIR opposite;   // use the static initializer to resolve forward references static { N.opposite = S; S.opposite = N; E.opposite = W; W.opposite = E; }   private DIR(int bit, int dx, int dy) { this.bit = bit; this.dx = dx; this.dy = dy; } };   public static void main(String[] args) { int x = args.length >= 1 ? (Integer.parseInt(args[0])) : 8; int y = args.length == 2 ? (Integer.parseInt(args[1])) : 8; MazeGenerator maze = new MazeGenerator(x, y); maze.display(); }   }
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#SPAD
SPAD
(1) -> A:=matrix [[0,-%i],[%i,0]]   +0 - %i+ (1) | | +%i 0 + Type: Matrix(Complex(Integer)) (2) -> A^4   +1 0+ (2) | | +0 1+ Type: Matrix(Complex(Integer)) (3) -> A^(-1)   +0 - %i+ (3) | | +%i 0 + Type: Matrix(Fraction(Complex(Integer))) (4) -> inverse A   +0 - %i+ (4) | | +%i 0 + Type: Union(Matrix(Fraction(Complex(Integer))),...)
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Stata
Stata
real matrix matpow(real matrix a, real scalar n) { real matrix p, x real scalar i, s s = n<0 n = abs(n) x = a p = I(rows(a)) for (i=n; i>0; i=floor(i/2)) { if (mod(i,2)==1) p = p*x x = x*x } return(s?luinv(p):p) }
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#JavaScript
JavaScript
// Javascript doesn't have built-in support for ranges // Insted we use arrays of two elements to represent ranges var mapRange = function(from, to, s) { return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]); };   var range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (var i = 0; i < range.length; i++) { range[i] = mapRange([0, 10], [-1, 0], range[i]); }   console.log(range);
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Scala
Scala
object MaximumTrianglePathSum extends App { // Solution: def sum(triangle: Array[Array[Int]]) = triangle.reduceRight((upper, lower) => upper zip (lower zip lower.tail) map {case (above, (left, right)) => above + Math.max(left, right)} ).head   // Tests: def triangle = """ 55 94 48 95 30 96 77 71 26 67 """ def parse(s: String) = s.trim.split("\\s+").map(_.toInt) def parseLines(s: String) = s.trim.split("\n").map(parse) def parseFile(f: String) = scala.io.Source.fromFile(f).getLines.map(parse).toArray println(sum(parseLines(triangle))) println(sum(parseFile("triangle.txt"))) }
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["The quick brown fox jumped over the lazy dog's back","MD5","HexString"]
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Clojure
Clojure
(ns mandelbrot (:refer-clojure :exclude [+ * <]) (:use (clojure.contrib complex-numbers) (clojure.contrib.generic [arithmetic :only [+ *]] [comparison :only [<]] [math-functions :only [abs]]))) (defn mandelbrot? [z] (loop [c 1 m (iterate #(+ z (* % %)) 0)] (if (and (> 20 c) (< (abs (first m)) 2) ) (recur (inc c) (rest m)) (if (= 20 c) true false))))   (defn mandelbrot [] (for [y (range 1 -1 -0.05) x (range -2 0.5 0.0315)] (if (mandelbrot? (complex x y)) "#" " ")))   (println (interpose \newline (map #(apply str %) (partition 80 (mandelbrot)))))  
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Fortran
Fortran
program Magic_Square implicit none   integer, parameter :: order = 15 integer :: i, j   write(*, "(a, i0)") "Magic Square Order: ", order write(*, "(a)") "----------------------" do i = 1, order do j = 1, order write(*, "(i4)", advance = "no") f1(order, i, j) end do write(*,*) end do write(*, "(a, i0)") "Magic number = ", f2(order)   contains   integer function f1(n, x, y) integer, intent(in) :: n, x, y   f1 = n * mod(x + y - 1 + n/2, n) + mod(x + 2*y - 2, n) + 1 end function   integer function f2(n) integer, intent(in) :: n   f2 = n * (1 + n * n) / 2 end function end program
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Erlang
Erlang
    %% Multiplies two matrices. Usage example: %% $ matrix:multiply([[1,2,3],[4,5,6]], [[4,4],[0,0],[1,4]]) %% If the dimentions are incompatible, an error is thrown. %% %% The erl shell may encode the lists output as strings. In order to prevent such %% behaviour, BEFORE running matrix:multiply, run shell:strings(false) to disable %% auto-encoding. When finished, run shell:strings(true) to reset the defaults.   -module(matrix). -export([multiply/2]).   transpose([[]|_]) -> []; transpose(B) -> [lists:map(fun hd/1, B) | transpose(lists:map(fun tl/1, B))].     red(Pair, Sum) -> X = element(1, Pair), %gets X Y = element(2, Pair), %gets Y X * Y + Sum.   %% Mathematical dot product. A x B = d %% A, B = 1-dimension vector %% d = scalar dot_product(A, B) -> lists:foldl(fun red/2, 0, lists:zip(A, B)).     %% Exposed function. Expected result is C = A x B. multiply(A, B) -> %% First transposes B, to facilitate the calculations (It's easier to fetch %% row than column wise). multiply_internal(A, transpose(B)).     %% This function does the actual multiplication, but expects the second matrix %% to be transposed. multiply_internal([Head | Rest], B) -> % multiply each row by Y Element = multiply_row_by_col(Head, B),   % concatenate the result of this multiplication with the next ones [Element | multiply_internal(Rest, B)];   multiply_internal([], B) -> % concatenating and empty list to the end of a list, changes nothing. [].     multiply_row_by_col(Row, [Col_Head | Col_Rest]) -> Scalar = dot_product(Row, Col_Head),   [Scalar | multiply_row_by_col(Row, Col_Rest)];   multiply_row_by_col(Row, []) -> [].  
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Python
Python
  def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 for r in range(n1, order-n1): r1 = sq[r][:n1] r2 = sq[order -r - 1][order-n1:] r1.reverse() r2.reverse() sq[r][:n1] = r2 sq[order -r - 1][order-n1:] = r1 return sq   def printsq(s): n = len(s) bl = len(str(n**2))+1 for i in range(n): print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] ) print "\nMagic constant = %d"%sum(s[0])   printsq(MagicSquareDoublyEven(8))  
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#J
J
A=:4 :0 L=.cocreate'' NB. L is context where names are defined. k__L=:x '`x1__L x2__L x3__L x4__L x5__L'=:y if.k__L<:0 do.a__L=:(x4__L + x5__L)f.'' else. L B '' end. (coerase L)]]]a__L )   B=:4 :0 L=.x k__L=:k__L-1 a__L=:k__L A L&B`(x1__L f.)`(x2__L f.)`(x3__L f.)`(x4__L f.) )
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Java
Java
import java.util.function.DoubleSupplier;   public class ManOrBoy {   static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {   DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDouble() { return A(--m, this, x1, x2, x3, x4); } };   return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); }   public static void main(String[] args) { System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); } }
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#ELLA
ELLA
MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t: [INT i = 1..m] [INT j = 1..n] matrix[j][i].
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#JavaScript
JavaScript
function maze(x,y) { var n=x*y-1; if (n<0) {alert("illegal maze dimensions");return;} var horiz =[]; for (var j= 0; j<x+1; j++) horiz[j]= [], verti =[]; for (var j= 0; j<x+1; j++) verti[j]= [], here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)], path = [here], unvisited = []; for (var j = 0; j<x+2; j++) { unvisited[j] = []; for (var k= 0; k<y+1; k++) unvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1)); } while (0<n) { var potential = [[here[0]+1, here[1]], [here[0],here[1]+1], [here[0]-1, here[1]], [here[0],here[1]-1]]; var neighbors = []; for (var j = 0; j < 4; j++) if (unvisited[potential[j][0]+1][potential[j][1]+1]) neighbors.push(potential[j]); if (neighbors.length) { n = n-1; next= neighbors[Math.floor(Math.random()*neighbors.length)]; unvisited[next[0]+1][next[1]+1]= false; if (next[0] == here[0]) horiz[next[0]][(next[1]+here[1]-1)/2]= true; else verti[(next[0]+here[0]-1)/2][next[1]]= true; path.push(here = next); } else here = path.pop(); } return {x: x, y: y, horiz: horiz, verti: verti}; }   function display(m) { var text= []; for (var j= 0; j<m.x*2+1; j++) { var line= []; if (0 == j%2) for (var k=0; k<m.y*4+1; k++) if (0 == k%4) line[k]= '+'; else if (j>0 && m.verti[j/2-1][Math.floor(k/4)]) line[k]= ' '; else line[k]= '-'; else for (var k=0; k<m.y*4+1; k++) if (0 == k%4) if (k>0 && m.horiz[(j-1)/2][k/4-1]) line[k]= ' '; else line[k]= '|'; else line[k]= ' '; if (0 == j) line[1]= line[2]= line[3]= ' '; if (m.x*2-1 == j) line[4*m.y]= ' '; text.push(line.join('')+'\r\n'); } return text.join(''); }
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Tcl
Tcl
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc}   proc matrix_exp {m pow} { if { ! [string is int -strict $pow]} { error "non-integer exponents not implemented" } if {$pow < 0} { error "negative exponents not implemented" } lassign [size $m] rows cols # assume square matrix set temp [identity $rows] for {set n 1} {$n <= $pow} {incr n} { set temp [matrix_multiply $temp $m] } return $temp }   proc identity {size} { set i [lrepeat $size [lrepeat $size 0]] for {set n 0} {$n < $size} {incr n} {lset i $n $n 1} return $i }
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#jq
jq
# The input is the value to be mapped. # The ranges, a and b, should each be an array defining the # left-most and right-most points of the range. def maprange(a; b): b[0] + (((. - a[0]) * (b[1] - b[0])) / (a[1] - a[0])) ;
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Julia
Julia
function maprange(s, a, b) a₁, a₂ = minimum(a), maximum(a) b₁, b₂ = minimum(b), maximum(b) return b₁ + (s - a₁) * (b₂ - b₁) / (a₂ - a₁) end   @show maprange(6, 1:10, -1:0) @show maprange(0:10, 0:10, -1:0)
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Sidef
Sidef
var sum = [0]   ARGF.each { |line| var x = line.words.map{.to_n} sum = [ x.first + sum.first, 1 ..^ x.end -> map{|i| x[i] + [sum[i-1, i]].max}..., x.last + sum.last, ] }   say sum.max
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#MATLAB
MATLAB
function digest = md5(message) % digest = md5(message) % Compute the MD5 digest of the message, as a hexadecimal digest.   % Follow the MD5 algorithm from RFC 1321 [1] and Wikipedia [2]. % [1] http://tools.ietf.org/html/rfc1321 % [2] http://en.wikipedia.org/wiki/MD5   % m is the modulus for 32-bit unsigned arithmetic. m = 2 ^ 32;   % s is the shift table for circshift(). Each shift is negative % because it is a left shift. s = [-7, -12, -17, -22 -5, -9, -14, -20 -4, -11, -16, -23 -6, -10, -15, -21];   % t is the sine table. Each sine is a 32-bit integer, unsigned. t = floor(abs(sin(1:64)) .* m);   % Initialize the hash, as a row vector of 32-bit integers. digest = [hex2dec('67452301') ... hex2dec('EFCDAB89') ... hex2dec('98BADCFE') ... hex2dec('10325476')];   % If message contains characters, convert them to ASCII values. message = double(message); bytelen = numel(message);   % Pad the message by appending a 1, then appending enough 0s to make % the bit length congruent to 448 mod 512. Because we have bytes, we % append 128 '10000000', then append enough 0s '00000000's to make % the byte length congruent to 56 mod 64. message = [message, 128, zeros(1, mod(55 - bytelen, 64))];   % Convert the message to 32-bit integers, little endian. % For little endian, first byte is least significant byte. message = reshape(message, 4, numel(message) / 4); message = message(1,:) + ... % least significant byte message(2,:) * 256 + ... message(3,:) * 65536 + ... message(4,:) * 16777216; % most significant byte   % Append the bit length as a 64-bit integer, little endian. bitlen = bytelen * 8; message = [message, mod(bitlen, m), mod(bitlen / m, m)];   % Process each 512-bit block. Because we have 32-bit integers, each % block has 16 elements, message(k + (0:15)). for k = 1:16:numel(message) % Copy hash. a = digest(1); b = digest(2); c = digest(3); d = digest(4);   % Do 64 operations. for i = (1:64) % Convert b, c, d to row vectors of bits (0s and 1s). bv = dec2bin(b, 32) - '0'; cv = dec2bin(c, 32) - '0'; dv = dec2bin(d, 32) - '0';   % Find f = mix of b, c, d. % ki = index in 0:15, to message(k + ki). % sr = row in 1:4, to s(sr, :). if i <= 16 % Round 1 f = (bv & cv) | (~bv & dv); ki = i - 1; sr = 1; elseif i <= 32 % Round 2 f = (bv & dv) | (cv & ~dv); ki = mod(5 * i - 4, 16); sr = 2; elseif i <= 48 % Round 3 f = xor(bv, xor(cv, dv)); ki = mod(3 * i + 2, 16); sr = 3; else % Round 4 f = xor(cv, bv | ~dv); ki = mod(7 * i - 7, 16); sr = 4; end   % Convert f, from row vector of bits, to 32-bit integer. f = bin2dec(char(f + '0'));   % Do circular shift of sum. sc = mod(i - 1, 4) + 1; sum = mod(a + f + message(k + ki) + t(i), m); sum = dec2bin(sum, 32); sum = circshift(sum, [0, s(sr, sc)]); sum = bin2dec(sum);   % Update a, b, c, d. temp = d; d = c; c = b; b = mod(b + sum, m); a = temp; end %for i   % Add hash of this block to hash of previous blocks. digest = mod(digest + [a, b, c, d], m); end %for k   % Convert hash from 32-bit integers, little endian, to bytes. digest = [digest % least significant byte digest / 256 digest / 65536 digest / 16777216]; % most significant byte digest = reshape(mod(floor(digest), 256), 1, numel(digest));   % Convert hash to hexadecimal. digest = dec2hex(digest); digest = reshape(transpose(digest), 1, numel(digest)); end %md5
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. MANDELBROT-SET-PROGRAM. DATA DIVISION. WORKING-STORAGE SECTION. 01 COMPLEX-ARITHMETIC. 05 X PIC S9V9(9). 05 Y PIC S9V9(9). 05 X-A PIC S9V9(6). 05 X-B PIC S9V9(6). 05 Y-A PIC S9V9(6). 05 X-A-SQUARED PIC S9V9(6). 05 Y-A-SQUARED PIC S9V9(6). 05 SUM-OF-SQUARES PIC S9V9(6). 05 ROOT PIC S9V9(6). 01 LOOP-COUNTERS. 05 I PIC 99. 05 J PIC 99. 05 K PIC 999. 77 PLOT-CHARACTER PIC X. PROCEDURE DIVISION. CONTROL-PARAGRAPH. PERFORM OUTER-LOOP-PARAGRAPH VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN 24. STOP RUN. OUTER-LOOP-PARAGRAPH. PERFORM INNER-LOOP-PARAGRAPH VARYING J FROM 1 BY 1 UNTIL J IS GREATER THAN 64. DISPLAY ''. INNER-LOOP-PARAGRAPH. MOVE SPACE TO PLOT-CHARACTER. MOVE ZERO TO X-A. MOVE ZERO TO Y-A. MULTIPLY J BY 0.0390625 GIVING X. SUBTRACT 1.5 FROM X. MULTIPLY I BY 0.083333333 GIVING Y. SUBTRACT 1 FROM Y. PERFORM ITERATION-PARAGRAPH VARYING K FROM 1 BY 1 UNTIL K IS GREATER THAN 100 OR PLOT-CHARACTER IS EQUAL TO '#'. DISPLAY PLOT-CHARACTER WITH NO ADVANCING. ITERATION-PARAGRAPH. MULTIPLY X-A BY X-A GIVING X-A-SQUARED. MULTIPLY Y-A BY Y-A GIVING Y-A-SQUARED. SUBTRACT Y-A-SQUARED FROM X-A-SQUARED GIVING X-B. ADD X TO X-B. MULTIPLY X-A BY Y-A GIVING Y-A. MULTIPLY Y-A BY 2 GIVING Y-A. SUBTRACT Y FROM Y-A. MOVE X-B TO X-A. ADD X-A-SQUARED TO Y-A-SQUARED GIVING SUM-OF-SQUARES. MOVE FUNCTION SQRT (SUM-OF-SQUARES) TO ROOT. IF ROOT IS GREATER THAN 2 THEN MOVE '#' TO PLOT-CHARACTER.
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#FreeBASIC
FreeBASIC
' version 23-06-2015 ' compile with: fbc -s console   Sub magicsq(size As Integer, filename As String ="")   If (size And 1) = 0 Or size < 3 Then Print : Beep ' alert Print "error: size is not odd or size is smaller then 3" Sleep 3000,1 'wait 3 seconds, ignore key press Exit Sub End If   ' filename <> "" then save magic square in a file ' filename can contain directory name ' if filename exist it will be overwriten, no error checking   Dim As Integer sq(size,size) ' array to hold square ' start in the middle of the first row Dim As Integer nr = 1, x = size - (size \ 2), y = 1 Dim As Integer max = size * size ' create format string for using Dim As String frmt = String(Len(Str(max)) +1, "#")   ' main loop for creating magic square Do If sq(x, y) = 0 Then sq(x, y) = nr If nr Mod size = 0 Then y += 1 Else x += 1 y -= 1 End If nr += 1 End If If x > size Then x = 1 Do While sq(x,y) <> 0 x += 1 Loop End If If y < 1 Then y = size Do While sq(x,y) <> 0 y -= 1 Loop EndIf Loop Until nr > max   ' printing square's bigger than 19 result in a wrapping of the line Print "Odd magic square size:"; size; " *"; size Print "The magic sum ="; ((max +1) \ 2) * size Print   For y = 1 To size For x = 1 To size Print Using frmt; sq(x,y); Next Print Next print   ' output magic square to a file with the name provided If filename <> "" Then nr = FreeFile Open filename For Output As #nr Print #nr, "Odd magic square size:"; size; " *"; size Print #nr, "The magic sum ="; ((max +1) \ 2) * size Print #nr,   For y = 1 To size For x = 1 To size Print #nr, Using frmt; sq(x,y); Next Print #nr, Next End If Close   End Sub   ' ------=< MAIN >=------   magicsq(5) magicsq(11) ' the next line will also print the square to a file called: magic_square_19.txt magicsq(19, "magic_square_19.txt")     ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#ERRE
ERRE
  PROGRAM MAT_PROD   DIM A[3,1],B[1,2],ANS[3,2]   BEGIN   DATA(1,2,3,4,5,6,7,8) DATA(1,2,3,4,5,6)   FOR I=0 TO 3 DO FOR J=0 TO 1 DO READ(A[I,J]) END FOR END FOR   FOR I=0 TO 1 DO FOR J=0 TO 2 DO READ(B[I,J]) END FOR END FOR   FOR I=0 TO UBOUND(ANS,1) DO FOR J=0 TO UBOUND(ANS,2) DO FOR K=0 TO UBOUND(A,2) DO ANS[I,J]=ANS[I,J]+(A[I,K]*B[K,J]) END FOR END FOR END FOR ! print answer FOR I=0 TO UBOUND(ANS,1) DO FOR J=0 TO UBOUND(ANS,2) DO PRINT(ANS[I,J],) END FOR PRINT END FOR   END PROGRAM  
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#R
R
magic <- function(n) { if (n %% 2 == 1) { p <- (n + 1) %/% 2 - 2 ii <- seq(n) outer(ii, ii, function(i, j) n * ((i + j + p) %% n) + (i + 2 * (j - 1)) %% n + 1) } else if (n %% 4 == 0) { p <- n * (n + 1) + 1 ii <- seq(n) outer(ii, ii, function(i, j) ifelse((i %/% 2 - j %/% 2) %% 2 == 0, p - n * i - j, n * (i - 1) + j)) } else { p <- n %/% 2 q <- p * p k <- (n - 2) %/% 4 + 1 a <- Recall(p) a <- rbind(cbind(a, a + 2 * q), cbind(a + 3 * q, a + q)) ii <- seq(p) jj <- c(seq(k - 1), seq(length.out=k - 2, to=n)) m <- a[ii, jj]; a[ii, jj] <- a[ii + p, jj]; a[ii + p, jj] <- m jj <- c(1, k) m <- a[k, jj]; a[k, jj] <- a[k + p, jj]; a[k + p, jj] <- m a } }
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Raku
Raku
1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 The magic number is 260
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#JavaScript
JavaScript
function a(k, x1, x2, x3, x4, x5) { function b() { k -= 1; return a(k, b, x1, x2, x3, x4); } return (k > 0) ? b() : x4() + x5(); }   // this uses lambda wrappers around the numeric arguments function x(n) { return function () { return n; }; } alert(a(10, x(1), x(-1), x(-1), x(1), x(0)));
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib)   (defun transpose (m) (apply #'cl-mapcar #'list m))   ;;test for transposition function (transpose '((2 3 4 5) (3 5 6 9) (9 9 9 9)))
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#Julia
Julia
using Random check(bound::Vector) = cell -> all([1, 1] .≤ cell .≤ bound) neighbors(cell::Vector, bound::Vector, step::Int=2) = filter(check(bound), map(dir -> cell + step * dir, [[0, 1], [-1, 0], [0, -1], [1, 0]]))   function walk(maze::Matrix, nxtcell::Vector, visited::Vector=[]) push!(visited, nxtcell) for neigh in shuffle(neighbors(nxtcell, collect(size(maze)))) if neigh ∉ visited maze[round.(Int, (nxtcell + neigh) / 2)...] = 0 walk(maze, neigh, visited) end end maze end function maze(w::Int, h::Int) maze = collect(i % 2 | j % 2 for i in 1:2w+1, j in 1:2h+1) firstcell = 2 * [rand(1:w), rand(1:h)] return walk(maze, firstcell) end
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#TI-89_BASIC
TI-89 BASIC
[3,2;4,1]^4
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Ursala
Ursala
#import nat #import lin   id = @h ^|CzyCK33/1.! 0.!* mex = ||id@l mmult:-0^|DlS/~& iota
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#K
K
f:{[a1;a2;b1;b2;s] b1+(s-a1)*(b2-b1)%(a2-a1)}   +(a; f[0;10;-1;0]'a:!11) ((0;-1.0) (1;-0.9) (2;-0.8) (3;-0.7) (4;-0.6) (5;-0.5) (6;-0.4) (7;-0.3) (8;-0.2) (9;-0.1) (10;0.0))
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Kotlin
Kotlin
// version 1.0.6   class FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange<Float>   fun mapRange(range1: FloatRange, range2: FloatRange, value: Float): Float { if (value !in range1) throw IllegalArgumentException("value is not within the first range") if (range1.endInclusive == range1.start) throw IllegalArgumentException("first range cannot be single-valued") return range2.start + (value - range1.start) * (range2.endInclusive - range2.start) / (range1.endInclusive - range1.start) }   fun main(args: Array<String>) { for (i in 0..10) { val mappedValue = mapRange(FloatRange(0.0f, 10.0f), FloatRange(-1.0f, 0.0f), i.toFloat()) println(String.format("%2d maps to %+4.2f", i, mappedValue)) } }
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Stata
Stata
import delimited triangle.txt, delim(" ") clear mata a = st_data(.,.) n = rows(a) for (i=n-1; i>=1; i--) { for (j=1; j<=i; j++) { a[i,j] = a[i,j]+max((a[i+1,j],a[i+1,j+1])) } } a[1,1] end
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#min
min
"The quick brown fox jumps over the lazy dog" md5 puts!
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Common_Lisp
Common Lisp
(defpackage #:mandelbrot (:use #:cl))   (in-package #:mandelbrot)   (deftype pixel () '(unsigned-byte 8)) (deftype image () '(array pixel))   (defun write-pgm (image filespec) (declare (image image)) (with-open-file (s filespec :direction :output :element-type 'pixel :if-exists :supersede) (let* ((width (array-dimension image 1)) (height (array-dimension image 0)) (header (format nil "P5~A~D ~D~A255~A" #\Newline width height #\Newline #\Newline))) (loop for c across header do (write-byte (char-code c) s)) (dotimes (row height) (dotimes (col width) (write-byte (aref image row col) s))))))   (defparameter *x-max* 800) (defparameter *y-max* 800) (defparameter *cx-min* -2.5) (defparameter *cx-max* 1.5) (defparameter *cy-min* -2.0) (defparameter *cy-max* 2.0) (defparameter *escape-radius* 2) (defparameter *iteration-max* 40)   (defun mandelbrot (filespec) (let ((pixel-width (/ (- *cx-max* *cx-min*) *x-max*)) (pixel-height (/ (- *cy-max* *cy-min*) *y-max*)) (image (make-array (list *y-max* *x-max*) :element-type 'pixel :initial-element 0))) (loop for y from 0 below *y-max* for cy from *cy-min* by pixel-height do (loop for x from 0 below *x-max* for cx from *cx-min* by pixel-width for iteration = (loop with c = (complex cx cy) for iteration from 0 below *iteration-max* for z = c then (+ (* z z) c) while (< (abs z) *escape-radius*) finally (return iteration)) for pixel = (round (* 255 (/ (- *iteration-max* iteration) *iteration-max*))) do (setf (aref image y x) pixel))) (write-pgm image filespec)))
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Frink
Frink
order = length[ARGS] > 0 ? eval[ARGS@0] : undef until isInteger[order] and order mod 2 == 1 order = eval[input["Enter order (must be odd): ", 3]]   a = new array[[order, order], undef] x = order div 2 y = 0   for i = 1 to order^2 { ny = (y - 1) mod order nx = (x + 1) mod order if a@ny@nx != undef { nx = x ny = (y + 1) mod order } a@y@x = i y = ny x = nx }   println[formatTable[a]] println["Magic number is " + sum[a@0]]
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Go
Go
package main   import ( "fmt" "log" )   func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m }   func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Euphoria
Euphoria
function matrix_mul(sequence a, sequence b) sequence c if length(a[1]) != length(b) then return 0 else c = repeat(repeat(0,length(b[1])),length(a)) for i = 1 to length(a) do for j = 1 to length(b[1]) do for k = 1 to length(a[1]) do c[i][j] += a[i][k]*b[k][j] end for end for end for return c end if end function
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#REXX
REXX
/*REXX program constructs a magic square of doubly even sides (a size divisible by 4).*/ n= 8; s= n%4; L= n%2-s+1; w= length(n**2) /*size; small sq; low middle; # width*/ @.= 0; H= n%2+s /*array default; high middle. */ call gen /*generate a grid in numerical order. */ call diag /*mark numbers on both diagonals. */ call corn /* " " in small corner boxen. */ call midd /* " " in the middle " */ call swap /*swap positive numbers with highest #.*/ call show /*display the doubly even magic square.*/ call sum /* " " magic number for square. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ o: parse arg ?; return n-?+1 /*calculate the "other" (right) column.*/ @: parse arg x,y; return abs(@.x.y) diag: do r=1 for n; @.r.r=-@(r,r); o=o(r); @.r.o=-@(r,o); end; return midd: do r=L to H; do c=L to H; @.r.c=-@(r,c); end; end; return gen: #=0; do r=1 for n; do c=1 for n; #=#+1; @.r.c=#; end; end; return show: #=0; do r=1 for n; $=; do c=1 for n; $=$ right(@(r,c),w); end; say $; end; return sum: #=0; do r=1 for n; #=#+@(r,1); end; say; say 'The magic number is: ' #; return max#: do a=n for n by -1; do b=n for n by -1; if @.a.b>0 then return; end; end /*──────────────────────────────────────────────────────────────────────────────────────*/ swap: do r=1 for n do c=1 for n; if @.r.c<0 then iterate; call max# /*find max number.*/ parse value -@.a.b (-@.r.c) with @.r.c @.a.b /*swap two values.*/ end /*c*/ end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ corn: do r=1 for n; if r>s & r<=n-s then iterate /*"corner boxen", size≡S*/ do c=1 for n; if c>s & c<=n-s then iterate; @.r.c= -@(r,c) /*negate*/ end /*c*/ end /*r*/; return
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Jsish
Jsish
/* Knuth's Man or boy test (local references in recursion), in Jsish */ /* As noted, needs a fair sized stack depth, default is 200 in jsish v2.8.24 */ Interp.conf({maxDepth:2048});   function a(k, x1, x2, x3, x4, x5) { function b() { k -= 1; return a(k, b, x1, x2, x3, x4); } return (k > 0) ? b() : x4() + x5(); }   // this uses lambda wrappers around the numeric arguments function x(n) { return function () { return n; }; }   puts(a(10, x(1), x(-1), x(-1), x(1), x(0)));   /* =!EXPECTSTART!= -67 =!EXPECTEND!= */
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Erlang
Erlang
  -module(transmatrix). -export([trans/1,transL/1]).   % using built-ins hd = head, tl = tail   trans([[]|_]) -> []; trans(M) -> [ lists:map(fun hd/1, M) | transpose( lists:map(fun tl/1, M) ) ].   % Purist version   transL( [ [Elem | Rest] | List] ) -> [ [Elem | [H || [H | _] <- List] ] | transL( [Rest | [ T || [_ | T] <- List ] ] ) ]; transL([ [] | List] ) -> transL(List); transL([]) -> [].  
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#Kotlin
Kotlin
import java.util.*   class MazeGenerator(val x: Int, val y: Int) { private val maze = Array(x) { IntArray(y) }   fun generate(cx: Int, cy: Int) { Direction.values().shuffle().forEach { val nx = cx + it.dx val ny = cy + it.dy if (between(nx, x) && between(ny, y) && maze[nx][ny] == 0) { maze[cx][cy] = maze[cx][cy] or it.bit maze[nx][ny] = maze[nx][ny] or it.opposite!!.bit generate(nx, ny) } } }   fun display() { for (i in 0..y - 1) { // draw the north edge for (j in 0..x - 1) print(if (maze[j][i] and 1 == 0) "+---" else "+ ") println('+')   // draw the west edge for (j in 0..x - 1) print(if (maze[j][i] and 8 == 0) "| " else " ") println('|') }   // draw the bottom line for (j in 0..x - 1) print("+---") println('+') }   inline private fun <reified T> Array<T>.shuffle(): Array<T> { val list = toMutableList() Collections.shuffle(list) return list.toTypedArray() }   private enum class Direction(val bit: Int, val dx: Int, val dy: Int) { N(1, 0, -1), S(2, 0, 1), E(4, 1, 0),W(8, -1, 0);   var opposite: Direction? = null   companion object { init { N.opposite = S S.opposite = N E.opposite = W W.opposite = E } } }   private fun between(v: Int, upper: Int) = v >= 0 && v < upper }   fun main(args: Array<String>) { val x = if (args.size >= 1) args[0].toInt() else 8 val y = if (args.size == 2) args[1].toInt() else 8 with(MazeGenerator(x, y)) { generate(0, 0) display() } }
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#VBA
VBA
Option Base 1 Private Function Identity(n As Integer) As Variant Dim I() As Variant ReDim I(n, n) For j = 1 To n For k = 1 To n I(j, k) = 0 Next k Next j For j = 1 To n I(j, j) = 1 Next j Identity = I End Function Function MatrixExponentiation(ByVal x As Variant, ByVal n As Integer) As Variant If n < 0 Then x = WorksheetFunction.MInverse(x) n = -n End If If n = 0 Then MatrixExponentiation = Identity(UBound(x)) Exit Function End If Dim y() As Variant y = Identity(UBound(x)) Do While n > 1 If n Mod 2 = 0 Then x = WorksheetFunction.MMult(x, x) n = n / 2 Else y = WorksheetFunction.MMult(x, y) x = WorksheetFunction.MMult(x, x) n = (n - 1) / 2 End If Loop MatrixExponentiation = WorksheetFunction.MMult(x, y) End Function Public Sub pp(x As Variant) For i_ = 1 To UBound(x) For j_ = 1 To UBound(x) Debug.Print x(i_, j_), Next j_ Debug.Print Next i_ End Sub Public Sub main() M2 = [{3,2;2,1}] M3 = [{1,2,0;0,3,1;1,0,0}] pp MatrixExponentiation(M2, -1) Debug.Print pp MatrixExponentiation(M2, 0) Debug.Print pp MatrixExponentiation(M2, 10) Debug.Print pp MatrixExponentiation(M3, 10) End Sub
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Lambdatalk
Lambdatalk
  {def maprange {lambda {:a0 :a1 :b0 :b1 :s} {+ :b0 {/ {* {- :s :a0} {- :b1 :b0}} {- :a1 :a0}}}}} -> maprange   {maprange 0 10 -1 0 5} -> -0.5   {S.map {maprange 0 10 -1 0} {S.serie 0 10}} -> 0 maps to -1 1 maps to -0.9 2 maps to -0.8 3 maps to -0.7 4 maps to -0.6 5 maps to -0.5 6 maps to -0.4 7 maps to -0.30000000000000004 8 maps to -0.19999999999999996 9 maps to -0.09999999999999998 10 maps to 0  
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Tcl
Tcl
package require Tcl 8.6   proc maxTrianglePathSum {definition} { # Parse the definition, stripping whitespace and leading zeroes. set lines [lmap line [split [string trim $definition] "\n"] { lmap val $line {scan $val %d} }] # Paths are bit strings (0 = go left, 1 = go right). # Enumerate the possible paths. set numPaths [expr {2 ** [llength $lines]}] for {set path 0; set max -inf} {$path < $numPaths} {incr path} { # Work out how much the current path costs. set sum [set idx [set row 0]] for {set bit 1} {$row < [llength $lines]} {incr row} { incr sum [lindex $lines $row $idx] if {$path & $bit} {incr idx} set bit [expr {$bit << 1}] } # Remember the max so far. if {$sum > $max} {set max $sum} } return $max }   puts [maxTrianglePathSum { 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 }] # Reading from a file is left as an exercise…
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#MOO
MOO
string = "The quick brown fox jumped over the lazy dog's back"; player:tell(string_hash(string));
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Cowgol
Cowgol
include "cowgol.coh";   const xmin := -8601; const xmax := 2867; const ymin := -4915; const ymax := 4915; const maxiter := 32;   const dx := (xmax-xmin)/79; const dy := (ymax-ymin)/24;   var cy: int16 := ymin; while cy <= ymax loop var cx: int16 := xmin; while cx <= xmax loop var x: int32 := 0; var y: int32 := 0; var x2: int32 := 0; var y2: int32 := 0; var iter: uint8 := 0;   while iter < maxiter and x2 + y2 <= 16384 loop y := ((x*y)>>11)+cy as int32; x := x2-y2+cx as int32; x2 := (x*x)>>12; y2 := (y*y)>>12; iter := iter + 1; end loop;   print_char(' ' + iter); cx := cx + dx; end loop; print_nl(); cy := cy + dy; end loop;
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) the first   N2   positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square. 8 1 6 3 5 7 4 9 2 Task For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here. Optionally, show the magic number. You should demonstrate the generator by showing at least a magic square for   N = 5. Related tasks Magic squares of singly even order Magic squares of doubly even order See also MathWorld™ entry: Magic_square Odd Magic Squares (1728.org)
#Haskell
Haskell
-- as a translation from imperative code, this is probably not a "good" implementation import Data.List   type Var = (Int, Int, Int, Int) -- sx sy sz c   magicSum :: Int -> Int magicSum x = ((x * x + 1) `div` 2) * x   wrapInc :: Int -> Int -> Int wrapInc max x | x + 1 == max = 0 | otherwise = x + 1   wrapDec :: Int -> Int -> Int wrapDec max x | x == 0 = max - 1 | otherwise = x - 1   isZero :: [[Int]] -> Int -> Int -> Bool isZero m x y = m !! x !! y == 0   setAt :: (Int,Int) -> Int -> [[Int]] -> [[Int]] setAt (x, y) val table | (upper, current : lower) <- splitAt x table, (left, this : right) <- splitAt y current = upper ++ (left ++ val : right) : lower | otherwise = error "Outside"   create :: Int -> [[Int]] create x = replicate x $ replicate x 0   cells :: [[Int]] -> Int cells m = x*x where x = length m   fill :: Var -> [[Int]] -> [[Int]] fill (sx, sy, sz, c) m | c < cells m = if isZero m sx sy then fill ((wrapInc sz sx), (wrapDec sz sy), sz, c + 1) (setAt (sx, sy) (c + 1) m) else fill ((wrapDec sz sx), (wrapInc sz(wrapInc sz sy)), sz, c) m | otherwise = m   magicNumber :: Int -> [[Int]] magicNumber d = transpose $ fill (d `div` 2, 0, d, 0) (create d)   display :: [[Int]] -> String display (x:xs) | null xs = vdisplay x | otherwise = vdisplay x ++ ('\n' : display xs)   vdisplay :: [Int] -> String vdisplay (x:xs) | null xs = show x | otherwise = show x ++ " " ++ vdisplay xs     magicSquare x = do putStr "Magic Square of " putStr $ show x putStr " = " putStrLn $ show $ magicSum x putStrLn $ display $ magicNumber x
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Excel
Excel
  let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) = let result_row = (matrix1.GetLength 0) let result_column = (matrix2.GetLength 1) let ret = Array2D.create result_row result_column 0 for x in 0 .. result_row - 1 do for y in 0 .. result_column - 1 do let mutable acc = 0 for z in 0 .. (matrix1.GetLength 1) - 1 do acc <- acc + matrix1.[x,z] * matrix2.[z,y] ret.[x,y] <- acc ret    
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Ruby
Ruby
def double_even_magic_square(n) raise ArgumentError, "Need multiple of four" if n%4 > 0 block_size, max = n/4, n*n pre_pat = [true, false, false, true, false, true, true, false] pre_pat += pre_pat.reverse pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size flat_ar = pattern.each_with_index.map{|yes, num| yes ? num+1 : max-num} flat_ar.each_slice(n).to_a end   def to_string(square) n = square.size fmt = "%#{(n*n).to_s.size + 1}d" * n square.inject(""){|str,row| str << fmt % row << "\n"} end   puts to_string(double_even_magic_square(8))
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction. 1 2 62 61 60 59 7 8 9 10 54 53 52 51 15 16 48 47 19 20 21 22 42 41 40 39 27 28 29 30 34 33 32 31 35 36 37 38 26 25 24 23 43 44 45 46 18 17 49 50 14 13 12 11 55 56 57 58 6 5 4 3 63 64 Task Create a magic square of   8 × 8. Related tasks Magic squares of odd order Magic squares of singly even order See also Doubly Even Magic Squares (1728.org)
#Rust
Rust
use std::env;   fn main() { let n: usize = match env::args() .nth(1) .and_then(|arg| arg.parse().ok()) .ok_or("Please specify the size of the magic square, as a positive multiple of 4.") { Ok(arg) if arg >= 4 && arg % 4 == 0 => arg, Err(e) => panic!(e), _ => panic!("Argument must be a positive multiple of 4."), };   let mc = (n * n + 1) * n / 2; println!("Magic constant: {}\n", mc); let bits = 0b1001_0110_0110_1001u32; let size = n * n; let width = size.to_string().len() + 1; let mult = n / 4; let mut i = 0; for r in 0..n { for c in 0..n { let bit_pos = c / mult + (r / mult) * 4; print!( "{e:>w$}", e = if bits & (1 << bit_pos) != 0 { i + 1 } else { size - i }, w = width ); i += 1; } println!(); } }
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not. I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers' — Donald Knuth Task: Imitate Knuth's example in Algol 60 in another language, as far as possible. Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem. In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation. So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. The table below shows the result, call depths, and total calls for a range of k: k 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 A 1 0 -2 0 1 0 1 -1 -10 -30 -67 -138 -291 -642 -1,446 -3,250 -7,244 -16,065 -35,601 -78,985 -175,416 -389,695 -865,609 -1,922,362 -4,268,854 -9,479,595 -21,051,458 -46,750,171 -103,821,058 -230,560,902 -512,016,658 A called 1 2 3 4 8 18 38 80 167 347 722 1,509 3,168 6,673 14,091 29,825 63,287 134,652 287,264 614,442 1,317,533 2,831,900 6,100,852 13,172,239 28,499,827 61,786,266 134,202,509 292,011,464       A depth 1 2 3 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 32,768 65,536 131,072 262,144 524,288 1,048,576 2,097,152 4,194,304 8,388,608             B called 0 1 2 3 7 17 37 79 166 346 721 1,508 3,167 6,672 14,090 29,824 63,286 134,651 287,263 614,441 1,317,532 2,831,899 6,100,851 13,172,238 28,499,826             B depth 0 1 2 3 7 15 31 63 127 255 511 1,023 2,047 4,095 8,191 16,383 32,767 65,535 131,071 262,143 524,287 1,048,575 2,097,151 4,194,303 8,388,607             Related tasks   Jensen's Device
#Julia
Julia
function a(k, x1, x2, x3, x4, x5) b = ()-> a(k-=1, b, x1, x2, x3, x4); k <= 0 ? (x4() + x5()) : b(); end   println(a(10, ()->1, ()->-1, ()->-1, ()->1, ()->0));