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/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
#Action.21
Action!
DEFINE MINCOLORS="2" DEFINE MAXCOLORS="20" DEFINE MINLENGTH="4" DEFINE MAXLENGTH="10" DEFINE MINGUESS="7" DEFINE MAXGUESS="20" TYPE Score=[BYTE spot,corr,err] TYPE Settings=[BYTE colors,length,guesses,repeat]   PROC GetSettings(Settings POINTER s) CHAR ARRAY tmp(10)   DO PrintF("Enter number of colors (%B-%B):",MINCOLORS,MAXCOLORS) s.colors=InputB() UNTIL s.colors>=MINCOLORS AND s.colors<=MAXCOLORS OD DO PrintF("Enter length of code (%B-%B):",MINLENGTH,MAXLENGTH) s.length=InputB() UNTIL s.length>=MINLENGTH AND s.length<=MAXLENGTH OD DO PrintF("Enter max number of guesses (%B-%B):",MINGUESS,MAXGUESS) s.guesses=InputB() UNTIL s.guesses>=MINGUESS AND s.guesses<=MAXGUESS OD IF s.colors<s.length THEN s.repeat=1 ELSE DO Print("Allow repeated colors (Y/N):") InputS(tmp) IF tmp(0)=1 THEN IF tmp(1)='y OR tmp(1)='Y THEN s.repeat=1 EXIT ELSEIF tmp(1)='n OR tmp(1)='N THEN s.repeat=0 EXIT FI FI OD FI RETURN   PROC Generate(CHAR ARRAY code Settings POINTER s) CHAR ARRAY col(MAXCOLORS) BYTE i,j,d,tmp,count   FOR i=0 TO MAXCOLORS-1 DO col(i)=i+'A OD code(0)=s.length count=s.colors FOR i=1 TO s.length DO d=Rand(count) code(i)=col(d) IF s.repeat=0 THEN count==-1 col(d)=col(count) FI OD RETURN   BYTE FUNC GetCount(CHAR ARRAY s CHAR c) BYTE i,count   count=0 FOR i=1 TO s(0) DO IF s(i)=c THEN count==+1 FI OD RETURN (count)   PROC CheckScore(CHAR ARRAY code,guess Settings POINTER s Score POINTER res) BYTE i,j,codeCount,guessCount   res.spot=0 res.corr=0 IF guess(0)#s.length THEN res.err=1 RETURN FI res.err=0   FOR i=0 TO s.colors-1 DO codeCount=GetCount(code,i+'A) guessCount=GetCount(guess,i+'A) IF codeCount<guessCount THEN res.corr==+codeCount ELSE res.corr==+guessCount FI OD FOR i=1 TO s.length DO IF guess(i)=code(i) THEN res.spot==+1 res.corr==-1 FI OD RETURN   PROC ToUpper(CHAR ARRAY s) BYTE i,c   IF s(0)=0 THEN RETURN FI FOR i=1 TO s(0) DO c=s(i) IF c>='a AND c<='z THEN s(i)=c-'a+'A FI OD RETURN   PROC PrintScore(Score POINTER res Settings POINTER s) INT i   FOR i=1 TO res.spot DO Put('X) OD FOR i=1 TO res.corr DO Put('O) OD FOR i=1 TO s.length-res.spot-res.corr DO Put('-) OD RETURN   PROC Main() CHAR ARRAY code(MAXLENGTH+1),guess(255) Score res Settings s BYTE tries   PrintE("Mastermind") PutE() GetSettings(s) PutE() Generate(code,s) tries=s.guesses PrintF("Enter your guess (%B tries):%E",tries) DO InputS(guess) ToUpper(guess) CheckScore(code,guess,s,res) Put(28) ;cursor up PrintF("%S -> ",guess) IF res.err THEN Print("Wrong input") ELSE PrintScore(res,s) IF res.spot=s.length THEN PutE() PutE() PrintE("You won!") EXIT FI tries==-1 IF tries=0 THEN PutE() PutE() PrintE("You lost!") EXIT FI FI PrintF(", try again (%B tries):%E",tries) OD RETURN
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.
#Fortran
Fortran
module optim_mod implicit none contains subroutine optim(a) implicit none integer :: a(:), n, i, j, k integer, allocatable :: u(:, :) integer(8) :: c integer(8), allocatable :: v(:, :)   n = ubound(a, 1) - 1 allocate (u(n, n), v(n, n)) v = huge(v) u(:, 1) = -1 v(:, 1) = 0 do j = 2, n do i = 1, n - j + 1 do k = 1, j - 1 c = v(i, k) + v(i + k, j - k) + int(a(i), 8) * int(a(i + k), 8) * int(a(i + j), 8) if (c < v(i, j)) then u(i, j) = k v(i, j) = c end if end do end do end do write (*, "(I0,' ')", advance="no") v(1, n) call aux(1, n) print * deallocate (u, v) contains recursive subroutine aux(i, j) integer :: i, j, k   k = u(i, j) if (k < 0) then write (*, "(I0)", advance="no") i else write (*, "('(')", advance="no") call aux(i, k) write (*, "('*')", advance="no") call aux(i + k, j - k) write (*, "(')')", advance="no") end if end subroutine end subroutine end module   program matmulchain use optim_mod implicit none   call optim([5, 6, 3, 1]) call optim([1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]) call optim([1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]) end program
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.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) /mh := \A[1] | 12 /mw := \A[2] | 16 mz := DisplayMaze(GenerateMaze(mh,mw)) WriteImage(mz.filename) # save file WAttrib(mz.window,"canvas=normal") # show it until Event() == &lpress # wait for left mouse press Solver(mz.maze) DisplayMazeSolution(mz) WriteImage(mz.filename ?:= (="maze-", "maze-solved-" || tab(0))) until Event() == &lpress # wait close(mz.window) 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.
#Factor
Factor
USING: grouping.extras io.encodings.utf8 io.files kernel math.order math.parser math.vectors prettyprint sequences splitting ; IN: rosetta-code.maximum-triangle-path-sum   : parse-triangle ( path -- seq ) utf8 file-lines [ " " split harvest ] map [ [ string>number ] map ] map ;   : max-triangle-path-sum ( seq -- n ) <reversed> unclip-slice [ swap [ max ] 2clump-map v+ ] reduce first ;   "triangle.txt" parse-triangle max-triangle-path-sum .
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.
#Perl
Perl
sub md4(@) { my @input = grep { defined && length > 0 } split /(.{64})/s, join '', @_; push @input, '' if !@input || length($input[$#input]) >= 56;   my @A = (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476); # initial regs my @T = (0, 0x5A827999, 0x6ED9EBA1); my @L = qw(3 7 11 19 3 5 9 13 3 9 11 15); # left rotate counts my @O = (1, 4, 4, # x stride for input index 4, 1, 1, # y stride for input index 0, 0, 1); # bitwise reverse both indexes my @I = map { my $z = int $_/16; my $x = $_%4; my $y = int $_%16/4; ($x,$y) = (R($x),R($y)) if $O[6+$z]; $O[$z] * $x + $O[3+$z] * $y } 0..47;   my ($a,$b,$c,$d); my($l,$p) = (0,0); foreach (@input) { my $r = length($_); $l += $r; $r++, $_.="\x80" if $r<64 && !$p++; my @W = unpack 'V16', $_ . "\0"x7; push @W, (0)x16 if @W < 16; $W[14] = $l*8 if $r < 57; # add bit-length in low 32-bits ($a,$b,$c,$d) = @A; for (0..47) { my $z = int $_/16; $a = L($L[4*($_>>4) + $_%4], M(&{(sub{$b&$c|~$b&$d}, # F sub{$b&$c|$b&$d|$c&$d}, # G sub{$b^$c^$d} # H )[$z]} + $a + $W[$I[$_]] + $T[$z])); ($a,$b,$c,$d) = ($d,$a,$b,$c); } my @v = ($a, $b, $c, $d); $A[$_] = M($A[$_] + $v[$_]) for 0..3; } pack 'V4', @A; }   sub L { # left-rotate my ($n, $x) = @_; $x<<$n | 2**$n - 1 & $x>>(32-$n); }   sub M { # mod 2**32 no integer; my ($x) = @_; my $m = 1+0xffffffff; $x - $m * int $x/$m; }   sub R { # reverse two bit number my $n = pop; ($n&1)*2 + ($n&2)/2; }   sub md4_hex(@) { # convert to hexadecimal unpack 'H*', &md4; }   print "Rosetta Code => " . md4_hex( "Rosetta Code" ) . "\n";
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.
#Swift
Swift
var num:Int = \\enter your number here if num<0{num = -num} var numArray:[Int]=[] while num>0{ var temp:Int=num%10 numArray.append(temp) num=num/10 } var i:Int=numArray.count if i<3||i%2==0{ print("Invalid Input") } else{ i=i/2 print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])") }
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Crystal
Crystal
require "digest/md5"   puts Digest::MD5.hexdigest("The quick brown fox jumped over the lazy dog's back")
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).
#Perl
Perl
use ntheory qw/forperm gcd vecmin/;   sub Mcnugget_number { my $counts = shift;   return 'No maximum' if 1 < gcd @$counts;   my $min = vecmin @$counts; my @meals; my @min;   my $a = -1; while (1) { $a++; for my $b (0..$a) { for my $c (0..$b) { my @s = ($a, $b, $c); forperm { $meals[ $s[$_[0]] * $counts->[0] + $s[$_[1]] * $counts->[1] + $s[$_[2]] * $counts->[2] ] = 1; } @s; } } for my $i (0..$#meals) { next unless $meals[$i]; if ($min[-1] and $i == ($min[-1] + 1)) { push @min, $i; last if $min == @min } else { @min = $i; } } last if $min == @min } $min[0] ? $min[0] - 1 : 0 }   for my $counts ([6,9,20], [6,7,20], [1,3,20], [10,5,18], [5,17,44], [2,4,6], [3,6,15]) { print 'Maximum non-Mcnugget number using ' . join(', ', @$counts) . ' is: ' . Mcnugget_number($counts) . "\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]
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[MakeLengthFive, MayanNumeral] MakeLengthFive[ci_String] := Module[{c}, c = If[EvenQ[StringLength[ci]], ci <> " ", ci]; While[StringLength[c] < 5, c = " " <> c <> " "]; c ] MayanNumeral[n_Integer?Positive] := Module[{nums, q, r, c}, nums = IntegerDigits[n, 20]; Row[Table[ {q, r} = QuotientRemainder[m, 5]; If[{q, r} =!= {0, 0}, c = Prepend[ConstantArray["-----", q], StringJoin[ConstantArray[".", r]]]; c = Join[ConstantArray["", 4 - Length[c]], c]; c , c = {"", "", "", "\[Theta]"} ]; Column[MakeLengthFive /@ c, Frame -> True] , {m, nums} ], Spacer[1]] ] MayanNumeral[4005] MayanNumeral[8017] MayanNumeral[326205] MayanNumeral[886205] MayanNumeral[1337]
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]
#Nim
Nim
  import algorithm   type Border = enum UL = "╔", UC = "╦", UR = "╗", LL = "╚", LC = "╩", LR = "╝", HB = "═", VB = "║"   const   Mayan = [" ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙"]   M0 = " Θ " M5 = "────"   type Digit = range[0..19] Numeral = array[4, string] MayanNumber = seq[Numeral]     func toBase20(n: Natural): seq[Digit] = ## Return "n" expressed as a sequence of base 20 digits. result.add(n mod 20) var n = n div 20 while n != 0: result.add n mod 20 n = n div 20 result.reverse()     func toMayanNumeral(d: Digit): Numeral = ## Return the Numeral representing a base 20 digits.   result = [Mayan[0], Mayan[0], Mayan[0], Mayan[0]] if d == 0: result[3] = M0 return   var d = d for i in countdown(3, 0): if d >= 5: result[i] = M5 dec d, 5 else: result[i] = Mayan[d] break     proc draw(mayans: MayanNumber) = ## Draw the representation fo a mayan number.   let idx = mayans.high   stdout.write UL for i in 0..idx: for j in 0..3: stdout.write HB if i < idx: stdout.write UC else: echo UR   for i in 1..4: stdout.write VB for j in 0..idx: stdout.write mayans[j][i-1], VB stdout.write '\n'   stdout.write LL for i in 0..idx: for j in 0..3: stdout.write HB if i < idx: stdout.write LC else: echo LR     when isMainModule:   import sequtils, strutils   for n in [4005, 8017, 326205, 886205, 1081439556]: echo "Converting $1 to Mayan:".format(n) let digits = n.toBase20() let mayans = digits.mapIt(it.toMayanNumeral) mayans.draw() echo ""
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#11l
11l
F transpose(&matrix) V toRet = [[0] * matrix.len] * matrix[0].len L(row) (0 .< matrix.len) L(col) (0 .< matrix[row].len) toRet[col][row] = matrix[row][col] R toRet   V m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print("Original") print(m) print("After Transposition") print(transpose(&m))
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#AutoHotkey
AutoHotkey
; Initially build the board Width := 11 Height := 8 Loop % height*2+1 { Outer := A_Index Loop % Width maze .= Outer & 1 ? "+-" : "|0" maze .= (Outer & 1 ? "+" : "|") "`n" } StringTrimRight, maze, maze, 1 ; removes trailing newline Clipboard := Walk(maze)   Walk(S, x=0, y=0){ If !x{ ; --Start at a random cell... StringReplace, junk, S, `n,,UseErrorLevel ; Calculate rows Random, y, 1, ErrorLevel//2 Random, x, 1, InStr(S, "`n")//2-1 ; Calculate height }   ; --Obtain a list of its neighbors... neighbors := x "," y+1 "`n" x "," y-1 "`n" x+1 "," y "`n" x-1 "," y ; --Randomize the list... Sort neighbors, random   ; --Then for each neighbor... Loop Parse, neighbors, `n { pC := InStr(A_LoopField, ","), x2 := SubStr(A_LoopField, 1, pC-1), y2 := SubStr(A_LoopField, pC+1) ; If it has not been visited... If GetChar(S, 2*x2, 2*y2) = "0"{ ; Mark it as visited... S := ChangeChar(s, 2*x2, 2*y2, " ") ; Remove the wall between this cell and the neighbor... S := ChangeChar(S, x+x2, y+y2, " ") ; Then recurse with the neighbor as the current cell S := Walk(S, x2, y2) } } return S }   ; Change a character in a string using x and y coordinates ChangeChar(s, x, y, c){ Loop Parse, s, `n { If (A_Index = Y) Loop Parse, A_LoopField If (A_Index = x) out .= c Else out .= A_LoopField Else out .= A_LoopField out .= "`n" } StringTrimRight, out, out, 1 return out }   ; retrieve a character in a string using x and y coordinates GetChar(s, x, y, n=1){ x*=n, y*=n Loop Parse, s, `n If (A_Index = Y) return SubStr(A_LoopField, x, 1) }
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.
#Chapel
Chapel
proc **(a, e) { // create result matrix of same dimensions var r:[a.domain] a.eltType; // and initialize to identity matrix forall ij in r.domain do r(ij) = if ij(1) == ij(2) then 1 else 0;   for 1..e do r *= a;   return r; }
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.
#Common_Lisp
Common Lisp
(defun multiply-matrices (matrix-0 matrix-1) "Takes two 2D arrays and returns their product, or an error if they cannot be multiplied" (let* ((m0-dims (array-dimensions matrix-0)) (m1-dims (array-dimensions matrix-1)) (m0-dim (length m0-dims)) (m1-dim (length m1-dims))) (if (or (/= 2 m0-dim) (/= 2 m1-dim)) (error "Array given not a matrix") (let ((m0-rows (car m0-dims)) (m0-cols (cadr m0-dims)) (m1-rows (car m1-dims)) (m1-cols (cadr m1-dims))) (if (/= m0-cols m1-rows) (error "Incompatible dimensions") (do ((rarr (make-array (list m0-rows m1-cols) :initial-element 0) rarr) (n 0 (if (= n (1- m0-cols)) 0 (1+ n))) (cc 0 (if (= n (1- m0-cols)) (if (/= cc (1- m1-cols)) (1+ cc) 0) cc)) (cr 0 (if (and (= (1- m0-cols) n) (= (1- m1-cols) cc)) (1+ cr) cr))) ((= cr m0-rows) rarr) (setf (aref rarr cr cc) (+ (aref rarr cr cc) (* (aref matrix-0 cr n) (aref matrix-1 n cc))))))))))   (defun matrix-identity (dim) "Creates a new identity matrix of size dim*dim" (do ((rarr (make-array (list dim dim) :initial-element 0) rarr) (n 0 (1+ n))) ((= n dim) rarr) (setf (aref rarr n n) 1)))   (defun matrix-expt (matrix exp) "Takes the first argument (a matrix) and multiplies it by itself exp times" (let* ((m-dims (array-dimensions matrix)) (m-rows (car m-dims)) (m-cols (cadr m-dims))) (cond ((/= m-rows m-cols) (error "Non-square matrix")) ((zerop exp) (matrix-identity m-rows)) ((= 1 exp) (do ((rarr (make-array (list m-rows m-cols)) rarr) (cc 0 (if (= cc (1- m-cols)) 0 (1+ cc))) (cr 0 (if (= cc (1- m-cols)) (1+ cr) cr))) ((= cr m-rows) rarr) (setf (aref rarr cr cc) (aref matrix cr cc)))) ((zerop (mod exp 2)) (let ((me2 (matrix-expt matrix (/ exp 2)))) (multiply-matrices me2 me2))) (t (let ((me2 (matrix-expt matrix (/ (1- exp) 2)))) (multiply-matrices matrix (multiply-matrices me2 me2)))))))
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.
#C
C
$ sudo apt install libncurses5-dev
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
#Ada
Ada
with Ada.Text_IO; with Ada.Numerics.Discrete_Random; with Ada.Strings.Fixed; with Ada.Containers.Ordered_Sets;   use Ada.Strings.Fixed;   procedure MasterMind is subtype Color_Number is Positive range 2 .. 20; subtype Code_Size is Positive range 4 .. 10; subtype Guesses_Number is Positive range 7 .. 20; subtype Color is Character range 'A' .. 'T';   function Hint(correct, guess : in String) return String is Xs : Natural := 0; Os : Natural := 0; to_display : String(1 .. correct'Length) := (others => '-'); begin for I in guess'Range loop if guess(I) = correct(I) then Xs := Xs + 1; to_display(I) := 'X'; end if; end loop; for I in guess'Range loop if to_display(I) = '-' then for J in correct'Range loop if J /= I and to_display(J) /= 'X' and correct(J) = guess(I) then Os := Os + 1; exit; end if; end loop; end if; end loop; return Xs * 'X' & Os * 'O' & (guess'Length - Xs - Os) * '-'; end Hint;   generic type Data is (<>); function Input(message : in String) return Data; -- Input will loop until a correct value is given by the user. -- For each wrong input, the program will prompt the range of expected values.   function Input(message : in String) return Data is begin loop Ada.Text_IO.Put(message); declare S : constant String := Ada.Text_IO.Get_Line; begin return Data'Value(S); exception when Constraint_Error => Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Invalid input!"); Ada.Text_IO.Put_Line ("Expected values in range:" & Data'First'Img & " .." & Data'Last'Img); Ada.Text_IO.New_Line; end; end loop; end;   function Input_Color_Number is new Input(Color_Number); function Input_Code_Size is new Input(Code_Size); function Input_Guesses_Number is new Input(Guesses_Number); function Input_Boolean is new Input(Boolean);   CN : constant Color_Number := Input_Color_Number("How many colors? "); GN : constant Guesses_Number := Input_Guesses_Number("How many guesses? "); CS : constant Code_Size := Input_Code_Size("Size of the code? "); repeats : Boolean := Input_Boolean("With repeats? "); -- Not constant: if Color < Code_Size, we will have repetitions anyway.   subtype Actual_Colors is Color range Color'First .. Color'Val(Color'Pos(Color'First) + CN - 1); package Actual_Colors_Sets is new Ada.Containers.Ordered_Sets(Element_Type => Actual_Colors);   package Color_Random is new Ada.Numerics.Discrete_Random(Result_Subtype => Actual_Colors); generator : Color_Random.Generator;   function Random return String is C : String(1 .. CS); seen : Actual_Colors_Sets.Set; begin for I in C'Range loop C(I) := Color_Random.Random(generator); while (not repeats) and seen.Contains(C(I)) loop C(I) := Color_Random.Random(generator); end loop; seen.Include(C(I)); end loop; return C; end Random;   function Get_Code return String is begin loop Ada.Text_IO.Put("> "); declare input : constant String := Ada.Text_IO.Get_Line; begin if input'Length /= CS then raise Constraint_Error; end if; for C of input loop if C not in Actual_Colors then raise Constraint_Error; end if; end loop; return input; exception when Constraint_Error => Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("Invalid input!"); Ada.Text_IO.New_Line; end; end loop; end Get_Code;   found : Boolean := False; begin if (not repeats) and (CN < CS) then Ada.Text_IO.Put_Line("Not enough colors! Using repeats anyway."); repeats := True; end if;   Color_Random.Reset(generator);   declare answer : constant String := Random; previous : array(1 .. GN) of String(1 .. CS*2); begin for I in 1 .. GN loop declare guess : constant String := Get_Code; begin if guess = answer then Ada.Text_IO.Put_Line("You won, congratulations!"); found := True; else previous(I) := guess & Hint(answer, guess); Ada.Text_IO.Put_Line(44 * '-'); for J in 1 .. I loop Ada.Text_IO.Put_Line (previous(J)(1 .. CS) & " => " & previous(J)(CS+1 .. previous(J)'Last)); end loop; Ada.Text_IO.Put_Line(44 * '-'); Ada.Text_IO.New_Line; end if; end; exit when found; end loop; if not found then Ada.Text_IO.Put_Line("You lost, sorry! The answer was: " & answer); end if; end; end MasterMind;  
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.
#Go
Go
package main   import "fmt"   // PrintMatrixChainOrder prints the optimal order for chain // multiplying matrices. // Matrix A[i] has dimensions dims[i-1]×dims[i]. func PrintMatrixChainOrder(dims []int) { n := len(dims) - 1 m, s := newSquareMatrices(n)   // m[i,j] will be minimum number of scalar multiplactions // needed to compute the matrix A[i]A[i+1]…A[j] = A[i…j]. // Note, m[i,i] = zero (no cost). // s[i,j] will be the index of the subsequence split that // achieved minimal cost. for lenMinusOne := 1; lenMinusOne < n; lenMinusOne++ { for i := 0; i < n-lenMinusOne; i++ { j := i + lenMinusOne m[i][j] = -1 for k := i; k < j; k++ { cost := m[i][k] + m[k+1][j] + dims[i]*dims[k+1]*dims[j+1] if m[i][j] < 0 || cost < m[i][j] { m[i][j] = cost s[i][j] = k } } } }   // Format and print result. const MatrixNames = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" var subprint func(int, int) subprint = func(i, j int) { if i == j { return } k := s[i][j] subprint(i, k) subprint(k+1, j) fmt.Printf("%*s -> %s × %s%*scost=%d\n", n, MatrixNames[i:j+1], MatrixNames[i:k+1], MatrixNames[k+1:j+1], n+i-j, "", m[i][j], ) } subprint(0, n-1) }   func newSquareMatrices(n int) (m, s [][]int) { // Allocates two n×n matrices as slices of slices but // using only one [2n][]int and one [2n²]int backing array. m = make([][]int, 2*n) m, s = m[:n:n], m[n:] tmp := make([]int, 2*n*n) for i := range m { m[i], tmp = tmp[:n:n], tmp[n:] } for i := range s { s[i], tmp = tmp[:n:n], tmp[n:] } return m, s }   func main() { cases := [...][]int{ {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}, } for _, tc := range cases { fmt.Println("Dimensions:", tc) PrintMatrixChainOrder(tc) fmt.Println() } }
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.
#J
J
  maze=:4 :0 assert.0<:n=.<:x*y horiz=. 0$~x,y-1 verti=. 0$~(x-1),y path=.,:here=. ?x,y unvisited=.0 (<here+1)} 0,0,~|:0,0,~1$~y,x while.n do. neighbors=. here+"1 (,-)=0 1 neighbors=. neighbors #~ (<"1 neighbors+1) {unvisited if.#neighbors do. n=.n-1 next=. ({~ ?@#) neighbors unvisited=.0 (<next+1)} unvisited if.{.next=here do. horiz=.1 (<-:here+next-0 1)} horiz else. verti=. 1 (<-:here+next-1 0)} verti end. path=.path,here=.next else. here=.{:path path=.}:path end. end. horiz;verti )   NB. source Dijkstra_equal_weights graph NB. NB. + +---+---+ NB. | 0 1 2 | (sample cell numbers) NB. +---+ + + NB. | 3 4 | 5 NB. +---+---+---+ NB. NB. graph =: 1;0 2 4;1 5;4;1 3;2 NB. The graph is a vector of boxed vectors of neighbors.   Dijkstra_equal_weights =: 4 : 0 dist =. previous =. #&_ n =. # graph =. y [ source =. x dist =. 0 source } dist Q =. 0 while. #Q do. u =. {.Q Q =. }.Q if. _ = u{dist do. break. end. for_v. >u{graph do. if. -. v e. previous do. alt =. >: u { dist if. alt < v { dist do. dist =. alt v } dist previous =. u v } previous if. v e. Q do. echo 'belch' else. Q =. Q,v end. end. end. end. end. dist;previous )   path =: 3 : 0 p =. <:#y while. _ > {:p do. p =. p,y{~{:p end. |.}:p )   solve=:3 :0 NB. convert walls to graph shape =. }.@$@:> ew =. (,.&0 ,: 0&,.)@>@{. NB. east west doors ns =. (, &0 ,: 0&, )@>@{: cell_offsets =. 1 _1 1 _1 * 2 # 1 , {:@shape cell_numbers =. i.@shape neighbors =. (cell_numbers +"_ _1 cell_offsets *"_1 (ew , ns))y graph =. (|:@(,/"_1) <@-."1 0 ,@i.@shape)neighbors NB. list of boxed neighbors NB. solve it path , > {: 0 Dijkstra_equal_weights graph )   display=:3 :0 size=. >.&$&>/y text=. (}:1 3$~2*1+{:size)#"1":size$<' ' 'hdoor vdoor'=. 2 4&*&.>&.> (#&,{@;&i./@$)&.> y ' ' (a:-.~0 1;0 2; 0 3;(2 1-~$text);(1 4&+&.> hdoor),,vdoor+&.>"0/2 1;2 2;2 3)} text : a=. display y size=. >.&$&>/y columns=. {: size cells =. <"1(1 2&p.@<.@(%&columns) ,. 2 4&p.@(columns&|))x 'o' cells } a NB. exercise, replace cells with a gerund to draw arrows on the path. )  
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.
#Forth
Forth
  \ Triangle representation; words created by this defining word return the address of element \ specified by its row number and position within that row, both indexed from 0. : TRIANGLE ( "name" -- |DOES: row pos -- addr ) CREATE DOES> ROT DUP 1+ * 2/ CELLS + SWAP CELLS + ;   18 CONSTANT #ROWS \ total number of rows in triangle TRIANGLE triang 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 ,   \ Starting from the row above the bottom row and ending on the top, for every item in row \ find the bigger number from the two neighbours underneath and add it to this item. At \ the end, the result will be returned from the top element of the triangle. : MAX-SUM ( -- n ) 0 #ROWS 2 - DO I 1+ 0 DO J 1+ I triang @ J 1+ I 1+ triang @ MAX J I triang +! LOOP -1 +LOOP 0 0 triang @ ;   MAX-SUM .
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.
#Phix
Phix
-- -- demo\rosetta\md4.exw -- ==================== -- -- Non-optimised. If there is a genuine need for something faster, I can give #ilASM a bash. -- MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. -- Even the replacement, MD5 is now considered severly comprimised. -- without js -- (allocate/poke/peek) function r32(atom a) if a<0 then a+=#100000000 end if return remainder(a,#100000000) end function function rol(atom word, integer bits) -- left rotate the bits of a 32-bit number by the specified number of bits word = r32(word) -- trim to a 32-bit uint again return r32(word*power(2,bits))+floor(word/power(2,32-bits)) end function function f(atom x,y,z) return or_bits(and_bits(x,y),and_bits(not_bits(x),z)) end function function g(atom x,y,z) return or_all({r32(and_bits(x,y)),and_bits(x,z),and_bits(y,z)}) end function function h(atom x,y,z) return xor_bits(r32(xor_bits(x,y)),z) end function function md4(sequence data) integer bytes_to_add = 64-remainder(length(data)+9,64) if bytes_to_add=64 then bytes_to_add = 0 end if data = data&#80&repeat(0,bytes_to_add)& int_to_bytes(length(data)*8,8) atom a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476 atom m64 = allocate(64,true) integer i for x=1 to length(data)-1 by 64 do poke(m64,data[x..x+63]) sequence z = peek4u({m64,16}) atom a2 = a, b2 = b, c2 = c, d2 = d for i=0 to 12 by 4 do a = rol(a + f(b, c, d) + z[i+1], 3) d = rol(d + f(a, b, c) + z[i+2], 7) c = rol(c + f(d, a, b) + z[i+3], 11) b = rol(b + f(c, d, a) + z[i+4], 19) end for for i=1 to 4 do a = rol(a + g(b, c, d) + z[i+0] + 0x5a827999, 3) d = rol(d + g(a, b, c) + z[i+4] + 0x5a827999, 5) c = rol(c + g(d, a, b) + z[i+8] + 0x5a827999, 9) b = rol(b + g(c, d, a) + z[i+12] + 0x5a827999, 13) end for for j=1 to 4 do i = {1, 3, 2, 4}[j] a = rol(a + h(b, c, d) + z[i+0] + 0x6ed9eba1, 3) d = rol(d + h(a, b, c) + z[i+8] + 0x6ed9eba1, 9) c = rol(c + h(d, a, b) + z[i+4] + 0x6ed9eba1, 11) b = rol(b + h(c, d, a) + z[i+12] + 0x6ed9eba1, 15) end for a = r32(a+a2) b = r32(b+b2) c = r32(c+c2) d = r32(d+d2) end for poke4(m64,{a,b,c,d}) return peek({m64,16}) end function function hexify(sequence s) for i=1 to length(s) do s[i] = sprintf("%02X",s[i]) end for return join(s,"") end function ?hexify(md4("Rosetta Code")) {} = wait_key()
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.
#Tcl
Tcl
proc middleThree n { if {$n < 0} { set n [expr {-$n}] } set idx [expr {[string length $n] - 2}] if {$idx % 2 == 0} { error "no middle three digits: input is of even length" } if {$idx < 1} { error "no middle three digits: insufficient digits" } set idx [expr {$idx / 2}] string range $n $idx [expr {$idx+2}] }
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.
#D
D
void main() { import std.stdio, std.digest.md;   auto txt = "The quick brown fox jumped over the lazy dog's back"; writefln("%-(%02x%)", txt.md5Of); }
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).
#Phix
Phix
with javascript_semantics constant limit=100 sequence nuggets = repeat(false,limit+1) for sixes=0 to limit by 6 do for nines=sixes to limit by 9 do for twenties=nines to limit by 20 do nuggets[twenties+1] = true end for end for end for printf(1,"Maximum non-McNuggets number is %d\n", rfind(false,nuggets)-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]
#Perl
Perl
use ntheory qw/fromdigits todigitstring/;   my $t_style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"'; my $c_style = '"border: solid black 2px;background-color: #fffff0;border-bottom: double 6px;'. 'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'. 'vertical-align: bottom;width: 3.25em;"';   sub cartouches { my($num, @digits) = @_; my $render; for my $d (@digits) { $render .= "| style=$c_style | $_\n" for glyphs(@$d); } chomp $render; join "\n", "\{| style=$t_style", "|+ $num", '|-', $render, '|}' }   sub glyphs { return 'Θ' unless $_[0] || $_[1]; join '<br>', '●' x $_[0], ('───') x $_[1]; }   sub mmod { my($n,$b) = @_; my @nb; return 0 unless $n; push @nb, fromdigits($_, $b) for split '', todigitstring($n, $b); return @nb; }   for $n (qw<4005 8017 326205 886205 26960840421>) { push @output, cartouches($n, map { [reverse mmod($_,5)] } mmod($n,20) ); }   print join "\n<br>\n", @output;
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#360_Assembly
360 Assembly
... KN EQU 3 KM EQU 5 N DC AL2(KN) M DC AL2(KM) A DS (KN*KM)F matrix a(n,m) B DS (KM*KN)F matrix b(m,n) ... * b(j,i)=a(i,j) * transposition using Horner's formula LA R4,0 i,from 1 LA R7,KN to n LA R6,1 step 1 LOOPI BXH R4,R6,ELOOPI do i=1 to n LA R5,0 j,from 1 LA R9,KM to m LA R8,1 step 1 LOOPJ BXH R5,R8,ELOOPJ do j=1 to m LR R1,R4 i BCTR R1,0 i-1 MH R1,M (i-1)*m LR R2,R5 j BCTR R2,0 j-1 AR R1,R2 r1=(i-1)*m+(j-1) SLA R1,2 r1=((i-1)*m+(j-1))*itemlen L R0,A(R1) r0=a(i,j) LR R1,R5 j BCTR R1,0 j-1 MH R1,N (j-1)*n LR R2,R4 i BCTR R2,0 i-1 AR R1,R2 r1=(j-1)*n+(i-1) SLA R1,2 r1=((j-1)*n+(i-1))*itemlen ST R0,B(R1) b(j,i)=r0 B LOOPJ next j ELOOPJ EQU * out of loop j B LOOPI next i ELOOPI EQU * out of loop i ...
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth-first search algorithm. Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell. Related tasks Maze solving.
#AWK
AWK
#!/usr/bin/awk -f   # Remember: AWK is 1-based, for better or worse.   BEGIN { # The maze dimensions. width = 20; # Global height = 20; # Global resetMaze();   # Some constants. top = 1; bottom = 2; left = 3; right = 4;   # Randomize the PRNG. randomize();   # Visit all the cells starting at a random point. visitCell(getRandX(), getRandY());   # Show the result. printMaze(); }   # Wander through the maze removing walls as we go. function visitCell(x, y, dirList, dir, nx, ny, ndir, pi) { setVisited(x, y); # This cell has been visited.   # Visit neighbors in a random order. dirList = getRandDirList(); for (dir = 1; dir <= 4; dir++) { # Get coordinates of a random neighbor (next in random direction list). ndir = substr(dirList, dir, 1); nx = getNextX(x, ndir); ny = getNextY(y, ndir);   # Visit an unvisited neighbor, removing the separating walls. if (wasVisited(nx, ny) == 0) { rmWall(x, y, ndir); rmWall(nx, ny, getOppositeDir(ndir)); visitCell(nx, ny) } } }   # Display the text-mode maze. function printMaze( x, y, r, w) { for (y = 1; y <= height; y++) { for (pass = 1; pass <= 2; pass++) { # Go over each row twice: top, middle for (x = 1; x <= width; x++) { if (pass == 1) { # top printf("+"); printf(hasWall(x, y, top) == 1 ? "---" : " "); if (x == width) printf("+"); } else if (pass == 2) { # left, right printf(hasWall(x, y, left) == 1 ? "|" : " "); printf(" "); if (x == width) printf(hasWall(x, y, right) == 1 ? "|" : " "); } } print; } } for (x = 1; x <= width; x++) printf("+---"); # bottom row print("+"); # bottom right corner }   # Given a direction, get its opposite. function getOppositeDir(d) { if (d == top) return bottom; if (d == bottom) return top; if (d == left) return right; if (d == right) return left; }   # Build a list (string) of the four directions in random order. function getRandDirList( dirList, randDir, nx, ny, idx) { dirList = ""; while (length(dirList) < 4) { randDir = getRandDir(); if (!index(dirList, randDir)) { dirList = dirList randDir; } } return dirList; }   # Get x coordinate of the neighbor in a given a direction. function getNextX(x, dir) { if (dir == left) x = x - 1; if (dir == right) x = x + 1; if (!isGoodXY(x, 1)) return -1; # Off the edge. return x; }   # Get y coordinate of the neighbor in a given a direction. function getNextY(y, dir) { if (dir == top) y = y - 1; if (dir == bottom) y = y + 1; if (!isGoodXY(1, y)) return -1; # Off the edge. return y; }   # Mark a cell as visited. function setVisited(x, y, cell) { cell = getCell(x, y); if (cell == -1) return; cell = substr(cell, 1, 4) "1"; # walls plus visited setCell(x, y, cell); }   # Get the visited state of a cell. function wasVisited(x, y, cell) { cell = getCell(x, y); if (cell == -1) return 1; # Off edges already visited. return substr(getCell(x,y), 5, 1); }   # Remove a cell's wall in a given direction. function rmWall(x, y, d, i, oldCell, newCell) { oldCell = getCell(x, y); if (oldCell == -1) return; newCell = ""; for (i = 1; i <= 4; i++) { # Ugly as concat of two substrings and a constant?. newCell = newCell (i == d ? "0" : substr(oldCell, i, 1)); } newCell = newCell wasVisited(x, y); setCell(x, y, newCell); }   # Determine if a cell has a wall in a given direction. function hasWall(x, y, d, cell) { cell = getCell(x, y); if (cell == -1) return 1; # Cells off edge always have all walls. return substr(getCell(x, y), d, 1); }   # Plunk a cell into the maze. function setCell(x, y, cell, idx) { if (!isGoodXY(x, y)) return; maze[x, y] = cell }   # Get a cell from the maze. function getCell(x, y, idx) { if (!isGoodXY(x, y)) return -1; # Bad cell marker. return maze[x, y]; }   # Are the given coordinates in the maze? function isGoodXY(x, y) { if (x < 1 || x > width) return 0; if (y < 1 || y > height) return 0; return 1; }   # Build the empty maze. function resetMaze( x, y) { delete maze; for (y = 1; y <= height; y++) { for (x = 1; x <= width; x++) { maze[x, y] = "11110"; # walls (up, down, left, right) and visited state. } } }   # Random things properly scaled.   function getRandX() { return 1 + int(rand() * width); }   function getRandY() { return 1 +int(rand() * height); }   function getRandDir() { return 1 + int(rand() * 4); }   function randomize() { "echo $RANDOM" | getline t; srand(t); }  
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.
#D
D
import std.stdio, std.string, std.math, std.array, std.algorithm;   struct SquareMat(T = creal) { public static string fmt = "%8.3f"; private alias TM = T[][]; private TM a;   public this(in size_t side) pure nothrow @safe in { assert(side > 0); } body { a = new TM(side, side); }   public this(in TM m) pure nothrow @safe in { assert(!m.empty); assert(m.all!(row => row.length == m.length)); // Is square. } body { // 2D dup. a.length = m.length; foreach (immutable i, const row; m) a[i] = row.dup; }   string toString() const @safe { return format("<%(%(" ~ fmt ~ ", %)\n %)>", a); }   public static SquareMat identity(in size_t side) pure nothrow @safe { auto m = SquareMat(side); foreach (immutable r, ref row; m.a) foreach (immutable c; 0 .. side) row[c] = (r == c) ? 1+0i : 0+0i; return m; }   public SquareMat opBinary(string op:"*")(in SquareMat other) const pure nothrow @safe in { assert (a.length == other.a.length); } body { immutable side = other.a.length; auto d = SquareMat(side); foreach (immutable r; 0 .. side) foreach (immutable c; 0 .. side) { d.a[r][c] = 0+0i; foreach (immutable k, immutable ark; a[r]) d.a[r][c] += ark * other.a[k][c]; } return d; }   public SquareMat opBinary(string op:"^^")(int n) // The task part. const pure nothrow @safe in { assert(n >= 0, "Negative exponent not implemented."); } body { auto sq = SquareMat(this.a); auto d = SquareMat.identity(a.length); for (; n > 0; sq = sq * sq, n >>= 1) if (n & 1) d = d * sq; return d; } }   void main() { alias M = SquareMat!(); enum real q = 0.5.sqrt; immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li], [0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li], [0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]); M.fmt = "%5.2f"; foreach (immutable p; [0, 1, 23, 24]) writefln("m ^^ %d =\n%s", p, m ^^ p); }
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#11l
11l
F maprange(a, b, s) R b[0] + (Float(s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]))   L(s) 0..10 print(‘#2 maps to #.’.format(s, maprange((0, 10), (-1, 0), s)))
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.
#Common_Lisp
Common Lisp
  (defun matrix-digital-rain () (with-screen (scr :input-echoing nil :input-blocking nil :cursor-visible nil) (let* ((width (width scr)) (height (height scr)) ;; start at a random height in each column. (positions (loop repeat width collect (random height))) ;; run each column at a random speed. (speeds (loop repeat width collect (random 4)))) ;; generate a random ascii char (flet ((randch () (+ 64 (random 58)))) ;; hit the q key to exit the main loop. (bind scr #\q 'exit-event-loop) (bind scr nil (lambda (win event) (loop for col from 0 to (1- width) do (loop repeat (nth col speeds) do ;; position of the first point in the current column (let ((pos (nth col positions))) (setf (attributes win) '(:bold)) (setf (fgcolor win) :green) (add win (randch) :y (mod pos height) :x col :fgcolor :white) (add win (randch) :y (mod (- pos 1) height) :x col) (add win (randch) :y (mod (- pos 2) height) :x col) (setf (attributes win) '()) (add win (randch) :y (mod (- pos 3) height) :x col) ;; overwrite the last char half the height from the first char. (add win #\space :y (mod (- pos (floor height 2)) height) :x col) (refresh win) ;; advance the current column (setf (nth col positions) (mod (+ pos 1) height)))))))) (setf (frame-rate scr) 20) (run-event-loop scr))))  
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
#APL
APL
#!/usr/local/bin/apl -s -f --   ⍝ Define the alphabet A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'   ⍝ Make ASCII values upper case ∇n←AscUp c n←c-32×(c≥97)∧(c≤122) ∇   ⍝ Does a list have repeated values? ∇r←Rpts l r←(l⍳l)≢⍳⍴l ∇   ⍝ Keyboard input using ⎕ and ⍞ doesn't work well using GNU APL in script mode, ⍝ so you kind of have to write your own. ⍝ Read a line of text from the keyboard ∇l←ReadLine up;k;z;data data←'' ⋄ csr←0 ⍝ Start out with empty string and cursor at 0   ⍝⍝⍝ Keyboard input in: k←1⎕fio[41]1 ⍝ Read byte from stdin handle: →(k>127)/skip ⍝ Unicode is not supported (Wumpus doesn't need it) →(k∊8 127)/back ⍝ Handle backspace →(k=10)/done ⍝ Newline = Enter key pressed →(k<32)/in ⍝ For simplicity, disregard terminal control entirely   k←(AscUp⍣up)k ⍝ Make key uppercase if necessary z←k⎕fio[42]0 ⍝ Echo key to stdout data←data,k ⍝ Insert key into data →in ⍝ Go get next key   ⍝⍝⍝ Skip UTF-8 input (read until byte ≤ 127) skip: k←1⎕fio[41]1 ⋄ →(k>127)/skip ⋄ →handle   ⍝⍝ Backspace back: →(0=⍴data)/in ⍝ If already at beginning, ignore z←k⎕fio[42]0 ⍝ Backspace to terminal data←¯1↓data ⍝ Remove character →in ⍝ Get next key   ⍝⍝ We are done, return the line as text done: l←⎕UCS data ∇   ⍝ Read a positive number from the keyboard in the range [min...max] ∇n←min ReadNum max;l;z in: l←ReadLine 0 z←10⎕fio[42]0 →(~l∧.∊'0123456789')/no →((min≤n)∧max≥n←⍎l)/0 no: ⍞←'Please enter a number between ',(⍕min),' and ',(⍕max),': ' →in ∇   ⍝ Ask a numeric question ∇n←q Question lim;min;max (min max)←lim ⍞←q,' [',(⍕min),'..',(⍕max),']? ' n←min ReadNum max ∇   ⍝ Read a choice from the keyboard ∇c←Choice cs;ks;k;z ks←AscUp ⎕UCS ↑¨cs ⍝ User should press first letter of choice in: →(~(k←AscUp 1⎕fio[41]1)∊ks)/in ⍝ Wait for user to make choice z←(c←⊃cs[↑ks⍳k])⎕fio[42]0 ⍝ Select and output correspoinding choice ∇   ⍝ Ask the user for game parameters ∇parms←InitGame;clrs;len;gss;rpts ⎕←'∘∘∘ MASTERMIND ∘∘∘' ⋄ ⎕←'' clrs←'How many colors' Question 2 20 len←'Code length' Question 4 10 gss←'Maximum amount of guesses' Question 7 20 ⍞←'Allow repeated colors in code (Y/N)? ' rpts←'Yes'≡Choice 'Yes' 'No' parms←clrs len gss rpts ∇   ⍝ Generate a code. ∇c←rpts MakeCode parms;clrs;len (clrs len)←parms c←A[(1+rpts)⊃(len?clrs)(?len/clrs)] ∇   ⍝ Let user make a guess and handle errors ∇g←parms Guess code;clrs;rpts;l;right;in (clrs rpts num)←parms   guess: ⍞←'Guess ',(¯2↑⍕num),': ' ⋄ g←ReadLine 1 ⍝ Read a guess from the keyboard   ⍝ Don't count obvously invalid input against the user →((⍴code)≢⍴g)/len ⍝ Length is wrong →(~g∧.∊A[⍳clrs])/inv ⍝ Invalid code in input →((~rpts)∧Rpts g)/rpt ⍝ No repeats allowed   ⍝ Give feedback right←g=code ⍝ Colors in right position in←g∊code ⍝ Colors not in right position fb←(+/right)/'X' ⍝ X = amount of matching ones fb←fb,(+/in∧~right)/'O' ⍝ O = amount of non-matching ones fb←fb,(+/~in)/'-' ⍝ - = amount of colors not in code ⍞←' --→ ',fb,⎕UCS 10 →0 len: ⎕←'Invalid length.' ⋄ →guess inv: ⎕←'Invalid color.' ⋄ →guess rpt: ⎕←'No repeats allowed.' ⋄ →guess ∇   ⍝ Play the game ∇ Mastermind;clrs;len;gsmax;rpts;code;gs ⎕rl←(2*32)|×/⎕ts ⍝ initialize random seed (clrs len gsmax rpts)←InitGame code←rpts MakeCode clrs len ⎕←2 0⍴'' ⎕←'The code consists of: ',A[⍳clrs] gs←0 loop: gs←gs+1 →(gs>gsmax)/lose →(code≢(clrs rpts gs)Guess code)/loop ⎕←'○○○ Congratulations! ○○○' ⎕←'You won in ',(⍕gs),' guesses.' →0 lose: ⎕←'Alas, you are out of guesses.' ⎕←'The code was: ',code ∇   Mastermind )OFF
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
#AutoHotkey
AutoHotkey
w := h := 32, maxRows := 10, numPegs := 8 ww := floor(w/2-2), hh := floor(h/2-2) grid := [], dx := w*4.5 gosub, Decode   Gui, Font, S18, Consolas loop, 4 { i := A_Index-1 Gui, add, button, % "x" (Mod(i, 4)?"+0":"30") " y" . (Mod(i, 4)?"10" : "10") " w" w " h" h " vGoal" A_Index , ? }   Gui, Add, Text, % "section x30 h1 0x1000 w" w*6 loop, % maxRows { Gui, Font, S18, consolas row := maxRows - A_Index + 1 loop 4 { col := A_Index, i:= col-1 Gui, add, button, % "x" (Mod(i, 4)?"+0":"s") " y" (Mod(i, 4)?"p":"+2") . " w" w " h" h " vButton" row "_" col " gButton" } Gui, Font, S13, wingdings 2 loop 2 { col := A_Index, i:= col-1 Gui, add, text, % "x" (Mod(i,2)?"+1":"s+" dx) " y" (Mod(i,2)?"p":"p+1") . " w" ww " h" hh " vKeyPeg" row "_" col, % Chr(167) } loop 2 { col := A_Index+2, i:= col-1 Gui, add, text, % "x" (Mod(i,2)?"+1":"s+" dx) " y" (Mod(i,2)?"p":"+1") . " w" ww " h" hh " vKeyPeg" row "_" col, % Chr(167) } Gui, Add, Text, % "section xs h1 0x1000 w" w*6 " y+4" } Gui, Font, S12, consolas Gui, add, Button, % "xs y+10 gSubmit w" W*2 , Submit Gui, add, Button, % "x+0 gResetMM w" W*2, Reset Gui, add, Checkbox, % "x+4 vNoDup", No`nDuplicates Gui, Font, S18 for i, v in pegs Gui, add, Radio, % "x" (!Mod(i-1, 4)?"10":"+10") " h" h " w" w+20 " vRadio" A_Index, % v Gui, show Row := 1 return ;----------------------------------------------------------------------- GuiClose: ExitApp return ;----------------------------------------------------------------------- Decode: Gui, Submit, NoHide pegs:=[], goal := [], usedPeg :=[] pool := ["😺","🎃","🧨","⚽","😀","☠","👽","❄","🙉","💗" ,"💥","🖐","🏈","🎱","👁","🗨","🤙","👄","🐶","🐴" ,"🦢","🐍","🐞","💣","🐪","🐘","🐰","🐸","🌴","🏀"]   loop, % numPegs { Random, rnd, 1, % pool.count() pegs[A_Index] := pool.RemoveAt(rnd) } i := 1 while (goal.count()<4) { Random, rnd, 1, % pegs.count() if (NoDup && usedPeg[pegs[rnd]]) continue goal[i++] := pegs[rnd] usedPeg[pegs[rnd]] := true } return ;----------------------------------------------------------------------- Button: if GameEnd return   Gui, Submit, NoHide RegExMatch(A_GuiControl, "Button(\d+)_(\d+)", m) if (m1 <> row) { thisPeg := Grid[m1, m2] for i, v in pegs if (v=thisPeg) GuiControl,, Radio%i%, 1 GuiControl,, % "Button" row "_" m2, % thisPeg Grid[row,m2] := thisPeg } else { loop, % pegs.count() if Radio%A_Index% GuiControl,, % A_GuiControl , % grid[m1, m2] := pegs[A_Index] } return ;----------------------------------------------------------------------- Submit: if (grid[row].count()<4) || GameEnd return   Gui, submit, NoHide Ans := [], FIP := [], inGoal := [] CIP := CNP := 0, KeyPeg := 1   for i, G in Goal inGoal[G] := (inGoal[G] ? inGoal[G] : 0) +1 ; save inGoal loop, 4 Ans[A_Index] := Grid[row, A_Index] ; save Ans for i, A in Ans if (goal[A_Index] = A) CIP++, FIP.push(i), inGoal[A]:=inGoal[A] -1 ; Correct In Place, inGoal-- for i, v in FIP Ans.RemoveAt(v-i+1) ; remove Correct In Place from Answers for i, A in Ans if (inGoal[A] > 0) CNP++, inGoal[A] := inGoal[A] -1 ; Correct Not in Place loop % CIP GuiControl,, % "KeyPeg" row "_" KeyPeg++, % Chr(82) ; "✔" loop % CNP GuiControl,, % "KeyPeg" row "_" KeyPeg++, % Chr(83) ; "X"   if (CIP=4 || row=maxRows) { loop 4 GuiControl,, Goal%A_Index%, % Goal[A_Index] MsgBox % CIP = 4 ? "You Win" : "You lose" GameEnd := true } Row++ return ;----------------------------------------------------------------------- LAlt:: ; peak at solution (for troubleshooting purposes only!) loop 4 GuiControl,, Goal%A_Index%, % Goal[A_Index] While GetKeyState("Lalt", "P") continue loop 4 GuiControl,, Goal%A_Index%, % "?" return ;----------------------------------------------------------------------- ResetMM: Grid :=[], GameEnd:= false loop, 4 { Random, rnd, 1, % pegs.count() goal[A_Index] := pegs[rnd] GuiControl,, Goal%A_Index%, ? }   loop, % maxRows { row := maxRows - A_Index + 1 loop 4 { col := A_Index GuiControl,, % "KeyPeg" row "_" col, % Chr(167) ; "O" GuiControl,, % "Button" row "_" col } } gosub Decode loop, 8 GuiControl,, Radio%A_Index%, % pegs[A_Index] return ;-----------------------------------------------------------------------
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.
#Haskell
Haskell
import Data.List (elemIndex) import Data.Char (chr, ord) import Data.Maybe (fromJust)   mats :: [[Int]] mats = [ [5, 6, 3, 1] , [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] ]   cost :: [Int] -> Int -> Int -> (Int, Int) cost a i j | i < j = let m = [ fst (cost a i k) + fst (cost a (k + 1) j) + (a !! i) * (a !! (j + 1)) * (a !! (k + 1)) | k <- [i .. j - 1] ] mm = minimum m in (mm, fromJust (elemIndex mm m) + i) | otherwise = (0, -1)   optimalOrder :: [Int] -> Int -> Int -> String optimalOrder a i j | i < j = let c = cost a i j in "(" ++ optimalOrder a i (snd c) ++ optimalOrder a (snd c + 1) j ++ ")" | otherwise = [chr ((+ i) $ ord 'a')]   printBlock :: [Int] -> IO () printBlock v = let c = cost v 0 (length v - 2) in putStrLn ("for " ++ show v ++ " we have " ++ show (fst c) ++ " possibilities, z.B " ++ optimalOrder v 0 (length v - 2))   main :: IO () main = mapM_ printBlock mats
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.
#Java
Java
import java.io.*; import java.util.*;   public class MazeSolver { /** * Reads a file into an array of strings, one per line. */ private static String[] readLines (InputStream f) throws IOException { BufferedReader r = new BufferedReader (new InputStreamReader (f, "US-ASCII")); ArrayList<String> lines = new ArrayList<String>(); String line; while ((line = r.readLine()) != null) lines.add (line); return lines.toArray(new String[0]); }   /** * Makes the maze half as wide (i. e. "+---+" becomes "+-+"), so that * each cell in the maze is the same size horizontally as vertically. * (Versus the expanded version, which looks better visually.) * Also, converts each line of the maze from a String to a * char[], because we'll want mutability when drawing the solution later. */ private static char[][] decimateHorizontally (String[] lines) { final int width = (lines[0].length() + 1) / 2; char[][] c = new char[lines.length][width]; for (int i = 0 ; i < lines.length ; i++) for (int j = 0 ; j < width ; j++) c[i][j] = lines[i].charAt (j * 2); return c; }   /** * Given the maze, the x and y coordinates (which must be odd), * and the direction we came from, return true if the maze is * solvable, and draw the solution if so. */ private static boolean solveMazeRecursively (char[][] maze, int x, int y, int d) { boolean ok = false; for (int i = 0 ; i < 4 && !ok ; i++) if (i != d) switch (i) { // 0 = up, 1 = right, 2 = down, 3 = left case 0: if (maze[y-1][x] == ' ') ok = solveMazeRecursively (maze, x, y - 2, 2); break; case 1: if (maze[y][x+1] == ' ') ok = solveMazeRecursively (maze, x + 2, y, 3); break; case 2: if (maze[y+1][x] == ' ') ok = solveMazeRecursively (maze, x, y + 2, 0); break; case 3: if (maze[y][x-1] == ' ') ok = solveMazeRecursively (maze, x - 2, y, 1); break; } // check for end condition if (x == 1 && y == 1) ok = true; // once we have found a solution, draw it as we unwind the recursion if (ok) { maze[y][x] = '*'; switch (d) { case 0: maze[y-1][x] = '*'; break; case 1: maze[y][x+1] = '*'; break; case 2: maze[y+1][x] = '*'; break; case 3: maze[y][x-1] = '*'; break; } } return ok; }   /** * Solve the maze and draw the solution. For simplicity, * assumes the starting point is the lower right, and the * ending point is the upper left. */ private static void solveMaze (char[][] maze) { solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1); }   /** * Opposite of decimateHorizontally(). Adds extra characters to make * the maze "look right", and converts each line from char[] to * String at the same time. */ private static String[] expandHorizontally (char[][] maze) { char[] tmp = new char[3]; String[] lines = new String[maze.length]; for (int i = 0 ; i < maze.length ; i++) { StringBuilder sb = new StringBuilder(maze[i].length * 2); for (int j = 0 ; j < maze[i].length ; j++) if (j % 2 == 0) sb.append (maze[i][j]); else { tmp[0] = tmp[1] = tmp[2] = maze[i][j]; if (tmp[1] == '*') tmp[0] = tmp[2] = ' '; sb.append (tmp); } lines[i] = sb.toString(); } return lines; }   /** * Accepts a maze as generated by: * http://rosettacode.org/wiki/Maze_generation#Java * in a file whose name is specified as a command-line argument, * or on standard input if no argument is specified. */ public static void main (String[] args) throws IOException { InputStream f = (args.length > 0 ? new FileInputStream (args[0]) : System.in); String[] lines = readLines (f); char[][] maze = decimateHorizontally (lines); solveMaze (maze); String[] solvedLines = expandHorizontally (maze); for (int i = 0 ; i < solvedLines.length ; i++) System.out.println (solvedLines[i]); } }
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.
#Fortran
Fortran
  MODULE PYRAMIDS !Produces a pyramid of numbers in 1-D array. INTEGER MANY !The usual storage issues. PARAMETER (MANY = 666) !This should suffice. INTEGER BRICK(MANY),IN,LAYERS !Defines a pyramid. CONTAINS SUBROUTINE IMHOTEP(PLAN)!The architect. Counting is from the apex down, the Erich von Daniken construction. CHARACTER*(*) PLAN !The instruction file. INTEGER I,IT !Steppers. CHARACTER*666 ALINE !A scratchpad for input. IN = 0 !No bricks. LAYERS = 0 !In no courses. WRITE (6,*) "Reading from ",PLAN !Here we go. OPEN(10,FILE=PLAN,FORM="FORMATTED",ACTION="READ",ERR=6) !I hope. GO TO 10 !Why can't OPEN be a function?@*&%#^%! 6 STOP "Can't grab the file!" Chew into the plan. 10 READ (10,11,END = 20) ALINE !Get the whole line in one piece. 11 FORMAT (A) !As plain text. IF (ALINE .EQ. "") GO TO 10 !Ignoring any blank lines. IF (ALINE(1:1).EQ."%") GO TO 10 !A comment opportunity. LAYERS = LAYERS + 1 !Righto, this should be the next layer. IF (IN + LAYERS.GT.MANY) STOP "Too many bricks!" !Perhaps not. READ (ALINE,*,END = 15,ERR = 15) BRICK(IN + 1:IN + LAYERS) !Free format. IN = IN + LAYERS !Insufficient numbers will provoke trouble. GO TO 10 !Extra numbers/stuff will be ignored. Caught a crab? A bad number, or too few numbers on a line? No read-next-record antics, thanks. 15 WRITE (6,16) LAYERS,ALINE !Just complain. 16 FORMAT ("Bad layer ",I0,": ",A) Completed the plan. 20 WRITE (6,21) IN,LAYERS !Announce some details. 21 FORMAT (I0," bricks in ",I0," layers.") CLOSE(10) !Finished with input. Cast forth the numbers in a nice pyramid. 30 IT = 0 !For traversing the pyramid. DO I = 1,LAYERS !Each course has one more number than the one before. WRITE (6,31) BRICK(IT + 1:IT + I) !Sweep along the layer. 31 FORMAT (<LAYERS*2 - 2*I>X,666I4) !Leading spaces may be zero in number. IT = IT + I !Thus finger the last of a layer. END DO !On to the start of the next layer. END SUBROUTINE IMHOTEP !The pyramid's plan is ready.   SUBROUTINE TRAVERSE !Clamber around the pyramid. Thoroughly. C The idea is that a pyramid of numbers is provided, and then, starting at the peak, c work down to the base summing the numbers at each step to find the maximum value path. c The constraint is that from a particular brick, only the two numbers below left and below right c may be reached in stepping to that lower layer. c Since that is a 0/1 choice, recorded in MOVE, a base-two scan searches the possibilities. INTEGER MOVE(LAYERS) !Choices are made at the various positions. INTEGER STEP(LAYERS),WALK(LAYERS) !Thus determining the path. INTEGER I,L,IT !Steppers. INTEGER PS,WS !Scores. WRITE (6,1) LAYERS !Announce the intention. 1 FORMAT (//,"Find the highest score path across a pyramid of ", 1 I0," layers."/) !I'm not worrying over singular/plural. MOVE = 0 !All 0/1 values to zero. MOVE(1) = 1 !Except the first. STEP(1) = 1 !Every path starts here, without option. WS = -666 !The best score so far. Commence a multi-level loop, using the values of MOVE as the digits, one digit per level. 10 IT = 1 !All paths start with the first step. PS = BRICK(1) !The starting score,. c write (6,8) "Move",MOVE,WS DO L = 2,LAYERS !Deal with the subsequent layers. IT = IT + L - 1 + MOVE(L) !Choose a brick. STEP(L) = IT !Remember this step. PS = PS + BRICK(IT) !Count its score. c WRITE (6,6) L,IT,BRICK(IT),PS 6 FORMAT ("Layer ",I0,",Brick(",I0,")=",I0,",Sum=",I0) END DO !Thus is the path determined. IF (PS .GT. WS) THEN !An improvement? IF (WS.GT.0) WRITE (6,7) WS,PS !Yes! Announce. 7 FORMAT ("Improved path score: ",I0," to ",I0) WRITE (6,8) "Moves",MOVE !Show the choices at each layer.. WRITE (6,8) "Steps",STEP !That resulted in this path. WRITE (6,8) "Score",BRICK(STEP) !Whose steps were scored thus. 8 FORMAT (A8,666I4) !This should suffice. WS = PS !Record the new best value. WALK = STEP !And the path thereby. END IF !So much for an improvement. DO L = LAYERS,1,-1 !Now add one to the number in MOVE. IF (MOVE(L).EQ.0) THEN !By finding the lowest order zero. MOVE(L) = 1 !Making it one, MOVE(L + 1:LAYERS) = 0 !And setting still lower orders back to zero. GO TO 10 !And if we did, there's more to do! END IF !But if that bit wasn't zero, END DO !Perhaps the next one up will be. WRITE (6,*) WS," is the highest score." !So much for that. END SUBROUTINE TRAVERSE !All paths considered...   SUBROUTINE REFINE !Ascertain the highest score without searching. INTEGER BEST(LAYERS) !A scratchpad. INTEGER I,L !Steppers. L = LAYERS*(LAYERS - 1)/2 + 1 !Finger the first brick of the lowest layer. BEST = BRICK(L:L + LAYERS - 1)!Syncopation. Copy the lowest layer. DO L = LAYERS - 1,1,-1 !Work towards the peak. FORALL (I = 1:L) BEST(I) = BRICK(L*(L - 1)/2 + I) !Add to each brick's value 1 + MAXVAL(BEST(I:I + 1)) !The better of its two possibles. END DO !On to the next layer. WRITE (6,*) BEST(1)," is the highest score. By some path." END SUBROUTINE REFINE !Who knows how we get there. END MODULE PYRAMIDS   PROGRAM TRICKLE USE PYRAMIDS c CALL IMHOTEP("Sakkara.txt") CALL IMHOTEP("Cheops.txt") CALL TRAVERSE !Do this the definite way. CALL REFINE !Only the result by more cunning. END  
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.
#PHP
PHP
  echo hash('md4', "Rosetta Code"), "\n";  
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.
#UNIX_Shell
UNIX Shell
function middle3digits { typeset -i n="${1#-}" typeset -i l=${#n} if (( l < 3 )); then echo >&2 "$1 has less than 3 digits" return 1 elif (( l % 2 == 0 )); then echo >&2 "$1 has an even number of digits" return 1 else echo ${n:$((l/2-1)):3} return 0 fi }   # test testdata=(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0) for n in ${testdata[@]}; do printf "%10d: " $n middle3digits "$n" done
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.
#Delphi
Delphi
program MD5Hash;   {$APPTYPE CONSOLE}   uses SysUtils, IdHashMessageDigest;   function MD5(aValue: string): string; begin with TIdHashMessageDigest5.Create do begin Result:= HashStringAsHex(aValue); Free; end; end;   begin Writeln(MD5('')); Writeln(MD5('a')); Writeln(MD5('abc')); Writeln(MD5('message digest')); Writeln(MD5('abcdefghijklmnopqrstuvwxyz')); Writeln(MD5('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')); Writeln(MD5('12345678901234567890123456789012345678901234567890123456789012345678901234567890')); Readln; end.
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).
#Picat
Picat
import cp.   go => N :: 0..100, foreach(X in 0..16, Y in 0..11, Z in 0..5) 6*X + 9*Y + 20*Z #!= N end, solve($[max(N)],N), println(n=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]
#PL.2FM
PL/M
/* MAYAN NUMERALS IN PL/M   THIS PROGRAM RUNS UNDER CP/M AND TAKES THE NUMBER ON THE COMMAND LINE */ 100H: /* CP/M CALLS */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   /* CP/M COMMAND LINE */ DECLARE CL$PTR ADDRESS INITIAL (80H), CMD$LEN BASED CL$PTR BYTE; DECLARE CMD$PTR ADDRESS INITIAL (81H), CMD$LINE BASED CMD$PTR BYTE;   /* THE PIPE AND AT SYMBOLS ARE NOT INCLUDED IN THE PL/M CHARSET */ DECLARE PIPE LITERALLY '7CH', AT LITERALLY '40H';   /* PRINT BORDER FOR N DIGITS */ BORDER: PROCEDURE (N); DECLARE (I, N) BYTE; DO I=1 TO N; CALL PRINT(.'+----$'); END; CALL PRINT(.('+',13,10,'$')); END BORDER;   /* PRINT LINE FOR GIVEN DIGIT */ DIGIT$LINE: PROCEDURE (LINE, DIGIT); DECLARE (I, LINE, DIGIT, UPB) BYTE; DECLARE PARTS (6) ADDRESS; PARTS(0) = .(PIPE,' $'); PARTS(1) = .(PIPE,' . $'); PARTS(2) = .(PIPE,' .. $'); PARTS(3) = .(PIPE,'... $'); PARTS(4) = .(PIPE,'....$'); PARTS(5) = .(PIPE,'----$');   IF DIGIT = 0 THEN DO; IF LINE = 3 THEN CALL PRINT(.(PIPE,' ',AT,' $')); ELSE CALL PRINT(PARTS(0)); END; ELSE DO; UPB = 15-LINE*5; IF DIGIT < UPB THEN CALL PRINT(PARTS(0)); ELSE IF DIGIT >= UPB+5 THEN CALL PRINT(PARTS(5)); ELSE CALL PRINT(PARTS(DIGIT-UPB)); END; END DIGIT$LINE;   /* PRINT LINE GIVEN DIGITS */ LINE: PROCEDURE (L, DIGITS, NDIGITS); DECLARE DIGITS ADDRESS; DECLARE (L, I, D BASED DIGITS, NDIGITS) BYTE; DO I=0 TO NDIGITS-1; CALL DIGIT$LINE(L, D(I)); END; CALL PRINT(.(PIPE,13,10,'$')); END LINE;   /* CHECK FOR ARGUMENT */ IF CMD$LEN < 2 THEN DO; CALL PRINT(.'NO INPUT$'); CALL EXIT; END;   /* PREPROCESS COMMAND LINE - TURN EACH ASCII DIGIT INTO 0-9 */ DECLARE (I, J) BYTE; DO I = 1 TO CMD$LEN-1; CMD$LINE(I) = CMD$LINE(I) - '0'; IF CMD$LINE(I) > 9 THEN DO; /* ERROR MESSAGE FOR INVALID INPUT */ CALL PRINT(.'INVALID DIGIT IN INPUT$'); CALL EXIT; END; END;   /* CONVERT TO BASE 20 DIGIT BY DIGIT */ J = CMD$LEN-2; DO WHILE J > 0; DO I = 1 TO J; CMD$LINE(I+1) = CMD$LINE(I+1) + 10*(CMD$LINE(I) AND 1); CMD$LINE(I) = CMD$LINE(I) / 2; END; J = J - 1; END;   /* FIND FIRST NONZERO DIGIT */ J = 1; DO WHILE CMD$LINE(J) = 0 AND J < CMD$LEN-1; J = J + 1; END;   /* PRINT CARTOUCHES */ DECLARE SIZE BYTE; SIZE = CMD$LEN-J; CALL BORDER(SIZE); DO I=0 TO 3; CALL LINE(I, .CMD$LINE(J), SIZE); END; CALL BORDER(SIZE);   CALL EXIT; EOF
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#11l
11l
F matrix_mul(m1, m2) assert(m1[0].len == m2.len) V r = [[0.0] * m2[0].len] * m1.len L(j) 0 .< m1.len L(i) 0 .< m2[0].len V s = 0.0 L(k) 0 .< m2.len s += m1[j][k] * m2[k][i] r[j][i] = s R r   F to_str(m) V result = ‘([’ L(r) m I result.len > 2 result ‘’= "]\n [" L(val) r result ‘’= ‘#5.2’.format(val) R result‘])’   V a = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]]   V b = [[ 4.0, -3.0 , 4/3.0, -1/4.0], [-13/3.0, 19/4.0, -7/3.0, 11/24.0], [ 3/2.0, -2.0 , 7/6.0, -1/4.0], [ -1/6.0, 1/4.0, -1/6.0, 1/24.0]]   print(to_str(a)) print(to_str(b)) print(to_str(matrix_mul(a, b))) print(to_str(matrix_mul(b, a)))
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#68000_Assembly
68000 Assembly
Transpose2DArray_B: ;INPUT: ;A0 = POINTER TO SOURCE ARRAY ;A1 = POINTER TO BACKUP AREA ; (YOU NEED THE SAME AMOUNT OF FREE SPACE AS THE SOURCE ARRAY.) ; (IT'S YOUR RESPONSIBILITY TO KNOW WHERE THAT IS.) ;D0.W = ARRAY ROW LENGTH-1 ;D1.W = ARRAY COLUMN HEIGHT-1   MOVEM.L D2-D7,-(SP) MOVE.W D0,D4 ;width - this copy is our loop counter   .outerloop: MOVE.W D1,D7 ;height MOVEQ.L #0,D3 MOVE.W D0,D6 ;width - this copy is used to offset the array ADDQ.L #1,D6   .innerloop: MOVE.B (A0,D3),(A1)+ ADD.W D6,D3 DBRA D7,.innerloop   ADDA.L #1,A0 DBRA D4,.outerloop   MOVEM.L (SP)+,D2-D7 RTS
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.
#BASIC
BASIC
OPTION BASE 0 RANDOMIZE TIMER   REM must be even width% = 40 height% = 20   REM make array and fill DIM maze$(width%, height%) FOR x% = 0 TO width% FOR y% = 0 TO height% maze$(x%, y%) = "#" NEXT y% NEXT x%   REM initial start location currentx% = INT(RND * (width% - 1)) currenty% = INT(RND * (height% - 1)) REM value must be odd IF currentx% MOD 2 = 0 THEN currentx% = currentx% + 1 IF currenty% MOD 2 = 0 THEN currenty% = currenty% + 1 maze$(currentx%, currenty%) = " "   REM generate maze done% = 0 DO WHILE done% = 0 FOR i% = 0 TO 99 oldx% = currentx% oldy% = currenty%   REM move in random direction SELECT CASE INT(RND * 4) CASE 0 IF currentx% + 2 < width% THEN currentx% = currentx% + 2 CASE 1 IF currenty% + 2 < height% THEN currenty% = currenty% + 2 CASE 2 IF currentx% - 2 > 0 THEN currentx% = currentx% - 2 CASE 3 IF currenty% - 2 > 0 THEN currenty% = currenty% - 2 END SELECT   REM if cell is unvisited then connect it IF maze$(currentx%, currenty%) = "#" THEN maze$(currentx%, currenty%) = " " maze$(INT((currentx% + oldx%) / 2), ((currenty% + oldy%) / 2)) = " " END IF NEXT i%   REM check if all cells are visited done% = 1 FOR x% = 1 TO width% - 1 STEP 2 FOR y% = 1 TO height% - 1 STEP 2 IF maze$(x%, y%) = "#" THEN done% = 0 NEXT y% NEXT x% LOOP   REM draw maze FOR y% = 0 TO height% FOR x% = 0 TO width% PRINT maze$(x%, y%); NEXT x% PRINT NEXT y%   REM wait DO: LOOP WHILE INKEY$ = ""
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.
#Delphi
Delphi
  program Matrix_exponentiation_operator;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   type TCells = array of array of double;   TMatrix = record private FCells: TCells; function GetCells(r, c: Integer): Double; procedure SetCells(r, c: Integer; const Value: Double); class operator Implicit(a: TMatrix): string; class operator BitwiseXor(a: TMatrix; e: Integer): TMatrix; class operator Multiply(a: TMatrix; b: TMatrix): TMatrix; public constructor Create(w, h: integer); overload; constructor Create(c: TCells); overload; constructor Ident(size: Integer); function Rows: Integer; function Columns: Integer; property Cells[r, c: Integer]: Double read GetCells write SetCells; default; end;   { TMatrix }   constructor TMatrix.Create(c: TCells); begin Create(Length(c), Length(c[0])); FCells := c; end;   constructor TMatrix.Create(w, h: integer); begin SetLength(FCells, w, h); end;   class operator TMatrix.BitwiseXor(a: TMatrix; e: Integer): TMatrix; begin if e < 0 then raise Exception.Create('Matrix inversion not implemented');   Result.Ident(a.Rows); while e > 0 do begin Result := Result * a; dec(e); end; end;   function TMatrix.Rows: Integer; begin Result := Length(FCells); end;   function TMatrix.Columns: Integer; begin Result := 0; if Rows > 0 then Result := Length(FCells); end;   function TMatrix.GetCells(r, c: Integer): Double; begin Result := FCells[r, c]; end;   constructor TMatrix.Ident(size: Integer); var i: Integer; begin Create(size, size);   for i := 0 to size - 1 do Cells[i, i] := 1; end;   class operator TMatrix.Implicit(a: TMatrix): string; var i, j: Integer; begin Result := '['; if a.Rows > 0 then for i := 0 to a.Rows - 1 do begin if i > 0 then Result := Trim(Result) + ']'#10'['; for j := 0 to a.Columns - 1 do begin Result := Result + Format('%f', [a[i, j]]) + ' '; end; end; Result := trim(Result) + ']'; end;   class operator TMatrix.Multiply(a, b: TMatrix): TMatrix; var size: Integer; r: Integer; c: Integer; k: Integer; begin if (a.Rows <> b.Rows) or (a.Columns <> b.Columns) then raise Exception.Create('The matrix must have same size');   size := a.Rows; Result.Create(size, size);   for r := 0 to size - 1 do for c := 0 to size - 1 do begin Result[r, c] := 0; for k := 0 to size - 1 do Result[r, c] := Result[r, c] + a[r, k] * b[k, c]; end; end;   procedure TMatrix.SetCells(r, c: Integer; const Value: Double); begin FCells[r, c] := Value; end;   var M: TMatrix;   begin M.Create([[3, 2], [2, 1]]); // Delphi don't have a ** and can't override ^ operator, then XOR operator was used Writeln(string(M xor 0), #10); Writeln(string(M xor 1), #10); Writeln(string(M xor 2), #10); Writeln(string(M xor 3), #10); Writeln(string(M xor 4), #10); Writeln(string(M xor 50), #10); Readln; end.  
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#ACL2
ACL2
(defun mapping (a1 a2 b1 b2 s) (+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))   (defun map-each (a1 a2 b1 b2 ss) (if (endp ss) nil (cons (mapping a1 a2 b1 b2 (first ss)) (map-each a1 a2 b1 b2 (rest ss)))))   (map-each 0 10 -1 0 '(0 1 2 3 4 5 6 7 8 9 10))   ;; (-1 -9/10 -4/5 -7/10 -3/5 -1/2 -2/5 -3/10 -1/5 -1/10 0)    
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.
#Go
Go
package main   import ( gc "github.com/rthornton128/goncurses" "log" "math/rand" "time" )   // Time between row updates in microseconds. // Controls the speed of the digital rain effect. const rowDelay = 40000   func main() { start := time.Now() rand.Seed(time.Now().UnixNano())   // Characters to randomly appear in the rain sequence. chars := []byte("0123456789") totalChars := len(chars)   // Set up ncurses screen and colors. stdscr, err := gc.Init() if err != nil { log.Fatal("init", err) } defer gc.End()   gc.Echo(false) gc.Cursor(0)   if !gc.HasColors() { log.Fatal("Program requires a colour capable terminal") }   if err := gc.StartColor(); err != nil { log.Fatal(err) }   if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil { log.Fatal("InitPair failed: ", err) } stdscr.ColorOn(1) maxY, maxX := stdscr.MaxYX()   /* Create slices of columns based on screen width. */   // Slice containing the current row of each column. columnsRow := make([]int, maxX)   // Slice containing the active status of each column. // A column draws characters on a row when active. columnsActive := make([]int, maxX)   // Set top row as current row for all columns. for i := 0; i < maxX; i++ { columnsRow[i] = -1 columnsActive[i] = 0 }   for { for i := 0; i < maxX; i++ { if columnsRow[i] == -1 { // If a column is at the top row, pick a // random starting row and active status. columnsRow[i] = rand.Intn(maxY + 1) columnsActive[i] = rand.Intn(2) } }   // Loop through columns and draw characters on rows. for i := 0; i < maxX; i++ { if columnsActive[i] == 1 { // Draw a random character at this column's current row. charIndex := rand.Intn(totalChars) stdscr.MovePrintf(columnsRow[i], i, "%c", chars[charIndex]) } else { // Draw an empty character if the column is inactive. stdscr.MovePrintf(columnsRow[i], i, "%c", ' ') }   columnsRow[i]++   // When a column reaches the bottom row, reset to top. if columnsRow[i] >= maxY { columnsRow[i] = -1 }   // Randomly alternate the column's active status. if rand.Intn(1001) == 0 { if columnsActive[i] == 0 { columnsActive[i] = 1 } else { columnsActive[i] = 0 } } } time.Sleep(rowDelay * time.Microsecond) stdscr.Refresh() elapsed := time.Since(start) // Stop after 1 minute. if elapsed.Minutes() >= 1 { break } } }
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
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector>   typedef std::vector<char> vecChar;   class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST";   if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10; if( !rpt && clr_count < code_len ) clr_count = code_len; if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20; if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;   codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;   for( size_t s = 0; s < colorsCnt; s++ ) { colors.append( 1, color.at( s ) ); } } void play() { bool win = false; combo = getCombo();   while( guessCnt ) { showBoard(); if( checkInput( getInput() ) ) { win = true; break; } guessCnt--; } if( win ) { std::cout << "\n\n--------------------------------\n" << "Very well done!\nYou found the code: " << combo << "\n--------------------------------\n\n"; } else { std::cout << "\n\n--------------------------------\n" << "I am sorry, you couldn't make it!\nThe code was: " << combo << "\n--------------------------------\n\n"; } } private: void showBoard() { vecChar::iterator y; for( int x = 0; x < guesses.size(); x++ ) { std::cout << "\n--------------------------------\n"; std::cout << x + 1 << ": "; for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) { std::cout << *y << " "; }   std::cout << " : "; for( y = results[x].begin(); y != results[x].end(); y++ ) { std::cout << *y << " "; }   int z = codeLen - results[x].size(); if( z > 0 ) { for( int x = 0; x < z; x++ ) std::cout << "- "; } } std::cout << "\n\n"; } std::string getInput() { std::string a; while( true ) { std::cout << "Enter your guess (" << colors << "): "; a = ""; std::cin >> a; std::transform( a.begin(), a.end(), a.begin(), ::toupper ); if( a.length() > codeLen ) a.erase( codeLen ); bool r = true; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { if( colors.find( *x ) == std::string::npos ) { r = false; break; } } if( r ) break; } return a; } bool checkInput( std::string a ) { vecChar g; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { g.push_back( *x ); } guesses.push_back( g );   int black = 0, white = 0; std::vector<bool> gmatch( codeLen, false ); std::vector<bool> cmatch( codeLen, false );   for( int i = 0; i < codeLen; i++ ) { if( a.at( i ) == combo.at( i ) ) { gmatch[i] = true; cmatch[i] = true; black++; } }   for( int i = 0; i < codeLen; i++ ) { if (gmatch[i]) continue; for( int j = 0; j < codeLen; j++ ) { if (i == j || cmatch[j]) continue; if( a.at( i ) == combo.at( j ) ) { cmatch[j] = true; white++; break; } } }   vecChar r; for( int b = 0; b < black; b++ ) r.push_back( 'X' ); for( int w = 0; w < white; w++ ) r.push_back( 'O' ); results.push_back( r );   return ( black == codeLen ); } std::string getCombo() { std::string c, clr = colors; int l, z;   for( size_t s = 0; s < codeLen; s++ ) { z = rand() % ( int )clr.length(); c.append( 1, clr[z] ); if( !repeatClr ) clr.erase( z, 1 ); } return c; }   size_t codeLen, colorsCnt, guessCnt; bool repeatClr; std::vector<vecChar> guesses, results; std::string colors, combo; };   int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); master m( 4, 8, 12, false ); m.play(); 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.
#J
J
moo =: verb define s =. m =. 0 $~ ,~ n=._1+#y for_lmo. 1+i.<:n do. for_i. i. n-lmo do. j =. i + lmo m =. _ (<i;j)} m for_k. i+i.j-i do. cost =. ((<i;k){m) + ((<(k+1);j){m) + */ y {~ i,(k+1),(j+1) if. cost < ((<i;j){m) do. m =. cost (<i;j)} m s =. k (<i;j)} s end. end. end. end.   m;s )   poco =: dyad define 'i j' =. y if. i=j do. a. {~ 65 + i NB. 65 = a.i.'A' else. k =. x {~ <y NB. y = i,j '(' , (x poco i,k) , (x poco j ,~ 1+k) , ')' end. )   optMM =: verb define 'M S' =. moo y smoutput 'Cost: ' , ": x: M {~ <0;_1 smoutput 'Order: ', S poco 0 , <:#M )
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.
#Java
Java
  import java.util.Arrays;   public class MatrixChainMultiplication {   public static void main(String[] args) { runMatrixChainMultiplication(new int[] {5, 6, 3, 1}); runMatrixChainMultiplication(new int[] {1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2}); runMatrixChainMultiplication(new int[] {1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}); }   private static void runMatrixChainMultiplication(int[] dims) { System.out.printf("Array Dimension = %s%n", Arrays.toString(dims)); System.out.printf("Cost = %d%n", matrixChainOrder(dims)); System.out.printf("Optimal Multiply = %s%n%n", getOptimalParenthesizations()); }   private static int[][]cost; private static int[][]order;   public static int matrixChainOrder(int[] dims) { int n = dims.length - 1; cost = new int[n][n]; order = new int[n][n];   for (int lenMinusOne = 1 ; lenMinusOne < n ; lenMinusOne++) { for (int i = 0; i < n - lenMinusOne; i++) { int j = i + lenMinusOne; cost[i][j] = Integer.MAX_VALUE; for (int k = i; k < j; k++) { int currentCost = cost[i][k] + cost[k+1][j] + dims[i]*dims[k+1]*dims[j+1]; if (currentCost < cost[i][j]) { cost[i][j] = currentCost; order[i][j] = k; } } } } return cost[0][n-1]; }   private static String getOptimalParenthesizations() { return getOptimalParenthesizations(order, 0, order.length - 1); }   private static String getOptimalParenthesizations(int[][]s, int i, int j) { if (i == j) { return String.format("%c", i+65); } else { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(getOptimalParenthesizations(s, i, s[i][j])); sb.append(" * "); sb.append(getOptimalParenthesizations(s, s[i][j] + 1, j)); sb.append(")"); return sb.toString(); } }   }  
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.
#JavaScript
JavaScript
  var ctx, wid, hei, cols, rows, maze, stack = [], start = {x:-1, y:-1}, end = {x:-1, y:-1}, grid = 8; function drawMaze() { for( var i = 0; i < cols; i++ ) { for( var j = 0; j < rows; j++ ) { switch( maze[i][j] ) { case 0: ctx.fillStyle = "black"; break; case 1: ctx.fillStyle = "green"; break; case 2: ctx.fillStyle = "red"; break; case 3: ctx.fillStyle = "yellow"; break; case 4: ctx.fillStyle = "#500000"; break; } ctx.fillRect( grid * i, grid * j, grid, grid ); } } } function getFNeighbours( sx, sy, a ) { var n = []; if( sx - 1 > 0 && maze[sx - 1][sy] == a ) { n.push( { x:sx - 1, y:sy } ); } if( sx + 1 < cols - 1 && maze[sx + 1][sy] == a ) { n.push( { x:sx + 1, y:sy } ); } if( sy - 1 > 0 && maze[sx][sy - 1] == a ) { n.push( { x:sx, y:sy - 1 } ); } if( sy + 1 < rows - 1 && maze[sx][sy + 1] == a ) { n.push( { x:sx, y:sy + 1 } ); } return n; } function solveMaze() { if( start.x == end.x && start.y == end.y ) { for( var i = 0; i < cols; i++ ) { for( var j = 0; j < rows; j++ ) { switch( maze[i][j] ) { case 2: maze[i][j] = 3; break; case 4: maze[i][j] = 0; break; } } } drawMaze(); return; } var neighbours = getFNeighbours( start.x, start.y, 0 ); if( neighbours.length ) { stack.push( start ); start = neighbours[0]; maze[start.x][start.y] = 2; } else { maze[start.x][start.y] = 4; start = stack.pop(); }   drawMaze(); requestAnimationFrame( solveMaze ); } function getCursorPos( event ) { var rect = this.getBoundingClientRect(); var x = Math.floor( ( event.clientX - rect.left ) / grid ), y = Math.floor( ( event.clientY - rect.top ) / grid ); if( maze[x][y] ) return; if( start.x == -1 ) { start = { x: x, y: y }; } else { end = { x: x, y: y }; maze[start.x][start.y] = 2; solveMaze(); } } function getNeighbours( sx, sy, a ) { var n = []; if( sx - 1 > 0 && maze[sx - 1][sy] == a && sx - 2 > 0 && maze[sx - 2][sy] == a ) { n.push( { x:sx - 1, y:sy } ); n.push( { x:sx - 2, y:sy } ); } if( sx + 1 < cols - 1 && maze[sx + 1][sy] == a && sx + 2 < cols - 1 && maze[sx + 2][sy] == a ) { n.push( { x:sx + 1, y:sy } ); n.push( { x:sx + 2, y:sy } ); } if( sy - 1 > 0 && maze[sx][sy - 1] == a && sy - 2 > 0 && maze[sx][sy - 2] == a ) { n.push( { x:sx, y:sy - 1 } ); n.push( { x:sx, y:sy - 2 } ); } if( sy + 1 < rows - 1 && maze[sx][sy + 1] == a && sy + 2 < rows - 1 && maze[sx][sy + 2] == a ) { n.push( { x:sx, y:sy + 1 } ); n.push( { x:sx, y:sy + 2 } ); } return n; } function createArray( c, r ) { var m = new Array( c ); for( var i = 0; i < c; i++ ) { m[i] = new Array( r ); for( var j = 0; j < r; j++ ) { m[i][j] = 1; } } return m; } function createMaze() { var neighbours = getNeighbours( start.x, start.y, 1 ), l; if( neighbours.length < 1 ) { if( stack.length < 1 ) { drawMaze(); stack = []; start.x = start.y = -1; document.getElementById( "canvas" ).addEventListener( "mousedown", getCursorPos, false ); return; } start = stack.pop(); } else { var i = 2 * Math.floor( Math.random() * ( neighbours.length / 2 ) ) l = neighbours[i]; maze[l.x][l.y] = 0; l = neighbours[i + 1]; maze[l.x][l.y] = 0; start = l stack.push( start ) } drawMaze(); requestAnimationFrame( createMaze ); } function createCanvas( w, h ) { var canvas = document.createElement( "canvas" ); wid = w; hei = h; canvas.width = wid; canvas.height = hei; canvas.id = "canvas"; ctx = canvas.getContext( "2d" ); ctx.fillStyle = "black"; ctx.fillRect( 0, 0, wid, hei ); document.body.appendChild( canvas ); } function init() { cols = 73; rows = 53; createCanvas( grid * cols, grid * rows ); maze = createArray( cols, rows ); start.x = Math.floor( Math.random() * ( cols / 2 ) ); start.y = Math.floor( Math.random() * ( rows / 2 ) ); if( !( start.x & 1 ) ) start.x++; if( !( start.y & 1 ) ) start.y++; maze[start.x][start.y] = 0; createMaze(); }  
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.
#FreeBASIC
FreeBASIC
' version 21-06-2015 ' compile with: fbc -s console   Data " 55" Data " 94 48" Data " 95 30 96" Data " 77 71 26 67" Data " 97 13 76 38 45" Data " 07 36 79 16 37 68" Data " 48 07 09 18 70 26 06" Data " 18 72 79 46 59 79 29 90" Data " 20 76 87 11 32 07 07 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 " 02 90 03 60 48 49 41 46 33 36 47 23" Data " 92 50 48 02 36 59 42 79 72 20 82 77 42" Data " 56 78 38 80 39 75 02 71 66 66 01 03 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 01 01 99 89 52" Data " 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15" Data " 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93" Data "END" ' no more data   ' ------=< MAIN >=------   Dim As String ln Dim As Integer matrix(1 To 20, 1 To 20) Dim As Integer x = 1, y, s1, s2, size   Do Read ln ln = Trim(ln) If ln = "END" Then Exit Do For y = 1 To x matrix(x, y) = Val(Left(ln, 2)) ln = Mid(ln, 4) Next x += 1 size += 1 Loop   For x = size - 1 To 1 Step - 1 For y = 1 To x s1 = matrix(x + 1, y) s2 = matrix(x + 1, y + 1) If s1 > s2 Then matrix(x, y) += s1 Else matrix(x, y) += s2 End If Next Next   Print Print " maximum triangle path sum ="; matrix(1, 1)   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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.
#PicoLisp
PicoLisp
(de *Md4-W . (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 1 9 5 13 3 11 7 15 2 10 6 14 4 12 8 16 .)) (de *Md4-R1 . (3 7 11 19 .)) (de *Md4-R2 . (3 5 9 13 .)) (de *Md4-R3 . (3 9 11 15 .))   (de mod32 (N) (& N `(hex "FFFFFFFF")) )   (de not32 (N) (x| N `(hex "FFFFFFFF")) )   (de add32 @ (mod32 (pass +)) )   (de leftRotate (X C) (| (mod32 (>> (- C) X)) (>> (- 32 C) X)) )   (de md4 (Str) (let Len (length Str) (setq Str (conc (need (- 8 (* 64 (/ (+ Len 1 8 63) 64))) # Pad to 64-8 bytes (conc (mapcar char (chop Str)) # Works only with ASCII characters (cons `(hex "80")) ) # '1' bit 0 ) # Pad with '0' (make (setq Len (* 8 Len)) (do 8 (link (& Len 255)) (setq Len (>> 8 Len )) ) ) ) ) ) (let (H0 `(hex "67452301") H1 `(hex "EFCDAB89") H2 `(hex "98BADCFE") H3 `(hex "10325476") R2 `(hex "5A827999") R3 `(hex "6ED9EBA1") ) (while Str (let (A H0 B H1 C H2 D H3 W (make (do 16 (link (apply | (mapcar >> (0 -8 -16 -24) (cut 4 'Str)) ) ) ) ) ) (for I 12 (cond ((>= 4 I) (setq A (leftRotate (add32 A (| (& B C) (& (not32 B) D)) (get W (pop '*Md4-W)) ) (pop '*Md4-R1) ) D (leftRotate (add32 D (| (& A B) (& (not32 A) C)) (get W (pop '*Md4-W)) ) (pop '*Md4-R1) ) C (leftRotate (add32 C (| (& D A) (& (not32 D) B)) (get W (pop '*Md4-W)) ) (pop '*Md4-R1) ) B (leftRotate (add32 B (| (& C D) (& (not32 C) A)) (get W (pop '*Md4-W)) ) (pop '*Md4-R1) ) ) ) ((>= 8 I) (setq A (leftRotate (add32 A (| (& B (| C D)) (& C D) ) (get W (pop '*Md4-W)) R2 ) (pop '*Md4-R2) ) D (leftRotate (add32 D (| (& A (| B C)) (& B C) ) (get W (pop '*Md4-W)) R2 ) (pop '*Md4-R2) ) C (leftRotate (add32 C (| (& D (| A B)) (& A B) ) (get W (pop '*Md4-W)) R2 ) (pop '*Md4-R2) ) B (leftRotate (add32 B (| (& C (| D A)) (& D A) ) (get W (pop '*Md4-W)) R2 ) (pop '*Md4-R2) ) ) ) (T (setq A (leftRotate (add32 A (x| B C D) (get W (pop '*Md4-W)) R3 ) (pop '*Md4-R3) ) D (leftRotate (add32 D (x| A B C) (get W (pop '*Md4-W)) R3 ) (pop '*Md4-R3) ) C (leftRotate (add32 C (x| D A B) (get W (pop '*Md4-W)) R3 ) (pop '*Md4-R3) ) B (leftRotate (add32 B (x| C D A) (get W (pop '*Md4-W)) R3 ) (pop '*Md4-R3) ) ) ) ) ) (setq H0 (add32 H0 A) H1 (add32 H1 B) H2 (add32 H2 C) H3 (add32 H3 D) ) ) ) (make (for N (list H0 H1 H2 H3) (do 4 (link (& N 255)) (setq N (>> 8 N)) ) ) ) ) )   (let Str "Rosetta Code" (println (pack (mapcar '((B) (pad 2 (hex B))) (md4 Str) ) ) ) (println (pack (mapcar '((B) (pad 2 (hex B))) (native "libcrypto.so" "MD4" '(B . 16) Str (length Str) '(NIL (16)) ) ) ) ) )   (bye)
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.
#VBA
VBA
  Option Explicit   Sub Main_Middle_three_digits() Dim Numbers, i& Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _ 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) For i = 0 To 16 Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i))) Next End Sub   Function Middle3digits(strNb As String) As String If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1) If Len(strNb) < 3 Then Middle3digits = "Error ! Number of digits must be >= 3" ElseIf Len(strNb) Mod 2 = 0 Then Middle3digits = "Error ! Number of digits must be odd" Else Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3) End If End Function  
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.
#E
E
def makeMessageDigest := <import:java.security.makeMessageDigest> def sprintf := <import:java.lang.makeString>.format   def digest := makeMessageDigest.getInstance("MD5") \ .digest("The quick brown fox jumped over the lazy dog's back".getBytes("iso-8859-1"))   for b in digest { print(sprintf("%02x", [b])) } 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).
#PicoLisp
PicoLisp
(de nuggets1 (M) (let Lst (range 0 M) (for A (range 0 M 6) (for B (range A M 9) (for C (range B M 20) (set (nth Lst (inc C))) ) ) ) (apply max Lst) ) )
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).
#PL.2FI
PL/I
mcnugget: procedure options(main); declare nugget(0:100) bit, (a, b, c) fixed; do a=0 to 100; nugget(a) = '0'b; end;   do a=0 to 100 by 6; do b=a to 100 by 9; do c=b to 100 by 20; nugget(c) = '1'b; end; end; end;   do a=100 to 0 by -1; if ^nugget(a) then do; put skip list('Maximum non-McNuggets number:', a); stop; end; end; end mcnugget;
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]
#Phix
Phix
-- demo\rosetta\Mayan_numerals.exw without js -- (file i/o [when as_html is true]) constant as_html = true, -- false == nasty ascii inline_css = true -- also uses wiki tables ({| etc) if false string html = "" constant t_style = "border-collapse: separate; text-align: center; border-spacing: 3px 0px;", c_style = "border: solid black 2px;background-color: #fffff0;border-bottom: double 6px;"& "border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;"& "vertical-align: bottom;width: 3.25em;", dot = "●", bar = "───", zero = "Θ", digits = {" 0 "," . "," .. ","... ","...."} function to_seq(atom a) sequence s = {} while true do s = prepend(s,remainder(a,20)) a = floor(a/20) if a=0 then exit end if end while return s end function procedure show_mayan(atom a) sequence s = to_seq(a) if not as_html then string tb = join(repeat('+',length(s)+1),"------"), ln = join(repeat('|',length(s)+1)," ") sequence res = {tb,ln,ln,ln,ln,tb} for i=1 to length(s) do integer si = s[i], l = 5, m = i*7-4 while true do res[l][m..m+3] = digits[min(si+1,5)] si -= 5 if si<=0 then exit end if l -= 1 end while end for printf(1,"%d\n%s\n\n",{a,join(res,"\n")}) else for i=1 to length(s) do sequence res = repeat("",4) integer si = s[i], l = 4 while true do res[l] = iff(si>=5?bar:iff(si?join(repeat(dot,si),""):zero)) si -= 5 if si<=0 then exit end if l -= 1 end while s[i] = join(res,"<br>") end for if inline_css then html &= sprintf(" <table>\n <caption>%d</caption>\n <tr>\n",a) for i=1 to length(s) do html &= sprintf(" <td>%s</td>\n",{s[i]}) end for html &= " </tr>\n </table>\n" else html &= sprintf("{| style=\"%s\"\n|+ %d\n|-\n",{t_style,a}) for i=1 to length(s) do html &= sprintf("| style=\"%s\" | %s\n",{c_style,s[i]}) end for html &= "|}\n" end if end if end procedure constant html_header = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Mayan numerals</title> <style> table {%s} td { %s } </style> </head> <body> <h2>Mayan numerals</h2> """, wiki_header = """ The following is intended to be pasted into the rosettacode wiki, or similar<br> """, html_footer = """ </body> </html> """ constant tests = {4005, 8017, 326205, 886205, 26960840421, 126524984376952} for i=1 to length(tests) do show_mayan(tests[i]) end for if as_html then string filename = "Mayan_numerals.html" integer fn = open(filename,"w") if inline_css then printf(fn,html_header,{t_style,c_style}) else printf(fn,wiki_header) end if puts(fn,html) if inline_css then puts(fn,html_footer) end if close(fn) if inline_css then system(filename) else printf(1,"See %s\n",{filename}) {} = wait_key() end if else ?"done" {} = wait_key() end if
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#360_Assembly
360 Assembly
* Matrix multiplication 06/08/2015 MATRIXRC CSECT Matrix multiplication USING MATRIXRC,R13 SAVEARA B STM-SAVEARA(R15) DC 17F'0' STM STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 LA R7,1 i=1 LOOPI1 CH R7,M do i=1 to m (R7) BH ELOOPI1 LA R8,1 j=1 LOOPJ1 CH R8,P do j=1 to p (R8) BH ELOOPJ1 LR R1,R7 i BCTR R1,0 MH R1,P LR R6,R8 j BCTR R6,0 AR R1,R6 SLA R1,2 LA R6,0 ST R6,C(R1) c(i,j)=0 LA R9,1 k=1 LOOPK1 CH R9,N do k=1 to n (R9) BH ELOOPK1 LR R1,R7 i BCTR R1,0 MH R1,P LR R6,R8 j BCTR R6,0 AR R1,R6 SLA R1,2 L R2,C(R1) R2=c(i,j) LR R10,R1 R10=offset(i,j) LR R1,R7 i BCTR R1,0 MH R1,N LR R6,R9 k BCTR R6,0 AR R1,R6 SLA R1,2 L R3,A(R1) R3=a(i,k) LR R1,R9 k BCTR R1,0 MH R1,P LR R6,R8 j BCTR R6,0 AR R1,R6 SLA R1,2 L R4,B(R1) R4=b(k,j) LR R15,R3 a(i,k) MR R14,R4 a(i,k)*b(k,j) LR R3,R15 AR R2,R3 R2=R2+a(i,k)*b(k,j) ST R2,C(R10) c(i,j)=c(i,j)+a(i,k)*b(k,j) LA R9,1(R9) k=k+1 B LOOPK1 ELOOPK1 LA R8,1(R8) j=j+1 B LOOPJ1 ELOOPJ1 LA R7,1(R7) i=i+1 B LOOPI1 ELOOPI1 MVC Z,=CL80' ' clear buffer LA R7,1 LOOPI2 CH R7,M do i=1 to m BH ELOOPI2 LA R8,1 LOOPJ2 CH R8,P do j=1 to p BH ELOOPJ2 LR R1,R7 i BCTR R1,0 MH R1,P LR R6,R8 j BCTR R6,0 AR R1,R6 SLA R1,2 L R6,C(R1) c(i,j) LA R3,Z AH R3,IZ XDECO R6,W MVC 0(5,R3),W+7 output c(i,j) LH R3,IZ LA R3,5(R3) STH R3,IZ LA R8,1(R8) j=j+1 B LOOPJ2 ELOOPJ2 XPRNT Z,80 print buffer MVC IZ,=H'0' LA R7,1(R7) i=i+1 B LOOPI2 ELOOPI2 L R13,4(0,R13) LM R14,R12,12(R13) XR R15,R15 BR R14 A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8' a(4,2) B DC F'1',F'2',F'3',F'4',F'5',F'6' b(2,3) C DS 12F c(4,3) N DC H'2' dim(a,2)=dim(b,1) M DC H'4' dim(a,1) P DC H'3' dim(b,2) Z DS CL80 IZ DC H'0' W DS CL16 YREGS END MATRIXRC
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return successfully. Ideally implementations will work equally well cross-platform (on windows, linux, and OS X). It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
#11l
11l
fs:create_dirs(path)
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#ACL2
ACL2
(defun cons-each (xs xss) (if (or (endp xs) (endp xss)) nil (cons (cons (first xs) (first xss)) (cons-each (rest xs) (rest xss)))))   (defun list-each (xs) (if (endp xs) nil (cons (list (first xs)) (list-each (rest xs)))))   (defun transpose-list (xss) (if (endp (rest xss)) (list-each (first xss)) (cons-each (first xss) (transpose-list (rest xss)))))
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.
#Batch_File
Batch File
:amaze Rows Cols [wall char] :: A stack-less, iterative, depth-first maze generator in native WinNT batch. :: Rows and Cols must each be >1 and Rows*Cols cannot exceed 2096. :: Default wall character is #, [wall char] is used if provided.   @ECHO OFF SETLOCAL EnableDelayedExpansion :: check for valid input, else GOTO :help IF /I "%~2" EQU "" GOTO :amaze_help FOR /F "tokens=* delims=0123456789" %%A IN ("%~1%~2") DO IF "%%~A" NEQ "" GOTO :amaze_help SET /A "rows=%~1, cols=%~2, mTmp=rows*cols" IF !rows! LSS 2 GOTO :amaze_help IF !cols! LSS 2 GOTO :amaze_help IF !mTmp! GTR 2096 GOTO :amaze_help :: set map characters and use 1st character of %3 for wall, if defined SET "wall=#" SET "hall= " SET "crumb=." IF "%~3" NEQ "" SET "wall=%~3" SET "wall=!wall:~0,1!" :: assign width, height, cursor position, loop count, and offsets for NSEW SET /A "cnt=0, wide=cols*2-1, high=rows*2-1, size=wide*high, N=wide*-2, S=wide*2, E=2, W=-2" :: different random entrance points :: ...on top :: SET /A "start=(!RANDOM! %% cols)*2" :: ...on bottom :: SET /A "start=size-(!RANDOM! %% cols)*2-1" :: ...on top or bottom :: SET /A ch=cols*2, ch=!RANDOM! %% ch :: IF !ch! GEQ !cols! ( SET /A "start=size-(ch-cols)*2-1" :: ) ELSE SET /A start=ch*2 :: random entrance inside maze SET /A "start=(!RANDOM! %% cols*2)+(!RANDOM! %% rows*2)*wide" SET /A "curPos=start, cTmp=curPos+1, loops=cols*rows*2+1" :: fill the maze with 8186 wall characters, clip to size, and open 1st cell SET "mz=!wall!" FOR /L %%A IN (1,1,6) DO SET mz=!mz!!mz!!mz!!mz! SET bdr=!mz:~-%wide%! SET mz=!mz:~3!!mz:~3! SET mz=!mz:~-%size%! SET mz=!mz:~0,%curPos%!!hall!!mz:~%cTmp%! :: iterate #cells*2+1 steps of random depth-first search FOR /L %%@ IN (1,1,%loops%) DO ( SET "rand=" & SET "crmPos=" REM set values for NSEW cell and wall positions SET /A "rCnt=rTmp=0, cTmp=curPos+1, np=curPos+N, sp=curPos+S, ep=curPos+E, wp=curPos+W, wChk=curPos/wide*wide, eChk=wChk+wide, nw=curPos-wide, sw=curPos+wide, ew=curPos+1, ww=curPos-1" REM examine adjacent cells, build direction list, and find last crumb position FOR /F "tokens=1-8" %%A IN ("!np! !sp! !ep! !wp! !nw! !sw! !ew! !ww!") DO ( IF !np! GEQ 0 IF "!mz:~%%A,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=n !rand!" ) ELSE IF "!mz:~%%E,1!" EQU "!crumb!" SET /A crmPos=np, cw=nw IF !sp! LEQ !size! IF "!mz:~%%B,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=s !rand!" ) ELSE IF "!mz:~%%F,1!" EQU "!crumb!" SET /A crmPos=sp, cw=sw IF !ep! LEQ !eChk! IF "!mz:~%%C,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=e !rand!" ) ELSE IF "!mz:~%%G,1!" EQU "!crumb!" SET /A crmPos=ep, cw=ew IF !wp! GEQ !wChk! IF "!mz:~%%D,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=w !rand!" ) ELSE IF "!mz:~%%H,1!" EQU "!crumb!" SET /A crmPos=wp, cw=ww ) IF DEFINED rand ( REM adjacent unvisited cell is available SET /A rCnt=!RANDOM! %% rCnt FOR %%A IN (!rand!) DO ( REM pick random cell + wall IF !rTmp! EQU !rCnt! SET /A "curPos=!%%Ap!, cTmp=curPos+1, mw=!%%Aw!, mTmp=mw+1" SET /A rTmp+=1 ) REM write the 2 new characters into the maze FOR /F "tokens=1-4" %%A IN ("!mw! !mTmp! !curPos! !cTmp!") DO ( SET "mz=!mz:~0,%%A!!crumb!!mz:~%%B!" SET "mz=!mz:~0,%%C!!hall!!mz:~%%D!" ) ) ELSE IF DEFINED crmPos ( REM follow the crumbs backward SET /A mTmp=cw+1 REM erase the crumb character and set new cursor position FOR /F "tokens=1-2" %%A IN ("!cw! !mTmp!") DO SET "mz=!mz:~0,%%A!!hall!!mz:~%%B!" SET "curPos=!crmPos!" ) ) SET /A open=cols/2*2, mTmp=open+1 ECHO !wall!!bdr:~0,%open%!!hall!!bdr:~%mTmp%!!wall! FOR /L %%A IN (0,!wide!,!size!) DO IF %%A LSS !size! ECHO !wall!!mz:~%%A,%wide%!!wall! ECHO !wall!!bdr:~0,%open%!!hall!!bdr:~%mTmp%!!wall! ENDLOCAL EXIT /B 0   :amaze_help ECHO Usage: %~0 Rows Cols [wall char] ECHO Rows^>1, Cols^>1, and Rows*Cols^<=2096 ECHO Example: %~0 11 39 @ ENDLOCAL EXIT /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.
#ERRE
ERRE
10 This example calculates | 3 2 | | 2 1 |
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.
#Factor
Factor
USING: kernel math math.matrices sequences ;   : my-m^n ( m n -- m' ) dup 0 < [ "no negative exponents" throw ] [ [ drop length identity-matrix ] [ swap '[ _ m. ] times ] 2bi ] if ;
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Map(REAL POINTER a1,a2,b1,b2,s,res) REAL tmp1,tmp2,tmp3   RealSub(s,a1,tmp1) ;tmp1=s-a1 RealSub(b2,b1,tmp2) ;tmp2=b2-b1 RealMult(tmp1,tmp2,tmp3) ;tmp3=(s-a1)*(b2-b1) RealSub(a2,a1,tmp1) ;tmp1=a2-a1 RealDiv(tmp3,tmp1,tmp2) ;tmp2=(s-a1)*(b2-b1)/(a2-a1) RealAdd(b1,tmp2,res) ;res=b1+(s-a1)*(b2-b1)/(a2-a1) RETURN   PROC Main() BYTE i REAL a1,a2,b1,b2,s,res   Put(125) PutE() ;clear screen   ValR("0",a1) ValR("10",a2) ValR("-1",b1) ValR("0",b2)   FOR i=0 TO 10 DO IntToReal(i,s) Map(a1,a2,b1,b2,s,res) PrintR(s) Print(" maps to ") PrintRE(res) OD RETURN
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Ada
Ada
with Ada.Text_IO; procedure Map is type First_Range is new Float range 0.0 .. 10.0; type Second_Range is new Float range -1.0 .. 0.0; function Translate (Value : First_Range) return Second_Range is B1 : Float := Float (Second_Range'First); B2 : Float := Float (Second_Range'Last); A1 : Float := Float (First_Range'First); A2 : Float := Float (First_Range'Last); Result : Float; begin Result := B1 + (Float (Value) - A1) * (B2 - B1) / (A2 - A1); return Second_Range (Result); end; function Translate (Value : Second_Range) return First_Range is B1 : Float := Float (First_Range'First); B2 : Float := Float (First_Range'Last); A1 : Float := Float (Second_Range'First); A2 : Float := Float (Second_Range'Last); Result : Float; begin Result := B1 + (Float (Value) - A1) * (B2 - B1) / (A2 - A1); return First_Range (Result); end; Test_Value : First_Range := First_Range'First; begin loop Ada.Text_IO.Put_Line (First_Range'Image (Test_Value) & " maps to: " & Second_Range'Image (Translate (Test_Value))); exit when Test_Value = First_Range'Last; Test_Value := Test_Value + 1.0; end loop; end Map;
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.
#J
J
require'ide/qt/gl2' coinsert'jgl2'   junk=: 7 u:;48 65 16b30a1(+i.)&.>10 26 90 sz=:40 25 len=: <.1.4*{:sz heat=: (224 255 255),~(<.0.5+255*(%>./)(-<./)^>:(% >./)i.len)*/0 1 0   cols=: i.0 rows=: i.0 scale=: 24 live=: (#heat)#<i.3 0   update=: {{ try. glfill 0 0 0 255 catch. wd'timer 0' return. end. glfont font=.'courier ',":0.8*scale upd=. 0>._3++/?2 2 2 2 4 cols=: cols,upd{.(?~{.sz)-.(-<.0.3*{:sz){.cols rows=: (#cols){.rows live=: }.live,<(scale*cols,.rows),.?(#cols)##junk for_p. live do. gltextcolor glrgb p_index{heat if.p_index=<:#live do. glfont font,' bold' end. for_xyj.;p do. gltextxy 2{.xyj gltext 8 u:junk{~{:xyj end. end. glpaint'' keep=: rows<{:sz-1 cols=: keep#cols rows=: keep#rows+1 EMPTY }} sys_timer_z_=: update_base_   wd rplc&('DIMS';":scale*sz) {{)n pc rain closeok; setp wh DIMS; cc green isidraw flush; pshow; timer 100 }}
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
#EasyLang
EasyLang
col[] = [ 802 990 171 229 950 808 ] len code[] 4 len guess[] 4 # subr init_vars row = 7 . func draw_rate r black white . . for j range 2 for c range 2 move c * 3.5 + 71.5 r * 11.5 + 10.4 + j * 3.5 if black > 0 color 000 circle 1.4 black -= 1 elif white > 0 color 999 circle 1.4 white -= 1 else color 310 circle 0.7 . . . . func show_code . . color 531 move 22 0 rect 46 8 for i range 4 move i * 8 + 28 3 color col[code[i]] circle 2 . . func draw_guess . . for c range 4 move c * 12 + 20 row * 11.5 + 12 color col[guess[c]] circle 3.8 . . func next_row . . color 420 linewidth 11 move 17 row * 11.5 + 12 line 60 row * 11.5 + 12 call draw_guess move 73.5 row * 11.5 + 12 color 310 circle 5.0 color 753 move 71.5 row * 11.5 + 8.5 textsize 7 text "✓" . func rate . . move 73.5 row * 11.5 + 12 color 531 circle 5.2 c[] = code[] g[] = guess[] for i range 4 if c[i] = g[i] black += 1 c[i] = -1 g[i] = -2 . . for i range 4 for j range 4 if c[i] = g[j] white += 1 c[i] = -1 g[j] = -2 . . . call draw_rate row black white color 531 linewidth 12 move 17 row * 11.5 + 12 line 60 row * 11.5 + 12 call draw_guess row -= 1 if black = 4 row = -1 . if row = -1 call show_code timer 2 else call next_row . . on timer row = -2 . func new . . call init_vars for i range 4 code[i] = random 6 . color 531 move 10 10 rect 70 80 linewidth 10 move 5 5 line 5 95 line 85 95 line 85 5 line 5 5 color 310 linewidth 7 move 28 3.5 line 58 3.5 move 30 1.5 color 864 textsize 4 text "Mastermind" color 310 linewidth 0.5 move 10 10 line 10 96 move 67 10 line 67 96 move 80 10 line 80 96 for r range 8 for c range 4 move c * 12 + 20 r * 11.5 + 12 circle 2 . call draw_rate r 0 0 . guess[0] = 0 guess[1] = 0 guess[2] = 1 guess[3] = 1 call next_row . func do_move . . c = (mouse_x - 15) div 12 guess[c] = (guess[c] + 1) mod 6 call draw_guess . on mouse_down if row = -2 call new elif mouse_y > row * 11.5 + 7 and mouse_y < row * 11.5 + 17 and row >= 0 if mouse_x > 15 and mouse_x < 61 call do_move elif mouse_x > 67 and mouse_x < 80 call rate . . . call new
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
#FreeBASIC
FreeBASIC
'--- Declaration of global variables --- Dim As String colors(1 To 4) => {"A", "B", "C", "D"} Dim Shared As Integer nr, ub', numlet=4, lencod=4 Dim Shared As String*4 master, pz ub = Ubound(colors) nr = 0   '--- SUBroutines and FUNCtions --- Sub Encabezado Dim As String dup Color 11: Print "Welcome to Mastermind" Print "=====================" + Chr(13) + Chr(10) : Color 15 Print "You will need to guess a random code." Print "For each guess, you will receive a hint:" Print "X - denotes a correct letter," Print "O - denotes a letter in the original" Print " string but a different position." Print "You have 12 attempts." Print "Duplicates are not allowed." + Chr(10) Print "Good luck!" + Chr(10) + Chr(10) : Color 7 End Sub   Sub showresult(test() As String, place1 As Byte, place2 As Byte, place3 As Byte) Dim As Integer r, n1, n2, n3 Print Using "##: "; nr; For r = 1 To Ubound(test) Print test(r); Next R Print "  : "; For n1 = 1 To place1 Print "X"; " "; Next N1 For n2 = 1 To place2 Print "O"; " "; Next N2 For n3 = 1 To place3 Print "-"; " "; Next N3 Print : Print End Sub   Sub Inicio Dim As Integer mind(ub), rands(ub) Dim As Integer n, aleat Dim As Boolean repeat = false   For n = 1 To ub While true aleat = (Rnd * (ub-1)) + 1 If rands(aleat) <> 1 Then mind(n) = aleat rands(aleat) = 1 Exit While End If Wend Next n   For n = 1 To ub Mid(master,n,1) = Chr(64 + mind(n)) pz &= Chr(64 + mind(n)) Next n End Sub     '--- Main Program --- Randomize Timer Cls Dim As Integer guesses = 12 Encabezado Inicio Color 15: Print pz : Color 7 Do Dim As Integer n, p, d, x, posic Dim As Integer places(1 To 2), place1, place2, place3 Dim As String*4 testbegin Dim As String test(ub), mastertemp, tmp Dim As Boolean flag = True   For p = 1 To Ubound(places) places(p) = 0 Next p nr += 1 Input "Your guess (ABCD)? " , testbegin For d = 1 To Ubound(test) test(d) = Mid(testbegin,d,1) Next d   For n = 1 To Ubound(test) If Ucase(test(n)) <> Mid(master,n,1) Then flag = False Next n If flag = True Then Color 10: Print !"\nWell done! You guess correctly." : Sleep : Exit Do Else For x = 1 To Len(master) If Ucase(test(x)) = Mid(master,x,1) Then places(1) += 1 Next x mastertemp = master For p = 1 To Ubound(test) posic = Instr(mastertemp, Ucase(test(p))) If posic > 0 Then tmp = mastertemp mastertemp = Left(tmp,posic-1) + Mid(tmp, posic+1, Len(tmp)-1) places(2) += 1 End If Next p End If place1 = places(1) place2 = places(2) - place1 place3 = Len(master) - (place1 + place2) showresult(test(), place1, place2, place3) Loop Until nr = guesses Color 14: Print "The correct combination was: "; pz Color 7: Print !"\nEnd of game" Sleep
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.
#jq
jq
# Input: array of dimensions # output: {m, s} def optimalMatrixChainOrder: . as $dims | (($dims|length) - 1) as $n | reduce range(1; $n) as $len ({m: [], s: []}; reduce range(0; $n-$len) as $i (.; ($i + $len) as $j | .m[$i][$j] = infinite | reduce range($i; $j) as $k (.; ($dims[$i] * $dims [$k + 1] * $dims[$j + 1]) as $temp | (.m[$i][$k] + .m[$k + 1][$j] + $temp) as $cost | if $cost < .m[$i][$j] then .m[$i][$j] = $cost | .s[$i][$j] = $k else . end ) )) ;   # input: {s} def printOptimalChainOrder($i; $j): if $i == $j then [$i + 65] | implode #=> "A", "B", ... else "(" + printOptimalChainOrder($i; .s[$i][$j]) + printOptimalChainOrder(.s[$i][$j] + 1; $j) + ")" end;   def dimsList: [ [5, 6, 3, 1], [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] ];   dimsList[] | "Dims  : \(.)", (optimalMatrixChainOrder | "Order : \(printOptimalChainOrder(0; .s|length - 1))", "Cost  : \(.m[0][.s|length - 1])\n" )
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.
#Julia
Julia
module MatrixChainMultiplications   using OffsetArrays   function optim(a) n = length(a) - 1 u = fill!(OffsetArray{Int}(0:n, 0:n), 0) v = fill!(OffsetArray{Int}(0:n, 0:n), typemax(Int)) u[:, 1] .= -1 v[:, 1] .= 0 for j in 2:n, i in 1:n-j+1, k in 1:j-1 c = v[i, k] + v[i+k, j-k] + a[i] * a[i+k] * a[i+j] if c < v[i, j] u[i, j] = k v[i, j] = c end end return v[1, n], aux(u, 1, n) end   function aux(u, i, j) k = u[i, j] if k < 0 return sprint(print, i) else return sprint(print, '(', aux(u, i, k), '×', aux(u, i + k, j - k), ")") end end   end # module MatrixChainMultiplications
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.
#Kotlin
Kotlin
// Version 1.2.31   lateinit var m: List<IntArray> lateinit var s: List<IntArray>   fun optimalMatrixChainOrder(dims: IntArray) { val n = dims.size - 1 m = List(n) { IntArray(n) } s = List(n) { IntArray(n) } for (len in 1 until n) { for (i in 0 until n - len) { val j = i + len m[i][j] = Int.MAX_VALUE for (k in i until j) { val temp = dims[i] * dims [k + 1] * dims[j + 1] val cost = m[i][k] + m[k + 1][j] + temp if (cost < m[i][j]) { m[i][j] = cost s[i][j] = k } } } } }   fun printOptimalChainOrder(i: Int, j: Int) { if (i == j) print("${(i + 65).toChar()}") else { print("(") printOptimalChainOrder(i, s[i][j]) printOptimalChainOrder(s[i][j] + 1, j) print(")") } }   fun main(args: Array<String>) { val dimsList = listOf( intArrayOf(5, 6, 3, 1), intArrayOf(1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2), intArrayOf(1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10) ) for (dims in dimsList) { println("Dims  : ${dims.asList()}") optimalMatrixChainOrder(dims) print("Order : ") printOptimalChainOrder(0, s.size - 1) println("\nCost  : ${m[0][s.size - 1]}\n") } }
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.
#Julia
Julia
""" + +---+---+ | 1 2 3 | +---+ + + | 4 5 | 6 +---+---+---+   julia> const graph = [ 0 1 0 0 0 0; 1 0 1 0 1 0; 0 1 0 0 0 1; 0 0 0 0 1 0; 0 1 0 1 0 0; 0 0 1 0 0 0]   julia> dist, path = dijkstra(graph, 1) (Dict(4=>3,2=>1,3=>2,5=>2,6=>3,1=>0), Dict(4=>5,2=>1,3=>2,5=>2,6=>3,1=>0))   julia> printpath(path, 6) # Display solution of the maze 1 -> 2 -> 3 -> 6   """ function dijkstra(graph, source::Int=1) # ensure that the adjacency matrix is squared @assert size(graph, 1) == size(graph, 2) inf = typemax(Int64) n = size(graph, 1)   Q = IntSet(1:n) # Set of unvisited nodes dist = Dict(n => inf for n in Q) # Unknown distance function from source to v prev = Dict(n => 0 for n in Q) # Previous node in optimal path from source dist[source] = 0 # Distance from source to source   function _minimumdist(nodes) # Find the less distant node among nodes kmin, vmin = nothing, inf for (k, v) in dist if k ∈ nodes && v ≤ vmin kmin, vmin = k, v end end return kmin end # Until all nodes are visited... while !isempty(Q) u = _minimumdist(Q) # Vertex in Q with smallest dist[] pop!(Q, u) if dist[u] == inf break end # All remaining vertices are inaccessible from source for v in 1:n # Each neighbor v of u if graph[u, v] != 0 && v ∈ Q # where v has not yet been visited alt = dist[u] + graph[u, v] if alt < dist[v] # Relax (u, v, a) dist[v] = alt prev[v] = u end end end end   return dist, prev end   function printpath(prev::Dict, target::Int) path = "$target" while prev[target] != 0 target = prev[target] path = "$target -> " * path end println(path) end   const graph = [ 0 1 0 0 0 0; 1 0 1 0 1 0; 0 1 0 0 0 1; 0 0 0 0 1 0; 0 1 0 1 0 0; 0 0 1 0 0 0]   dist, path = dijkstra(graph) printpath(path, 6)
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.
#Go
Go
package main   import ( "fmt" "strconv" "strings" )   const t = ` 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`   func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[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.
#Python
Python
import hashlib print hashlib.new("md4",raw_input().encode('utf-16le')).hexdigest().upper()
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.
#VBScript
VBScript
'http://rosettacode.org/wiki/Middle_three_digits Function mid3n(n) 'Remove the number's sign. n = CStr(Abs(n)) If Len(n) < 3 Or Len(n) Mod 2 = 0 Then mid3n = "Invalid: Either the length of n < 3 or an even number." ElseIf Round(Len(n)/2) > Len(n)/2 Then mid3n = Mid(n,Round(Len(n)/2)-1,3) Else mid3n = Mid(n,Round(Len(n)/2),3) End If End Function   'Calling the function. arrn = Array(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,_ 1,2,-1,-10,2002,-2002,0) For Each n In arrn WScript.StdOut.Write n & ": " & mid3n(n) WScript.StdOut.WriteLine Next
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.
#Emacs_Lisp
Emacs Lisp
(md5 "The quick brown fox jumped over the lazy dog's back") ;=> "e38ca1d920c4b8b8d3946b2c72f01680" (secure-hash 'md5 "The quick brown fox jumped over the lazy dog's back") ;=> "e38ca1d920c4b8b8d3946b2c72f01680"
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).
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (6) BYTE INITIAL ('...',13,10,'$'); DECLARE P ADDRESS, (N, C BASED P) BYTE; P = .S(3); DIGIT: P = P-1; C = N MOD 10 + '0'; N = N/10; IF N>0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   DECLARE (A, B, C) BYTE; DECLARE NUGGET (101) BYTE;   DO A=0 TO 100; NUGGET(A) = 0; END; DO A=0 TO 100 BY 6; DO B=A TO 100 BY 9; DO C=B TO 100 BY 20; NUGGET(C) = -1; END; END; END;   A = 100; DO WHILE NUGGET(A); A = A-1; END; CALL PRINT$NUMBER(A); CALL EXIT; EOF
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).
#PowerShell
PowerShell
$possible = @{} For ($i=0; $i -lt 18; $i++) { For ($j=0; $j -lt 13; $j++) { For ( $k=0; $k -lt 6; $k++ ) { $possible[ $i*6 + $j*9 + $k*20 ] = $true } } }   For ( $n=100; $n -gt 0; $n-- ) { If ($possible[$n]) { Continue } Else { Break } } Write-Host "Maximum non-McNuggets number is $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]
#PureBasic
PureBasic
#START_X=-4 : #START_Y=2 Dim pl$(5) pl$(0)=" Θ " : pl$(1)=" • " : pl$(2)=" •• " pl$(3)="••• " : pl$(4)="••••" : pl$(5)="‒‒‒‒" If OpenConsole() : EnableGraphicalConsole(1) : Else : End 1 : EndIf   Procedure.s Dec2Mayan(wert.i) result$="" If wert=0 : result$="0;" : EndIf While wert : result$=Str(wert%20)+";"+result$ : wert/20 : Wend ProcedureReturn result$ EndProcedure   Procedure PutMayan(may$) Shared pl$() X=#START_X+6 : Y=#START_Y For i=1 To CountString(may$,";") m=Val(StringField(may$,i,";")) yp=Y+4 If m=0 : ConsoleLocate(X,yp) : Print(pl$(0)) : X+5 : Continue : EndIf While m If m-5>=0 ConsoleLocate(X,yp) : Print(pl$(5)) : yp-1 : m-5 ElseIf m-4>=0 ConsoleLocate(X,yp) : Print(pl$(4)) : yp-1 : m-4 ElseIf m-3>=0 ConsoleLocate(X,yp) : Print(pl$(3)) : yp-1 : m-3 ElseIf m-2>=0 ConsoleLocate(X,yp) : Print(pl$(2)) : yp-1 : m-2 ElseIf m-1>=0 ConsoleLocate(X,yp) : Print(pl$(1)) : yp-1 : m-1 EndIf Wend X+5 Next EndProcedure   Procedure MayanNumerals(may$) X=#START_X : Y=#START_Y m.i=CountString(may$,";") For i=1 To m X+5 ConsoleLocate(X,Y)  : Print("╔════╗") ConsoleLocate(X,Y+1)  : Print("║ ║") ConsoleLocate(X,Y+2)  : Print("║ ║") ConsoleLocate(X,Y+3)  : Print("║ ║") ConsoleLocate(X,Y+4)  : Print("║ ║") ConsoleLocate(X,Y+5)  : Print("╚════╝") Next X=#START_X For i=1 To m X+5 If i<m ConsoleLocate(X+5,Y)  : Print("╦") ConsoleLocate(X+5,Y+5) : Print("╩") EndIf Next PutMayan(may$) EndProcedure   Repeat ConsoleLocate(0,0)  : Print(LSet(" ",60)) ConsoleLocate(0,0)  : Print("MAYAN: ? ") : i$=Input() ClearConsole()  : If i$="" : End : EndIf j$=Dec2Mayan(Val(i$))  : MayanNumerals(j$) ConsoleLocate(0,#START_Y+7) : Print("Dezimal = "+i$) ConsoleLocate(0,#START_Y+8) : Print("Vigesimal= "+j$) ForEver
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Action.21
Action!
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit   DEFINE PTR="CARD"   TYPE Matrix=[ BYTE width,height PTR data] ;INT ARRAY   PROC PrintMatrix(Matrix POINTER m) BYTE i,j INT ARRAY d CHAR ARRAY s(10)   d=m.data FOR j=0 TO m.height-1 DO FOR i=0 TO m.width-1 DO StrI(d(j*m.width+i),s) PrintF("%2S ",s) OD PutE() OD RETURN   PROC Create(MATRIX POINTER m BYTE w,h INT ARRAY a) m.width=w m.height=h m.data=a RETURN   PROC MatrixMul(Matrix POINTER m1,m2,res) BYTE i,j,k INT ARRAY d1,d2,dres,sum   IF m1.width#m2.height THEN Print("Invalid size of matrices for multiplication!") Break() FI d1=m1.data d2=m2.data dres=res.data   res.width=m2.width res.height=m1.height   FOR j=0 TO res.height-1 DO FOR i=0 TO res.width-1 DO sum=0 FOR k=0 TO m1.width-1 DO sum==+d1(k+j*m1.width)*d2(i+k*m2.width) OD dres(j*res.width+i)=sum OD OD RETURN   PROC Main() MATRIX m1,m2,res INT ARRAY d1=[2 1 4 0 1 1], d2=[6 3 65535 0 1 1 0 4 65534 5 0 2], dres(8)   Put(125) PutE() ;clear the screen   Create(m1,3,2,d1) Create(m2,4,3,d2) Create(res,0,0,dres) MatrixMul(m1,m2,res)   PrintMatrix(m1) PutE() PrintE("multiplied by") PutE() PrintMatrix(m2) PutE() PrintE("equals") PutE() PrintMatrix(res) RETURN
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return successfully. Ideally implementations will work equally well cross-platform (on windows, linux, and OS X). It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
#Ada
Ada
with Ada.Command_Line; with Ada.Directories; with Ada.Text_IO;   procedure Make_Directory_Path is begin if Ada.Command_Line.Argument_Count /= 1 then Ada.Text_IO.Put_Line ("Usage: make_directory_path <path/to/dir>"); return; end if;   declare Path : String renames Ada.Command_Line.Argument (1); begin Ada.Directories.Create_Path (Path); end; end Make_Directory_Path;
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return successfully. Ideally implementations will work equally well cross-platform (on windows, linux, and OS X). It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
#Aime
Aime
void mkdirp(text path) { list l; text p, s;   file().b_affix(path).news(l, 0, 0, "/");   for (, s in l) { p = p + s + "/"; trap_q(mkdir, p, 00755); } }   integer main(void) { mkdirp("./path/to/dir");   0; }
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return successfully. Ideally implementations will work equally well cross-platform (on windows, linux, and OS X). It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
#AppleScript
AppleScript
use framework "Foundation" use scripting additions     -- createOrFindDirectoryMay :: Bool -> FilePath -> Maybe IO () on createOrFindDirectoryMay(fp) createDirectoryIfMissingMay(true, fp) end createOrFindDirectoryMay     -- createDirectoryIfMissingMay :: Bool -> FilePath -> Maybe IO () on createDirectoryIfMissingMay(blnParents, fp) if doesPathExist(fp) then nothing("Directory already exists: " & fp) else set e to reference set ca to current application set oPath to (ca's NSString's stringWithString:(fp))'s ¬ stringByStandardizingPath set {bool, nse} to ca's NSFileManager's ¬ defaultManager's createDirectoryAtPath:(oPath) ¬ withIntermediateDirectories:(blnParents) ¬ attributes:(missing value) |error|:(e) if bool then just(fp) else nothing((localizedDescription of nse) as string) end if end if end createDirectoryIfMissingMay   -- TEST ---------------------------------------------------------------------- on run   createOrFindDirectoryMay("~/Desktop/Notes/today")   end run   -- GENERIC FUNCTIONS ---------------------------------------------------------   -- doesPathExist :: FilePath -> IO Bool on doesPathExist(strPath) set ca to current application ca's NSFileManager's defaultManager's ¬ fileExistsAtPath:((ca's NSString's ¬ stringWithString:strPath)'s ¬ stringByStandardizingPath) end doesPathExist   -- just :: a -> Just a on just(x) {nothing:false, just:x} end just   -- nothing :: () -> Nothing on nothing(msg) {nothing:true, msg:msg} end nothing
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Action.21
Action!
DEFINE PTR="CARD"   TYPE Matrix=[ BYTE width,height PTR data] ;BYTE ARRAY   PROC PrintB2(BYTE b) IF b<10 THEN Put(32) FI PrintB(b) RETURN   PROC PrintMatrix(Matrix POINTER m) BYTE i,j BYTE ARRAY d   d=m.data FOR j=0 TO m.height-1 DO FOR i=0 TO m.width-1 DO PrintB2(d(j*m.width+i)) Put(32) OD PutE() OD RETURN   PROC Create(MATRIX POINTER m BYTE w,h BYTE ARRAY a) m.width=w m.height=h m.data=a RETURN   PROC Transpose(Matrix POINTER in,out) BYTE i,j BYTE ARRAY din,dout   din=in.data dout=out.data out.width=in.height out.height=in.width FOR j=0 TO in.height-1 DO FOR i=0 TO in.width-1 DO dout(i*out.width+j)=din(j*in.width+i) OD OD RETURN   PROC Main() MATRIX in,out BYTE ARRAY din(35),dout(35) BYTE i   FOR i=0 TO 34 DO din(i)=i OD Create(in,7,5,din) Create(out,0,0,dout) Transpose(in,out)   PrintE("Input:") PrintMatrix(in) PutE() PrintE("Transpose:") PrintMatrix(out) RETURN
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.
#BBC_BASIC
BBC BASIC
MazeWidth% = 11 MazeHeight% = 9 MazeCell% = 50   VDU 23,22,MazeWidth%*MazeCell%/2+3;MazeHeight%*MazeCell%/2+3;8,16,16,128 VDU 23,23,3;0;0;0; : REM Line thickness PROCgeneratemaze(Maze&(), MazeWidth%, MazeHeight%, MazeCell%) END   DEF PROCgeneratemaze(RETURN m&(), w%, h%, s%) LOCAL x%, y% DIM m&(w%, h%) FOR y% = 0 TO h% LINE 0,y%*s%,w%*s%,y%*s% NEXT FOR x% = 0 TO w% LINE x%*s%,0,x%*s%,h%*s% NEXT GCOL 15 PROCcell(m&(), RND(w%)-1, y% = RND(h%)-1, w%, h%, s%) ENDPROC   DEF PROCcell(m&(), x%, y%, w%, h%, s%) LOCAL i%, p%, q%, r% m&(x%,y%) OR= &40 : REM Mark visited r% = RND(4) FOR i% = r% TO r%+3 CASE i% MOD 4 OF WHEN 0: p% = x%-1 : q% = y% WHEN 1: p% = x%+1 : q% = y% WHEN 2: p% = x% : q% = y%-1 WHEN 3: p% = x% : q% = y%+1 ENDCASE IF p% >= 0 IF p% < w% IF q% >= 0 IF q% < h% IF m&(p%,q%) < &40 THEN IF p% > x% m&(p%,q%) OR= 1 : LINE p%*s%,y%*s%+4,p%*s%,(y%+1)*s%-4 IF q% > y% m&(p%,q%) OR= 2 : LINE x%*s%+4,q%*s%,(x%+1)*s%-4,q%*s% IF x% > p% m&(x%,y%) OR= 1 : LINE x%*s%,y%*s%+4,x%*s%,(y%+1)*s%-4 IF y% > q% m&(x%,y%) OR= 2 : LINE x%*s%+4,y%*s%,(x%+1)*s%-4,y%*s% PROCcell(m&(), p%, q%, w%, h%, s%) ENDIF NEXT 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.
#Fermat
Fermat
  Array a[2,2]; {illustrate with a 2x2 matrix} [a]:=[(2/3, 1/3, 4/5, 1/5)]; [a]^-1; {matrix inverse} [a]^0; {identity matrix} [a]^2; [a]^3; [a]^10;  
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.
#Fortran
Fortran
module matmod implicit none   ! Overloading the ** operator does not work because the compiler cannot ! differentiate between matrix exponentiation and the elementwise raising ! of an array to a power therefore we define a new operator interface operator (.matpow.) module procedure matrix_exp end interface   contains   function matrix_exp(m, n) result (res) real, intent(in) :: m(:,:) integer, intent(in) :: n real :: res(size(m,1),size(m,2)) integer :: i   if(n == 0) then res = 0 do i = 1, size(m,1) res(i,i) = 1 end do return end if   res = m do i = 2, n res = matmul(res, m) end do   end function matrix_exp end module matmod   program Matrix_exponentiation use matmod implicit none   integer, parameter :: n = 3 real, dimension(n,n) :: m1, m2 integer :: i, j   m1 = reshape((/ (i, i = 1, n*n) /), (/ n, n /), order = (/ 2, 1 /))   do i = 0, 4 m2 = m1 .matpow. i do j = 1, size(m2,1) write(*,*) m2(j,:) end do write(*,*) end do   end program Matrix_exponentiation
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#ALGOL_68
ALGOL 68
# maps a real s in the range [ a1, a2 ] to the range [ b1, b2 ] # # there are no checks that s is in the range or that the ranges are valid # PROC map range = ( REAL s, a1, a2, b1, b2 )REAL: b1 + ( ( s - a1 ) * ( b2 - b1 ) ) / ( a2 - a1 );   # test the mapping # FOR i FROM 0 TO 10 DO print( ( whole( i, -2 ), " maps to ", fixed( map range( i, 0, 10, -1, 0 ), -8, 2 ), newline ) ) OD
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\displaystyle t}   in range   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]}   where:   t = b 1 + ( s − a 1 ) ( b 2 − b 1 ) ( a 2 − a 1 ) {\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}} Task Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0]. Extra credit Show additional idiomatic ways of performing the mapping, using tools available to the language.
#Amazing_Hopper
Amazing Hopper
  double inc = (nHasta - nDesde) / ( nTotal - 1); lista[0] = nDesde; lista[nTotal] = nHasta; for( n=1; n<nTotal; n++){ lista[n] = lista[n-1] + inc; }  
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.
#JavaScript
JavaScript
var tileSize = 20; // a higher fade factor will make the characters fade quicker var fadeFactor = 0.05;   var canvas; var ctx;   var columns = []; var maxStackHeight;   function init() { canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d');   // https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver const resizeObserver = new ResizeObserver(entries => { for (let entry of entries) { if (entry.contentBoxSize) { // Firefox implements `contentBoxSize` as a single content rect, rather than an array const contentBoxSize = Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0] : entry.contentBoxSize;   canvas.width = contentBoxSize.inlineSize; canvas.height = window.innerHeight;   initMatrix(); } } });   // observe the size of the document resizeObserver.observe(document.documentElement);   // start the main loop tick(); }   function initMatrix() { columns = [];   maxStackHeight = Math.ceil(canvas.height/tileSize);   // divide the canvas into columns for (let i = 0 ; i < canvas.width/tileSize ; ++i) { var column = {}; // save the x position of the column column.x = i*tileSize; // create a random stack height for the column column.stackHeight = 10+Math.random()*maxStackHeight; // add a counter to count the stack height column.stackCounter = 0; // add the column to the list columns.push(column); } }   function draw() { // draw a semi transparent black rectangle on top of the scene to slowly fade older characters ctx.fillStyle = "rgba(0 , 0 , 0 , "+fadeFactor+")"; ctx.fillRect(0 , 0 , canvas.width , canvas.height);   ctx.font = (tileSize-2)+"px monospace"; ctx.fillStyle = "rgb(0 , 255 , 0)"; for (let i = 0 ; i < columns.length ; ++i) { // pick a random ascii character (change the 94 to a higher number to include more characters) var randomCharacter = String.fromCharCode(33+Math.floor(Math.random()*94)); ctx.fillText(randomCharacter , columns[i].x , columns[i].stackCounter*tileSize+tileSize);   // if the stack is at its height limit, pick a new random height and reset the counter if (++columns[i].stackCounter >= columns[i].stackHeight) { columns[i].stackHeight = 10+Math.random()*maxStackHeight; columns[i].stackCounter = 0; } } }   // MAIN LOOP function tick() { draw(); setTimeout(tick , 50); }   var b_isFullscreen = false;   function fullscreen() { var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); // Safari } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); // IE11 } }   function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); // Safari } else if (document.msExitFullscreen) { document.msExitFullscreen(); // IE11 } }   function toggleFullscreen() { if (!b_isFullscreen) { fullscreen(); b_isFullscreen = true; } else { exitFullscreen(); b_isFullscreen = false; } }   function updateTileSize() { tileSize = Math.min(Math.max(document.getElementById("tileSize").value , 10) , 100); initMatrix(); }   function updateFadeFactor() { fadeFactor = Math.min(Math.max(document.getElementById("fadeFactor").value , 0.0) , 1.0); initMatrix(); }
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
#Go
Go
package main   import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" )   func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse()   rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } }   type mastermind struct { colours int holes int guesses int unique bool   code string past []string // history of guesses scores []string // history of scores }   func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") }   return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil }   func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil }   const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------"   func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) }   func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d:  %s : %s\n", i+1, g, m.scores[i]) } }   func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) //log.Printf("code is %q", m.code) }   func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } }   func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true }   func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return }   func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
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.
#Lua
Lua
-- Matrix A[i] has dimension dims[i-1] x dims[i] for i = 1..n local function MatrixChainOrder(dims) local m = {} local s = {} local n = #dims - 1; -- m[i,j] = Minimum number of scalar multiplications (i.e., cost) -- needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] -- The cost is zero when multiplying one matrix for i = 1,n do m[i] = {} m[i][i] = 0 s[i] = {} end   for len = 2,n do -- Subsequence lengths for i = 1,(n - len + 1) do local j = i + len - 1 m[i][j] = math.maxinteger for k = i,(j - 1) do local cost = m[i][k] + m[k+1][j] + dims[i]*dims[k+1]*dims[j+1]; if (cost < m[i][j]) then m[i][j] = cost; s[i][j] = k; --Index of the subsequence split that achieved minimal cost end end end end return m,s end   local function printOptimalChainOrder(s) local function find_path(start,finish) local chainOrder = "" if (start == finish) then chainOrder = chainOrder .."A"..start else chainOrder = chainOrder .."(" .. find_path(start,s[start][finish]) .. find_path(s[start][finish]+1,finish) .. ")" end return chainOrder end print("Order : "..find_path(1,#s)) end   local dimsList = {{5, 6, 3, 1},{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}}   for k,dim in ipairs(dimsList) do io.write("Dims  : [") for v=1,(#dim-1) do io.write(dim[v]..", ") end print(dim[#dim].."]") local m,s = MatrixChainOrder(dim) printOptimalChainOrder(s) print("Cost  : "..tostring(m[1][#s]).."\n") end
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.
#Kotlin
Kotlin
// Version 1.2.31   import java.io.File   typealias Maze = List<CharArray>   /** * Makes the maze half as wide (i. e. "+---+" becomes "+-+"), so that * each cell in the maze is the same size horizontally as vertically. * (Versus the expanded version, which looks better visually.) * Also, converts each line of the maze from a String to a * char[], because we'll want mutability when drawing the solution later. */ fun decimateHorizontally(lines: List<String>): Maze { val width = (lines[0].length + 1) / 2 val c = List(lines.size) { CharArray(width) } for (i in 0 until lines.size) { for (j in 0 until width) c[i][j] = lines[i][j * 2] } return c }   /** * Given the maze, the x and y coordinates (which must be odd), * and the direction we came from, return true if the maze is * solvable, and draw the solution if so. */ fun solveMazeRecursively(maze: Maze, x: Int, y: Int, d: Int): Boolean { var ok = false var i = 0 while (i < 4 && !ok) { if (i != d) { // 0 = up, 1 = right, 2 = down, 3 = left when(i) { 0 -> if (maze[y - 1][x] == ' ') ok = solveMazeRecursively (maze, x, y - 2, 2) 1 -> if (maze[y][x + 1] == ' ') ok = solveMazeRecursively (maze, x + 2, y, 3) 2 -> if (maze[y + 1][x] == ' ') ok = solveMazeRecursively (maze, x, y + 2, 0) 3 -> if (maze[y][x - 1] == ' ') ok = solveMazeRecursively (maze, x - 2, y, 1) else -> {} } } i++ }   // check for end condition if (x == 1 && y == 1) ok = true   // once we have found a solution, draw it as we unwind the recursion if (ok) { maze[y][x] = '*' when (d) { 0 -> maze[y - 1][x] = '*' 1 -> maze[y][x + 1] = '*' 2 -> maze[y + 1][x] = '*' 3 -> maze[y][x - 1] = '*' else -> {} } } return ok }   /** * Solve the maze and draw the solution. For simplicity, * assumes the starting point is the lower right, and the * ending point is the upper left. */ fun solveMaze(maze: Maze) = solveMazeRecursively(maze, maze[0].size - 2, maze.size - 2, -1)   /** * Opposite of decimateHorizontally(). Adds extra characters to make * the maze "look right", and converts each line from char[] to * String at the same time. */ fun expandHorizontally(maze: Maze): Array<String> { val tmp = CharArray(3) val lines = Array<String>(maze.size) { "" } for (i in 0 until maze.size) { val sb = StringBuilder(maze[i].size * 2) for (j in 0 until maze[i].size) { if (j % 2 == 0) sb.append(maze[i][j]) else { for (k in 0..2) tmp[k] = maze[i][j] if (tmp[1] == '*') { tmp[0] = ' ' tmp[2] = ' ' } sb.append(tmp) } } lines[i] = sb.toString() } return lines }   /** * Accepts a maze as generated by: * http://rosettacode.org/wiki/Maze_generation#Kotlin * in a file whose name is specified as a command-line argument. */ fun main(args: Array<String>) { if (args.size != 1) { println("The maze file to be read should be passed as a single command line argument.") return } val f = File(args[0]) if (!f.exists()) { println("Sorry ${args[0]} does not exist.") return } val lines = f.readLines(Charsets.US_ASCII) val maze = decimateHorizontally(lines) solveMaze(maze) val solvedLines = expandHorizontally(maze) println(solvedLines.joinToString("\n")) }
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.
#Haskell
Haskell
parse = map (map read . words) . lines f x y z = x + max y z g xs ys = zipWith3 f xs ys $ tail ys solve = head . foldr1 g main = readFile "triangle.txt" >>= print . solve . parse
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.
#Racket
Racket
  #lang racket (require (planet soegaard/digest:1:2/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.
