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/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.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Class cArray { a=(,) Function Power(n as integer){ cArr=This ' create a copy dim new() new()=cArr.a ' get a pointer from a to new() Let cArr.a=new() ' now new() return a copy cArr.a*=0 ' make zero all elements link cArr.a to v() for i=dimension(cArr.a,1,0) to dimen...
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.
#Maple
Maple
> M := <<1,2>|<3,4>>; > M ^ 2;
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...
#Delphi
Delphi
  (lib 'plot) ;; interpolation functions (lib 'compile)   ;; rational version (define (q-map-range x xmin xmax ymin ymax) (+ ymin (/ ( * (- x xmin) (- ymax ymin)) (- xmax xmin))))   ;; float version (define (map-range x xmin xmax ymin ymax) (+ ymin (// ( * (- x xmin) (- ymax ymin)) (- xmax xmin)))) ; accelerate it (com...
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.
#Yabasic
Yabasic
open window 640,512,"swiss12" backcolor 0,0,0 clear window mx=50 my=42 dim scr(mx,my) for y=0 to my for x=0 to mx scr(x,y)=int(ran(96)+33) next x next y ms=50 dim sx(ms) dim sy(ms) for a=1 to ms sx(a)=int(ran(mx)) sy(a)=int(ran(my)) next a do for s=1 to ms x=sx(s) y=sy(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.
#zkl
zkl
var [const] codes=Walker.chain( // a bunch of UTF non ascii chars [0x0391..0x03a0], [0x03a3..0x0475], [0x0400..0x0475], [0x048a..0x052f], [0x03e2..0x03ef], [0x2c80..0x2ce9], [0x2200..0x2217], [0x2100..0x213a], [0x2a00..0x2aff]) .apply(fcn(utf){ utf.toString(-8) }), // jeez this is lame ...
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 (...
#SQL
SQL
  -- Create Table -- Distinct combination --- R :Red, B :Blue, G: Green, V: Violet, O: Orange, Y: Yellow DROP TYPE IF EXISTS color cascade;CREATE TYPE color AS ENUM ('R', 'B', 'G', 'V', 'O', 'Y');   DROP TABLE IF EXISTS guesses cascade ; CREATE TABLE guesses ( FIRST color, SECOND col...
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.
#Raku
Raku
constant mapping = :OPEN(' '), :N< ╵ >, :E< ╶ >, :NE< └ >, :S< ╷ >, :NS< │ >, :ES< ┌ >, :NES< ├ >, :W< ╴ >, :NW< ┘ >, :EW< ─ >, :NEW< ┴ >, :SW< ┐ >, :NSW< ┤ >, :ESW< ┬ >, :NESW< ┼ >, :TODO< x >, :TRIED...
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...
#Pascal
Pascal
program TriSum; {'triangle.txt' * one element per line 55 94 48 95 30 96 ...} const cMaxTriHeight = 18; cMaxTriElemCnt = (cMaxTriHeight+1)*cMaxTriHeight DIV 2 +1; type tElem = longint; tbaseRow = array[0..cMaxTriHeight] of tElem; tmyTri = array[0..cMaxTriElemCnt] of tElem;   function ReadTri( fname:stri...
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:...
#Haxe
Haxe
import haxe.crypto.Md5;   class Main { static function main() { var md5 = Md5.encode("The quick brown fox jumped over the lazy dog's back"); Sys.println(md5); } }
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,...
#J
J
  odd =: i:@<.@-: |."0 1&|:^:2 >:@i.@,~ t =: ((*: * i.@4:) +"0 2 odd)@-: l =: (f=:$~ # , #)@((<. , >.)@%&4 # (1: , 0:)) sh =: <:@-: * (bn=:-: # 2:) #: (2: ^ <.@%&4) lm =: sh |."0 1 l rm =: f@bn #: <:@(2: ^ <:@<.@%&4) a =: ((-.@lm * {.@t) + lm * {:@t) b =: ((-.@rm * 1&{@t) + rm * 2&{@t) c =: ((rm * 1&{@t) + -.@rm * 2&...
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,...
#Java
Java
public class MagicSquareSinglyEven {   public static void main(String[] args) { int n = 6; for (int[] row : magicSquareSinglyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant:...
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Amazing_Hopper
Amazing Hopper
  #!/usr/bin/hopper   #include <hopper.h>   main: ancho=500 alto=500 min real=-2 minReal=minreal min complex=-2 max real = 2 max complex = 2   mandel=0,{ancho,alto}nanarray(mandel)   i=1,a2=0,b2=0,a=0,b=0,t1=0,t2=0 {","}toksep tic(t1)   for(i=1,{i} le than (ancho),++i)   for(j=1,{j} le than (alto),++j)   {min...
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Arturo
Arturo
oddMagicSquare: function [n][ ensure -> and? odd? n n >= 0   map 1..n 'i [ map 1..n 'j [ (n * ((i + (j - 1) + n / 2) % n)) + (((i - 2) + 2 * j) % n) + 1 ] ] ]   loop [3 5 7] 'n [ print ["Size:" n ", Magic sum:" n*(1+n*n)/2 "\n"] lo...
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.
#Burlesque
Burlesque
  blsq ) {{1 2}{3 4}{5 6}{7 8}}{{1 2 3}{4 5 6}}mmsp 9 12 15 19 26 33 29 40 51 39 54 69  
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...
#Rust
Rust
use std::fs;   fn main() { fs::create_dir_all("./path/to/dir").expect("An Error Occured!") }
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...
#Scala
Scala
new java.io.File("/path/to/dir").mkdirs
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "cli_cmds.s7i";   const proc: main is func begin doMkdirCmd(argv(PROGRAM), TRUE); end func;
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...
#Sidef
Sidef
Dir.new(Dir.cwd, "path", "to", "dir").make_path; # works cross-platform
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...
#Tcl
Tcl
file mkdir ./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...
#UNIX_Shell
UNIX Shell
function mkdirp() { mkdir -p "$1"; }
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#C.2B.2B
C++
#include <iostream> #include <sstream> #include <iomanip> using namespace std;   class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; }   void display() const { cout << ...
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...
#Delphi
Delphi
type TFunc<T> = reference to function: T;   function C(x: Integer): TFunc<Integer>; begin Result := function: Integer begin Result := x; end; end;   function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer; var b: TFunc<Integer>; begin b := function: Integer begin Dec(k); Result := ...
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 ...
#Racket
Racket
  #lang racket   (define k8 (bytes 14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7)) (define k7 (bytes 15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10)) (define k6 (bytes 10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8)) (define k5 (bytes 7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15)) (define k4 (bytes 2 12 4 1 ...
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 ...
#Raku
Raku
# sboxes from http://en.wikipedia.org/wiki/GOST_(block_cipher) constant sbox = [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, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3], ...
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'is_prime';   sub magnanimous { my($n) = @_; my $last; for my $c (1 .. length($n) - 1) { ++$last and last unless is_prime substr($n,0,$c) + substr($n,$c) } not $last; }   my @M; for ( my $i = 0, my $count = 0; $count < 400; $i++ ) { ...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#BASIC256
BASIC256
arraybase 1 dim matriz= {{78,19,30,12,36}, {49,10,65,42,50}, {30,93,24,78,10}, {39,68,27,64,29}} dim mtranspuesta(matriz[,?], matriz[?,])   for fila = 1 to matriz[?,] for columna = 1 to matriz[,?] print matriz[fila, columna]; " "; mtranspuesta[columna, fila] = matriz[fila, columna] next columna print next fil...
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...
#Elixir
Elixir
defmodule Maze do def generate(w, h) do maze = (for i <- 1..w, j <- 1..h, into: Map.new, do: {{:vis, i, j}, true}) |> walk(:rand.uniform(w), :rand.uniform(h)) print(maze, w, h) maze end   defp walk(map, x, y) do Enum.shuffle( [[x-1,y], [x,y+1], [x+1,y], [x,y-1]] ) |> Enum.reduce(Map...
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = {{3, 2}, {4, 1}}; MatrixPower[a, 0] MatrixPower[a, 1] MatrixPower[a, -1] MatrixPower[a, 4] MatrixPower[a, 1/2] MatrixPower[a, Pi]
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.
#MATLAB
MATLAB
function [output] = matrixexponentiation(matrixA, exponent) output = matrixA^(exponent);
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...
#EchoLisp
EchoLisp
  (lib 'plot) ;; interpolation functions (lib 'compile)   ;; rational version (define (q-map-range x xmin xmax ymin ymax) (+ ymin (/ ( * (- x xmin) (- ymax ymin)) (- xmax xmin))))   ;; float version (define (map-range x xmin xmax ymin ymax) (+ ymin (// ( * (- x xmin) (- ymax ymin)) (- xmax xmin)))) ; accelerate it (com...
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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 CLEAR 61999 20 BORDER 0: POKE 23624,4: POKE 23693,0: CLS: REM easier than "bright 0: flash 0: ink 0: paper 0" 30 PRINT INK 4; FLASH 1;"Initialising": GO SUB 9000: LET m=USR 62000: CLS: REM set up and run machine code; USR is the call function 40 DIM s(32,2): REM current top and bottom of character sequence for each ...
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 (...
#Wren
Wren
import "random" for Random import "/ioutil" for Input import "/str" for Str   var Rand = Random.new()   class Mastermind { construct new(codeLen, colorsCnt, guessCnt, repeatClr) { var color = "ABCDEFGHIJKLMNOPQRST" _codeLen = codeLen.clamp(4, 10) var cl = colorsCnt if (!repeatClr && ...
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.
#Red
Red
Red ["Maze solver"]   do %mazegen.red print [ "start:" start: random size - 1x1 "end:" end: random size - 1x1 ] isnew?: function [pos] [not find visited pos] open?: function [pos d] [ o: pos/y * size/x + pos/x + 1 0 = pick walls/:o d ] expand: function [pos][ either any [ all [pos/x > 0 isnew? p: pos - 1x0 ope...
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...
#Perl
Perl
use 5.10.0; use List::Util 'max';   my @sum; while (<>) { my @x = split; @sum = ($x[0] + $sum[0], map($x[$_] + max(@sum[$_-1, $_]), 1 .. @x-2), $x[-1] + $sum[-1]); }   say max(@sum);
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:...
#Icon_and_Unicon
Icon and Unicon
procedure main() # validate against the RFC test strings and more testMD5("The quick brown fox jumps over the lazy dog", 16r9e107d9d372bb6826bd81d3542a419d6) testMD5("The quick brown fox jumps over the lazy dog.", 16re4d909c290d0fb1ca068ffaddf22cbd0) testMD5("", 16rd41d8cd98f00b204e9800998ecf8427e) end   ...
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,...
#Julia
Julia
function oddmagicsquare(order) if iseven(order) order += 1 end q = zeros(Int, (order, order)) p = 1 i = div(order, 2) + 1 j = 1 while p <= order * order q[i, j] = p ti = (i + 1 > order) ? 1 : i + 1 tj = (j - 1 < 1) ? order : j - 1 if q[ti, tj] != 0 ...
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,...
#Kotlin
Kotlin
// version 1.0.6   fun magicSquareOdd(n: Int): Array<IntArray> { if (n < 3 || n % 2 == 0) throw IllegalArgumentException("Base must be odd and > 2")   var value = 0 val gridSize = n * n var c = n / 2 var r = 0 val result = Array(n) { IntArray(n) } while (++value <= gridSize) { ...
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Arturo
Arturo
inMandelbrot?: function [c][ z: to :complex [0 0] do.times: 50 [ z: c + z*z if 4 < abs z -> return false ] return true ]   mandelbrot: function [settings][ y: 0 while [y < settings\height][ Y: settings\yStart + y * settings\yStep x: 0 while [x < settings\w...
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#AutoHotkey
AutoHotkey
  msgbox % OddMagicSquare(5) msgbox % OddMagicSquare(7) return   OddMagicSquare(oddN){ sq := oddN**2 obj := {} loop % oddN obj[A_Index] := {} ; dis is row mid := Round((oddN+1)/2) sum := Round(sq*(sq+1)/2/oddN) obj[1][mid] := 1 cR := 1 , cC := mid loop % sq-1 { done := 0 , a := A_index+1 while !done { ...
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.
#C
C
#include <stdio.h>   #define MAT_ELEM(rows,cols,r,c) (r*cols+c)   //Improve performance by assuming output matrices do not overlap with //input matrices. If this is C++, use the __restrict extension instead #ifdef __cplusplus typedef double * const __restrict MAT_OUT_t; #else typedef double * const restrict MAT...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() System.IO.Directory.CreateDirectory("some/where") End Sub   End Module
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...
#Wren
Wren
import "io" for FileSystem   class Main { construct new() {}   init() { FileSystem.createDirectory("path/to/dir") }   update() {}   draw(alpha) {} }   var Game = Main.new()
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...
#zkl
zkl
System.cmd("mkdir -p ../foo/bar")
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#D
D
import std.stdio;   void main() { int n=8; foreach(row; magicSquareDoublyEven(n)) { foreach(col; row) { writef("%2s ", col); } writeln; } writeln("\nMagic constant: ", (n*n+1)*n/2); }   int[][] magicSquareDoublyEven(int n) { import std.exception; enforce(n>=4 ...
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...
#Dyalect
Dyalect
func _C(i) { () => i }   func _A(k, x1, x2, x3, x4, x5) { var b b = () => { k -= 1 _A(k, b, x1, x2, x3, x4) } if k <= 0 { x4() + x5() } else { b() } }   for i in 1..20 { let res = _A(i, _C(1), _C(-1), _C(-1), _C(1), _C(0)) print("\(i)\t= \(res)") }
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...
#Dylan
Dylan
define method a (k :: <integer>, x1 :: <function>, x2 :: <function>, x3 :: <function>, x4 :: <function>, x5 :: <function>) => (i :: <integer>)   local b() => (i :: <integer>) k := k - 1; a(k, b, x1, x2, x3, x4) end;   if (k <= 0) x4() + x5() else b() end if   end method a;   defi...
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 ...
#REXX
REXX
/*REXX program implements main step GOST 28147-89 based on a Feistel network. */ numeric digits 12 /* ┌── a list of 4─bit S─box values used by */ /* ↓ the Central Bank of Russian Federation.*/ @.0 = 4 10 9 2 13 ...
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...
#Phix
Phix
with javascript_semantics function magnanimous(integer n) integer p = 1, r = 0 while n>=10 do r += remainder(n,10)*p n = floor(n/10) if not is_prime(n+r) then return false end if p *= 10 end while return true end function sequence mag = {} integer n = 0 while length(ma...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"ARRAYLIB"   DIM matrix(3,4), transpose(4,3) matrix() = 78,19,30,12,36,49,10,65,42,50,30,93,24,78,10,39,68,27,64,29   PROC_transpose(matrix(), transpose())   FOR row% = 0 TO DIM(matrix(),1) FOR col% = 0 TO DIM(matrix(),2) PRINT ;matrix(row%,col%) " "; ...
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...
#Elm
Elm
import Maybe as M import Result as R import Matrix import Mouse import Random exposing (Seed) import Matrix.Random import Time exposing (Time, every, second) import Set exposing (Set, fromList) import List exposing (..) import String exposing (join) import Html exposing (Html, br, input, h1, h2, text, div, button) imp...
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.
#Maxima
Maxima
a: matrix([3, 2], [4, 1])$   a ^^ 4; /* matrix([417, 208], [416, 209]) */   a ^^ -1; /* matrix([-1/5, 2/5], [4/5, -3/5]) */
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.
#Nim
Nim
import sequtils, strutils   type Matrix[N: static int; T] = array[1..N, array[1..N, T]]   func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] = for i in 1..N: for j in 1..N: for k in 1..N: result[i][j] += a[i][k] * b[k][j]     func identityMatrix[N; T](): Matrix[N, T] = for i in 1..N: result[i][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...
#Elixir
Elixir
defmodule RC do def map_range(a1 .. a2, b1 .. b2, s) do b1 + (s - a1) * (b2 - b1) / (a2 - a1) end end   Enum.each(0..10, fn s ->  :io.format "~2w map to ~7.3f~n", [s, RC.map_range(0..10, -1..0, s)] 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...
#Emacs_Lisp
Emacs Lisp
(defun maprange (a1 a2 b1 b2 s) (+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))   (dotimes (i 10) (message "%s" (maprange 0.0 10.0 -1.0 0.0 i)))
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 (...
#zkl
zkl
class MasterMind{ fcn init(code_len,guess_count){ var codeLen =code_len.max(4).min(10); var guessCnt=guess_count.max(7).min(20); var colors ="ABCDEFGHIJKLMNOPQRST"[0,codeLen]; } fcn play{ guesses,win,blackWhite:=List(),False,Void; code:=codeLen.pump(String,'wrap(_){ colors[(0).ra...
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.
#Ruby
Ruby
class Maze # Solve via breadth-first algorithm. # Each queue entry is a path, that is list of coordinates with the # last coordinate being the one that shall be visited next. def solve   # Clean up. reset_visiting_state   # Enqueue start position. @queue = [] enqueue_cell([], @start_x, @star...
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...
#Phix
Phix
with javascript_semantics sequence tri = {{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}, ...
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:...
#Io
Io
Io> MD5 ==> MD5_0x97663e0: appendSeq = MD5_appendSeq() md5 = MD5_md5() md5String = MD5_md5String() Io> MD5 clone appendSeq("The quick brown fox jumped over the lazy dog's back") md5String ==> e38ca1d920c4b8b8d3946b2c72f01680
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,...
#Lua
Lua
import sequtils, strutils   type Square = seq[seq[int]]   func magicSquareOdd(n: Positive): Square = ## Build a magic square of odd order.   assert n >= 3 and (n and 1) != 0, "base must be odd and greater than 2." result = newSeqWith(n, newSeq[int](n))   var r = 0 c = n div 2 value = 0   while val...
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,...
#Nim
Nim
import sequtils, strutils   type Square = seq[seq[int]]   func magicSquareOdd(n: Positive): Square = ## Build a magic square of odd order.   assert n >= 3 and (n and 1) != 0, "base must be odd and greater than 2." result = newSeqWith(n, newSeq[int](n))   var r = 0 c = n div 2 value = 0   while val...
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,...
#Perl
Perl
 
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#AutoHotkey
AutoHotkey
Max_Iteration := 256 Width := Height := 400   File := "MandelBrot." Width ".bmp" Progress, b2 w400 fs9, Creating Colours ... Gosub, CreateColours Gosub, CreateBitmap Progress, Off Gui, -Caption Gui, Margin, 0, 0 Gui, Add, Picture,, %File% Gui, Show,, MandelBrot Return   GuiClose: GuiEscape: ExitApp       ;-------------...
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#AWK
AWK
  # syntax: GAWK -f MAGIC_SQUARES_OF_ODD_ORDER.AWK BEGIN { build(5) build(3,1) # verify sum build(7) exit(0) } function build(n,check, arr,i,width,x,y) { if (n !~ /^[0-9]*[13579]$/ || n < 3) { printf("error: %s is invalid\n",n) return } printf("\nmagic constant for %dx%d is %d\n...
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.
#C.23
C#
public class Matrix { int n; int m; double[,] a;   public Matrix(int n, int m) { if (n <= 0 || m <= 0) throw new ArgumentException("Matrix dimensions must be positive"); this.n = n; this.m = m; a = new double[n, m]; }   //indices start from one public double this[int i, int j] { get { return a[i -...
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#Elena
Elena
import system'routines; import extensions; import extensions'routines;   MagicSquareDoublyEven(int n) { if(n < 4 || n.mod(4) != 0) { InvalidArgumentException.new:"base must be a positive multiple of 4".raise() };   int bits := 09669h; int size := n * n; int mult := n / 4;   var result := Int...
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#Elixir
Elixir
defmodule Magic_square do def doubly_even(n) when rem(n,4)!=0, do: raise ArgumentError, "must be even, but not divisible by 4." def doubly_even(n) do n2 = n * n Enum.zip(1..n2, make_pattern(n)) |> Enum.map(fn {i,p} -> if p, do: i, else: n2 - i + 1 end) |> Enum.chunk(n) |> to_string(n) |> IO....
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
a k x1 x2 x3 x4 x5: local b: set :k -- k a k @b @x1 @x2 @x3 @x4 if <= k 0: + x4 x5 else: b local x i: labda: i   !. a 10 x 1 x -1 x -1 x 1 x 0
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#E
E
def a(var k, &x1, &x2, &x3, &x4, &x5) { def bS; def &b := bS bind bS { to get() { k -= 1 return a(k, &b, &x1, &x2, &x3, &x4) } } return if (k <= 0) { x4 + x5 } else { b } }   def p := 1 def n := -1 def z := 0 println(a(10, &p, &n, &n, &p, &z))
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 ...
#Rust
Rust
use std::convert::TryInto; use std::env; use std::num::Wrapping;   const REPLACEMENT_TABLE: [[u8; 16]; 8] = [ [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, 8, 9, 15...
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 ...
#Tcl
Tcl
namespace eval ::GOST { proc tcl::mathfunc::k {a b} { variable ::GOST::replacementTable lindex $replacementTable $a $b }   proc mainStep {textBlock idx key} { variable replacementTable lassign [lindex $textBlock $idx] N0 N1 set S [expr {($N0 + $key) & 0xFFFFFFFF}] set newS 0 for {set i 0} {$i < 4} {i...
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...
#PicoLisp
PicoLisp
(de **Mod (X Y N) (let M 1 (loop (when (bit? 1 Y) (setq M (% (* M X) N)) ) (T (=0 (setq Y (>> 1 Y))) M ) (setq X (% (* X X) N)) ) ) ) (de isprime (N) (cache '(NIL) N (if (== N 2) T (and (> N 1) (bit? 1 N) ...
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...
#PL.2FM
PL/M
100H: /* FIND SOME MAGNANIMOUS NUMBERS - THOSE WHERE INSERTING '+' BETWEEN */ /* ANY TWO OF THE DIGITS AND EVALUATING THE SUM RESULTS IN A PRIME */ BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */ DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END BDOS; PRINT$CHAR: PROCEDURE( C ); DECLARE...
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...
#Raku
Raku
my @magnanimous = lazy flat ^10, (10 .. 1001).map( { my int $last; (1 ..^ .chars).map: -> \c { $last = 1 and last unless (.substr(0,c) + .substr(c)).is-prime } next if $last; $_ } ),   (1002 .. ∞).map: { # optimization for numbers > 1001; First and last digit can not both be even or both be odd ...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Burlesque
Burlesque
  blsq ) {{78 19 30 12 36}{49 10 65 42 50}{30 93 24 78 10}{39 68 27 64 29}}tpsp 78 49 30 39 19 10 93 68 30 65 24 27 12 42 78 64 36 50 10 29  
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...
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib)   (cl-defstruct maze rows cols data)   (defmacro maze-pt (w r c) `(+ (* (mod ,r (maze-rows ,w)) (maze-cols ,w)) (mod ,c (maze-cols ,w))))   (defmacro maze-ref (w r c) `(aref (maze-data ,w) (maze-pt ,w ,r ,c)))   (defun new-maze (rows cols) (setq rows (1+ rows) cols (1+ cols)) (le...
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.
#OCaml
OCaml
(* identity matrix *) let eye n = let a = Array.make_matrix n n 0.0 in for i=0 to n-1 do a.(i).(i) <- 1.0 done; (a) ;;   (* matrix dimensions *) let dim a = Array.length a, Array.length a.(0);;   (* make matrix from list in row-major order *) let matrix p q v = if (List.length v) <> (p * q) then failwit...
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...
#Erlang
Erlang
-module(map_range). -export([map_value/3]).   map_value({A1,A2},{B1,B2},S) -> B1 + (S - A1) * (B2 - B1) / (A2 - A1).  
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.
#Rust
Rust
use rand::{thread_rng, Rng, rngs::ThreadRng};   const WIDTH: usize = 16; const HEIGHT: usize = 16;   #[derive(Clone, Copy, PartialEq)] struct Cell { col: usize, row: usize, }   impl Cell { fn from(col: usize, row: usize) -> Cell { Cell {col, row} } }   struct Maze { cells: [[bool; HEIGHT]; W...
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...
#Picat
Picat
table (+,+,+,max) pp(Row,_Column,Tri,Sum),Row>Tri.length => Sum=0. pp(Row,Column,Tri,Sum) ?=> pp(Row+1,Column,Tri,Sum1), Sum = Sum1+Tri[Row,Column]. pp(Row,Column,Tri,Sum) => pp(Row+1,Column+1,Tri,Sum1), Sum = Sum1+Tri[Row,Column].
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:...
#J
J
require 'convert/misc/md5' md5 'The quick brown fox jumped over the lazy dog''s back' e38ca1d920c4b8b8d3946b2c72f01680
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,...
#Phix
Phix
with javascript_semantics function swap(sequence s, integer x1, y1, x2, y2) {s[x1,y1],s[x2,y2]} = {s[x2,y2],s[x1,y1]} return s end function function se_magicsq(integer n) if n<6 or mod(n-2,4)!=0 then crash("illegal size (%d)",{n}) end if sequence sq = repeat(repeat(0,n),n) integer ...
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#AWK
AWK
BEGIN { XSize=59; YSize=21; MinIm=-1.0; MaxIm=1.0;MinRe=-2.0; MaxRe=1.0; StepX=(MaxRe-MinRe)/XSize; StepY=(MaxIm-MinIm)/YSize; for(y=0;y<YSize;y++) { Im=MinIm+StepY*y; for(x=0;x<XSize;x++) { Re=MinRe+StepX*x; Zr=Re; Zi=Im; for(n=0;n<30;n++) { a=Zr*Zr; b=Zi*Zi; ...
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#BASIC
BASIC
  100 : 110 REM MAGIC SQUARE OF ODD ORDER 120 : 130 DEF FN MOD(A) = A - INT (A / N) * N 140 DEF FN NR(J) = FN MOD((J + 2 * I + 1)) 200 INPUT "ENTER N: ";N 210 IF N < 3 OR (N - INT (N / 2) * 2) = 0 GOTO 200 220 FOR I = 0 TO (N - 1) 230 FOR J = 0 TO (N - 1): HTAB 4...
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Batch_File
Batch File
@echo off rem Magic squares of odd order setlocal EnableDelayedExpansion set n=9 echo The square order is: %n% for /l %%i in (1,1,%n%) do ( set w= for /l %%j in (1,1,%n%) do ( set /a v1=%%i*2-%%j+n-1 set /a v1=v1%%n*n set /a v2=%%i*2+%%j+n-2 set /a v2=v2%%n set /a v=v1+v2...
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.
#C.2B.2B
C++
#include <iostream> #include <blitz/tinymat.h>   int main() { using namespace blitz;   TinyMatrix<double,3,3> A, B, C;   A = 1, 2, 3, 4, 5, 6, 7, 8, 9;   B = 1, 0, 0, 0, 1, 0, 0, 0, 1;   C = product(A, B);   std::cout << C << std::endl; }
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#Factor
Factor
USING: arrays combinators.short-circuit formatting fry generalizations kernel math math.matrices prettyprint sequences ; IN: rosetta-code.doubly-even-magic-squares   : top? ( loc n -- ? ) [ second ] dip 1/4 * <  ; : bottom? ( loc n -- ? ) [ second ] dip 3/4 * >= ; : left? ( loc n -- ? ) [ first ] dip 1/4 * <  ; :...
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#FreeBASIC
FreeBASIC
' version 18-03-2016 ' compile with: fbc -s console ' doubly even magic square 4, 8, 12, 16...   Sub Err_msg(msg As String) Print msg Beep : Sleep 5000, 1 : Exit Sub End Sub   Sub de_magicsq(n As UInteger, filename As String = "")   ' filename <> "" then save square in a file ' filename can contain dire...
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...
#EchoLisp
EchoLisp
  ;; copied from Scheme (define (A k x1 x2 x3 x4 x5) (define (B) (set! k (- k 1)) (A k B x1 x2 x3 x4)) (if (<= k 0) (+ (x4) (x5)) (B)))   (A 10 (lambda () 1) (lambda () -1) (lambda () -1) (lambda () 1) (lambda () 0)) → -67 (A 13 (lambda () 1) (lambda () -1) (lambda () -1) (lambda () 1) (lambd...
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 ...
#X86_Assembly
X86 Assembly
.386 .model flat .code _gost32 proc near32 public _gost32 ; The inner loop of a subroutine ; 1. Beginning of the cycle, and preservation of the old N1 iloop: mov EBP,EAX ; 2. Adding to the S key modulo 2^32 add EAX,[ESI] ; add the key add ESI,4 ; the n...
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 ...
#Wren
Wren
import "/fmt" for Fmt   class GOST { // assumes 's' is an 8 x 16 integer array construct new(s) { _k87 = List.filled(256, 0) _k65 = List.filled(256, 0) _k43 = List.filled(256, 0) _k21 = List.filled(256, 0) _enc = List.filled(8, 0) for (i in 0..255) { _...
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...
#REXX
REXX
/*REXX pgm finds/displays magnanimous #s (#s with a inserted + sign to sum to a prime).*/ parse arg bet.1 bet.2 bet.3 highP . /*obtain optional arguments from the CL*/ if bet.1=='' | bet.1=="," then bet.1= 1..45 /* " " " " " " */ if bet.2=='' | bet.2=="," then bet.2= 241..250...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#C
C
#include <stdio.h>   void transpose(void *dest, void *src, int src_h, int src_w) { int i, j; double (*d)[src_h] = dest, (*s)[src_w] = src; for (i = 0; i < src_h; i++) for (j = 0; j < src_w; j++) d[j][i] = s[i][j]; }   int main() { int i, j; double a[3][5] = {{ 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 1...
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...
#Erlang
Erlang
  -module( maze ).   -export( [cell_accessible_neighbours/1, cell_content/1, cell_content_set/2, cell_pid/3, cell_position/1, display/1, generation/2, stop/1, task/0] ).   -record( maze, {dict, max_x, max_y, start} ). -record( state, {content=" ", controller, is_dug=false, max_x, max_y, neighbours=[], position, walls=[...
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.
#Octave
Octave
M = [ 3, 2; 2, 1 ]; M^0 M^1 M^2 M^(-1) M^0.5
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.
#PARI.2FGP
PARI/GP
M^n
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#ERRE
ERRE
PROGRAM RANGE   BEGIN AL=0 AH=10 BL=-1 BH=0 FOR N=0 TO 10 DO RANGE=BL+(N-AL)*(BH-BL)/(AH-AL) WRITE("### maps to ##.##";N;RANGE) ! PRINT(N;" maps to ";RANGE) END FOR END PROGRAM  
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...
#Euphoria
Euphoria
function map_range(sequence a, sequence b, atom s) return b[1]+(s-a[1])*(b[2]-b[1])/(a[2]-a[1]) end function   for i = 0 to 10 do printf(1, "%2g maps to %4g\n", {i, map_range({0,10},{-1,0},i)}) end for
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.
#Swift
Swift
enum errors: Error { //Occurs when a start or end position is given that is outside of bounds case IndexOutsideMazeBoundary } ///Used to solve any maze generated by the swift implementation of maze generator at: ///https://www.rosettacode.org/wiki/Maze_generation#Swift class MazeSolver { ///your starting in...
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...
#PicoLisp
PicoLisp
(de maxpath (Lst) (let (Lst (reverse Lst) R (car Lst)) (for I (cdr Lst) (setq R (mapcar + (maplist '((L) (and (cdr L) (max (car L) (cadr L))) ) R ) I ) ) ) (car R) ) )
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:...
#Java
Java
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;   public class Digester {   public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); }   static String hexDigest(String str, String diges...