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/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Java
Java
public class McNuggets {   public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100; // Works like Sieve of Eratosthenes int numSizes = SIZES.length; int[] counts = new int[numSizes]; int maxFound = MAX_TOTAL + 1; boolean[] found = new boolean[maxFound]; int numFound = 0; int total = 0; boolean advancedState = false; do { if (!found[total]) { found[total] = true; numFound++; }   // Advance state advancedState = false; for (int i = 0; i < numSizes; i++) { int curSize = SIZES[i]; if ((total + curSize) > MAX_TOTAL) { // Reset to zero and go to the next box size total -= counts[i] * curSize; counts[i] = 0; } else { // Adding a box of this size still keeps the total at or below the maximum counts[i]++; total += curSize; advancedState = true; break; } }   } while ((numFound < maxFound) && advancedState);   if (numFound < maxFound) { // Did not find all counts within the search space for (int i = MAX_TOTAL; i >= 0; i--) { if (!found[i]) { System.out.println("Largest non-McNugget number in the search space is " + i); break; } } } else { System.out.println("All numbers in the search space are McNugget numbers"); }   return; } }
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#BASIC
BASIC
10 DEFINT A-Z: DIM L$(5) 15 FOR I=0 TO 5: READ L$(I): NEXT I 20 LINE INPUT I$ 30 M=LEN(I$): DIM D(M) 40 FOR I=1 TO M: D(I)=VAL(MID$(I$,I,1)): NEXT I 50 FOR J=M-1 TO 1 STEP -1 60 FOR I=1 TO J 70 D(I+1) = D(I+1) + 10*(D(I) AND 1) 80 D(I) = D(I)\2 90 NEXT I,J 100 S=1 110 IF D(S)=0 AND S<M THEN S=S+1: GOTO 110 120 FOR I=S TO M: PRINT "+----";: NEXT I: PRINT "+" 130 FOR L=3 TO 0 STEP -1 140 FOR I=S TO M 150 IF (D(I) OR L)=0 THEN PRINT "| @ ";: GOTO 180 160 N=D(I)-5*L: IF N>5 THEN N=5 ELSE IF N<0 THEN N=0 170 PRINT "|";L$(N); 180 NEXT I 190 PRINT "|" 200 NEXT L 210 FOR I=S TO M: PRINT "+----";: NEXT I: PRINT "+" 220 END 230 DATA " "," . "," .. ","... ","....","----"
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#BCPL
BCPL
get "libhdr"   let reads(v) be $( v%0 := 0 $( let ch = rdch() if ch = '*N' | ch = endstreamch break v%0 := v%0 + 1 v%(v%0) := ch $) repeat $)   let digits(v) = valof $( for i=1 to v%0 $( unless '0' <= v%i <= '9' resultis false v%i := v%i - '0' $) resultis true $)   let base20(v) be $( let i = ? for j=v%0-1 to 1 by -1 for i=1 to j $( v%(i+1) := v%(i+1) + 10*(v%i & 1) v%i := v%i >> 1 $) i := 1 while v%i=0 & i<v%0 do i := i+1 for j=i to v%0 do v%(j-i+1) := v%j v%0 := v%0-i+1 $)   let mayan(v) be $( let border(n) be $( for i=1 to n do writes("+----") writes("+*N") $) let part(num, line) be test num=0 do writes(line=0 -> " @ ", " ") or $( num := num - line*5 writes(num<=0 -> " ", num =1 -> " . ", num =2 -> " .. ", num =3 -> "... ", num =4 -> "....", "----") $) border(v%0) for l=3 to 0 by -1 $( for d=1 to v%0 $( wrch('|') part(v%d, l) $) writes("|*N") $) border(v%0) $)   let start() be $( let v = vec 1+255/BYTESPERWORD $( writes("Number? ") reads(v) if v%0=0 finish unless digits(v) loop base20(v) mayan(v) $) repeat $)
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#D
D
import std.stdio, std.random, std.string, std.array, std.algorithm, std.file, std.conv;   enum int cx = 4, cy = 2; // Cell size x and y. enum int cx2 = cx / 2, cy2 = cy / 2; enum pathSymbol = '.'; struct V2 { int x, y; }   bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc { if (s == end) return true;   foreach (immutable d; [V2(0, -cy), V2(+cx, 0), V2(0, +cy), V2(-cx, 0)]) if (maze[s.y + (d.y / 2)][s.x + (d.x / 2)] == ' ' && maze[s.y + d.y][s.x + d.x] == ' ') { //Would this help? // maze[s.y + (d.y / 2)][s.x + (d.x / 2)] = pathSymbol; maze[s.y + d.y][s.x + d.x] = pathSymbol; if (solveMaze(maze, V2(s.x + d.x, s.y + d.y), end)) return true; maze[s.y + d.y][s.x + d.x] = ' '; }   return false; }   void main() { auto maze = "maze.txt".File.byLine.map!(r => r.chomp.dup).array; immutable h = (maze.length.signed - 1) / cy; assert (h > 0); immutable w = (maze[0].length.signed - 1) / cx;   immutable start = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h)); immutable end = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h));   maze[start.y][start.x] = pathSymbol; if (!solveMaze(maze, start, end)) return "No solution path found.".writeln; maze[start.y][start.x] = 'S'; maze[end.y][end.x] = 'E'; writefln("%-(%s\n%)", maze); }
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.
#C.23
C#
  using System;   namespace RosetaCode { class MainClass { public static void Main (string[] args) { int[,] list = new int[18,19]; string input = @"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"; var charArray = input.Split ('\n');   for (int i=0; i < charArray.Length; i++) { var numArr = charArray[i].Trim().Split(' ');   for (int j = 0; j<numArr.Length; j++) { int number = Convert.ToInt32 (numArr[j]); list [i, j] = number; } }   for (int i = 16; i >= 0; i--) { for (int j = 0; j < 18; j++) { list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]); } } Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0])); } } }    
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Java
Java
import org.bouncycastle.crypto.digests.MD4Digest; import org.bouncycastle.util.encoders.Hex;   public class RosettaMD4 { public static void main (String[] argv) throws Exception { byte[] r = "Rosetta Code".getBytes("US-ASCII"); MD4Digest d = new MD4Digest(); d.update (r, 0, r.length); byte[] o = new byte[d.getDigestSize()]; d.doFinal (o, 0); Hex.encode (o, System.out); System.out.println(); } }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#REXX
REXX
/* REXX *************************************************************** * 03.02.2013 Walter Pachl * 19.04.2013 mid 3 is now a function returning the middle 3 digits * or an error indication **********************************************************************/ sl='123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345', '2 -1 -10 2002 -2002 0 abc 1e3 -17e-3' Do While sl<>'' /* loop through test values */ Parse Var sl s sl /* pick next value */ Say left(s,12) '->' mid3(s) /* test it */ End Exit   mid3: Procedure Parse arg d /* take the argument */ Select /* first test for valid input */ When datatype(d)<>'NUM' Then Return 'not a number' When pos('E',translate(d))>0 Then Return 'not just digits' When length(abs(d))<3 Then Return 'less than 3 digits' When length(abs(d))//2<>1 Then Return 'not an odd number of digits' Otherwise Do /* input is ok */ dx=abs(d) /* get rid of optional sign */ ld=length(dx) /* length of digit string */ z=(ld-3)/2 /* number of digits to cut */ res=substr(dx,z+1,3) /* get middle 3 digits */ End End Return res
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.
#BASIC256
BASIC256
print MD5("") print MD5("a") print MD5("abc") print MD5("message digest") print MD5("abcdefghijklmnopqrstuvwxyz") print MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") print MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") end
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Ursa
Ursa
def _menu (string<> items) for (decl int i) (< i (size items)) (inc i) out " " i ") " items<i> endl console end for end _menu   def _ok (string reply, int itemcount) try decl int n set n (int reply) return (and (or (> n 0) (= n 0)) (< n itemcount)) catch return false end try end _ok   def selector (string<> items, string prompt) # Prompt to select an item from the items if (= (size items) 0) return "" end if decl int itemcount reply set reply -1 set itemcount (size items) while (not (_ok reply itemcount)) _menu items out prompt console set reply (in int console) end while return items<(int reply)> end selector   decl string<> items append "fee fie" "huff and puff" "mirror mirror" "tick tock" items decl string item set item (selector items "Which is from the three pigs: ") out "You chose: " item endl console
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#VBScript
VBScript
'The Function Function Menu(ArrList, Prompt) Select Case False 'Non-standard usage hahaha Case IsArray(ArrList) Menu = "" 'Empty output string for non-arrays Exit Function Case UBound(ArrList) >= LBound(ArrList) Menu = "" 'Empty output string for empty arrays Exit Function End Select 'Display menu and prompt Do While True For i = LBound(ArrList) To UBound(ArrList) WScript.StdOut.WriteLine((i + 1) & ". " & ArrList(i)) Next WScript.StdOut.Write(Prompt) Choice = WScript.StdIn.ReadLine 'Check if input is valid If IsNumeric(Choice) Then 'Check for numeric-ness If CStr(CLng(Choice)) = Choice Then 'Check for integer-ness (no decimal part) Index = Choice - 1 'Arrays are 0-based 'Check if Index is in array If LBound(ArrList) <= Index And Index <= UBound(ArrList) Then Exit Do End If End If End If WScript.StdOut.WriteLine("Invalid choice.") Loop Menu = ArrList(Index) End Function   'The Main Thing Sample = Array("fee fie", "huff and puff", "mirror mirror", "tick tock") InputText = "Which is from the three pigs: " WScript.StdOut.WriteLine("Output: " & Menu(Sample, InputText))
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => { const size = n => enumFromTo(0)( quot(100, n) ), nuggets = new Set( size(6).flatMap( x => size(9).flatMap( y => size(20).flatMap( z => { const v = sum([6 * x, 9 * y, 20 * z]); return 101 > v ? ( [v] ) : []; } ), ) ) ), xs = dropWhile( x => nuggets.has(x), enumFromThenTo(100, 99, 1) );   return 0 < xs.length ? ( xs[0] ) : 'No unreachable quantities found in this range'; };     // GENERIC FUNCTIONS ----------------------------------   // dropWhile :: (a -> Bool) -> [a] -> [a] const dropWhile = (p, xs) => { const lng = xs.length; return 0 < lng ? xs.slice( until( i => i === lng || !p(xs[i]), i => 1 + i, 0 ) ) : []; };   // enumFromThenTo :: Int -> Int -> Int -> [Int] const enumFromThenTo = (x1, x2, y) => { const d = x2 - x1; return Array.from({ length: Math.floor(y - x2) / d + 2 }, (_, i) => x1 + (d * i)); };   // ft :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i);   // quot :: Int -> Int -> Int const quot = (n, m) => Math.floor(n / m);   // sum :: [Num] -> Num const sum = xs => xs.reduce((a, x) => a + x, 0);   // until :: (a -> Bool) -> (a -> a) -> a -> a const until = (p, f, x) => { let v = x; while (!p(v)) v = f(v); return v; };   // MAIN --- return console.log( main() ); })();
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#C
C
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h>   #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define MIN(x,y) ((x) < (y) ? (x) : (y))   /* Find base-20 digits. */ size_t base20(unsigned int n, uint8_t *out) { /* generate digits */ uint8_t *start = out; do {*out++ = n % 20;} while (n /= 20); size_t length = out - start;   /* put digits in high-endian order */ while (out > start) { uint8_t x = *--out; *out = *start; *start++ = x; } return length; }   /* Write a Mayan digit */ void make_digit(int n, char *place, size_t line_length) { static const char *parts[] = {" "," . "," .. ","... ","....","----"}; int i;   /* write 4-part digit */ for (i=4; i>0; i--, n -= 5) memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);   /* if digit was 0 we should put '@' in 2nd position of last line */ if (n == -20) place[4 * line_length + 1] = '@'; }   /* Make a Mayan numeral */ char *mayan(unsigned int n) { if (n == 0) return NULL;   uint8_t digits[15]; /* 2**64 is 15 Mayan digits long */ size_t n_digits = base20(n, digits);   /* a digit is 4 chars wide, plus N+1 divider lines, plus a newline makes for a length of 5*n+2 */ size_t line_length = n_digits*5 + 2;   /* we need 6 lines - four for the digits, plus top and bottom row */ char *str = malloc(line_length * 6 + 1); if (str == NULL) return NULL; str[line_length * 6] = 0;   /* make the cartouche divider lines */ char *ptr; unsigned int i; /* top and bottom row */ for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "+----", 5); memcpy(ptr-5, "+\n", 2); memcpy(str+5*line_length, str, line_length); /* middle rows */ for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "| ", 5); memcpy(ptr-5, "|\n", 2); memcpy(str+2*line_length, str+line_length, line_length); memcpy(str+3*line_length, str+line_length, 2*line_length);   /* copy in the digits */ for (i=0; i<n_digits; i++) make_digit(digits[i], str+1+5*i, line_length);   return str; }   int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: mayan <number>\n"); return 1; } int i = atoi(argv[1]); if (i <= 0) { fprintf(stderr, "number must be positive\n"); return 1; } char *m = mayan(i); printf("%s",m); free(m); return 0; }
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Delphi
Delphi
procedure SolveMaze(var AMaze: TMaze; const S, E: TPoint); var Route : TRoute; Position : TPoint; V : TPoint; // delta vector begin ClearVisited(AMaze); Position := S; Route := TStack<TPoint>.Create; with Position do try AMaze[x, y].Visited := True; repeat if (y > 0) and not AMaze[x, y-1].Visited and AMaze[x, y].PassTop then V := Point(0, -1) else if (x < mwidth-1) and not AMaze[x+1, y].Visited and AMaze[x+1, y].PassLeft then V := Point(1, 0) else if (y < mheight-1) and not AMaze[x, y+1].Visited and AMaze[x, y+1].PassTop then V := Point(0, 1) else if (x > 0) and not AMaze[x-1, y].Visited and AMaze[x, y].PassLeft then V := Point(-1, 0) else begin if Route.Count = 0 then Exit; // we are back at start so no way found Position := Route.Pop; // step back Continue; end;   Route.Push(Position); // save current position to route Offset(V); // move forward AMaze[x, y].Visited := True; until Position = E; // solved   ClearVisited(AMaze); while Route.Count > 0 do // Route to Maze with Route.Pop do AMaze[x, y].Visited := True;   finally Route.Free; end; end;   procedure Main; var Maze: TMaze; S, E: TPoint; begin Randomize; PrepareMaze(Maze); S := Point(Random(mwidth), Random(mheight)); E := Point(Random(mwidth), Random(mheight)); SolveMaze(Maze, S, E); Write(MazeToString(Maze, S, E)); ReadLn; end;   begin Main; 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.
#C.2B.2B
C++
  /* Algorithm complexity: n*log(n) */ #include <iostream>   int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 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, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 };   const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); // size should be a triangular number   // walk backward by rows, replacing each element with max attainable therefrom for (int n = tn - 1; n > 0; --n) // n is size of row, note we do not process last row for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) // from the start to the end of row triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);   std::cout << "Maximum total: " << triangle[0] << "\n\n"; }  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#JavaScript
