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/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 succe...
#AWK
AWK
  # syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ... BEGIN { for (i=1; i<=ARGC-1; i++) { path = ARGV[i] msg = (make_dir_path(path) == 0) ? "created" : "exists" printf("'%s' %s\n",path,msg) } exit(0) } function make_dir_path(path, cmd) { # cmd = sprintf("mkdir -p '%s'",path) # Unix c...
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 succe...
#C
C
#include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h>   int main (int argc, char **argv) { char *str, *s; struct stat statBuf;   if (argc != 2) { fprintf (stderr, "usage: %s <path>\n", basename (argv[0])); exit (1); } ...
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Man_Or_Boy is function Zero return Integer is begin return 0; end Zero; function One return Integer is begin return 1; end One; function Neg return Integer is begin return -1; end Neg;   function A ( K : Integer; X1, X2, X3, X4,...
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#BBC_BASIC
BBC BASIC
DIM table&(7,15), test%(1) table&() = 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3, \ \ 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9, \ \ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11, \ \ 7, 13, 10, 1, 0, ...
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#ALGOL_68
ALGOL 68
BEGIN # find some magnanimous numbers - numbers where inserting a + between any # # digits ab=nd evaluatinf the sum results in a prime in all cases # # returns the first n magnanimous numbers # # uses global sieve prime which must include 0 and be large en...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#ActionScript
ActionScript
function transpose( m:Array):Array { //Assume each element in m is an array. (If this were production code, use typeof to be sure)   //Each element in m is a row, so this gets the length of a row in m, //which is the same as the number of rows in m transpose. var mTranspose = new Array(m[0].length); for(var i:uin...
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...
#Befunge
Befunge
45*28*10p00p020p030p006p0>20g30g00g*+::"P"%\"P"/6+gv>$\1v@v1::\+g02+*g00+g03-\< 0_ 1!%4+1\-\0!::\-\2%2:p<pv0<< v0p+6/"P"\%"P":\+4%4<^<v-<$>+2%\1-*20g+\1+4%::v^ #| +2%\1-*30g+\1\40g1-:v0+v2?1#<v>+:00g%!55+*>:#0>#,_^>:!|>\#%"P"v#:*+*g00g0<>1 02!:++`\0\`-1g01:\+`\< !46v3<^$$<^1,g2+1%2/2,g1+1<v%g00:\<*g01,<>:30p\:20p:v^3g ...
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.
#FreeBASIC
FreeBASIC
#include once "matmult.bas" #include once "rowech.bas" #include once "matinv.bas"   operator ^ (byval M as Matrix, byval n as integer ) as Matrix dim as uinteger i, j, k = ubound( M.m, 1 ) if n < 0 then return matinv(M) ^ (-n) if n = 0 then return M * matinv(M) return (M ^ (n-1)) * M end operator   dim ...
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 {\di...
#AppleScript
AppleScript
------------------------ MAP RANGE -----------------------   -- rangeMap :: (Num, Num) -> (Num, Num) -> Num -> Num on rangeMap(a, b) script on |λ|(s) set {a1, a2} to a set {b1, b2} to b b1 + ((s - a1) * (b2 - b1)) / (a2 - a1) end |λ| end script end rangeMap   ...
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.
#Julia
Julia
using Gtk, Colors, Cairo import Base.iterate, Base.IteratorSize, Base.IteratorEltype   const caps = [c for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"] startfall() = rand() < 0.2 endfall() = rand() < 0.2 startblank() = rand() < 0.1 endblank() = rand() < 0.05 bechangingchar() = rand() < 0.03   struct RainChars chars::Vector{Char}...
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.
#Locomotive_Basic
Locomotive Basic
10 mode 0:defint a-z:randomize time:ink 0,0:ink 1,26:ink 2,19:border 0 20 dim p(20):mm=5:dim act(mm):for i=1 to mm:act(i)=rnd*19+1:next 30 md=mm-2:dim del(md):for i=1 to md:del(i)=rnd*19+1:next 40 for i=1 to mm:x=act(i):locate x,p(x)+1:pen 1:print chr$(rnd*55+145); 50 if p(x)>0 then locate x,p(x):pen 2:print chr$(rnd*5...
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 (...
#JavaScript
JavaScript
  class Mastermind { constructor() { this.colorsCnt; this.rptColors; this.codeLen; this.guessCnt; this.guesses; this.code; this.selected; this.game_over; this.clear = (el) => { while (el.hasChildNodes()) { el.removeChild(el.firstChild); } }; this.colors ...
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 whe...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[optim, aux] optim[a_List] := Module[{u, v, n, c, r, s}, n = Length[a] - 1; u = ConstantArray[0, {n, n}]; v = ConstantArray[\[Infinity], {n, n}]; u[[All, 1]] = -1; v[[All, 1]] = 0; Do[ Do[ Do[ c = v[[i, k]] + v[[i + k, j - k]] + a[[i]] a[[i + k]] a[[i + j]]; If[c < v[[i, j]]...
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 whe...
#MATLAB
MATLAB
function [r,s] = optim(a) n = length(a)-1; u = zeros(n,n); v = ones(n,n)*inf; u(:,1) = -1; v(:,1) = 0; for j = 2:n for i = 1:n-j+1 for k = 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; ...
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
HighlightGraph[maze, PathGraph@FindShortestPath[maze, 1, 273]]
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...
#J
J
padTri=: 0 ". ];._2 NB. parse triangle and (implicitly) pad with zeros maxSum=: [: {. (+ (0 ,~ 2 >./\ ]))/ NB. find 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 specifi...
#Raku
Raku
sub md4($str) { my @buf = $str.ords; my $buflen = @buf.elems;   my \mask = (1 +< 32) - 1; my &f = -> $x, $y, $z { ($x +& $y) +| ($x +^ mask) +& $z } my &g = -> $x, $y, $z { ($x +& $y) +| ($x +& $z) +| ($y +& $z) } my &h = -> $x, $y, $z { $x +^ $y +^ $z } my &r = -> $v, $s { (($v +< $s) +& ma...
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;...
#Wart
Wart
def (mid3 n) withs (digits (with outstring # itoa (pr abs.n)) max len.digits mid (int max/2)) if (and odd?.max (max >= 3)) (digits mid-1 mid+2)
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;...
#Wren
Wren
import "/fmt" for Fmt   var middle3 = Fn.new { |n| if (n < 0) n = -n var s = "%(n)" var c = s.count if (c < 3) return "Minimum is 3 digits, only has %(c)." if (c%2 == 0) return "Number of digits must be odd, %(c) is even." if (c == 3) return s var d = (c - 3)/2 return s[d..d+2] }   var a...
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:...
#F.23
F#
let md5ootb (msg: string) = use md5 = System.Security.Cryptography.MD5.Create() msg |> System.Text.Encoding.ASCII.GetBytes |> md5.ComputeHash |> Seq.map (fun c -> c.ToString("X2")) |> Seq.reduce ( + )   md5ootb @"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...
#Quackery
Quackery
0 temp put 100 6 / times [ i 6 * 100 9 / times [ dup i 9 * + 100 20 / times [ dup i 20 * + dup 101 < if [ dup bit temp take | temp put ] drop ] drop ] drop ] -1 temp take 101 times [ dup i bit & 0 = if [ nip ...
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...
#R
R
allInputs <- expand.grid(x = 0:(100 %/% 6), y = 0:(100 %/% 9), z = 0:(100 %/% 20)) mcNuggets <- do.call(function(x, y, z) 6 * x + 9 * y + 20 * z, allInputs)
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 signific...
#Raku
Raku
### Formatting ### 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...
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.
#ALGOL_68
ALGOL 68
MODE FIELD = LONG REAL; # field type is LONG REAL # INT default upb:=3; MODE VECTOR = [default upb]FIELD; MODE MATRIX = [default upb,default upb]FIELD;   # crude exception handling # PROC VOID raise index error := VOID: GOTO exception index error;   # define the vector/matrix operators # OP * = (VECTOR a,b)FIELD: ( # b...
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 succe...
#C.23
C#
System.IO.Directory.CreateDirectory(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 succe...
#C.2B.2B
C++
  #include <filesystem> #include <iostream>   namespace fs = std::filesystem;   int main(int argc, char* argv[]) { if(argc != 2) { std::cout << "usage: mkdir <path>\n"; return -1; }   fs::path pathToCreate(argv[1]);   if (fs::exists(pathToCreate)) return 0;   if (fs::create_directories(pathToCreate)) retu...
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 succe...
#Clojure
Clojure
(defn mkdirp [path] (let [dir (java.io.File. path)] (if (.exists dir) true (.mkdirs dir))))
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Aime
Aime
integer F(list l) { l[1]; }   integer eval(list l) { l[0](l); }   integer A(list);   integer B(list l) { A(list(B, l[1] = l[1] - 1, l, l[-5], l[-4], l[-3], l[-2])); }   integer A(list l) { integer x;   if (l[1] < 1) { x = eval(l[-2]) + eval(l[-1]); } else { x = B(l); }   ...
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#ALGOL_60
ALGOL 60
begin real procedure A (k, x1, x2, x3, x4, x5); value k; integer k; real x1, x2, x3, x4, x5; begin real procedure B; begin k:= k - 1; B:= A := A (k, B, x1, x2, x3, x4) end; if k <= 0 then A:= x4 + x5 else B end; outreal (A (10, 1, -1, -1, 1, 0)) end
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#C
C
static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }; static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }; static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }; static ...
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#ALGOL_W
ALGOL W
begin  % find some Magnanimous numbers - numbers where inserting a "+" between  %  % any two of the digits and evaluating the sum results in a prime number %  % implements the sieve of Eratosthenes  % procedure sieve( logical array s ( * ); integer value n ) ; begin ...
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#AWK
AWK
  # syntax: GAWK -f MAGNANIMOUS_NUMBERS.AWK # converted from C BEGIN { magnanimous(1,45) magnanimous(241,250) magnanimous(391,400) exit(0) } function is_magnanimous(n, p,q,r) { if (n < 10) { return(1) } for (p=10; ; p*=10) { q = int(n/p) r = n % p if (!is_prime(q+r)) { return(...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Ada
Ada
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; with Ada.Text_IO; use Ada.Text_IO;   procedure Matrix_Transpose is procedure Put (X : Real_Matrix) is type Fixed is delta 0.01 range -500.0..500.0; begin for I in X'Range (1) loop for J in X'Range (2) loop ...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h>   #define DOUBLE_SPACE 1   #if DOUBLE_SPACE # define SPC " " #else # define SPC " " #endif   wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄";   typedef unsigned char byte; enum { N = 1, S = 2, W = 4, E = 8, V = 16 };   byte **cell...
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.
#GAP
GAP
# Matrix exponentiation is built-in A := [[0 , 1], [1, 1]]; PrintArray(A); # [ [ 0, 1 ], # [ 1, 1 ] ] PrintArray(A^10); # [ [ 34, 55 ], # [ 55, 89 ] ]
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.
#Go
Go
package main   import "fmt"   type vector = []float64 type matrix []vector   func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i ...
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Arturo
Arturo
getMapped: function [a,b,i][ round .to:1 b\0 + ((i - a\0) * (b\1 - b\0))/(a\1 - a\0) ]   rangeA: @[0.0 10.0] rangeB: @[0-1.0 0.0]   loop 0..10 'x [ mapped: getMapped rangeA rangeB to :floating x print [x "maps to" mapped] ]
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 {\di...
#AutoHotkey
AutoHotkey
  mapRange(a1, a2, b1, b2, s) { return b1 + (s-a1)*(b2-b1)/(a2-a1) }   out := "Mapping [0,10] to [-1,0] at intervals of 1:`n"   Loop 11 out .= "f(" A_Index-1 ") = " mapRange(0,10,-1,0,A_Index-1) "`n" MsgBox % out  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SeedRandom[1234]; ClearAll[ColorFunc] chars = RandomSample[Flatten[CharacterRange @@@ Partition[Characters["\[CapitalAlpha]\[CapitalPi]ЀѵҊԯ\:03e2\:03efヲンⲀ⳩\[ForAll]∗℀℺⨀⫿"], 2]]]; charlen = Length[chars]; fadelength = 6; ColorFunc[fade_] := ColorFunc[fade] = Blend[{Black, Green}, fade/fadelength] rows = 30; cols = 50; n...
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 (...
#Julia
Julia
using Gtk, Colors, Cairo, Graphics   struct Guess code::Vector{Color} guess::Vector{Color} hint::Vector{Color} end   function Guess(code, guess) len = length(code) hints = fill(colorant"gray", len) # gray default for (i, g) in enumerate(guess), (j, c) in enumerate(code) if g == c ...
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 (...
#Kotlin
Kotlin
// version 1.2.51   import java.util.Random   val rand = Random()   class Mastermind { private val codeLen: Int private val colorsCnt: Int private var guessCnt = 0 private val repeatClr: Boolean   private val colors: String private var combo = ""   private val guesses = mutableListOf<CharArr...
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 whe...
#Nim
Nim
import sequtils   type Optimizer = object dims: seq[int] m: seq[seq[Natural]] s: seq[seq[Natural]]     proc initOptimizer(dims: openArray[int]): Optimizer = ## Create an optimizer for the given dimensions. Optimizer(dims: @dims)   proc findMatrixChainOrder(opt: var Optimizer) = ## Find the best order for ma...
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 whe...
#Perl
Perl
use strict; use feature 'say';   sub matrix_mult_chaining { my(@dimensions) = @_; my(@cp,@path);   # a matrix never needs to be multiplied with itself, so it has cost 0 $cp[$_][$_] = 0 for keys @dimensions;   my $n = $#dimensions; for my $chain_length (1..$n) { for my $start (0 .. $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.
#Nim
Nim
import random, strutils   type   Direction {.pure.} = enum None, Up, Left, Down, Right   Maze = object cells: seq[string] hwalls: seq[string] vwalls: seq[string]     #################################################################################################### # Maze creation.   func initMaze(rows...
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...
#Java
Java
import java.nio.file.*; import static java.util.Arrays.stream;   public class MaxPathSum {   public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::par...
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 specifi...
#Ruby
Ruby
require 'openssl' puts OpenSSL::Digest::MD4.hexdigest('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;...
#XPL0
XPL0
include c:\cxpl\stdlib;   func Mid3Digits(I); \Return the middle three digits of I int I; int Len, Mid; char S(10); [ItoA(abs(I), S); Len:= StrLen(S); if Len<3 or (Len&1)=0 then return "Must be 3, 5, 7 or 9 digits"; Mid:= Len/2; S:= S + Mid - 1; S(2):= S(2) ! $80; \terminate string return S; \W...
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:...
#Factor
Factor
USING: kernel strings io checksums checksums.md5 ; "The quick brown fox jumps over the lazy dog" md5 checksum-bytes hex-string print
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...
#Racket
Racket
#lang racket (apply max (set->list (for*/fold ((s (list->set (range 1 101)))) ((x (in-range 0 101 20)) (y (in-range x 101 9)) (n (in-range y 101 6))) (set-remove s n))))
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...
#Raku
Raku
sub Mcnugget-number (*@counts) {   return '∞' if 1 < [gcd] @counts;   my $min = min @counts; my @meals; my @min;   for ^Inf -> $a { for 0..$a -> $b { for 0..$b -> $c { ($a, $b, $c).permutations.map: { @meals[ sum $_ Z* @counts ] = True } } } ...
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 signific...
#REXX
REXX
/*REXX program converts decimal numbers to the Mayan numbering system (with cartouches).*/ parse arg $ /*obtain optional arguments from the CL*/ if $='' then $= 4005 8017 326205 886205, /*Not specified? Then use the default.*/ 172037122592320200101 ...
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 signific...
#Ruby
Ruby
numbers = ARGV.map(&:to_i) if numbers.length == 0 puts puts("usage: #{File.basename(__FILE__)} number...") exit end   def maya_print(number) digits5s1s = number.to_s(20).chars.map { |ch| ch.to_i(20) }.map { |dig| dig.divmod(5) } puts(('+----' * digits5s1s.length) + '+') 3.downto(0) do |row| digits5s1s.e...
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.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> main: first matrix=0, second matrix=0,a=-1 {5,2},rand array(a),mulby(10),ceil, cpy(first matrix), puts,{"\n"},puts {2,3},rand array(a),mulby(10),ceil, cpy(second matrix), puts,{"\n"},puts {first matrix,second matrix},mat mul, println exit(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 succe...
#Common_Lisp
Common Lisp
  (ensure-directories-exist "your/path/name")  
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 succe...
#D
D
import std.stdio;   void main() { makeDir("parent/test"); }   /// Manual implementation of what mkdirRecurse in std.file does. void makeDir(string path) out { import std.exception : enforce; import std.file : exists; enforce(path.exists, "Failed to create the requested directory."); } body { import ...
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 succe...
#Delphi
Delphi
  program Make_directory_path;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IOUtils;   const Path1 = '.\folder1\folder2\folder3'; // windows relative path (others OS formats are acepted) Path2 = 'folder4\folder5\folder6';   begin // "ForceDirectories" work with relative path if start with "./" if For...
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#ALGOL_68
ALGOL 68
PROC a = (INT in k, PROC INT xl, x2, x3, x4, x5) INT:( INT k := in k; PROC b = INT: a(k-:=1, b, xl, x2, x3, x4); ( k<=0 | x4 + x5 | b ) );   test:( printf(($gl$,a(10, INT:1, INT:-1, INT:-1, INT:1, INT:0))) )
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#C.2B.2B
C++
UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2) { UINT_64 N; N = N1; N = (N<<32)|N2; return UINT_64(N); }   UINT_32 TGost::ReplaceBlock(UINT_32 x) { register i; UINT_32 res = 0UL; for(i=7;i>=0;i--) { ui4_0 = x>>(i*4); ui4_0 = BS[ui4_0][i]; res = (res<<4)|ui4_0; } ret...
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#D
D
import std.stdio, std.range, std.algorithm;   /// Rotate uint left. uint rol(in uint x, in uint nBits) @safe pure nothrow @nogc { return (x << nBits) | (x >> (32 - nBits)); }   alias Nibble = ubyte; // 4 bits used. alias SBox = immutable Nibble[16][8];   private bool _validateSBox(in SBox data) @safe pure nothrow @...
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#C
C
#include <stdio.h> #include <string.h>   typedef int bool; typedef unsigned long long ull;   #define TRUE 1 #define FALSE 0   /* OK for 'small' numbers. */ bool is_prime(ull n) { ull d; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; d = 5; while (d * d <= n) ...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Agda
Agda
module Matrix where   open import Data.Nat open import Data.Vec   Matrix : (A : Set) → ℕ → ℕ → Set Matrix A m n = Vec (Vec A m) n   transpose : ∀ {A m n} → Matrix A m n → Matrix A n m transpose [] = replicate [] transpose (xs ∷ xss) = zipWith _∷_ xs (transpose xss)   a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ [] b = tra...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Drawing;   namespace MazeGeneration { public static class Extensions { public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng) { var e ...
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.
#Haskell
Haskell
import Data.List (transpose)   (<+>) :: Num a => [a] -> [a] -> [a] (<+>) = zipWith (+)   (<*>) :: Num a => [a] -> [a] -> a (<*>) = (sum .) . zipWith (*)   newtype Mat a = Mat [[a]] deriving (Eq, Show)   instance Num a => Num (Mat a) where negate (Mat x) = Mat $ map (map negate) x Mat x + Mat y ...
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 {\di...
#AWK
AWK
  # syntax: GAWK -f MAP_RANGE.AWK BEGIN { a1 = 0 a2 = 10 b1 = -1 b2 = 0 for (i=a1; i<=a2; i++) { printf("%g maps to %g\n",i,map_range(a1,a2,b1,b2,i)) } exit(0) } function map_range(a1,a2,b1,b2,num) { return b1 + ((num-a1) * (b2-b1) / (a2-a1)) }  
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 {\di...
#Axiom
Axiom
)abbrev package TESTP TestPackage TestPackage(R:Field) : with mapRange: (Segment(R), Segment(R)) -> (R->R) == add mapRange(fromRange, toRange) == (a1,a2,b1,b2) := (lo fromRange,hi fromRange,lo toRange,hi toRange) (x:R):R +-> b1+(x-a1)*(b2-b1)/(a2-a1)
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.
#Nim
Nim
import os, random, sequtils import ncurses   const RowDelay = 40 # In milliseconds.   proc exit() {.noconv.} = endwin() quit QuitSuccess   proc run() =   const Chars = "0123456789" # Characters to randomly appear in the rain sequence.   let stdscr = initscr() noEcho() cursSet(0) startColor() in...
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 (...
#Lua
Lua
  math.randomseed( os.time() ) local black, white, none, code = "X", "O", "-" local colors, codeLen, maxGuess, rept, alpha, opt = 6, 4, 10, false, "ABCDEFGHIJKLMNOPQRST", "" local guesses, results function createCode() code = "" local dic, a = "" for i = 1, colors do dic = dic .. alpha:sub( i, i ) ...
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 whe...
#Phix
Phix
with javascript_semantics function optimal_chain_order(int i, int j, sequence s) if i==j then return i+'A'-1 end if return "("&optimal_chain_order(i,s[i,j],s) &optimal_chain_order(s[i,j]+1,j,s)&")" end function function optimal_matrix_chain_order(sequence dims) integer n = length...
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.
#Perl
Perl
  #!perl use strict; use warnings;   my ($width, $height) = @ARGV; $_ ||= 10 for $width, $height;   my %visited;   my $h_barrier = "+" . ("--+" x $width) . "\n"; my $v_barrier = "|" . (" |" x $width) . "\n"; my @output = ($h_barrier, $v_barrier) x $height; push @output, $h_barrier; my @dx = qw(-1 1 0 0); my @dy = qw(0...
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#JavaScript
JavaScript
  var arr = [ [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,...
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 specifi...
#Rust
Rust
// MD4, based on RFC 1186 and RFC 1320. // // https://www.ietf.org/rfc/rfc1186.txt // https://tools.ietf.org/html/rfc1320 //   use std::fmt::Write; use std::mem;   // Let not(X) denote the bit-wise complement of X. // Let X v Y denote the bit-wise OR of X and Y. // Let X xor Y denote the bit-wise XOR of X and Y. // Let...
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;...
#zkl
zkl
fcn middle(ns){ ns.apply("toString").apply('-("-")) .apply(fcn(n){nl:=n.len(); if(nl<3 or nl.isEven) return(False); n[(nl-3)/2,3] : "%03d".fmt(_) }) } middle(T(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)).println() middle(T(1, 2, -1, -10, 2002, -2002, 0)).println();
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:...
#Forth
Forth
include ffl/md5.fs   \ Create a MD5 variable md1 in the dictionary   md5-create md1   \ Update the variable with data   s" The quick brown fox jumps over the lazy dog" md1 md5-update   \ Finish the MD5 calculation resulting in four unsigned 32 bit words \ on the stack representing the hash value   md1 md5-finish   \ Co...
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...
#REXX
REXX
/*REXX pgm solves the McNuggets problem: the largest McNugget number for given meals. */ parse arg y /*obtain optional arguments from the CL*/ if y='' | y="," then y= 6 9 20 /*Not specified? Then use the defaults*/ say 'The number of McNuggets in the serving siz...
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 signific...
#Rust
Rust
const ONE: &str = "●"; const FIVE: &str = "——"; const ZERO: &str = "Θ";   fn main() { println!("{}", mayan(4005)); println!("{}", mayan(8017)); println!("{}", mayan(326_205)); println!("{}", mayan(886_205)); println!("{}", mayan(69)); println!("{}", mayan(420)); println!("{}", mayan(1_063_71...
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 signific...
#Wren
Wren
import "/fmt" for Conv   var ul = "╔" var uc = "╦" var ur = "╗" var ll = "╚" var lc = "╩" var lr = "╝" var hb = "═" var vb = "║"   var mayan= [ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙" ]   var m0 = " Θ " var m5 = "────"   var dec2vig = Fn.new { |n| Conv.itoa(n, 20).map { |c| Conv.atoi(c, 20) }.toList...
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#11l
11l
-V LOG_10 = 2.302585092994   F build_oms(=s) I s % 2 == 0 s++ V q = [[0] * s] * s V p = 1 V i = s I/ 2 V j = 0   L p <= (s * s) q[i][j] = p V ti = i + 1 I ti >= s ti = 0 V tj = j - 1 I tj < 0 tj = s - 1 I q[ti][tj] != 0 ti = i ...
http://rosettacode.org/wiki/Magic_constant
Magic constant
A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant. EG A 3 x 3 magic square always sums to ...
#ALGOL_68
ALGOL 68
BEGIN # find some magic constants - the row, column and diagonal sums of a magin square # # translation of the Free Basic sample with the Julia/Wren inverse function # # returns the magic constant of a magic square of order n + 2 # PROC a = ( INT n )LONG LONG INT: BEGIN LONG LONG ...
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.
#APL
APL
x ← +.×   A ← ↑A*¨⊂A←⍳4 ⍝ Same A as in other examples (1 1 1 1⍪ 2 4 8 16⍪ 3 9 27 81,[0.5] 4 16 64 256) B ← ⌹A ⍝ Matrix inverse of A   'F6.2' ⎕FMT A x B 1.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 1.00
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 succe...
#Elixir
Elixir
File.mkdir_p("./path/to/dir")
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 succe...
#ERRE
ERRE
OS_MKDIR("C:\EXAMPLES\03192015")
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 succe...
#F.23
F#
> System.IO.Directory.CreateDirectory (System.IO.Directory.GetCurrentDirectory()) ;; val it : System.IO.DirectoryInfo = Temp {Attributes = Directory; CreationTime = 2016-06-01 04:12:25; CreationTimeUtc = 2016-06-01 02:12:25; Exists = true; Extension = ""; FullName = "C:\Users\K...
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 succe...
#Factor
Factor
USE: io.directories "path/to/dir" make-directories
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 succe...
#FreeBASIC
FreeBASIC
#ifdef __FB_WIN32__ Dim pathname As String = "Ring\docs" #else Dim pathname As String = "Ring/docs" #endif   Dim As String mkpathname = "mkdir " & pathname Dim result As Long = Shell (mkpathname)   If result = 0 Then Print "Created the directory..." Chdir(pathname) Print Curdir Else Print "error...
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#ALGOL_W
ALGOL W
begin real procedure A (integer value k; real procedure x1, x2, x3, x4, x5); begin real procedure B; begin k:= k - 1; A (k, B, x1, x2, x3, x4) end; if k <= 0 then x4 + x5 else B end; write (r_format := "A", r_w := 8, r_d := 2, A (10, 1, -1, -1, 1, 0)) end.
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#AppleScript
AppleScript
on a(k, x1, x2, x3, x4, x5) script b set k to k - 1 return a(k, b, x1, x2, x3, x4) end script if k ≤ 0 then return (run x4) + (run x5) else return (run b) end if end a   on int(x) script s return x end script return s end int   a(10, int(1), int(-1), int(-1), int(1), int(0))  
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#FreeBASIC
FreeBASIC
Dim Shared As Ubyte k87(255), k65(255), k43(255), k21(255)   Sub kboxinit() Dim As Ubyte k8(15) = {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7} Dim As Ubyte k7(15) = {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10} Dim As Ubyte k6(15) = {10, 0, 9, 14, 6, 3, 15, 5, 1...
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#C.23
C#
using System; using static System.Console;   class Program {   static bool[] np; // not-prime array   static void ms(long lmt) { // populates array, a not-prime is true np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#ALGOL_68
ALGOL 68
main:(   [,]REAL m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625));   OP ZIP = ([,]REAL in)[,]REAL:( [2 LWB in:2 UPB in,1 LWB in:1UPB in]REAL out; FOR i FROM LWB in TO UPB in DO out[,i]:=in[i,] OD; ...
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...
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 512, CELL_S...
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.
#J
J
mp=: +/ .* NB. Matrix multiplication pow=: pow0=: 4 : 'mp&x^:y =i.#x'
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.
#JavaScript
JavaScript
// IdentityMatrix is a "subclass" of Matrix function IdentityMatrix(n) { this.height = n; this.width = n; this.mtx = []; for (var i = 0; i < n; i++) { this.mtx[i] = []; for (var j = 0; j < n; j++) { this.mtx[i][j] = (i == j ? 1 : 0); } } } IdentityMatrix.prototype...
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 {\di...
#BASIC
BASIC
function MapRange(s, a1, a2, b1, b2) return b1+(s-a1)*(b2-b1)/(a2-a1) end function   for i = 0 to 10 print i; " maps to "; MapRange(i,0,10,-1,0) next i 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 {\di...
#bc
bc
/* map s from [a, b] to [c, d] */ define m(a, b, c, d, s) { return (c + (s - a) * (d - c) / (b - a)) }   scale = 6 /* division to 6 decimal places */ "[0, 10] => [-1, 0] " for (i = 0; i <= 10; i += 2) { /* * If your bc(1) has a print statement, you can try * print i, " => ", m(0, 10, -1, 0, i), "\n" */ ...
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.
#Perl
Perl
#!/user/bin/perl   use strict; use warnings; use Tk;   my $delay = 50; # milliseconds my $fade = 8; # number of characters to "fade" my $base_color = '#004000'; # dark green my $fontname = 'Times'; # Whatever m...
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 (...
#Nim
Nim
import random, sequtils, strformat, strutils   proc encode(correct, guess: string): string = result.setlen(correct.len) for i in 0..correct.high: result[i] = if correct[i] == guess[i]: 'X' else: (if guess[i] in correct: 'O' else: '-') result.join(" ")   proc safeIntInput(prompt: string; minVal, maxVal: Positi...
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 whe...
#Python
Python
def parens(n): def aux(n, k): if n == 1: yield k elif n == 2: yield [k, k + 1] else: a = [] for i in range(1, n): for u in aux(i, k): for v in aux(n - i, k + i): yield [u, v] yield...
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 whe...
#R
R
aux <- function(i, j, u) { k <- u[[i, j]] if (k < 0) { i } else { paste0("(", Recall(i, k, u), "*", Recall(i + k, j - k, u), ")") } }   chain.mul <- function(a) { n <- length(a) - 1 u <- matrix(0, n, n) v <- matrix(0, n, n) u[, 1] <- -1   for (j in seq(2, n)) { for (i in seq(n - j + 1)) { ...
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.
#Phix
Phix
-- -- demo\rosetta\Maze_solving.exw -- ============================= -- with javascript_semantics constant w = 11, h = 8 sequence wall = join(repeat("+",w+1),"---")&"\n", cell = join(repeat("|",w+1)," ? ")&"\n", grid = split(join(repeat(wall,h+1),cell),'\n') procedure amaze(integer x, y) grid[...
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...
#jq
jq
# Usage: TRIANGLE | solve def solve:   # update(next) updates the input row of maxima: def update(next): . as $maxima | [ range(0; next|length) | next[.] + ([$maxima[.], $maxima[. + 1]] | max) ];   . as $in | reduce range(length -2; -1; -1) as $i ($in[-1]; update( $in[$i] ) ) ;