#Vedit_macro_language
Vedit macro language
do { #1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE) Ins_Text("Input: ") Num_Ins(#1, COUNT, 10) Call("MIDDLE_3_DIGITS") Ins_Text(" Result: ") Reg_Ins(10) Ins_Newline Update() } while (#1); Return   // Find middle 3 digits of a number // in: #1 = numeric value // out: @10 = the result, or error text // :MIDDLE_3_DIGITS: Buf_Switch(Buf_Free) Num_Ins(abs(#1), LEFT+NOCR) // the input value as string #2 = Cur_Col-1 // #2 = number of digits if (#2 < 3) { Reg_Set(10, "Too few digits!") } else { if ((#2 & 1) == 0) { Reg_Set(10, "Not odd number of digits!") } else { Goto_Pos((#2-3)/2) Reg_Copy_Block(10, Cur_Pos, Cur_Pos+3) } } Buf_Quit(OK) Return
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.
#Erlang
Erlang
-module(tests). -export([md5/1]).   md5(S) -> string:to_upper( lists:flatten([io_lib:format("~2.16.0b",[N]) || <<N>> <= erlang:md5(S)]) ).
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).
#Python
Python
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t)     >>> max(nuggets) 43 >>>
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]
#Python
Python
'''Mayan numerals'''   from functools import (reduce)     # -------------------- MAYAN NUMERALS --------------------   # mayanNumerals :: Int -> [[String]] def mayanNumerals(n): '''Rows of Mayan digit cells, representing the integer n. ''' return showIntAtBase(20)( mayanDigit )(n)([])     # mayanDigit :: Int -> [String] def mayanDigit(n): '''List of strings representing a Mayan digit.''' if 0 < n: r = n % 5 return [ (['●' * r] if 0 < r else []) + (['━━'] * (n // 5)) ] else: return ['Θ']     # mayanFramed :: Int -> String def mayanFramed(n): '''Mayan integer in the form of a Wiki table source string. ''' return 'Mayan ' + str(n) + ':\n\n' + ( wikiTable({ 'class': 'wikitable', 'style': cssFromDict({ 'text-align': 'center', 'background-color': '#F0EDDE', 'color': '#605B4B', 'border': '2px solid silver' }), 'colwidth': '3em', 'cell': 'vertical-align: bottom;' })([[ '<br>'.join(col) for col in mayanNumerals(n) ]]) )     # ------------------------- TEST -------------------------   # main :: IO () def main(): '''Mayan numeral representations of various integers''' print( main.__doc__ + ':\n\n' + '\n'.join(mayanFramed(n) for n in [ 4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000 ]) )     # ------------------------ BOXES -------------------------   # wikiTable :: Dict -> [[a]] -> String def wikiTable(opts): '''Source text for wiki-table display of rows of cells, using CSS key-value pairs in the opts dictionary. ''' def colWidth(): return 'width:' + opts['colwidth'] + '; ' if ( 'colwidth' in opts ) else ''   def cellStyle(): return opts['cell'] if 'cell' in opts else ''   return lambda rows: '{| ' + reduce( lambda a, k: ( a + k + '="' + opts[k] + '" ' if ( k in opts ) else a ), ['class', 'style'], '' ) + '\n' + '\n|-\n'.join( '\n'.join( ('|' if ( 0 != i and ('cell' not in opts) ) else ( '|style="' + colWidth() + cellStyle() + '"|' )) + ( str(x) or ' ' ) for x in row ) for i, row in enumerate(rows) ) + '\n|}\n\n'     # ----------------------- GENERIC ------------------------   # cssFromDict :: Dict -> String def cssFromDict(dct): '''CSS string from a dictinary of key-value pairs''' return reduce( lambda a, k: a + k + ':' + dct[k] + '; ', dct.keys(), '' )     # showIntAtBase :: Int -> (Int -> String) # -> Int -> String -> String def showIntAtBase(base): '''String representation of an integer in a given base, using a supplied function for the string representation of digits. ''' def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) )     # MAIN --- if __name__ == '__main__': main()
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;   procedure Matrix_Product is   procedure Put (X : Real_Matrix) is type Fixed is delta 0.01 range -100.0..100.0; begin for I in X'Range (1) loop for J in X'Range (2) loop Put (Fixed'Image (Fixed (X (I, J)))); end loop; New_Line; end loop; end Put;   A : constant Real_Matrix := ( ( 1.0, 1.0, 1.0, 1.0), ( 2.0, 4.0, 8.0, 16.0), ( 3.0, 9.0, 27.0, 81.0), ( 4.0, 16.0, 64.0, 256.0) ); B : constant Real_Matrix := ( ( 4.0, -3.0, 4.0/3.0, -1.0/4.0 ), (-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0), ( 3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0 ), ( -1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0) ); begin Put (A * B); end Matrix_Product;
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return successfully. Ideally implementations will work equally well cross-platform (on windows, linux, and OS X). It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
#Arturo
Arturo
write.directory "path/to/some/directory" ø