JavaScript
const md4func = () => {   const hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ const b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ const chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */   const tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";   /** * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ const safe_add = (x, y) => { const lsw = (x & 0xFFFF) + (y & 0xFFFF); const msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); };   /** * Bitwise rotate a 32-bit number to the left. */ const rol = (num, cnt) => (num << cnt) | (num >>> (32 - cnt));   /** * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ const str2binl = str => { const bin = Array(); const mask = (1 << chrsz) - 1; for (let i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32); return bin; };   /** * Convert an array of little-endian words to a string */ const binl2str = bin => { let str = ""; const mask = (1 << chrsz) - 1; for (let i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask); return str; };   /** * Convert an array of little-endian words to a hex string. */ const binl2hex = binarray => { let str = ""; for (let i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF); } return str; };   /** * Convert an array of little-endian words to a base-64 string */ const binl2b64 = binarray => { let str = ""; for (let i = 0; i < binarray.length * 4; i += 3) { const triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF); for (let j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F); } } return str; };     /** * Calculate the MD4 of an array of little-endian words, and a bit length */ const core_md4 = (x, len) => {   x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; let a = 1732584193; let b = -271733879; let c = -1732584194; let d = 271733878;   for (let i = 0; i < x.length; i += 16) {   const olda = a; const oldb = b; const oldc = c; const oldd = d;   a = md4_ff(a, b, c, d, x[i], 3); d = md4_ff(d, a, b, c, x[i + 1], 7); c = md4_ff(c, d, a, b, x[i + 2], 11); b = md4_ff(b, c, d, a, x[i + 3], 19); a = md4_ff(a, b, c, d, x[i + 4], 3); d = md4_ff(d, a, b, c, x[i + 5], 7); c = md4_ff(c, d, a, b, x[i + 6], 11); b = md4_ff(b, c, d, a, x[i + 7], 19); a = md4_ff(a, b, c, d, x[i + 8], 3); d = md4_ff(d, a, b, c, x[i + 9], 7); c = md4_ff(c, d, a, b, x[i + 10], 11); b = md4_ff(b, c, d, a, x[i + 11], 19); a = md4_ff(a, b, c, d, x[i + 12], 3); d = md4_ff(d, a, b, c, x[i + 13], 7); c = md4_ff(c, d, a, b, x[i + 14], 11); b = md4_ff(b, c, d, a, x[i + 15], 19);   a = md4_gg(a, b, c, d, x[i], 3); d = md4_gg(d, a, b, c, x[i + 4], 5); c = md4_gg(c, d, a, b, x[i + 8], 9); b = md4_gg(b, c, d, a, x[i + 12], 13); a = md4_gg(a, b, c, d, x[i + 1], 3); d = md4_gg(d, a, b, c, x[i + 5], 5); c = md4_gg(c, d, a, b, x[i + 9], 9); b = md4_gg(b, c, d, a, x[i + 13], 13); a = md4_gg(a, b, c, d, x[i + 2], 3); d = md4_gg(d, a, b, c, x[i + 6], 5); c = md4_gg(c, d, a, b, x[i + 10], 9); b = md4_gg(b, c, d, a, x[i + 14], 13); a = md4_gg(a, b, c, d, x[i + 3], 3); d = md4_gg(d, a, b, c, x[i + 7], 5); c = md4_gg(c, d, a, b, x[i + 11], 9); b = md4_gg(b, c, d, a, x[i + 15], 13);   a = md4_hh(a, b, c, d, x[i], 3); d = md4_hh(d, a, b, c, x[i + 8], 9); c = md4_hh(c, d, a, b, x[i + 4], 11); b = md4_hh(b, c, d, a, x[i + 12], 15); a = md4_hh(a, b, c, d, x[i + 2], 3); d = md4_hh(d, a, b, c, x[i + 10], 9); c = md4_hh(c, d, a, b, x[i + 6], 11); b = md4_hh(b, c, d, a, x[i + 14], 15); a = md4_hh(a, b, c, d, x[i + 1], 3); d = md4_hh(d, a, b, c, x[i + 9], 9); c = md4_hh(c, d, a, b, x[i + 5], 11); b = md4_hh(b, c, d, a, x[i + 13], 15); a = md4_hh(a, b, c, d, x[i + 3], 3); d = md4_hh(d, a, b, c, x[i + 11], 9); c = md4_hh(c, d, a, b, x[i + 7], 11); b = md4_hh(b, c, d, a, x[i + 15], 15);   a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); }   return Array(a, b, c, d);   };   /** * These functions implement the basic operation for each round of the * algorithm. */ const md4_cmn = (q, a, b, x, s, t) => safe_add( rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);   const md4_ff = (a, b, c, d, x, s) => md4_cmn( (b & c) | ((~b) & d), a, 0, x, s, 0);   const md4_gg = (a, b, c, d, x, s) => md4_cmn( (b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249);   const md4_hh = (a, b, c, d, x, s) => md4_cmn( b ^ c ^ d, a, 0, x, s, 1859775393);   /** * Calculate the HMAC-MD4, of a key and some data */ const core_hmac_md4 = (key, data) => {   let bkey = str2binl(key); if (bkey.length > 16) { bkey = core_md4(bkey, key.length * chrsz) }   const ipad = Array(16); const opad = Array(16);   for (let i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } const hash = core_md4( ipad.concat(str2binl(data)), 512 + data.length * chrsz);   return core_md4(opad.concat(hash), 512 + 128); };   /** * These are the functions you'll usually want to call */ return { hex_md4: s => binl2hex(core_md4(str2binl(s), s.length * chrsz)), b64_md4: s => binl2b64(core_md4(str2binl(s), s.length * chrsz)), str_md4: s => binl2str(core_md4(str2binl(s), s.length * chrsz)), hex_hmac_md4: (key, data) => binl2hex(core_hmac_md4(key, data)), b64_hmac_md4: (key, data) => binl2b64(core_hmac_md4(key, data)), str_hmac_md4: (key, data) => binl2str(core_hmac_md4(key, data)), };   };   const md4 = md4func(); console.log(md4.hex_md4('Rosetta Code'));
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Ring
Ring
  n = 1234567 middle(n)   func middle nr mnr = floor(len(string(nr))/2) lennr = len(string(nr)) if lennr = 3 see "" + nr + nl but lennr < 3 see "Number must have at least three digits" but lennr%2=0 see "Number must have an odd number of digits" else cnr = substr(string(nr),mnr,3) see cnr + nl ok  
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.
#BBC_BASIC
BBC BASIC
PRINT FN_MD5("") PRINT FN_MD5("a") PRINT FN_MD5("abc") PRINT FN_MD5("message digest") PRINT FN_MD5("abcdefghijklmnopqrstuvwxyz") PRINT FN_MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") PRINT FN_MD5(STRING$(8,"1234567890")) END   DEF FN_MD5(message$) LOCAL I%, MD5$, MD5_CTX{} DIM MD5_CTX{i%(1), buf%(3), in&(63), digest&(15)} SYS "MD5Init", MD5_CTX{} SYS "MD5Update", MD5_CTX{}, message$, LEN(message$) SYS "MD5Final", MD5_CTX{} FOR I% = 0 TO 15 MD5$ += RIGHT$("0"+STR$~(MD5_CTX.digest&(I%)),2) NEXT = MD5$
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Wren
Wren
import "/ioutil" for Input   var menu = Fn.new { |list| var n = list.count if (n == 0) return "" var prompt = "\n M E N U\n\n" for (i in 0...n) prompt = prompt + "%(i+1). %(list[i])\n" prompt = prompt + "\nEnter your choice (1 - %(n)): " var index = Input.integer(prompt, 1, n) return list[index-1] }   var list = ["fee fie", "huff and puff", "mirror mirror", "tick tock"] var choice = menu.call(list) System.print("\nYou chose : %(choice)")
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#jq
jq
[ [range(18) as $n6 | range(13) as $n9 | range(6) as $n20 | ($n6 * 6 + $n9 * 9 + $n20 * 20)] | unique | . as $possible | range(101) | . as $n | select($possible|contains([$n])|not) ] | max
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#CLU
CLU
% This program must be linked with PCLU's "misc.lib" and "useful.lib"   base20 = proc (n: bigint) returns (sequence[int]) own zero: bigint := bigint$i2bi(0) own twenty: bigint := bigint$i2bi(20) if n=zero then return(sequence[int]$[0]) end   digits: array[int] := array[int]$[] while n>zero do array[int]$addl(digits, bigint$bi2i(n//twenty)) n := n/twenty end return(sequence[int]$a2s(digits)) end base20   mayan = proc (digits: sequence[int]) returns (string) own parts: array[string] := array[string]$[0: " ", " . ", " .. ", "... ", "....", "----" ]  % generate edges edge: stream := stream$create_output() for i: int in int$from_to(1, sequence[int]$size(digits)) do stream$puts(edge, "+----") end stream$putl(edge, "+")    % generate digits lines: stream := stream$create_output() for i: int in int$from_to_by(15, 0, -5) do for d: int in sequence[int]$elements(digits) do p: int := d-i if p<0 then p:=0 end if p>5 then p:=5 end if i=0 & p=0 then stream$puts(lines, "| @ ") else stream$puts(lines, "|" || parts[p]) end end stream$putl(lines, "|") end   s_edge: string := stream$get_contents(edge) return(s_edge || stream$get_contents(lines) || s_edge) end mayan   start_up = proc () po: stream := stream$primary_output() n: bigint := bigint$parse(sequence[string]$bottom(get_argv())) stream$puts(po, mayan(base20(n))) end start_up
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # convert number to base 20 sub base20(n: uint32, out: [uint8]): (n_digits: uint8) is n_digits := 0; loop [out] := (n % 20) as uint8; n := n / 20; out := @next out; n_digits := n_digits + 1; if n == 0 then break; end if; end loop; end sub;   # get the N'th line (from the top) for a Mayan digit sub digit_line(n: uint8, line: uint8): (s: [uint8]) is var parts: [uint8][] := {" "," . "," .. ","... ","....","----"}; if n == 0 then if line == 3 then s := " @ "; else s := parts[0]; end if; else var nn := n - 5*(3-line); if nn > 128 then s := parts[0]; elseif nn > 5 then s := parts[5]; else s := parts[nn]; end if; end if; end sub;   # print Mayan number sub print_mayan(n: uint32) is sub edge(n: uint8) is while n>0 loop print("+----"); n := n-1; end loop; print_char('+'); print_nl(); end sub;   var digits: uint8[8]; # 8 digits is enough for 2**32 var size := base20(n, &digits[0]);   edge(size); var line: uint8 := 0; while line < 4 loop var d: uint8 := size-1; loop print_char('|'); print(digit_line(digits[d], line)); if d==0 then break; end if; d := d - 1; end loop; print_char('|'); print_nl(); line := line + 1; end loop; edge(size); end sub;   sub Error() is print("usage: mayan <number>. number must be positive"); print_nl(); ExitWithError(); end sub;   # read number from command line ArgvInit(); var arg := ArgvNext(); if arg == 0 as [uint8] then Error(); end if; var n: int32; (n, arg) := AToI(arg); if n <= 0 then Error(); end if; print_mayan(n as uint32);
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#EasyLang
EasyLang
size = 20 n = 2 * size + 1 endpos = n * n - 2 startpos = n + 1 # f = 100 / (n - 0.5) len m[] n * n # background 000 func show_maze . . clear for i range len m[] if m[i] = 0 x = i mod n y = i div n color 777 move x * f - f / 2 y * f - f / 2 rect f * 1.5 f * 1.5 . . sleep 0.001 . offs[] = [ 1 n -1 (-n) ] brdc[] = [ n - 2 -1 1 -1 ] brdr[] = [ -1 n - 2 -1 1 ] # func m_maze pos . . m[pos] = 0 call show_maze d[] = [ 0 1 2 3 ] for i = 3 downto 0 d = random (i + 1) dir = d[d] d[d] = d[i] r = pos div n c = pos mod n posn = pos + 2 * offs[dir] if c <> brdc[dir] and r <> brdr[dir] and m[posn] <> 0 posn = pos + 2 * offs[dir] m[(pos + posn) div 2] = 0 call m_maze posn . . . func make_maze . . for i range len m[] m[i] = 1 . call m_maze startpos m[endpos] = 0 . call make_maze call show_maze # func mark pos col . . x = pos mod n y = pos div n color col move x * f + f / 4 y * f + f / 4 circle f / 4 . func solve dir0 pos . found . call mark pos 900 sleep 0.05 if pos = endpos found = 1 else for dir range 4 posn = pos + offs[dir] if dir <> dir0 and m[posn] = 0 and found = 0 call solve (dir + 2) mod 4 posn found if found = 0 call mark posn 777 sleep 0.05 . . . . . sleep 3 call solve -1 startpos found
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.
#Clojure
Clojure
  (ns clojure.examples.rosetta (:gen-class) (:require [clojure.string :as string]))   (def rosetta "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")   ;; The technique is described here in more detail http://mishadoff.com/blog/clojure-euler-problem-018/ ;; Most of the code converts the string data to a nested array of integers. ;; The code to calculate the max sum is then only a single line   ;; First convert string data to nested list ;; with each inner list containing one row of the triangle ;; [[55] [94 48] [95 30 96] ... [...10 69 93] (defn parse-int [s] " Convert digits to a number (finds digits when could be surrounded by non-digits" (Integer. (re-find #"\d+" s)))   (defn data-int-array [s] " Convert string to integer array" (map parse-int (string/split (string/trim s) #"\s+")))   (defn nested-triangle [s] " Convert triangle to nested vector, with each inner vector containing one triangle row" (loop [lst s n 1 newlist nil] (if (empty? lst) (reverse newlist) (recur (drop n lst) (inc n) (cons (take n lst) newlist))))) ; Create nested list (def nested-list (nested-triangle (data-int-array rosetta)))   ;; Function to compute maximum path sum (defn max-sum [s] " Compute maximum path sum using a technique described here: http://mishadoff.com/blog/clojure-euler-problem-018/" (reduce (fn [a b] (map + b (map max a (rest a)))) (reverse s)))   ; Print result (println (max-sum nested-list))    
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Julia
Julia
  using Nettle   msg = "Rosetta Code"   h = HashState(MD4) update!(h, msg) h = hexdigest!(h)   println("\"", msg, "\" => ", h)  
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Ruby
Ruby
def middle_three_digits(num) # minus sign doesn't factor into digit count, # and calling #abs acts as a duck-type assertion num = num.abs   # convert to string and find length length = (str = num.to_s).length   # check validity raise ArgumentError, "Number must have at least three digits" if length < 3 raise ArgumentError, "Number must have an odd number of digits" if length.even?   return str[length/2 - 1, 3].to_i 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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h>   const char *string = "The quick brown fox jumped over the lazy dog's back";   int main() { int i; unsigned char result[MD5_DIGEST_LENGTH];   MD5(string, strlen(string), result);   // output for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n");   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#XPL0
XPL0
string 0;   func Menu(List); int List; int Size, I, C; [Size:= List(0); if Size < 1 then return List(0); \if empty list, return pointer to 0 for I:= 1 to Size-1 do [IntOut(0, I); Text(0, ": "); Text(0, List(I)); CrLf(0); ]; CrLf(0); Text(0, List(Size)); \display prompt loop [C:= ChIn(0); \buffered keyboard requires Enter key if C>=^1 & C<=Size-1+^0 then return List(C-^0); Text(0, "Please enter 1 thru "); IntOut(0, Size-1); Text(0, ": "); ]; ];   Text(0, Menu([5, "fee fie", "huff and puff", "mirror mirror", "tick tock", "Which phrase is from the Three Little Pigs? "]))
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Julia
Julia
function mcnuggets(max) b = BitSet(1:max) for i in 0:6:max, j in 0:9:max, k in 0:20:max delete!(b, i + j + k) end maximum(b) end   println(mcnuggets(100))  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Kotlin
Kotlin
// Version 1.2.71   fun mcnugget(limit: Int) { val sv = BooleanArray(limit + 1) // all false by default for (s in 0..limit step 6) for (n in s..limit step 9) for (t in n..limit step 20) sv[t] = true   for (i in limit downTo 0) { if (!sv[i]) { println("Maximum non-McNuggets number is $i") return } } }   fun main(args: Array<String>) { mcnugget(100) }
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#F.23
F#
  // Mayan numerals. Nigel Galloway: February 19th., 2021 let N=[|"│ ";"│. ";"│.. ";"│... ";"│....";"│~~~~"|] let fN g=(fun(n)->if g=0 && n=0 then "│ Θ " else N.[let g=g-5*n in if g>4 then 5 else if g<0 then 0 else g]) let rec fG n g=match n/20L,n%20L with (0L,0L)->(g,List.length g) |(i,n)->fG i ((fN(int n))::g) let mayan n=let n,g=fG n [] printf "┌────"; for _ in 2..g do printf "┬────" printfn "┐"; for g in 3.. -1 ..0 do n|>List.iter(fun n->printf "%s" (n(g))); printfn "│" printf "└────"; for _ in 2..g do printf "┴────" printfn "┘" [4005L;8017L;326205L;886205L]|>List.iter(fun n->printfn "%d" n; mayan n)  
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.
#11l
11l
F matrix_mul(m1, m2) assert(m1[0].len == m2.len) V r = [[0] * m2[0].len] * m1.len L(j) 0 .< m1.len L(i) 0 .< m2[0].len V s = 0 L(k) 0 .< m2.len s += m1[j][k] * m2[k][i] r[j][i] = s R r   F identity(size) V rsize = 0 .< size R rsize.map(j -> @rsize.map(i -> Int(i == @j)))   F matrixExp(m, pow) assert(pow >= 0 & Int(pow) == pow, ‘Only non-negative, integer powers allowed’) V accumulator = identity(m.len) L(i) 0 .< pow accumulator = matrix_mul(accumulator, m) R accumulator   F printtable(data) L(row) data print(row.map(cell -> ‘#<5’.format(cell)).join(‘ ’))   V m = [[3, 2], [2, 1]] L(i) 5 print("\n#.:".format(i)) printtable(matrixExp(m, i))   print("\n10:") printtable(matrixExp(m, 10))
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#EGL
EGL
program MazeGenAndSolve   // First and last columns/rows are "dead" cells. Makes generating // a maze with border walls much easier. Therefore, a visible // 20x20 maze has a maze size of 22. mazeSize int = 22;   south boolean[][]; west boolean[][]; visited boolean[][];   // Solution variables solution Dictionary; done boolean; startingRow, startingCol, endingRow, endingCol int;   function main() initMaze(); generateMaze(); drawMaze(false); // Draw maze without solution   solveMaze(); drawMaze(true); // Draw maze with solution end   private function initMaze()   visited = createBooleanArray(mazeSize, mazeSize, false);   // Initialize border cells as already visited for(col int from 1 to mazeSize) visited[col][1] = true; visited[col][mazeSize] = true; end for(row int from 1 to mazeSize) visited[1][row] = true; visited[mazeSize][row] = true; end   // Initialize all walls as present south = createBooleanArray(mazeSize, mazeSize, true); west = createBooleanArray(mazeSize, mazeSize, true);   end   private function createBooleanArray(col int in, row int in, initialState boolean in) returns(boolean[][])   newArray boolean[][] = new boolean[0][0];   for(i int from 1 to col) innerArray boolean[] = new boolean[0]; for(j int from 1 to row) innerArray.appendElement(initialState); end newArray.appendElement(innerArray); end   return(newArray);   end   private function createIntegerArray(col int in, row int in, initialValue int in) returns(int[][])   newArray int[][] = new int[0][0];   for(i int from 1 to col) innerArray int[] = new int[0]; for(j int from 1 to row) innerArray.appendElement(initialValue); end newArray.appendElement(innerArray); end   return(newArray);   end   private function generate(col int in, row int in)   // Mark cell as visited visited[col][row] = true;   // Keep going as long as there is an unvisited neighbor while(!visited[col][row + 1] || !visited[col + 1][row] ||  !visited[col][row - 1] || !visited[col - 1][row])   while(true) r float = MathLib.random(); // Choose a random direction   case when(r < 0.25 && !visited[col][row + 1]) // Go south south[col][row] = false; // South wall down generate(col, row + 1); exit while; when(r >= 0.25 && r < 0.50 && !visited[col + 1][row]) // Go east west[col + 1][row] = false; // West wall of neighbor to the east down generate(col + 1, row); exit while; when(r >= 0.5 && r < 0.75 && !visited[col][row - 1]) // Go north south[col][row - 1] = false; // South wall of neighbor to the north down generate(col, row - 1); exit while; when(r >= 0.75 && r < 1.00 && !visited[col - 1][row]) // Go west west[col][row] = false; // West wall down generate(col - 1, row); exit while; end end end   end   private function generateMaze()   // Pick random start position (within the visible maze space) randomStartCol int = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2); randomStartRow int = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2);   generate(randomStartCol, randomStartRow);   end   private function drawMaze(solve boolean in)   line string;   // Iterate over wall arrays (skipping dead border cells as required). // Construct a row at a time and output to console. for(row int from 1 to mazeSize - 1)   if(row > 1) line = ""; for(col int from 2 to mazeSize) if(west[col][row]) line ::= cellTest(col, row, solve); else line ::= cellTest(col, row, solve); end end Syslib.writeStdout(line); end   line = ""; for(col int from 2 to mazeSize - 1) if(south[col][row]) line ::= "+---"; else line ::= "+ "; end end line ::= "+"; SysLib.writeStdout(line);   end   end   private function cellTest(col int in, row int in, solve boolean in) returns(string)   wall string;   // Determine cell wall structure. If in solve mode, show start, end and // solution markers. if(!solve) if(west[col][row]) wall = "| "; else wall = " "; end else if(west[col][row])   case when(col == startingCol and row == startingRow) wall = "| S "; when(col == endingCol and row == endingRow) wall = "| E "; when(solution.containsKey("x=" + col + "y=" + row)) wall = "| * "; otherwise wall = "| "; end   else case when(col == startingCol and row == startingRow) wall = " S "; when(col == endingCol and row == endingRow) wall = " E "; when(solution.containsKey("x=" + col + "y=" + row)) wall = " * "; otherwise wall = " "; end end end   return(wall); end   private function solve(col int in, row int in)   if(col == 1 || row == 1 || col == mazeSize || row == mazeSize) return; end   if(done || visited[col][row]) return; end   visited[col][row] = true;   solution["x=" + col + "y=" + row] = true;   // Reached the end point if(col == endingCol && row == endingRow) done = true; end   if(!south[col][row]) // Go South solve(col, row + 1); end if(!west[col + 1][row]) // Go East solve(col + 1, row); end if(!south[col][row - 1]) // Go North solve(col, row - 1); end if(!west[col][row]) // Go West solve(col - 1, row); end   if(done) return; end   solution.removeElement("x=" + col + "y=" + row);   end   private function solveMaze() for(col int from 1 to mazeSize) for(row int from 1 to mazeSize) visited[col][row] = false; end end   solution = new Dictionary(false, OrderingKind.byInsertion); done = false;   // Pick random start position on first visible row startingCol = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2); startingRow = 2;   // Pick random end position on last visible row endingCol = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2); endingRow = mazeSize - 1;   solve(startingCol, startingRow); end   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.
#Common_Lisp
Common Lisp
(defun find-max-path-sum (s) (let ((triangle (loop for line = (read-line s NIL NIL) while line collect (with-input-from-string (str line) (loop for n = (read str NIL NIL) while n collect n))))) (flet ((get-max-of-pairs (xs) (maplist (lambda (ys) (and (cdr ys) (max (car ys) (cadr ys)))) xs))) (car (reduce (lambda (xs ys) (mapcar #'+ (get-max-of-pairs xs) ys)) (reverse triangle))))))   (defparameter *small-triangle* " 55 94 48 95 30 96 77 71 26 67") (format T "~a~%" (with-input-from-string (s *small-triangle*) (find-max-path-sum s))) (format T "~a~%" (with-open-file (f "triangle.txt") (find-max-path-sum f)))
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Kotlin
Kotlin
// version 1.0.6   import java.security.MessageDigest   class MD4() : MessageDigest("MD4"), Cloneable { private val blockLength = 64 private var context = IntArray(4) private var count = 0L private var buffer = ByteArray(blockLength) private var x = IntArray(16)   init { engineReset() }   private constructor(md: MD4): this() { context = md.context.clone() buffer = md.buffer.clone() count = md.count }   override fun clone(): Any = MD4(this)   override fun engineReset() { context[0] = 0x67452301 context[1] = 0xefcdab89.toInt() context[2] = 0x98badcfe.toInt() context[3] = 0x10325476 count = 0L for (i in 0 until blockLength) buffer[i] = 0 }   override fun engineUpdate(b: Byte) { val i = (count % blockLength).toInt() count++ buffer[i] = b if (i == blockLength - 1) transform(buffer, 0) }   override fun engineUpdate(input: ByteArray, offset: Int, len: Int) { if (offset < 0 || len < 0 || offset.toLong() + len > input.size.toLong()) throw ArrayIndexOutOfBoundsException() var bufferNdx = (count % blockLength).toInt() count += len val partLen = blockLength - bufferNdx var i = 0 if (len >= partLen) { System.arraycopy(input, offset, buffer, bufferNdx, partLen) transform(buffer, 0) i = partLen while (i + blockLength - 1 < len) { transform(input, offset + i) i += blockLength } bufferNdx = 0 } if (i < len) System.arraycopy(input, offset + i, buffer, bufferNdx, len - i) }   override fun engineDigest(): ByteArray { val bufferNdx = (count % blockLength).toInt() val padLen = if (bufferNdx < 56) 56 - bufferNdx else 120 - bufferNdx val tail = ByteArray(padLen + 8) tail[0] = 0x80.toByte() for (i in 0..7) tail[padLen + i] = ((count * 8) ushr (8 * i)).toByte() engineUpdate(tail, 0, tail.size) val result = ByteArray(16) for (i in 0..3) for (j in 0..3) result[i * 4 + j] = (context[i] ushr (8 * j)).toByte() engineReset() return result }   private fun transform (block: ByteArray, offset: Int) { var offset2 = offset for (i in 0..15) x[i] = ((block[offset2++].toInt() and 0xff) ) or ((block[offset2++].toInt() and 0xff) shl 8 ) or ((block[offset2++].toInt() and 0xff) shl 16) or ((block[offset2++].toInt() and 0xff) shl 24)   var a = context[0] var b = context[1] var c = context[2] var d = context[3]   a = ff(a, b, c, d, x[ 0], 3) d = ff(d, a, b, c, x[ 1], 7) c = ff(c, d, a, b, x[ 2], 11) b = ff(b, c, d, a, x[ 3], 19) a = ff(a, b, c, d, x[ 4], 3) d = ff(d, a, b, c, x[ 5], 7) c = ff(c, d, a, b, x[ 6], 11) b = ff(b, c, d, a, x[ 7], 19) a = ff(a, b, c, d, x[ 8], 3) d = ff(d, a, b, c, x[ 9], 7) c = ff(c, d, a, b, x[10], 11) b = ff(b, c, d, a, x[11], 19) a = ff(a, b, c, d, x[12], 3) d = ff(d, a, b, c, x[13], 7) c = ff(c, d, a, b, x[14], 11) b = ff(b, c, d, a, x[15], 19)   a = gg(a, b, c, d, x[ 0], 3) d = gg(d, a, b, c, x[ 4], 5) c = gg(c, d, a, b, x[ 8], 9) b = gg(b, c, d, a, x[12], 13) a = gg(a, b, c, d, x[ 1], 3) d = gg(d, a, b, c, x[ 5], 5) c = gg(c, d, a, b, x[ 9], 9) b = gg(b, c, d, a, x[13], 13) a = gg(a, b, c, d, x[ 2], 3) d = gg(d, a, b, c, x[ 6], 5) c = gg(c, d, a, b, x[10], 9) b = gg(b, c, d, a, x[14], 13) a = gg(a, b, c, d, x[ 3], 3) d = gg(d, a, b, c, x[ 7], 5) c = gg(c, d, a, b, x[11], 9) b = gg(b, c, d, a, x[15], 13)   a = hh(a, b, c, d, x[ 0], 3) d = hh(d, a, b, c, x[ 8], 9) c = hh(c, d, a, b, x[ 4], 11) b = hh(b, c, d, a, x[12], 15) a = hh(a, b, c, d, x[ 2], 3) d = hh(d, a, b, c, x[10], 9) c = hh(c, d, a, b, x[ 6], 11) b = hh(b, c, d, a, x[14], 15) a = hh(a, b, c, d, x[ 1], 3) d = hh(d, a, b, c, x[ 9], 9) c = hh(c, d, a, b, x[ 5], 11) b = hh(b, c, d, a, x[13], 15) a = hh(a, b, c, d, x[ 3], 3) d = hh(d, a, b, c, x[11], 9) c = hh(c, d, a, b, x[ 7], 11) b = hh(b, c, d, a, x[15], 15)   context[0] += a context[1] += b context[2] += c context[3] += d }   private fun ff(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int { val t = a + ((b and c) or (b.inv() and d)) + x return (t shl s) or (t ushr (32 - s)) }   private fun gg(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int { val t = a + ((b and (c or d)) or (c and d)) + x + 0x5a827999 return (t shl s) or (t ushr (32 - s)) }   private fun hh(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int { val t = a + (b xor c xor d) + x + 0x6ed9eba1 return (t shl s) or (t ushr (32 - s)) } }   fun main(args: Array<String>) { val text = "Rosetta Code" val bytes = text.toByteArray(Charsets.US_ASCII) val md: MessageDigest = MD4() val digest = md.digest(bytes) for (byte in digest) print("%02x".format(byte)) println() }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Rust
Rust
fn middle_three_digits(x: i32) -> Result<String, String> { let s: String = x.abs().to_string(); let len = s.len(); if len < 3 { Err("Too short".into()) } else if len % 2 == 0 { Err("Even number of digits".into()) } else { Ok(s[len/2 - 1 .. len/2 + 2].to_owned()) } }   fn print_result(x: i32) { print!("middle_three_digits({}) returned: ", x); match middle_three_digits(x) { Ok(s) => println!("Success, {}", s), Err(s) => println!("Failure, {}", s) } }   fn main() { let passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]; let failing = [1, 2, -1, -10, 2002, -2002, 0]; for i in passing.iter() { print_result(*i); } for i in failing.iter() { print_result(*i); } }
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.
#C.23
C#
using System.Text; using System.Security.Cryptography;   byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back"); byte[] hash = MD5.Create().ComputeHash(data); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Yabasic
Yabasic
// Rosetta Code problem: https://www.rosettacode.org/wiki/Menu // by Jjuanhdez, 06/2022   dim choose$(5) restore menudata for a = 0 to 5 : read choose$(a) : next a   print menu$(choose$()) end   sub menu$(m$()) clear screen repeat print color("green","black") at(0,0) "Menu selection" vc = 0 b = arraysize(m$(),1) while vc < 1 or vc > b for i = 1 to b-1 print i, " ", choose$(i) next i print choose$(b) print   input "Your choice: " c print at(0,7) "Your choice: " if c > 0 and c < 6 then vc = c print color("yellow","black") at(0,8) choose$(vc) else print color("red","black") at(0,8) choose$(0) break fi wend until vc = 5 end sub   label menudata data "Ack, not good", "fee fie ", "huff and puff" data "mirror mirror", "tick tock ", "exit "
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#zkl
zkl
fcn teleprompter(options){ os:=T("exit").extend(vm.arglist); N:=os.len(); if(N==1) return(""); while(1){ Utils.zipWith(fcn(n,o){"%d) %s".fmt(n,o).println()},[0..],os); a:=ask("Your choice: "); try{ n:=a.toInt(); if(0<=n<N) return(os[n]); } catch{} println("Ack, not good"); } }   teleprompter("fee fie" , "huff and puff" , "mirror mirror" , "tick tock") .println();
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Locomotive_Basic
Locomotive Basic
100 CLEAR 110 DIM a(100) 120 FOR a=0 TO 100/6 130 FOR b=0 TO 100/9 140 FOR c=0 TO 100/20 150 n=a*6+b*9+c*20 160 IF n<=100 THEN a(n)=1 170 NEXT c 180 NEXT b 190 NEXT a 200 FOR n=0 TO 100 210 IF a(n)=0 THEN l=n 220 NEXT n 230 PRINT"The Largest non McNugget number is:";l 240 END
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#Factor
Factor
USING: arrays formatting io kernel make math math.extras sequences ; IN: rosetta-code.mayan-numerals   : mayan-digit ( n -- m pair ) 20 /mod 5 /mod swap 2array ;   : integer>mayan ( n -- seq ) [ [ mayan-digit , ] until-zero ] { } make reverse ;   : ones ( n -- str ) [ CHAR: ● ] "" replicate-as ; : fives ( n -- str ) [ "——" ] replicate "<br>" join ;   : numeral ( pair -- str ) dup sum zero? [ drop "Θ" ] [ first2 [ ones ] [ fives ] bi* 2array harvest "<br>" join ] if ;   : .table-row ( pair -- ) "|style=\"width:3em;vertical-align:bottom;\"|" write numeral print ;   : .table-head ( -- ) "class=\"wikitable\" style=\"text-align:center;\"" print ;   : .table-body ( n -- ) integer>mayan [ .table-row ] each ;   : .mayan ( n -- ) [ "Mayan %d:\n" printf ] [ "{|" write .table-head .table-body "|}" print ] bi ;   : mayan-numerals ( -- ) { 4005 8017 326205 886205 } [ .mayan ] each ;   MAIN: mayan-numerals
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "strconv" )   const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" )   var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", }   const ( m0 = " Θ " m5 = "────" )   func dec2vig(n uint64) []uint64 { vig := strconv.FormatUint(n, 20) res := make([]uint64, len(vig)) for i, d := range vig { res[i], _ = strconv.ParseUint(string(d), 20, 64) } return res }   func vig2quin(n uint64) [4]string { if n >= 20 { panic("Cant't convert a number >= 20") } res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]} if n == 0 { res[3] = m0 return res } fives := n / 5 rem := n % 5 res[3-fives] = mayan[rem] for i := 3; i > 3-int(fives); i-- { res[i] = m5 } return res }   func draw(mayans [][4]string) { lm := len(mayans) fmt.Print(ul) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(uc) } else { fmt.Println(ur) } } for i := 1; i < 5; i++ { fmt.Print(vb) for j := 0; j < lm; j++ { fmt.Print(mayans[j][i-1]) fmt.Print(vb) } fmt.Println() } fmt.Print(ll) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(lc) } else { fmt.Println(lr) } } }   func main() { numbers := []uint64{4005, 8017, 326205, 886205, 1081439556} for _, n := range numbers { fmt.Printf("Converting %d to Mayan:\n", n) vigs := dec2vig(n) lv := len(vigs) mayans := make([][4]string, lv) for i, vig := range vigs { mayans[i] = vig2quin(vig) } draw(mayans) fmt.Println() } }
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.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Matrix is generic type Element is private; Zero : Element; One  : Element; with function "+" (A, B : Element) return Element is <>; with function "*" (A, B : Element) return Element is <>; with function Image (X : Element) return String is <>; package Matrices is type Matrix is array (Integer range <>, Integer range <>) of Element; function "*" (A, B : Matrix) return Matrix; function "**" (A : Matrix; Power : Natural) return Matrix; procedure Put (A : Matrix); end Matrices;   package body Matrices is function "*" (A, B : Matrix) return Matrix is R  : Matrix (A'Range (1), B'Range (2)); Sum : Element := Zero; begin for I in R'Range (1) loop for J in R'Range (2) loop Sum := Zero; for K in A'Range (2) loop Sum := Sum + A (I, K) * B (K, J); end loop; R (I, J) := Sum; end loop; end loop; return R; end "*";   function "**" (A : Matrix; Power : Natural) return Matrix is begin if Power = 1 then return A; end if; declare R : Matrix (A'Range (1), A'Range (2)) := (others => (others => Zero)); P : Matrix  := A; E : Natural := Power; begin for I in P'Range (1) loop -- R is identity matrix R (I, I) := One; end loop; if E = 0 then return R; end if; loop if E mod 2 /= 0 then R := R * P; end if; E := E / 2; exit when E = 0; P := P * P; end loop; return R; end; end "**";   procedure Put (A : Matrix) is begin for I in A'Range (1) loop for J in A'Range (1) loop Put (Image (A (I, J))); end loop; New_Line; end loop; end Put; end Matrices;   package Integer_Matrices is new Matrices (Integer, 0, 1, Image => Integer'Image); use Integer_Matrices;   M : Matrix (1..2, 1..2) := ((3,2),(2,1)); begin Put_Line ("M ="); Put (M); Put_Line ("M**0 ="); Put (M**0); Put_Line ("M**1 ="); Put (M**1); Put_Line ("M**2 ="); Put (M**2); Put_Line ("M*M ="); Put (M*M); Put_Line ("M**3 ="); Put (M**3); Put_Line ("M*M*M ="); Put (M*M*M); Put_Line ("M**4 ="); Put (M**4); Put_Line ("M*M*M*M ="); Put (M*M*M*M); Put_Line ("M**10 ="); Put (M**10); Put_Line ("M*M*M*M*M*M*M*M*M*M ="); Put (M*M*M*M*M*M*M*M*M*M); end Test_Matrix;
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib)   (cl-defstruct maze rows cols data)   (defmacro maze-pt (w r c) `(+ (* (mod ,r (maze-rows ,w)) (maze-cols ,w)) (mod ,c (maze-cols ,w))))   (defmacro maze-ref (w r c) `(aref (maze-data ,w) (maze-pt ,w ,r ,c)))   (defun new-maze (rows cols) (setq rows (1+ rows) cols (1+ cols)) (let ((m (make-maze :rows rows :cols cols :data (make-vector (* rows cols) nil))))   (dotimes (r rows) (dotimes (c cols) (setf (maze-ref m r c) (copy-sequence '(wall ceiling)))))   (dotimes (r rows) (maze-set m r (1- cols) 'visited))   (dotimes (c cols) (maze-set m (1- rows) c 'visited))   (maze-unset m 0 0 'ceiling) ;; Maze Entrance (maze-unset m (1- rows) (- cols 2) 'ceiling) ;; Maze Exit   m))   (defun maze-is-set (maze r c v) (member v (maze-ref maze r c)))   (defun maze-set (maze r c v) (let ((cell (maze-ref maze r c))) (when (not (member v cell)) (setf (maze-ref maze r c) (cons v cell)))))   (defun maze-unset (maze r c v) (setf (maze-ref maze r c) (delete v (maze-ref maze r c))))   (defun print-maze (maze &optional marks) (dotimes (r (1- (maze-rows maze)))   (dotimes (c (1- (maze-cols maze))) (princ (if (maze-is-set maze r c 'ceiling) "+---" "+ "))) (princ "+") (terpri)   (dotimes (c (1- (maze-cols maze))) (princ (if (maze-is-set maze r c 'wall) "|" " ")) (princ (if (member (cons r c) marks) " * " " "))) (princ "|") (terpri))   (dotimes (c (1- (maze-cols maze))) (princ (if (maze-is-set maze (1- (maze-rows maze)) c 'ceiling) "+---" "+ "))) (princ "+") (terpri))   (defun shuffle (lst) (sort lst (lambda (a b) (= 1 (random 2)))))   (defun to-visit (maze row col) (let (unvisited) (dolist (p '((0 . +1) (0 . -1) (+1 . 0) (-1 . 0))) (let ((r (+ row (car p))) (c (+ col (cdr p)))) (unless (maze-is-set maze r c 'visited) (push (cons r c) unvisited)))) unvisited))   (defun make-passage (maze r1 c1 r2 c2) (if (= r1 r2) (if (< c1 c2) (maze-unset maze r2 c2 'wall) ; right (maze-unset maze r1 c1 'wall)) ; left (if (< r1 r2) (maze-unset maze r2 c2 'ceiling) ; up (maze-unset maze r1 c1 'ceiling)))) ; down   (defun dig-maze (maze row col) (let (backup (run 0)) (maze-set maze row col 'visited) (push (cons row col) backup) (while backup (setq run (1+ run)) (when (> run (/ (+ row col) 3)) (setq run 0) (setq backup (shuffle backup))) (setq row (caar backup) col (cdar backup)) (let ((p (shuffle (to-visit maze row col)))) (if p (let ((r (caar p)) (c (cdar p))) (make-passage maze row col r c) (maze-set maze r c 'visited) (push (cons r c) backup)) (pop backup) (setq backup (shuffle backup)) (setq run 0))))))   (defun generate (rows cols) (let* ((m (new-maze rows cols))) (dig-maze m (random rows) (random cols)) (print-maze m)))   (defun parse-ceilings (line) (let (rtn (i 1)) (while (< i (length line)) (push (eq ?- (elt line i)) rtn) (setq i (+ i 4))) (nreverse rtn)))   (defun parse-walls (line) (let (rtn (i 0)) (while (< i (length line)) (push (eq ?| (elt line i)) rtn) (setq i (+ i 4))) (nreverse rtn)))   (defun parse-maze (file-name) (let ((rtn) (lines (with-temp-buffer (insert-file-contents-literally file-name) (split-string (buffer-string) "\n" t)))) (while lines (push (parse-ceilings (pop lines)) rtn) (push (parse-walls (pop lines)) rtn)) (nreverse rtn)))   (defun read-maze (file-name) (let* ((raw (parse-maze file-name)) (rows (1- (/ (length raw) 2))) (cols (length (car raw))) (maze (new-maze rows cols))) (dotimes (r rows) (let ((ceilings (pop raw))) (dotimes (c cols) (unless (pop ceilings) (maze-unset maze r c 'ceiling)))) (let ((walls (pop raw))) (dotimes (c cols) (unless (pop walls) (maze-unset maze r c 'wall))))) maze))   (defun find-exits (maze row col) (let (exits) (dolist (p '((0 . +1) (0 . -1) (-1 . 0) (+1 . 0))) (let ((r (+ row (car p))) (c (+ col (cdr p)))) (unless (cond ((equal p '(0 . +1)) (maze-is-set maze r c 'wall)) ((equal p '(0 . -1)) (maze-is-set maze row col 'wall)) ((equal p '(+1 . 0)) (maze-is-set maze r c 'ceiling)) ((equal p '(-1 . 0)) (maze-is-set maze row col 'ceiling))) (push (cons r c) exits)))) exits))   (defun drop-visited (maze points) (let (not-visited) (while points (unless (maze-is-set maze (caar points) (cdar points) 'visited) (push (car points) not-visited)) (pop points)) not-visited))   (defun solve-maze (maze) (let (solution (exit (cons (- (maze-rows maze) 2) (- (maze-cols maze) 2))) (pt (cons 0 0))) (while (not (equal pt exit)) (maze-set maze (car pt) (cdr pt) 'visited) (let ((exits (drop-visited maze (find-exits maze (car pt) (cdr pt))))) (if (null exits) (setq pt (pop solution)) (push pt solution) (setq pt (pop exits))))) (push pt solution)))   (defun solve (file-name) (let* ((maze (read-maze file-name)) (solution (solve-maze maze))) (print-maze maze solution)))   (solve "maze.txt")
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.
#D
D
void main() { import std.stdio, std.algorithm, std.range, std.file, std.conv;   "triangle.txt".File.byLine.map!split.map!(to!(int[])).array.retro .reduce!((x, y) => zip(y, x, x.dropOne) .map!(t => t[0] + t[1 .. $].max) .array)[0] .writeln; }
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Lasso
Lasso
cipher_digest('Rosetta Code', -digest='MD4')->encodeHex->asString
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#S-lang
S-lang
Educational Notes: 1) Array-style string manipulations (e.g. as = as[[1:]] ) always use bytes, not UTF-8 characters. As digits and '-' are all ASCII, all is copacetic. 2) The task doesn't require 64-bit integer support, but I added it, dependant on whether the S-Lang library compile supports them, which it generally does. [Main exception would be the current downloadable/installable MS-Win version of the Jed editor.] 3) S-Lang functions peel arguments off right-to-left, opposite of many languages. To align the order with other solutions, I enclosed the parameters in a list. One alternative would have been for m3() to call _stk_reverse(_NARGS), then pop each arg directly off the stack. Or of course just list the numbers backwards.
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.
#C.2B.2B
C++
#include <string> #include <iostream> #include "Poco/MD5Engine.h" #include "Poco/DigestStream.h"   using Poco::DigestEngine ; using Poco::MD5Engine ; using Poco::DigestOutputStream ;   int main( ) { std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ; MD5Engine md5 ; DigestOutputStream outstr( md5 ) ; outstr << myphrase ; outstr.flush( ) ; //to pass everything to the digest engine const DigestEngine::Digest& digest = md5.digest( ) ; std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Lua
Lua
  function range(A,B) return function() return coroutine.wrap(function() for i = A, B do coroutine.yield(i) end end) end end   function filter(stream, f) return function() return coroutine.wrap(function() for i in stream() do if f(i) then coroutine.yield(i) end end end) end end   function triple(s1, s2, s3) return function() return coroutine.wrap(function() for x in s1() do for y in s2() do for z in s3() do coroutine.yield{x,y,z} end end end end) end end   function apply(f, stream) return function() return coroutine.wrap(function() for T in stream() do coroutine.yield(f(table.unpack(T))) end end) end end   function exclude(s1, s2) local exlusions = {} for x in s1() do exlusions[x] = true end return function() return coroutine.wrap(function() for x in s2() do if not exlusions[x] then coroutine.yield(x) end end end) end end   function maximum(stream) local M = math.mininteger for x in stream() do M = math.max(M, x) end return M end   local N = 100 local A, B, C = 6, 9, 20   local Xs = filter(range(0, N), function(x) return x % A == 0 end) local Ys = filter(range(0, N), function(x) return x % B == 0 end) local Zs = filter(range(0, N), function(x) return x % C == 0 end) local sum = filter(apply(function(x, y, z) return x + y + z end, triple(Xs, Ys, Zs)), function(x) return x <= N end)   print(maximum(exclude(sum, range(1, N))))  
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#Go
Go
package main   import ( "fmt" "strconv" )   const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" )   var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", }   const ( m0 = " Θ " m5 = "────" )   func dec2vig(n uint64) []uint64 { vig := strconv.FormatUint(n, 20) res := make([]uint64, len(vig)) for i, d := range vig { res[i], _ = strconv.ParseUint(string(d), 20, 64) } return res }   func vig2quin(n uint64) [4]string { if n >= 20 { panic("Cant't convert a number >= 20") } res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]} if n == 0 { res[3] = m0 return res } fives := n / 5 rem := n % 5 res[3-fives] = mayan[rem] for i := 3; i > 3-int(fives); i-- { res[i] = m5 } return res }   func draw(mayans [][4]string) { lm := len(mayans) fmt.Print(ul) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(uc) } else { fmt.Println(ur) } } for i := 1; i < 5; i++ { fmt.Print(vb) for j := 0; j < lm; j++ { fmt.Print(mayans[j][i-1]) fmt.Print(vb) } fmt.Println() } fmt.Print(ll) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(lc) } else { fmt.Println(lr) } } }   func main() { numbers := []uint64{4005, 8017, 326205, 886205, 1081439556} for _, n := range numbers { fmt.Printf("Converting %d to Mayan:\n", n) vigs := dec2vig(n) lv := len(vigs) mayans := make([][4]string, lv) for i, vig := range vigs { mayans[i] = vig2quin(vig) } draw(mayans) fmt.Println() } }
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.
#11l
11l
F make_maze(w = 16, h = 8) V vis = [[0] * w [+] [1]] * h [+] [[1] * (w + 1)] V ver = [[‘| ’] * w [+] [String(‘|’)]] * h [+] [[String]()] V hor = [[‘+--’] * w [+] [String(‘+’)]] * (h + 1)   F walk(Int x, Int y) -> N @vis[y][x] = 1 V d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] random:shuffle(&d) L(=xx, =yy) d I yy == -1 yy = @vis.len - 1 I xx == -1 xx = @vis[0].len - 1 I @vis[yy][xx] L.continue I xx == x @hor[max(y, yy)][x] = ‘+ ’ I yy == y @ver[y][max(x, xx)] = ‘ ’ @walk(xx, yy)   walk(random:(w), random:(h))   V s = ‘’ L(a, b) zip(hor, ver) s ‘’= (a [+] [String("\n")] + b [+] [String("\n")]).join(‘’) R s   print(make_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.
#ALGOL_68
ALGOL 68
INT default upb=3; MODE VEC = [default upb]COSCAL; MODE MAT = [default upb,default upb]COSCAL;   OP * = (VEC a,b)COSCAL: ( COSCAL result:=0; FOR i FROM LWB a TO UPB a DO result+:= a[i]*b[i] OD; result );   OP * = (VEC a, MAT b)VEC: ( # overload vec times matrix # [2 LWB b:2 UPB b]COSCAL result; FOR j FROM 2 LWB b TO 2 UPB b DO result[j]:=a*b[,j] OD; result );   OP * = (MAT a, b)MAT: ( # overload matrix times matrix # [LWB a:UPB a, 2 LWB b:2 UPB b]COSCAL result; FOR k FROM LWB result TO UPB result DO result[k,]:=a[k,]*b OD; result );   OP IDENTITY = (INT upb)MAT:( [upb,upb] COSCAL out; FOR i TO upb DO FOR j TO upb DO out[i,j]:= ( i=j |1|0) OD OD; out );
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Erlang
Erlang
  -module( maze_solving ).   -export( [task/0] ).   cells( {Start_x, Start_y}, {Stop_x, Stop_y}, Maze ) -> Start_pid = maze:cell_pid( Start_x, Start_y, Maze ), Stop_pid = maze:cell_pid( Stop_x, Stop_y, Maze ), {ok, Cells} = loop( Start_pid, Stop_pid, maze:cell_accessible_neighbours(Start_pid), [Start_pid] ), Cells.   task() -> Max_x = 16, Max_y = 8, Maze = maze:generation( Max_x, Max_y ), Start_x = random:uniform( Max_x ), Start_y = random:uniform( Max_y ), Stop_x = random:uniform( Max_x ), Stop_y = random:uniform( Max_y ), Cells = cells( {Start_x, Start_y}, {Stop_x, Stop_y}, Maze ), [maze:cell_content_set(X, ".") || X <- Cells], maze:cell_content_set( maze:cell_pid(Start_x, Start_y, Maze), "S" ), maze:cell_content_set( maze:cell_pid(Stop_x, Stop_y, Maze), "G" ), maze:display( Maze ), maze:stop( Maze ).       loop( _Start, _Stop, [], _Acc) -> {error, dead_end}; loop( _Start, Stop, [Stop], Acc ) -> {ok, lists:reverse( [Stop | Acc] )}; loop( Start, Stop, [Next], [Previous | _T]=Acc ) -> loop( Start, Stop, lists:delete(Previous, maze:cell_accessible_neighbours(Next)), [Next | Acc] ); loop( Start, Stop, Nexts, Acc ) -> loop_stop( lists:member(Stop, Nexts), Start, Stop, Nexts, Acc ).   loop_stop( true, _Start, Stop, _Nexts, Acc ) -> {ok, lists:reverse( [Stop | Acc] )}; loop_stop( false, Start, Stop, Nexts, Acc ) -> My_pid = erlang:self(), [erlang:spawn( fun() -> My_pid ! loop( Start, Stop, [X], Acc ) end ) || X <- Nexts], receive {ok, Cells} -> {ok, Cells} 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.
#Elena
Elena
import system'routines; import extensions; import extensions'math;   string input = "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";   public program() { var list := IntMatrix.allocate(18,19);   int i := 0; int j := 0; input.splitBy(forward newLine).forEach:(string line) { j := 0; line.trim().splitBy(" ").forEach:(string num) { list[i][j] := num.toInt();   j += 1 };   i += 1 };   for(int i := 16, i >= 0, i-=1) { for(int j := 0, j < 18, j += 1) { list[i][j] := max(list[i][j] + list[i+1][j], list[i][j] + list[i+1][j+1]) } };   console.printLine("Maximum total: ", list[0][0]) }
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Lua
Lua
#!/usr/bin/lua   require "crypto"   print(crypto.digest("MD4", "Rosetta Code"))
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Scala
Scala
/** * Optionally return the middle three digits of an integer. * * @example List(123,12345,-789,1234,12) flatMap (middleThree(_)), returns: List(123, 234, 789) */ def middleThree( s:Int ) : Option[Int] = s.abs.toString match { case v if v.length % 2 == 0 => None // Middle three is undefined for even lengths case v if v.length < 3 => None case v => val i = (v.length / 2) - 1 Some( v.substring(i,i+3).toInt ) }     // A little test... val intVals = List(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0)   intVals map (middleThree(_)) map { case None => "No middle three" case Some(v) => "%03d".format(v) // Format the value, force leading zeroes } mkString("\n")  
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.
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>set hash=$System.Encryption.MD5Hash("The quick brown fox jumped over the lazy dog's back") USER>zzdump hash 0000: E3 8C A1 D9 20 C4 B8 B8 D3 94 6B 2C 72 F0 16 80
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#MAD
MAD
NORMAL MODE IS INTEGER BOOLEAN NUGGET DIMENSION NUGGET(101)   THROUGH CLEAR, FOR I=0, 1, I.G.100 CLEAR NUGGET(I) = 0B   THROUGH MARK, FOR A=0, 6, A.G.100 THROUGH MARK, FOR B=A, 9, B.G.100 THROUGH MARK, FOR C=B, 20, C.G.100 MARK NUGGET(C) = 1B   SEARCH THROUGH SEARCH, FOR I=100, -1, .NOT.NUGGET(I)   PRINT FORMAT F, I VECTOR VALUES F = $29HMAXIMUM NON-MCNUGGET NUMBER: ,I2*$ END OF PROGRAM
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FrobeniusNumber[{6, 9, 20}]
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#Haskell
Haskell
import Data.Bool (bool) import Data.List (intercalate, transpose) import qualified Data.Map.Strict as M import Data.Maybe (maybe)   --------------------------- MAIN ------------------------- main :: IO () main = (putStrLn . unlines) $ mayanFramed <$> [ 4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000 ]   ---------------------- MAYAN NUMBERS --------------------- mayanGlyph :: Int -> [[String]] mayanGlyph = filter (any (not . null)) . transpose . leftPadded . flip (showIntAtBaseS 20 mayanDigit) []   mayanDigit :: Int -> [String] mayanDigit n | 0 /= n = replicate (rem n 5) mayaOne : concat ( replicate (quot n 5) [mayaFive] ) | otherwise = [[mayaZero]]   mayanFramed :: Int -> String mayanFramed = ("Mayan " <>) . ( (<>) <$> show <*> ( (":\n\n" <>) . wikiTable ( M.fromList [ ( "style", concat [ "text-align:center;", "background-color:#F0EDDE;", "color:#605B4B;", "border:2px solid silver;" ] ), ("colwidth", "3em;") ] ) . mayanGlyph ) )   mayaZero, mayaOne :: Char mayaZero = '\920' mayaOne = '\9679'   mayaFive :: String mayaFive = "\9473\9473"   ---------------------- NUMERIC BASES --------------------- -- Based on the Prelude showIntAtBase but uses an -- (Int -> [String]) (rather than Int -> Char) function -- as its second argument. -- -- Shows a /non-negative/ 'Integral' number using the base -- specified by the first argument, and the **String** -- representation specified by the second. showIntAtBaseS :: Integral a => a -> (Int -> [String]) -> a -> [[String]] -> [[String]] showIntAtBaseS base toStr n0 r0 = let go (n, d) r = seq s $ case n of 0 -> r_ _ -> go (quotRem n base) r_ where s = toStr (fromIntegral d) r_ = s : r in go (quotRem n0 base) r0   ------------------------- DISPLAY ------------------------ wikiTable :: M.Map String String -> [[String]] -> String wikiTable opts rows | null rows = [] | otherwise = "{| " <> foldr ( \k a -> maybe a ( ((a <> k <> "=\"") <>) . ( <> "\" " ) ) (M.lookup k opts) ) [] ["class", "style"] <> ( '\n' : intercalate "|-\n" ( zipWith renderedRow rows [0 ..] ) ) <> "|}\n\n" where renderedRow row i = unlines ( fmap ( ( bool [] ( maybe "|" (("|style=\"width:" <>) . (<> "\"")) (M.lookup "colwidth" opts) ) (0 == i) <> ) . ('|' :) ) row )   leftPadded :: [[String]] -> [[String]] leftPadded xs = let w = maximum (length <$> xs) in ((<>) =<< flip replicate [] . (-) w . length) <$> xs
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.
#Action.21
Action!
DEFINE TOP="0" DEFINE RIGHT="1" DEFINE BOTTOM="2" DEFINE LEFT="3" DEFINE WIDTH="160" DEFINE HEIGHT="96"   DEFINE STACK_SIZE="5000" BYTE ARRAY stack(STACK_SIZE) INT stackSize   PROC InitStack() stackSize=0 RETURN   BYTE FUNC IsEmpty() IF stackSize=0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC IsFull() IF stackSize>=STACK_SIZE THEN RETURN (1) FI RETURN (0)   PROC Push(BYTE x,y) IF IsFull() THEN Break() RETURN FI stack(stackSize)=x stackSize==+1 stack(stackSize)=y stackSize==+1 RETURN   PROC Pop(BYTE POINTER x,y) IF IsEmpty() THEN Break() RETURN FI stackSize==-1 y^=stack(stackSize) stackSize==-1 x^=stack(stackSize) RETURN   PROC FillScreen() BYTE POINTER ptr ;pointer to the screen memory INT screenSize=[3840]   ptr=PeekC(88) SetBlock(ptr,screenSize,$55)   Color=0 Plot(0,HEIGHT-1) DrawTo(WIDTH-1,HEIGHT-1) DrawTo(WIDTH-1,0) RETURN   PROC GetNeighbors(BYTE x,y BYTE ARRAY n BYTE POINTER count) DEFINE WALL="1"   count^=0 IF y>2 AND Locate(x,y-2)=WALL THEN n(count^)=TOP count^==+1 FI IF x<WIDTH-3 AND Locate(x+2,y)=WALL THEN n(count^)=RIGHT count^==+1 FI IF y<HEIGHT-3 AND Locate(x,y+2)=WALL THEN n(count^)=BOTTOM count^==+1 FI IF x>2 AND Locate(x-2,y)=WALL THEN n(count^)=LEFT count^==+1 FI RETURN   PROC Maze(BYTE x,y) BYTE ARRAY stack,neighbors BYTE dir,nCount   FillScreen()   Color=2 InitStack() Push(x,y) WHILE IsEmpty()=0 DO Pop(@x,@y) GetNeighbors(x,y,neighbors,@nCount) IF nCount>0 THEN Push(x,y) Plot(x,y) dir=neighbors(Rand(nCount)) IF dir=TOP THEN y==-2 ELSEIF dir=RIGHT THEN x==+2 ELSEIF dir=BOTTOM THEN y==+2 ELSE x==-2 FI DrawTo(x,y) Push(x,y) FI OD RETURN   PROC Main() BYTE CH=$02FC,COLOR0=$02C4,COLOR1=$02C5 BYTE x,y   Graphics(7+16) COLOR0=$0A COLOR1=$04   x=Rand((WIDTH RSH 1)-1) LSH 1+1 y=Rand((HEIGHT RSH 1)-1) LSH 1+1 Maze(x,y)   DO UNTIL CH#$FF OD CH=$FF RETURN
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.
#BBC_BASIC
BBC BASIC
DIM matrix(1,1), output(1,1) matrix() = 3, 2, 2, 1   FOR power% = 0 TO 9 PROCmatrixpower(matrix(), output(), power%) PRINT "matrix()^" ; power% " = " FOR row% = 0 TO DIM(output(), 1) FOR col% = 0 TO DIM(output(), 2) PRINT output(row%,col%); NEXT PRINT NEXT row% NEXT power% END   DEF PROCmatrixpower(src(), dst(), pow%) LOCAL i% dst() = 0 FOR i% = 0 TO DIM(dst(), 1) : dst(i%,i%) = 1 : NEXT IF pow% THEN FOR i% = 1 TO pow% dst() = dst() . src() NEXT ENDIF ENDPROC
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.
#BQN
BQN
MatMul ← +˝∘×⎉1‿∞   MatEx ← {𝕨 MatMul⍟(𝕩-1) 𝕨}   (>⟨3‿2 2‿1⟩) MatEx 1‿2‿3‿4‿10
http://rosettacode.org/wiki/Matrix_chain_multiplication
Matrix chain multiplication
Problem Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved. For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors. Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1): AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105. BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48. In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases. Task Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions. Try this function on the following two lists: [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2] [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10] To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming. See also Matrix chain multiplication on Wikipedia.
#11l
11l
T Optimizer [Int] dims [[Int]] m, s   F (dims) .dims = dims   F findMatrixChainOrder() V n = .dims.len - 1 .m = [[0] * n] * n .s = [[0] * n] * n   L(lg) 1 .< n L(i) 0 .< n - lg V j = i + lg .m[i][j] = 7FFF'FFFF L(k) i .< j V cost = .m[i][k] + .m[k + 1][j] + .dims[i] * .dims[k + 1] * .dims[j + 1] I cost < .m[i][j] .m[i][j] = cost .s[i][j] = k   F optimalChainOrder(i, j) I i == j R String(Char(code' i + ‘A’.code)) E R ‘(’(.optimalChainOrder(i, .s[i][j]))‘’ ‘’(.optimalChainOrder(.s[i][j] + 1, j))‘)’   V Dims1 = [5, 6, 3, 1] V Dims2 = [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2] V Dims3 = [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]   L(dims) [Dims1, Dims2, Dims3] V opt = Optimizer(dims) opt.findMatrixChainOrder() print(‘Dims: ’dims) print(‘Order: ’opt.optimalChainOrder(0, dims.len - 2)) print(‘Cost: ’opt.m[0][dims.len - 2]) print(‘’)
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Frege
Frege
module MazeSolver where   import frege.IO import Data.Maybe   -- given two points, returns the average of them average :: (Int, Int) -> (Int, Int) -> (Int, Int) average (x, y) (x', y') = ((x + x') `div` 2, (y + y') `div` 2)   -- given a maze and a tuple of position and wall position, returns -- true if the wall position is not blocked (first position is unused) notBlocked :: [String] -> ((Int, Int), (Int, Int)) -> Bool notBlocked maze (_, (x, y)) = (' ' == String.charAt (maze !! y) x)   -- given a list, a position, and an element, returns a new list -- with the new element substituted at the position substitute :: [a] -> Int -> a -> [a] substitute orig pos el = let (before, after) = splitAt pos orig in before ++ [el] ++ tail after   -- like above, but for strings, since Frege strings are not -- lists of characters substituteString :: String -> Int -> String -> String substituteString orig pos el = let before = substr orig 0 pos after = strtail orig (pos + 1) in before ++ el ++ after   -- given a maze and a position, draw a '*' at that position in the maze draw :: [String] -> (Int, Int) -> [String] draw maze (x,y) = substitute maze y $ substituteString row x "*" where row = maze !! y   -- given a maze, a previous position, and a list of tuples of potential -- new positions and their wall positions, returns the solved maze, or -- None if it cannot be solved tryMoves :: [String] -> (Int, Int) -> [((Int, Int), (Int, Int))] -> Maybe [String] tryMoves _ _ [] = Nothing tryMoves maze prevPos ((newPos,wallPos):more) = case solve' maze newPos prevPos of Nothing -> tryMoves maze prevPos more Just maze' -> Just $ foldl draw maze' [newPos, wallPos]   -- given a maze, a new position, and a previous position, returns -- the solved maze, or None if it cannot be solved -- (assumes goal is upper-left corner of maze) solve' :: [String] -> (Int, Int) -> (Int, Int) -> Maybe [String] solve' maze (2, 1) _ = Just maze solve' maze (x, y) prevPos = let newPositions = [(x, y - 2), (x + 4, y), (x, y + 2), (x - 4, y)] notPrev pos' = pos' /= prevPos newPositions' = filter notPrev newPositions wallPositions = map (average (x,y)) newPositions' zipped = zip newPositions' wallPositions legalMoves = filter (notBlocked maze) zipped in tryMoves maze (x,y) legalMoves   -- given a maze, returns a solved maze, or None if it cannot be solved -- (starts at lower right corner and goes to upper left corner) solve :: [String] -> Maybe [String] solve maze = solve' (draw maze start) start (-1, -1) where startx = (length $ head maze) - 3 starty = (length maze) - 2 start = (startx, starty)   -- takes unsolved maze on standard input, prints solved maze on standard output main _ = do isin <- stdin isrin <- InputStreamReader.new isin brin <- BufferedReader.fromISR isrin lns <- BufferedReader.getlines brin printStr $ unlines $ fromMaybe ["can't solve"] $ solve lns
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.
#Elixir
Elixir
defmodule Maximum do def triangle_path(text) do text |> String.split("\n", trim: true) |> Enum.map(fn line -> line |> String.split() |> Enum.map(&String.to_integer(&1)) end) |> Enum.reduce([], fn x,total -> [0]++total++[0] |> Enum.chunk_every( 2, 1) |> Enum.map(&Enum.max(&1)) |> Enum.zip(x) |> Enum.map(fn{a,b} -> a+b end) end) |> Enum.max() end end   text = """ 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 """   IO.puts Maximum.triangle_path(text)  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["Rosetta Code", "MD4", "HexString"]
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Seed7
Seed7
$include "seed7_05.s7i";   const func string: middle3 (in integer: number) is func result var string: middle3 is ""; begin middle3 := str(abs(number)); if not odd(length(middle3)) or length(middle3) < 3 then middle3 := "error"; else middle3 := middle3[succ((length(middle3) - 3) div 2) len 3]; end if; end func;   const proc: main is func local var integer: number is 0; var string: mid3 is ""; begin for number range [] (123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) do writeln(number <& ": " <& middle3(number)); end for; end func;
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.
#Clojure
Clojure
(apply str (map (partial format "%02x") (.digest (doto (java.security.MessageDigest/getInstance "MD5") .reset (.update (.getBytes "The quick brown fox jumps over the lazy dog"))))))
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Modula-2
Modula-2
MODULE McNuggets; FROM InOut IMPORT WriteCard, WriteString, WriteLn;   CONST Max = 100; VAR a, b, c: CARDINAL; nugget: ARRAY [0..Max] OF BOOLEAN;   BEGIN FOR a := 0 TO Max DO nugget[a] := FALSE; END;   FOR a := 0 TO Max BY 6 DO FOR b := a TO Max BY 9 DO FOR c := b TO Max BY 20 DO nugget[c] := TRUE; END; END; END;   a := 100; REPEAT DEC(a); UNTIL NOT nugget[a]; WriteString("Maximum non-McNuggets number: "); WriteCard(a, 2); WriteLn(); END McNuggets.
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#J
J
elems =: 6 4$' . .. ... ....----' digit =: (elems{~5:<.0:>.15 10 5 0-~])`((4 4$_14{.'@')&[)@.(0&=) mayan =: ":@(digit each@(20&#.^:_1))
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#Java
Java
  import java.math.BigInteger;   public class MayanNumerals {   public static void main(String[] args) { for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) { displayMyan(BigInteger.valueOf(base10)); System.out.printf("%n"); } }   private static char[] digits = "0123456789ABCDEFGHJK".toCharArray(); private static BigInteger TWENTY = BigInteger.valueOf(20);   private static void displayMyan(BigInteger numBase10) { System.out.printf("As base 10:  %s%n", numBase10); String numBase20 = ""; while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) { numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20; numBase10 = numBase10.divide(TWENTY); } System.out.printf("As base 20:  %s%nAs Mayan:%n", numBase20); displayMyanLine1(numBase20); displayMyanLine2(numBase20); displayMyanLine3(numBase20); displayMyanLine4(numBase20); displayMyanLine5(numBase20); displayMyanLine6(numBase20); }   private static char boxUL = Character.toChars(9556)[0]; private static char boxTeeUp = Character.toChars(9574)[0]; private static char boxUR = Character.toChars(9559)[0]; private static char boxHorz = Character.toChars(9552)[0]; private static char boxVert = Character.toChars(9553)[0]; private static char theta = Character.toChars(952)[0]; private static char boxLL = Character.toChars(9562)[0]; private static char boxLR = Character.toChars(9565)[0]; private static char boxTeeLow = Character.toChars(9577)[0]; private static char bullet = Character.toChars(8729)[0]; private static char dash = Character.toChars(9472)[0];   private static void displayMyanLine1(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxUL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeUp : boxUR); } System.out.println(sb.toString()); }   private static String getBullet(int count) { StringBuilder sb = new StringBuilder(); switch ( count ) { case 1: sb.append(" " + bullet + " "); break; case 2: sb.append(" " + bullet + bullet + " "); break; case 3: sb.append("" + bullet + bullet + bullet + " "); break; case 4: sb.append("" + bullet + bullet + bullet + bullet); break; default: throw new IllegalArgumentException("Must be 1-4: " + count); } return sb.toString(); }   private static void displayMyanLine2(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'G': sb.append(getBullet(1)); break; case 'H': sb.append(getBullet(2)); break; case 'J': sb.append(getBullet(3)); break; case 'K': sb.append(getBullet(4)); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); }   private static String DASH = getDash();   private static String getDash() { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < 4 ; i++ ) { sb.append(dash); } return sb.toString(); }   private static void displayMyanLine3(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'B': sb.append(getBullet(1)); break; case 'C': sb.append(getBullet(2)); break; case 'D': sb.append(getBullet(3)); break; case 'E': sb.append(getBullet(4)); break; case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); }   private static void displayMyanLine4(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '6': sb.append(getBullet(1)); break; case '7': sb.append(getBullet(2)); break; case '8': sb.append(getBullet(3)); break; case '9': sb.append(getBullet(4)); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); }   private static void displayMyanLine5(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '0': sb.append(" " + theta + " "); break; case '1': sb.append(getBullet(1)); break; case '2': sb.append(getBullet(2)); break; case '3': sb.append(getBullet(3)); break; case '4': sb.append(getBullet(4)); break; case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); }   private static void displayMyanLine6(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxLL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeLow : boxLR); } System.out.println(sb.toString()); }   }  
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.
#Ada
Ada
generic Height : Positive; Width : Positive; package Mazes is   type Maze_Grid is private;   procedure Initialize (Maze : in out Maze_Grid);   procedure Put (Item : Maze_Grid);   private   type Directions is (North, South, West, East);   type Cell_Walls is array (Directions) of Boolean; type Cells is record Walls  : Cell_Walls := (others => True); Visited : Boolean  := False; end record;   subtype Height_Type is Positive range 1 .. Height; subtype Width_Type is Positive range 1 .. Width;   type Maze_Grid is array (Height_Type, Width_Type) of Cells;   end Mazes;
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.
#Burlesque
Burlesque
blsq ) {{1 1} {1 0}} 10 .*{mm}r[ {{89 55} {55 34}}
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.
#C
C
#include <math.h> #include <stdio.h> #include <stdlib.h>   typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx;   /* function for initializing row r of a new matrix */ typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);   SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf("Square Matrix allocation failure\n"); return NULL; } } else { printf("Malloc failed for square matrix\n"); } return sm; }   void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw];   for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } }   void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix;   for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } }   void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt;   for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); }   void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; }   void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); }   SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t;   while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; }   FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim;   fprintf(fout, "%s dim:%d =\n", mn, mtx->dim);   for (rw=0; rw<d; rw++) { fprintf(fout, " |"); for(col=0; col<d; col++) fprintf(fout, "%8.5f ",mtx->m[rw][col] ); fprintf(fout, " |\n"); } fprintf(fout, "\n"); }   void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta);   switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } }   int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2);   // fout = stdout; fout = fopen("matrx_exp.txt", "w"); SquareMtxPrint(m0, "m0"); FreeSquareMtx(m0); SquareMtxPrint(m1, "m0^5"); FreeSquareMtx(m1); SquareMtxPrint(m2, "m0^9"); FreeSquareMtx(m2); SquareMtxPrint(m3, "m0^2"); FreeSquareMtx(m3); fclose(fout);   return 0; }
http://rosettacode.org/wiki/Matrix_chain_multiplication
Matrix chain multiplication
Problem Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved. For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors. Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1): AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105. BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48. In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases. Task Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions. Try this function on the following two lists: [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2] [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10] To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming. See also Matrix chain multiplication on Wikipedia.
#Ada
Ada
  package mat_chain is type Vector is array (Natural range <>) of Integer; procedure Chain_Multiplication (Dims : Vector); end mat_chain;  
http://rosettacode.org/wiki/Matrix_chain_multiplication
Matrix chain multiplication
Problem Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved. For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors. Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1): AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105. BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48. In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases. Task Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions. Try this function on the following two lists: [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2] [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10] To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming. See also Matrix chain multiplication on Wikipedia.
#C
C
#include <stdio.h> #include <limits.h> #include <stdlib.h>   int **m; int **s;   void optimal_matrix_chain_order(int *dims, int n) { int len, i, j, k, temp, cost; n--; m = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; ++i) { m[i] = (int *)calloc(n, sizeof(int)); }   s = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; ++i) { s[i] = (int *)calloc(n, sizeof(int)); }   for (len = 1; len < n; ++len) { for (i = 0; i < n - len; ++i) { j = i + len; m[i][j] = INT_MAX; for (k = i; k < j; ++k) { temp = dims[i] * dims[k + 1] * dims[j + 1]; cost = m[i][k] + m[k + 1][j] + temp; if (cost < m[i][j]) { m[i][j] = cost; s[i][j] = k; } } } } }   void print_optimal_chain_order(int i, int j) { if (i == j) printf("%c", i + 65); else { printf("("); print_optimal_chain_order(i, s[i][j]); print_optimal_chain_order(s[i][j] + 1, j); printf(")"); } }   int main() { int i, j, n; int a1[4] = {5, 6, 3, 1}; int a2[13] = {1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2}; int a3[12] = {1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}; int *dims_list[3] = {a1, a2, a3}; int sizes[3] = {4, 13, 12}; for (i = 0; i < 3; ++i) { printf("Dims  : ["); n = sizes[i]; for (j = 0; j < n; ++j) { printf("%d", dims_list[i][j]); if (j < n - 1) printf(", "); else printf("]\n"); } optimal_matrix_chain_order(dims_list[i], n); printf("Order : "); print_optimal_chain_order(0, n - 2); printf("\nCost  : %d\n\n", m[0][n - 2]); for (j = 0; j <= n - 2; ++j) free(m[j]); free(m); for (j = 0; j <= n - 2; ++j) free(s[j]); free(s); } return 0; }
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Go
Go
package main   import ( "bytes" "fmt" "math/rand" "time" )   type maze struct { c2 [][]byte // cells by row h2 [][]byte // horizontal walls by row (ignore first row) v2 [][]byte // vertical walls by row (ignore first of each column) }   func newMaze(rows, cols int) *maze { c := make([]byte, rows*cols) // all cells h := bytes.Repeat([]byte{'-'}, rows*cols) // all horizontal walls v := bytes.Repeat([]byte{'|'}, rows*cols) // all vertical walls c2 := make([][]byte, rows) // cells by row h2 := make([][]byte, rows) // horizontal walls by row v2 := make([][]byte, rows) // vertical walls by row for i := range h2 { c2[i] = c[i*cols : (i+1)*cols] h2[i] = h[i*cols : (i+1)*cols] v2[i] = v[i*cols : (i+1)*cols] } return &maze{c2, h2, v2} }   func (m *maze) String() string { hWall := []byte("+---") hOpen := []byte("+ ") vWall := []byte("| ") vOpen := []byte(" ") rightCorner := []byte("+\n") rightWall := []byte("|\n") var b []byte for r, hw := range m.h2 { for _, h := range hw { if h == '-' || r == 0 { b = append(b, hWall...) } else { b = append(b, hOpen...) if h != '-' && h != 0 { b[len(b)-2] = h } } } b = append(b, rightCorner...) for c, vw := range m.v2[r] { if vw == '|' || c == 0 { b = append(b, vWall...) } else { b = append(b, vOpen...) if vw != '|' && vw != 0 { b[len(b)-4] = vw } } if m.c2[r][c] != 0 { b[len(b)-2] = m.c2[r][c] } } b = append(b, rightWall...) } for _ = range m.h2[0] { b = append(b, hWall...) } b = append(b, rightCorner...) return string(b) }   func (m *maze) gen() { m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0]))) }   const ( up = iota dn rt lf )   func (m *maze) g2(r, c int) { m.c2[r][c] = ' ' for _, dir := range rand.Perm(4) { switch dir { case up: if r > 0 && m.c2[r-1][c] == 0 { m.h2[r][c] = 0 m.g2(r-1, c) } case lf: if c > 0 && m.c2[r][c-1] == 0 { m.v2[r][c] = 0 m.g2(r, c-1) } case dn: if r < len(m.c2)-1 && m.c2[r+1][c] == 0 { m.h2[r+1][c] = 0 m.g2(r+1, c) } case rt: if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 { m.v2[r][c+1] = 0 m.g2(r, c+1) } } } }   func main() { rand.Seed(time.Now().UnixNano()) const height = 4 const width = 7 m := newMaze(height, width) m.gen() m.solve( rand.Intn(height), rand.Intn(width), rand.Intn(height), rand.Intn(width)) fmt.Print(m) }   func (m *maze) solve(ra, ca, rz, cz int) { var rSolve func(ra, ca, dir int) bool rSolve = func(r, c, dir int) bool { if r == rz && c == cz { m.c2[r][c] = 'F' return true } if dir != dn && m.h2[r][c] == 0 { if rSolve(r-1, c, up) { m.c2[r][c] = '^' m.h2[r][c] = '^' return true } } if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 { if rSolve(r+1, c, dn) { m.c2[r][c] = 'v' m.h2[r+1][c] = 'v' return true } } if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 { if rSolve(r, c+1, rt) { m.c2[r][c] = '>' m.v2[r][c+1] = '>' return true } } if dir != rt && m.v2[r][c] == 0 { if rSolve(r, c-1, lf) { m.c2[r][c] = '<' m.v2[r][c] = '<' return true } } return false } rSolve(ra, ca, -1) m.c2[ra][ca] = 'S' }
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.
#Erlang
Erlang
  -mode(compile). -import(lists, [foldl/3]).   main(_) -> {ok, Tmat} = file:open("triangle.txt", [read, raw, {read_ahead, 16384}]), Max = max_sum(Tmat, []), io:format("The maximum total is ~b~n", [Max]).   max_sum(FD, Last) -> case file:read_line(FD) of eof -> foldl(fun erlang:max/2, 0, Last); {ok, Line} -> Current = [binary_to_integer(B) || B <- re:split(Line, "[ \n]"), byte_size(B) > 0], max_sum(FD, fold_row(Last, Current)) end.   % The first argument has one more element than the second, so compute % the initial sum so that both lists have identical length for fold_rest(). fold_row([], L) -> L; fold_row([A|_] = Last, [B|Bs]) -> [A+B | fold_rest(Last, Bs)].   % Both lists must have same length fold_rest([A], [B]) -> [A+B]; fold_rest([A1 | [A2|_] = As], [B|Bs]) -> [B + max(A1,A2) | fold_rest(As, Bs)].  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Nim
Nim
import strutils   const MD4Len = 16   proc MD4(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: "libssl.so", importc.}   proc MD4(s: string): string = result = "" var s = MD4(s.cstring, s.len.culong) for i in 0 ..< MD4Len: result.add s[i].BiggestInt.toHex(2).toLower   echo MD4("Rosetta Code")
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#SenseTalk
SenseTalk
set inputs to [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]   repeat with each num in inputs put num into output put middle3digits of num into character 15 of output -- will autofill with "."s put output end repeat   to handle middle3digits of number put every occurrence of <digit> in number into digits if the number of items in digits is less than 3 then return "Error: too few digits" if the number of items in digits is an even number then return "Error: even number of digits" repeat while the number of items in digits is greater than 3 delete the first item of digits delete the last item of digits end repeat return digits joined by empty end middle3digits  
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Sidef
Sidef
func middle_three(n) { var l = n.len; if (l < 3) { "#{n} is too short" } elsif (l.is_even) { "#{n} has an even number of digits" } else { "The three middle digits of #{n} are: " + n.digits.ft(l-3 / 2, l/2 + 1).join } }   var nums = %n( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 ); nums.each { say middle_three(_) };
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.
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. MD5. AUTHOR. Bill Gunshannon INSTALLATION. Home. DATE-WRITTEN. 16 December 2021. ************************************************************ ** Program Abstract: ** Use the md5sum utility and pass the HASH back using ** a temp file. Not elegant, but it works. ************************************************************     ENVIRONMENT DIVISION.   INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Tmp-MD5 ASSIGN TO "/tmp/MD5" ORGANIZATION IS LINE SEQUENTIAL.     DATA DIVISION.   FILE SECTION.   FD Tmp-MD5 DATA RECORD IS MD5-Rec. 01 MD5-Rec PIC X(32).     WORKING-STORAGE SECTION.   01 Eof PIC X VALUE 'F'. 01 Str1. 05 Pre-cmd PIC X(8) VALUE 'echo -n '. 05 Str1-complete. 10 Str1-Part1 PIC X(26) VALUE 'The quick brown fox jumps'. 10 Str1-Part2 PIC X(19) VALUE ' over the lazy dog'. 05 Post-cmd PIC X(20) VALUE ' | md5sum > /tmp/MD5'. 01 Str1-MD5 PIC X(32).     PROCEDURE DIVISION.   Main-Program.   DISPLAY Str1-complete. PERFORM Get-MD5. DISPLAY Str1-MD5.   STOP RUN.   Get-MD5.   CALL "SYSTEM" USING Str1. OPEN INPUT Tmp-MD5. READ Tmp-MD5 INTO Str1-MD5. CLOSE Tmp-MD5. CALL "CBL_DELETE_FILE" USING '/tmp/MD5'.  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#MiniZinc
MiniZinc
  %McNuggets. Nigel Galloway, August 27th., 2019 var 0..99: n; constraint forall(x in 0..16,y in 0..11,z in 0..5)(6*x + 9*y + 20*z!=n); solve maximize n; output [show(n)]  
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => unlines( map(mayanFramed, [4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000] ) );   // MAYAN NUMBERS --------------------------------------   // mayanFramed :: Int -> String const mayanFramed = n => '\nMayan ' + n.toString() + ':\n\n' + wikiTable({ style: 'text-align:center; background-color:#F0EDDE; ' + 'color:#605B4B; border:2px solid silver', colwidth: '3em' })( mayanGlyph(n) );   // mayanGlyph :: Int -> [[String]] const mayanGlyph = n => filter(any(compose(not, isNull)), transpose(leftPadded( showIntAtBase(20, mayanDigit, n, []) )) );   // mayanDigit :: Int -> [String] const mayanDigit = n => 0 !== n ? cons( replicateString(rem(n, 5), '●'), replicate(quot(n, 5), '━━') ) : ['Θ'];   // FORMATTING -----------------------------------------   // wikiTable :: Dict -> [[a]] -> String const wikiTable = opts => rows => { const colWidth = () => 'colwidth' in opts ? ( '|style="width:' + opts.colwidth + ';"' ) : ''; return 0 < rows.length ? ( '{| ' + ['class', 'style'].reduce( (a, k) => k in opts ? ( a + k + '="' + opts[k] + '" ' ) : a, '' ) + '\n' + rows.map( (row, i) => row.map( x => (0 === i ? ( colWidth() + '| ' ) : '|') + (x.toString() || ' ') ).join('\n') ).join('\n|-\n') + '\n|}\n\n' ) : ''; };   // leftPadded :: [[String]] -> [[String]] const leftPadded = xs => { const w = maximum(map(length, xs)); return map( x => replicate(w - x.length, '').concat(x), xs ); };   // GENERIC FUNCTIONS ----------------------------------   // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // any :: (a -> Bool) -> [a] -> Bool const any = p => xs => xs.some(p);   // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => (x, y) => { const a = f(x), b = f(y); return a < b ? -1 : (a > b ? 1 : 0); };   // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (f, g) => x => f(g(x));   // concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = (f, xs) => xs.reduce((a, x) => a.concat(f(x)), []);   // cons :: a -> [a] -> [a] const cons = (x, xs) => Array.isArray(xs) ? ( [x].concat(xs) ) : 'GeneratorFunction' !== xs.constructor.constructor.name ? ( x + xs ) : ( // Existing generator wrapped with one additional element function*() { yield x; let nxt = xs.next() while (!nxt.done) { yield nxt.value; nxt = xs.next(); } } )();   // filter :: (a -> Bool) -> [a] -> [a] const filter = (f, xs) => xs.filter(f);   // foldl1 :: (a -> a -> a) -> [a] -> a const foldl1 = (f, xs) => 1 < xs.length ? xs.slice(1) .reduce(f, xs[0]) : xs[0];   // isNull :: [a] -> Bool // isNull :: String -> Bool const isNull = xs => Array.isArray(xs) || ('string' === typeof xs) ? ( 1 > xs.length ) : undefined;   // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc   // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f);   // maximum :: Ord a => [a] -> a const maximum = xs => 0 < xs.length ? ( foldl1((a, x) => x > a ? x : a, xs) ) : undefined;   // Ordering: (LT|EQ|GT): // GT: 1 (or other positive n) // EQ: 0 // LT: -1 (or other negative n)   // maximumBy :: (a -> a -> Ordering) -> [a] -> a const maximumBy = (f, xs) => 0 < xs.length ? ( xs.slice(1) .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0]) ) : undefined;   // not :: Bool -> Bool const not = b => !b;   // quot :: Int -> Int -> Int const quot = (n, m) => Math.floor(n / m);   // quotRem :: Int -> Int -> (Int, Int) const quotRem = (m, n) => Tuple(Math.floor(m / n), m % n);   // rem :: Int -> Int -> Int const rem = (n, m) => n % m;   // replicate :: Int -> a -> [a] const replicate = (n, x) => Array.from({ length: n }, () => x);   // replicateString :: Int -> String -> String const replicateString = (n, s) => s.repeat(n);   // showIntAtBase :: Int -> (Int -> [String]) // -> Int -> [[String]] -> [[String]] const showIntAtBase = (base, toStr, n, rs) => { const go = ([n, d], r) => { const r_ = cons(toStr(d), r); return 0 !== n ? ( go(Array.from(quotRem(n, base)), r_) ) : r_; }; return go(Array.from(quotRem(n, base)), rs); };   // transpose :: [[a]] -> [[a]] const transpose = tbl => { const gaps = replicate( length(maximumBy(comparing(length), tbl)), [] ), rows = map(xs => xs.concat(gaps.slice(xs.length)), tbl); return map( (_, col) => concatMap(row => [row[col]], rows), rows[0] ); };   // unlines :: [String] -> String const unlines = xs => xs.join('\n');   // MAIN --- return main(); })();
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.
#Aime
Aime
grid_maze(data b, integer N) { data d;   N.times(bb_cast, d, "+---"); bb_cast(d, "+\n");   N.times(bb_cast, d, "| * "); bb_cast(d, "|\n");   N.times(bb_copy, b, d);   b_size(d, N * 4 + 2);   bb_copy(b, d); }   void walk_cell(data b, integer N, line_size, x, y, list x_offsets, y_offsets) { integer i, p, q, r;   b_replace(b, y + x, ' ');   r = drand(3);   i = 0; while (i < 4) { p = x + x_offsets[q = (r + i) & 3]; q = y + y_offsets[q];   if (-1 < p && p < line_size && -1 < q && q < line_size * (N * 2 + 1)) { if (b[q + p] == '*') { walk_cell(b, N, line_size, p, q, x_offsets, y_offsets); b[(q + y) / 2 + (p + x) / 2] = ' '; if (p == x) { b[(q + y) / 2 + p - 1] = ' '; b[(q + y) / 2 + p + 1] = ' '; } } }   i += 1; } }   walk_maze(data b, integer N) { integer line_size, x, y; list x_offsets, y_offsets;   line_size = N * 4 + 1 + 1;   l_bill(x_offsets, 0, 4, 0, -4, 0); l_bill(y_offsets, 0, 0, line_size * 2, 0, line_size * -2);   x = drand(N - 1) * 4 + 2; y = line_size * (drand(N - 1) * 2 + 1);   walk_cell(b, N, line_size, x, y, x_offsets, y_offsets); }   main(void) { data b;   grid_maze(b, 10); walk_maze(b, 10);   o_(b);   0; }
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.
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class MatrixExponentation { public static double[,] Identity(int size) { double[,] matrix = new double[size, size]; for (int i = 0; i < size; i++) matrix[i, i] = 1; return matrix; }   public static double[,] Multiply(this double[,] left, double[,] right) { if (left.ColumnCount() != right.RowCount()) throw new ArgumentException(); double[,] m = new double[left.RowCount(), right.ColumnCount()]; foreach (var (row, column) in from r in Range(0, m.RowCount()) from c in Range(0, m.ColumnCount()) select (r, c)) { m[row, column] = Range(0, m.RowCount()).Sum(i => left[row, i] * right[i, column]); } return m; }   public static double[,] Pow(this double[,] matrix, int exp) { if (matrix.RowCount() != matrix.ColumnCount()) throw new ArgumentException("Matrix must be square."); double[,] accumulator = Identity(matrix.RowCount()); for (int i = 0; i < exp; i++) { accumulator = accumulator.Multiply(matrix); } return accumulator; }   private static int RowCount(this double[,] matrix) => matrix.GetLength(0); private static int ColumnCount(this double[,] matrix) => matrix.GetLength(1);   private static void Print(this double[,] m) { foreach (var row in Rows()) { Console.WriteLine("[ " + string.Join(" ", row) + " ]"); } Console.WriteLine();   IEnumerable<IEnumerable<double>> Rows() => Range(0, m.RowCount()).Select(row => Range(0, m.ColumnCount()).Select(column => m[row, column])); }   public static void Main() { var matrix = new double[,] { { 3, 2 }, { 2, 1 } };   matrix.Pow(0).Print(); matrix.Pow(1).Print(); matrix.Pow(2).Print(); matrix.Pow(3).Print(); matrix.Pow(4).Print(); matrix.Pow(50).Print(); }   }
http://rosettacode.org/wiki/Matrix_digital_rain
Matrix digital rain
Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia. Provided is a reference implementation in Common Lisp to be run in a terminal.
#Ada
Ada
with Ada.Text_IO; with Ada.Numerics.Discrete_Random; with Ada.Strings.Fixed;   procedure Digital_Rain is type Column_Type is range 0 .. 150; type Row_Type is range 0 .. 25; type Character_Range is new Character range 'A' .. 'Z'; subtype Delay_Range is Integer range 2 .. 6;   package Column_Random is new Ada.Numerics.Discrete_Random (Column_Type); package Row_Random is new Ada.Numerics.Discrete_Random (Row_Type); package Character_Random is new Ada.Numerics.Discrete_Random (Character_Range); package Delay_Random is new Ada.Numerics.Discrete_Random (Delay_Range);   Column_Generator  : Column_Random.Generator; Row_Generator  : Row_Random.Generator; Character_Generator : Character_Random.Generator; Delay_Generator  : Delay_Random.Generator;   Esc  : constant Character := Character'Val (8#33#); Running : Boolean  := True; Char  : Character; use Ada.Text_IO;   protected Text_Out is procedure Put_At (Row : Row_Type; Col : Column_Type; Color : Integer; Item : Character); end Text_Out;   protected body Text_Out is procedure Put_At (Row : Row_Type; Col : Column_Type; Color : Integer; Item : Character) is use Ada.Strings; begin Put (Esc & "[" & Fixed.Trim (Row'Image, Left) & ";" & Fixed.Trim (Col'Image, Left) & "H"); -- Place Cursor Put (Esc & "[" & Fixed.Trim (Color'Image, Left) & "m"); -- Foreground color Put (Item); end Put_At; end Text_Out;   task type Rainer;   task body Rainer is Row : Row_Type; Col : Column_Type; Del : Delay_Range; begin Outer_Loop: loop Col := Column_Random.Random (Column_Generator); Row := Row_Random.Random (Row_Generator); for Rain in reverse Boolean loop Del := Delay_Random.Random (Delay_Generator); for R in 0 .. Row loop if Rain then if R in 1 .. Row then Text_Out.Put_At (R - 1, Col, Color => 32, Item => Char); end if; Char := Character (Character_Random.Random (Character_Generator)); if R in 0 .. Row - 1 then Text_Out.Put_At (R, Col, Color => 97, Item => Char); end if; else Text_Out.Put_At (R, Col, Color => 30, Item => ' '); end if; delay 0.020 * Del; exit Outer_Loop when not Running; end loop; end loop; end loop Outer_Loop; end Rainer;   Dummy  : Character; Rainers : array (1 .. 50) of Rainer; begin Put (ESC & "[?25l"); -- Hide the cursor Put (ESC & "[40m"); -- Black background Put (ESC & "[2J"); -- Clear Terminal   Get_Immediate (Dummy); Running := False; delay 0.200;   Put (ESC & "[?25h"); -- Restore the cursor Put (ESC & "[0;0H"); -- Place cursor Put (ESC & "[39m"); -- Default foreground Put (ESC & "[49m"); -- Default backgound Put (ESC & "[2J"); -- Clear Terminal end Digital_Rain;
http://rosettacode.org/wiki/Mastermind
Mastermind
Create a simple version of the board game:   Mastermind. It must be possible to:   choose the number of colors will be used in the game (2 - 20)   choose the color code length (4 - 10)   choose the maximum number of guesses the player has (7 - 20)   choose whether or not colors may be repeated in the code The (computer program) game should display all the player guesses and the results of that guess. Display (just an idea): Feature Graphic Version Text Version Player guess Colored circles Alphabet letters Correct color & position Black circle X Correct color White circle O None Gray circle - A text version example:       1.   ADEF   -   XXO- Translates to: the first guess; the four colors (ADEF); result: two correct colors and spot, one correct color/wrong spot, one color isn't in the code. Happy coding! Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number   Guess the number/With Feedback
#11l
11l
F encode(correct, guess) [String] output_arr   L(i) 0 .< correct.len output_arr [+]= I guess[i] == correct[i] {‘X’} E I guess[i] C correct {‘O’} E ‘-’   R output_arr   F safe_int_input(prompt, min_val, max_val) L V user_input_str = input(prompt)   X.try V user_input = Int(user_input_str) I user_input C min_val .. max_val R user_input X.catch ValueError L.continue   F play_game() print(‘Welcome to Mastermind.’) print(‘You will need to guess a random code.’) print(‘For each guess, you will receive a hint.’) print(‘In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.’) print()   V number_of_letters = safe_int_input(‘Select a number of possible letters for the code (2-20): ’, 2, 20) V code_length = safe_int_input(‘Select a length for the code (4-10): ’, 4, 10)   V letters = ‘ABCDEFGHIJKLMNOPQRST’[0 .< number_of_letters] V code = ‘’ L 0 .< code_length code ‘’= random:choice(letters) [String] guesses   L print() V guess = input(‘Enter a guess of length #. (#.): ’.format(code_length, letters)).uppercase()   I guess.len != code_length | any(guess.map(char -> char !C @letters)) L.continue E I guess == code print("\nYour guess "guess‘ was correct!’) L.break E guesses.append(‘#.: #. => #.’.format(guesses.len + 1, Array(guess).join(‘ ’), encode(code, guess).join(‘ ’)))   L(i_guess) guesses print(‘------------------------------------’) print(i_guess) print(‘------------------------------------’)   play_game()
http://rosettacode.org/wiki/Matrix_chain_multiplication
Matrix chain multiplication
Problem Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved. For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors. Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1): AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105. BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48. In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases. Task Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions. Try this function on the following two lists: [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2] [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10] To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming. See also Matrix chain multiplication on Wikipedia.
#C.23
C#
using System;   class MatrixChainOrderOptimizer { private int[,] m; private int[,] s;   void OptimalMatrixChainOrder(int[] dims) { int n = dims.Length - 1; m = new int[n, n]; s = new int[n, n]; for (int len = 1; len < n; ++len) { for (int i = 0; i < n - len; ++i) { int j = i + len; m[i, j] = Int32.MaxValue; for (int k = i; k < j; ++k) { int temp = dims[i] * dims[k + 1] * dims[j + 1]; int cost = m[i, k] + m[k + 1, j] + temp; if (cost < m[i, j]) { m[i, j] = cost; s[i, j] = k; } } } } }   void PrintOptimalChainOrder(int i, int j) { if (i == j) Console.Write((char)(i + 65)); else { Console.Write("("); PrintOptimalChainOrder(i, s[i, j]); PrintOptimalChainOrder(s[i, j] + 1, j); Console.Write(")"); } }   static void Main() { var mcoo = new MatrixChainOrderOptimizer(); var dimsList = new int[3][]; dimsList[0] = new int[4] {5, 6, 3, 1}; dimsList[1] = new int[13] {1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2}; dimsList[2] = new int[12] {1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}; for (int i = 0; i < dimsList.Length; ++i) { Console.Write("Dims  : ["); int n = dimsList[i].Length; for (int j = 0; j < n; ++j) { Console.Write(dimsList[i][j]); if (j < n - 1) Console.Write(", "); else Console.WriteLine("]"); } mcoo.OptimalMatrixChainOrder(dimsList[i]); Console.Write("Order : "); mcoo.PrintOptimalChainOrder(0, n - 2); Console.WriteLine("\nCost  : {0}\n", mcoo.m[0, n - 2]); } } }
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Haskell
Haskell
#!/usr/bin/runhaskell   import Data.Maybe (fromMaybe)   -- given two points, returns the average of them average :: (Int, Int) -> (Int, Int) -> (Int, Int) average (x, y) (x_, y_) = ((x + x_) `div` 2, (y + y_) `div` 2)   -- given a maze and a tuple of position and wall position, returns -- true if the wall position is not blocked (first position is unused) notBlocked :: [String] -> ((Int, Int), (Int, Int)) -> Bool notBlocked maze (_, (x, y)) = ' ' == (maze !! y) !! x   -- given a list, a position, and an element, returns a new list -- with the new element substituted at the position -- (it seems such a function should exist in the standard library; -- I must be missing it) substitute :: [a] -> Int -> a -> [a] substitute orig pos el = let (before, after) = splitAt pos orig in before ++ [el] ++ tail after   -- given a maze and a position, draw a '*' at that position in the maze draw :: [String] -> (Int, Int) -> [String] draw maze (x, y) = let row = maze !! y in substitute maze y $ substitute row x '*'   -- given a maze, a previous position, and a list of tuples of potential -- new positions and their wall positions, returns the solved maze, or -- None if it cannot be solved tryMoves :: [String] -> (Int, Int) -> [((Int, Int), (Int, Int))] -> Maybe [String] tryMoves _ _ [] = Nothing tryMoves maze prevPos ((newPos, wallPos):more) = case solve_ maze newPos prevPos of Nothing -> tryMoves maze prevPos more Just maze_ -> Just $ foldl draw maze_ [newPos, wallPos]   -- given a maze, a new position, and a previous position, returns -- the solved maze, or None if it cannot be solved -- (assumes goal is upper-left corner of maze) solve_ :: [String] -> (Int, Int) -> (Int, Int) -> Maybe [String] solve_ maze (2, 1) _ = Just maze solve_ maze pos@(x, y) prevPos = let newPositions = [(x, y - 2), (x + 4, y), (x, y + 2), (x - 4, y)] notPrev pos_ = pos_ /= prevPos newPositions_ = filter notPrev newPositions wallPositions = map (average pos) newPositions_ zipped = zip newPositions_ wallPositions legalMoves = filter (notBlocked maze) zipped in tryMoves maze pos legalMoves   -- given a maze, returns a solved maze, or None if it cannot be solved -- (starts at lower right corner and goes to upper left corner) solve :: [String] -> Maybe [String] solve maze = solve_ (draw maze start) start (-1, -1) where startx = length (head maze) - 3 starty = length maze - 2 start = (startx, starty)   -- takes unsolved maze on standard input, prints solved maze on standard output main = let main_ = unlines . fromMaybe ["can_t solve"] . solve . lines in interact main_  
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.
#ERRE
ERRE
  PROGRAM TRIANGLE_PATH   CONST ROW=18   DIM TRI[200]   ! ! for rosettacode,org !   FUNCTION MAX(X,Y) MAX=-X*(X>=Y)-Y*(X<Y) END FUNCTION   BEGIN   DATA(55) DATA(94,48) DATA(95,30,96) DATA(77,71,26,67) DATA(97,13,76,38,45) DATA(7,36,79,16,37,68) DATA(48,7,9,18,70,26,6) DATA(18,72,79,46,59,79,29,90) DATA(20,76,87,11,32,7,7,49,18) DATA(27,83,58,35,71,11,25,57,29,85) DATA(14,64,36,96,27,11,58,56,92,18,55) DATA(2,90,3,60,48,49,41,46,33,36,47,23) DATA(92,50,48,2,36,59,42,79,72,20,82,77,42) DATA(56,78,38,80,39,75,2,71,66,66,1,3,55,72) DATA(44,25,67,84,71,67,11,61,40,57,58,89,40,56,36) DATA(85,32,25,85,57,48,84,35,47,62,17,1,1,99,89,52) DATA(6,71,28,75,94,48,37,10,23,51,6,48,53,18,74,98,15) DATA(27,2,92,23,8,71,76,84,15,52,92,63,81,10,44,10,69,93)   PRINT(CHR$(12);) !CLS LUNG=ROW*(ROW+1)/2 FOR I%=0 TO LUNG-1 DO READ(TRI[I%]) END FOR   BSE=(SQR(8*LUNG+1)-1)/2 STP=BSE-1 STEPC=0   FOR I%=LUNG-BSE-1 TO 0 STEP -1 DO TRI[I%]=TRI[I%]+MAX(TRI[I%+STP],TRI[I%+STP+1]) STEPC=STEPC+1 IF STEPC=STP THEN STP=STP-1 STEPC=0 END IF END FOR   PRINT(TRI[0]) END PROGRAM  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#PARI.2FGP
PARI/GP
#include <pari/pari.h> #include <openssl/md4.h>   #define HEX(x) (((x) < 10)? (x)+'0': (x)-10+'a')   /* * PARI/GP func: MD4 hash * * gp code: install("plug_md4", "s", "MD4", "<library path>"); */ GEN plug_md4(char *text) { char md[MD4_DIGEST_LENGTH]; char hash[sizeof(md) * 2 + 1]; int i;   MD4((unsigned char*)text, strlen(text), (unsigned char*)md);   for (i = 0; i < sizeof(md); i++) { hash[i+i] = HEX((md[i] >> 4) & 0x0f); hash[i+i+1] = HEX(md[i] & 0x0f); }   hash[sizeof(md) * 2] = 0;   return strtoGENstr(hash); }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#SQL
SQL
;WITH DATA AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum, NUMBER, LEN(CAST(ABS(NUMBER) AS NVARCHAR(MAX))) LcharNum FROM TABLE1) SELECT CASE WHEN ( LCHARNUM >= 3 AND LCHARNUM % 2 = 1 ) THEN SUBSTRING(CHARNUM, LCHARNUM / 2, 3) ELSE 'Error!' END Output, NUMBER INPUT FROM DATA
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.
#Common_Lisp
Common Lisp
(ql:quickload 'ironclad) (defun md5 (str) (ironclad:byte-array-to-hex-string (ironclad:digest-sequence :md5 (ironclad:ascii-string-to-byte-array str)))) (defvar *tests* '("" "a" "abc" "message digest" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" "12345678901234567890123456789012345678901234567890123456789012345678901234567890")) (dolist (msg *tests*) (format T "~s: ~a~%" msg (md5 msg)))  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Nim
Nim
const Limit = 100   var mcnuggets: array[0..Limit, bool]   for a in countup(0, Limit, 6): for b in countup(a, Limit, 9): for c in countup(b, Limit, 20): mcnuggets[c] = true   for n in countdown(Limit, 0): if not mcnuggets[n]: echo "The largest non-McNuggets number is: ", n break
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#jq
jq
def m: { ul: "╔", uc: "╦", ur: "╗", ll: "╚", lc: "╩", lr: "╝", hb: "═", vb: "║",   m0: " Θ ", m5: "────" };   def mayan: [ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙" ];   # decimal number to base-20 array, most significant digit first def dec2vig: [recurse(if . > 0 then ./20|floor else empty end) | . % 20] | if length > 1 then .[:-1] else . end | reverse;   def vig2quin: if . >= 20 then "Cannot convert a number >= 20." | error else . as $n | [mayan[0], mayan[0], mayan[0], mayan[0]] | if $n == 0 then .[3] = m.m0 else (($n/5)|floor) as $fives | ($n % 5) as $rem | .[3-$fives] = mayan[$rem] | reduce range(3; 3-$fives; -1) as $i (.; .[$i] = m.m5) end end;   def draw($mayans): ($mayans|length) as $lm | (reduce range(0; $lm) as $i (m.ul; . + m.hb * 4 + if $i < $lm - 1 then m.uc else m.ur + "\n" end ) ) + (reduce range(1; 5) as $i (""; . + m.vb + (reduce range(0; $lm) as $j (""; . + $mayans[$j][$i-1] + m.vb)) + "\n" ) ) + (reduce range(0; $lm) as $i (m.ll; . + (m.hb * 4) + if ($i < $lm - 1) then m.lc else m.lr + "\n" end ) );   def decimal2mayan: "Converting \(.) to Mayan:", draw(dec2vig | map( vig2quin ) ), "" ;   4005, 8017, 326205, 886205, 1081439556 | decimal2mayan
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#Julia
Julia
using Gumbo   mayan_glyphs(x, y) = (x == 0 && y == 0) ? "\n<td>Θ</td>\n" : "<td>\n" * "●" ^ x * "<br />\n───" ^ y * "</td>\n"   inttomayan(n) = (s = string(n, base=20); map(ch -> reverse(divrem(parse(Int, ch, base=20), 5)), split(s, "")))   function testmayan() startstring = """\n <style> table.roundedcorners { border: 1px solid DarkOrange; border-radius: 13px; border-spacing: 1; } table.roundedcorners td, table.roundedcorners th { border: 2px solid DarkOrange; border-radius: 13px; border-bottom: 3px solid DarkOrange; vertical-align: bottom; text-align: center; padding: 10px; } </style> \n"""   txt = startstring   for n in [4005, 8017, 326205, 886205, 70913241, 2147483647] txt *= "<h3>The Mayan representation for the integer $n is: </h3><table class=\"roundedcorners\"><tr>" * join(map(x -> mayan_glyphs(x[1], x[2]), inttomayan(n))) * "</tr></table>\n\n" end   println(parsehtml(txt)) end   testmayan()  
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.
#APL
APL
  This example shows how to use GNU APL scripting.   #!/usr/local/bin/apl --script -- ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝ ⍝ ⍝ ⍝ mazeGen.apl 2022-01-07 19:47:35 (GMT-8) ⍝ ⍝ ⍝ ⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝   ∇initPRNG ⍝⍝ Seed the internal PRNG used by APL ? operator ⎕RL ← +/ ⎕TS ⍝⍝ Not great... but good enough ∇   ∇offs ← cellTo dir ⍝⍝ Return the offset (row col) to cell which lies in compass (dir) offs ← ∊((¯1 0)(0 1)(1 0)(0 ¯1))[('nesw'⍳dir)] ∇   ∇doMaze rc ⍝⍝ Main function 0 0 mazeGen rc ⍝⍝ Do the maze gen m ⍝⍝ output result ∇   ∇b ← m isVisited coord;mr;mc →( ∨/ (coord[1] < 1) (coord[2] < 1) )/yes →( ∨/ (coord > ⌊(⍴m)÷2) )/yes b ← ' ' ∊ m[2×coord[1];2×coord[2]] →0 yes: b←1 ∇   ∇c mazeGen sz ;dirs;c;dir;cell;next →(c≠(0 0))/gen init: c ← ?sz[1],?sz[2] m ← mazeInit sz gen: cell ← c dirs ← 'nesw'[4?4] m[2×c[1];2×c[2]] ← ' ' ⍝ mark cell as visited dir1: dir ← dirs[1] next ← cell + cellTo dir →(m isVisited next)/dir2 m ← m openWall cell dir next mazeGen sz dir2: dir ← dirs[2] next ← cell + cellTo dir →(m isVisited next)/dir3 m ← m openWall cell dir next mazeGen sz dir3: dir ← dirs[3] next ← cell + cellTo dir →(m isVisited next)/dir4 m ← m openWall cell dir next mazeGen sz dir4: dir ← dirs[4] next ← cell + cellTo dir →(m isVisited next)/done m ← m openWall cell dir next mazeGen sz done: ∇   ∇m ← mazeInit sz;rows;cols;r ⍝⍝ Init an ASCII grid which ⍝⍝ has all closed and unvisited cells: ⍝⍝ ⍝⍝ +-+ ⍝⍝ |.| ⍝⍝ +-+ ⍝⍝ ⍝⍝ @param sz - tuple (rows cols) ⍝⍝ @return m - ASCII representation of (rows × cols) closed maze cells ⍝⍝⍝⍝   initPRNG (rows cols) ← sz r ← ∊ (cols ⍴ ⊂"+-" ),"+" r ← r,∊ (cols ⍴ ⊂"|." ),"|" r ← (rows,(⍴r))⍴r r ← ((2×rows),(1+2×cols))⍴r r ← r⍪ (∊ (cols ⍴ ⊂"+-" ),"+") m ← r ∇   ∇r ← m openWall cellAndDir ;ri;ci;rw;cw;row;col;dir (row col dir) ← ∊cellAndDir ri ← 2×row ci ← 2×col (rw cw) ← (ri ci) + cellTo dir m[rw;cw] ← ' ' ⍝ open wall in (dir) r ← m ∇   ⎕IO←1   doMaze 9 9 )OFF  
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.
#C.2B.2B
C++
#include <complex> #include <cmath> #include <iostream> using namespace std;   template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx;   private: Ax a; SqMx() { }   public: SqMx(const Ax &_a) { // constructor with pre-defined array for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; }   static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; }   friend ostream &operator<<(ostream& os, const Mx &p) { // ugly print for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; }   Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
http://rosettacode.org/wiki/Matrix_digital_rain
Matrix digital rain
Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia. Provided is a reference implementation in Common Lisp to be run in a terminal.
#Batch_File
Batch File
:: Matrix Digital Rain Task from RosettaCode :: Batch File Implementation   @echo off setlocal enabledelayedexpansion rem escape character (for Windows 10 VT100 escape sequences) rem info: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences for /f %%e in ('echo prompt $e^| cmd') do @set "esc=%%e" rem set window size set "col=120" %== please don't make this too large ==% set "row=30" %== please don't make this too large ==% mode con cols=%col% lines=%row% rem set up the variables for display set "rain_length=12" for /l %%y in (1,1,%col%) do set "disp_col[%%y]= " %== what to display ==% for /l %%y in (1,1,%col%) do set "ctr_col[%%y]=0" %== counter for rain length ==% rem hide the cursor, and clear the screen <nul set /p "=%esc%[?25l" cls   :matrix_loop for /l %%y in (1,1,%col%) do ( if !ctr_col[%%y]! equ 0 ( set "disp_col[%%y]= " ) else ( set /a "rnd_digit=!random! %% 10" if !ctr_col[%%y]! equ 1 ( set "disp_col[%%y]=%esc%[97m!rnd_digit!%esc%[32m" ) else if !ctr_col[%%y]! equ 2 ( set "disp_col[%%y]=%esc%[92m!rnd_digit!%esc%[32m" ) else ( set "disp_col[%%y]=!rnd_digit!" ) set /a "ctr_col[%%y]=(!ctr_col[%%y]! + 1) %% (%rain_length% + 1)" ) rem drop rain randomly set /a "rnd_drop=!random! %% 20" if !rnd_drop! equ 0 set "ctr_col[%%y]=1" ) set "disp_line=%esc%[32m" for /l %%y in (1,1,%col%) do set "disp_line=!disp_line!!disp_col[%%y]!" <nul set /p "=%esc%[1T%esc%[1;1H" %== scroll down and set cursor position to home ==% echo(%disp_line% goto matrix_loop