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/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,...
#Python
Python
  import math from sys import stdout   LOG_10 = 2.302585092994     # build odd magic square def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 ...
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 .
#B
B
main() { auto cx,cy,x,y,x2,y2; auto iter;   auto xmin,xmax,ymin,ymax,maxiter,dx,dy;   xmin = -8601; xmax = 2867; ymin = -4915; ymax = 4915;   maxiter = 32;   dx = (xmax-xmin)/79; dy = (ymax-ymin)/24;   cy=ymin; while( cy<=ymax ) { cx=xmin; while( cx<=xmax ) { x = 0; y = 0; ...
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#bc
bc
define magic_constant(n) { return(((n * n + 1) / 2) * n) }   define print_magic_square(n) { auto i, x, col, row, len, old_scale   old_scale = scale scale = 0 len = length(n * n)   print "Magic constant for n=", n, ": ", magic_constant(n), "\n" for (row = 1; row <= n; row++) { for (co...
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...
#BCPL
BCPL
get "libhdr"   let cell(n, x, y) = f(n, n-x-1, y)*n + f(n, x, y) + 1 and f(n, x, y) = (x + y*2 + 1) rem n   let magic(n) be $( writef("Magic square of order %N with constant %N:*N", n, (n*n+1)/2*n) for y = 0 to n-1 $( for x = 0 to n-1 do writed(cell(n, x, y), 4) wrch('*N') $) wrch('*N') $)   l...
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.
#Ceylon
Ceylon
alias Matrix => Integer[][];   void printMatrix(Matrix m) { value strings = m.collect((row) => row.collect(Integer.string)); value maxLength = max(expand(strings).map(String.size)) else 0; value padded = strings.collect((row) => row.collect((s) => s.padLeading(maxLength))); for (row in padded) { print("[``", ".jo...
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...
#Go
Go
package main   import ( "fmt" "log" "strings" )   const dimensions int = 8   func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 // 0b10010110011...
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...
#Ela
Ela
open monad io unsafe.cell unsafe.console   liftM2 f m1 m2 = do x1 <- m1 x2 <- m2 return (f x1 x2)   a k x1 x2 x3 x4 x5 = do r <- return $ ref k let b = & do k <- return $ pred (valueof r) a k b x1 x2 x3 x4 if k <= 0 then liftM2 (+) x4 x5 else b   _ = a 10 (!!1) (!! -1) (!! -1) (!!1) (!!0) >>= (...
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Elena
Elena
import extensions;   A(k,x1,x2,x3,x4,x5) { var m := new ref<int>(k);   var b := { m -= 1; ^ A(m,this self,x1,x2,x3,x4) };   if (m <= 0) { ^ x4() + x5() } else { ^ b() } }   public program() { for(int n := 0, n <= 14, n += 1) { console.printLine(A(n,{^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 ...
#zkl
zkl
class GOST{ var [const] // Central Bank of Russian Federation S-Boxes k8=Data(0,Int, 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3), k7=Data(0,Int,14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9), k6=Data(0,Int, 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11), k5=Da...
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...
#Ring
Ring
  load "stdlib.ring" n = -1 sum = 0 magn = []   while sum < 45 n = n + 1 if n < 10 add(magn,n) sum = sum + 1 else nStr = string(n) check = 0 for m = 1 to len(nStr)-1 nr1 = number(left(nStr,m)) nr2 = number(right(nStr,len(nStr)-m...
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...
#Ruby
Ruby
require "prime"   magnanimouses = Enumerator.new do |y| (0..).each {|n| y << n if (1..n.digits.size-1).all? {|k| n.divmod(10**k).sum.prime?} } end   puts "First 45 magnanimous numbers:" puts magnanimouses.first(45).join(' ')   puts "\n241st through 250th magnanimous numbers:" puts magnanimouses.first(250).last(10).jo...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#C.23
C#
using System; using System.Text;   namespace prog { class MainClass { public static void Main (string[] args) { double[,] m = { {1,2,3},{4,5,6},{7,8,9} };   double[,] t = Transpose( m );   for( int i=0; i<t.GetLength(0); i++ ) { for( int j=0; j<t.GetLength(1); j++ ) Console.Write( t[...
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...
#F.23
F#
let rnd : int -> int = let gen = new System.Random() fun max -> gen.Next(max)   // randomly choose an element of a list let choose (xs:_ list) = xs.[rnd xs.Length]   type Maze(width, height) = // (x,y) -> have we been here before? let visited = Array2D.create width height false // (x,y) -> is there a wall bet...
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.
#Perl
Perl
use strict; package SquareMatrix; use Carp; # standard, "it's not my fault" module   use overload ( '""' => \&_string, # overload string operator so we can just print '*' => \&_mult, # multiplication, needed for expo '*=' => \&_mult, # ditto, explicitly ...
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...
#F.23
F#
  let map (a1: float) (a2: float) (b1: float) (b2: float) (s: float): float = b1 + (s - a1) * (b2 - b1) / (a2 - a1)   let xs = [| for i in 0..10 -> map 0.0 10.0 -1.0 0.0 (float i) |]   for x in xs do printfn "%f" x  
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Factor
Factor
USE: locals :: map-range ( a1 a2 b1 b2 x -- y ) x a1 - b2 b1 - * a2 a1 - / b1 + ;
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.
#Tcl
Tcl
oo::define maze { method solve {} { ### Initialization of visited matrix and location/path queue set visited [lrepeat $x [lrepeat $y 0]] set queue {0 0 {}}   ### Loop to do the searching ### while 1 { # Check for running out of path; an error in maze construction if {[llength $queue] == 0} { error ...
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...
#PL.2FI
PL/I
*process source xref attributes or(!); triang: Proc Options(Main); Dcl nn(18,18) Bin Fixed(31); Dcl (rows,i,j) Bin Fixed(31); Dcl (p,k,kn) Bin Fixed(31); Call f_r(1 ,' 55 '); Call f_r(2 ,' 94 48 '); Call f_r(3 ,' ...
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:...
#Jsish
Jsish
/* MD5 hash in Jsish */ var str = 'Rosetta code'; puts(Util.hash(str, {type:'md5'}));   /* MD5 RFC1321 test suite */ function MD5(str) { return Util.hash(str, {type:'md5'}); }   ;MD5(''); ;MD5('a'); ;MD5('abc'); ;MD5('message digest'); ;MD5('abcdefghijklmnopqrstuvwxyz'); ;MD5('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop...
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,...
#R
R
> magic(6) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 35 1 6 26 19 24 [2,] 3 32 7 21 23 25 [3,] 31 9 2 22 27 20 [4,] 8 28 33 17 10 15 [5,] 30 5 34 12 14 16 [6,] 4 36 29 13 18 11
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,...
#Raku
Raku
35 1 6 26 19 24 3 32 7 21 23 25 31 9 2 22 27 20 8 28 33 17 10 15 30 5 34 12 14 16 4 36 29 13 18 11 The magic number is 111
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,...
#Ruby
Ruby
def odd_magic_square(n) n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} } end   def single_even_magic_square(n) raise ArgumentError, "must be even, but not divisible by 4." unless (n-2) % 4 == 0 raise ArgumentError, "2x2 magic square not possible." if n == 2   order = (n-2)/4 odd_squar...
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 .
#BASIC
BASIC
SCREEN 1,320,200,5,1 WINDOW 2,"Mandelbrot",,0,1   maxIteration = 100 xmin = -2 xmax = 1 ymin = -1.5 ymax = 1.5 xs = 300 ys = 180 st = .01 ' use e.g. st = .05 for a coarser but faster picture ' and perhaps also lower maxIteration = 10 or so xp = xs / (xmax - xmin) * st yp = ys / (ymax - ymin) * st   FOR x...
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...
#Befunge
Befunge
500p0>:::00g%00g\-1-\00g/2*+1+00g%00g*\:00g%v @<$<_^#!-*:g00:,+9!%g00:+1.+1+%g00+1+*2/g00\<
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...
#BQN
BQN
Magic ← {𝕏{+´1∾1‿𝕗×𝕨(𝕗|1+⊢+2×⊣)𝕩∾𝕗-𝕩+1}´¨↕2⥊𝕩} Magic¨ ⟨1,3,5,7⟩
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.
#Chapel
Chapel
proc *(a:[], b:[]) {   if (a.eltType != b.eltType) then writeln("type mismatch: ", a.eltType, " ", b.eltType);   var ad = a.domain.dims(); var bd = b.domain.dims(); var (arows, acols) = ad; var (brows, bcols) = bd; if (arows != bcols) then writeln("dimension mismatch: ", ad, " ",...
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...
#Haskell
Haskell
import Data.List (transpose, unfoldr, intercalate) import Data.List.Split (chunksOf) import Data.Bool (bool) import Control.Monad (forM_)   magicSquare :: Int -> [[Int]] magicSquare n | rem n 4 > 0 = [] | otherwise = chunksOf n $ zipWith (flip (bool =<< (-) limit)) series [1 .. sqr] where sqr = n * n ...
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...
#Elixir
Elixir
kounter = fn k, kounter -> receive do {:decr, pid} -> send(pid, k - 1) kounter.(k - 1, kounter) _ -> :ok end end a = fn k, x1, x2, x3, x4, x5, a -> kounter_process = spawn(fn -> kounter.(k, kounter) end) b = fn b -> send(kounter_process, {:decr, self()}) receive do...
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...
#Rust
Rust
fn is_prime(n: u32) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 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...
#Sidef
Sidef
func is_magnanimous(n) { 1..n.ilog10 -> all {|k| sum(divmod(n, k.ipow10)).is_prime } }   say "First 45 magnanimous numbers:" say is_magnanimous.first(45).join(' ')   say "\n241st through 250th magnanimous numbers:" say is_magnanimous.first(250).last(10).join(' ')   say "\n391st through 400th magnanimous...
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...
#Swift
Swift
import Foundation   func isPrime(_ n: Int) -> Bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } var p = 5 while p * p <= n { if n % p == 0 { return false } p += 2 if n % p =...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#C.2B.2B
C++
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp>   int main() { using namespace boost::numeric::ublas;   matrix<double> m(3,3);   for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j;   std::cout << trans(m) << std::endl; }
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...
#Forth
Forth
\ Bit Arrays   : to-bits ( c -- f f f f f f f f ) 8 0 ?do 2 /mod swap negate swap loop drop ;   : from-bits ( f f f f f f f f -- ) 8 0 ?do if [char] 1 emit else [char] 0 emit then loop ;   : byte-bin. ( c -- ) to-bits from-bits space ;   : byte. ( c -- ) dup byte-bin...
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.
#Phix
Phix
with javascript_semantics function identity(integer n) sequence res = repeat(repeat(0,n),n) for i=1 to n do res[i][i] = 1 end for return res end function function matrix_mul(sequence a, b) integer {ha,wa,hb,wb} = apply({a,a[1],b,b[1]},length) if wa!=hb then return 0 end if sequence...
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...
#Fantom
Fantom
  class FRange { const Float low const Float high // in constructing a range, ensure the low value is smaller than high new make (Float low, Float high) { this.low = ( low <= high ? low : high ) this.high = ( low <= high ? high : low ) }   // return range as a string override Str toStr () { "[$l...
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...
#Forth
Forth
\ linear interpolation   : lerp ( b2 b1 a2 a1 s -- t ) fover f- frot frot f- f/ frot frot fswap fover f- frot f* f+ ;   : test 11 0 do 0e -1e 10e 0e i s>f lerp f. loop ;
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.
#Wren
Wren
import "os" for Process import "/ioutil" for File, FileUtil   /* * Makes the maze half as wide (i. e. "+---+" becomes "+-+"), so that * each cell in the maze is the same size horizontally as vertically. * (Versus the expanded version, which looks better visually.) * Also, converts each line of the maze ...
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...
#Prolog
Prolog
max_path(N, V) :- data(N, T), path(0, T, V).   path(_N, [], 0) . path(N, [H | T], V) :- nth0(N, H, V0), N1 is N+1, path(N, T, V1), path(N1, T, V2), V is V0 + max(V1, V2).   data(1, P) :- P = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67]].     data(2, P) :- P = [ [55], [94, 48], [95, 30, 96...
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:...
#Julia
Julia
using Nettle   function Base.trunc(s::AbstractString, n::Integer) n > 0 || throw(DomainError()) l = length(s) l > n || return s n > 3 || return s[1:n] return s[1:n-3] * "..." end   tests = ["" => "d41d8cd98f00b204e9800998ecf8427e", "a" => "0cc175b9c0f1b6a831c399e269772661", "a...
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,...
#Rust
Rust
use std::env;   fn main() { let n: usize = match env::args().nth(1).and_then(|arg| arg.parse().ok()).ok_or( "Please specify the size of the magic square, as a positive multiple of 4 plus 2.", ) { Ok(arg) if arg % 2 == 1 || arg >= 6 && (arg - 2) % 4 == 0 => arg, Er...
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,...
#Stata
Stata
. mata magic(6) 1 2 3 4 5 6 +-------------------------------+ 1 | 35 1 6 26 19 24 | 2 | 3 32 7 21 23 25 | 3 | 31 9 2 22 27 20 | 4 | 8 28 33 17 10 15 | 5 | 30 5 34 12 14 16 | 6 | 4 36 29 13 18 11 | ...
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,...
#Wren
Wren
import "/fmt" for Fmt   var magicSquareOdd = Fn.new { |n| if (n < 3 || n%2 == 0) Fiber.abort("Base must be odd and > 2") var value = 1 var gridSize = n * n var c = (n/2).floor var r = 0 var result = List.filled(n, null) for (i in 0...n) result[i] = List.filled(n, 0) while (value <= gridS...
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 .
#Befunge
Befunge
0>:00p58*`#@_0>:01p78vv$$< @^+1g00,+55_v# !`\+*9<>4v$ @v30p20"?~^"< ^+1g10,+*8<$ @>p0\>\::*::882**02g*0v >^ `*:*" d":+*:-*"[Z"+g3 < |< v-*"[Z"+g30*g20**288\--\<# >2**5#>8*:*/00g"P"*58*:*v^ v*288 p20/**288:+*"[Z"+-<: >*%03 p58*:*/01g"3"* v>::^ \_^#!:-1\+-*2*:*85<^  
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...
#C
C
#include <stdio.h> #include <stdlib.h>   int f(int n, int x, int y) { return (x + y*2 + 1)%n; }   int main(int argc, char **argv) { int i, j, n;   //Edit: Add argument checking if(argc!=2) return 1;   //Edit: Input must be odd and not less than 3. n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2;   for (i =...
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.
#Clojure
Clojure
  (defn transpose [s] (apply map vector s))   (defn nested-for [f x y] (map (fn [a] (map (fn [b] (f a b)) y)) x))   (defn matrix-mult [a b] (nested-for (fn [x y] (reduce + (map * x y))) a (transpose b)))   (def ma [[1 1 1 1] [2 4 8 16] [3 9 27 81] [4 16 64 256]]) (def mb [[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...
#J
J
  masksq=: >:@#@, | _1&^ * 1 + i.@$ pat4=: ,:(+.|.)=i.4 mask=: ,/@(,./"3@$&pat4)@] ,~ % 4: demsq=: masksq@mask  
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...
#Java
Java
public class MagicSquareDoublyEven {   public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant:...
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...
#Erlang
Erlang
kloop(K) -> receive {decr,Pid} -> Pid ! K-1, kloop(K-1); _ -> ok end. a(K, X1, X2, X3, X4, X5) -> Kproc = spawn(fun() -> kloop(K) end), B = fun (B) -> Kproc ! {decr, self()}, receive Kdecr -> a(Kdecr, fun() -> B(B) 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...
#F.23
F#
  [<EntryPoint>] let main (args : string[]) = let k = int(args.[0])   let l x = fun() -> x   let rec a k x1 x2 x3 x4 x5 = if k <= 0 then x4() + x5() else let k = ref k let rec b() = k := !k - 1 a !k b x1 x2 x3 x4 ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System, System.Console   Module Module1   Dim np As Boolean()   Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n ...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Clojure
Clojure
(defmulti matrix-transpose "Switch rows with columns." class)   (defmethod matrix-transpose clojure.lang.PersistentList [mtx] (apply map list mtx))   (defmethod matrix-transpose clojure.lang.PersistentVector [mtx] (apply mapv vector mtx))  
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...
#FreeBASIC
FreeBASIC
' version 04-12-2016 ' compile with: fbc -s console ' when generating a big maze it's possible to run out of stack space ' increase stack with the -t xxxx (xxxx is the amount you want in Kbytes)   ReDim Shared As String d() ' directions ReDim Shared As ULong c() ' cell's   Sub cell(x As ULong, y As ULong, s As ULong) ...
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.
#PicoLisp
PicoLisp
(de matIdent (N) (let L (need N (1) 0) (mapcar '(() (copy (rot L))) L) ) )   (de matExp (Mat N) (let M (matIdent (length Mat)) (do N (setq M (matMul M Mat)) ) M ) )   (matExp '((3 2) (2 1)) 3)
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.
#Python
Python
>>> from operator import mul >>> def matrixMul(m1, m2): return map( lambda row: map( lambda *column: sum(map(mul, row, column)), *m2), m1)   >>> def identity(size): size = range(size) return [[(i==j)*1 for i in size] for j in size]   >>> def matrixExp(m, pow): assert pow>=0 ...
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Fortran
Fortran
program Map implicit none   real :: t integer :: i   do i = 0, 10 t = Maprange((/0.0, 10.0/), (/-1.0, 0.0/), real(i)) write(*,*) i, " maps to ", t end do   contains   function Maprange(a, b, s) real :: Maprange real, intent(in) :: a(2), b(2), s   Maprange = (s-a(1)) * (b(2)-b(1)) / (a(2)-a(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.
#zkl
zkl
ver,hor:=make_maze(); // see above link for this code   fcn munge(a,b){ String(a[0,2],b,a[3,*]) } // "+---" --> "+-*-"   fcn solveMaze(ver,hor, a,b, u,v, w,h){ if (a==u and b==v) return(True);   sh:=hor[b][a]; sv:=ver[b][a]; hor[b][a]=munge(sh,"*"); ver[b][a]=munge(sv,"*"); // drop breadcrumb   foreach d...
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...
#Python
Python
def solve(tri): while len(tri) > 1: t0 = tri.pop() t1 = tri.pop() tri.append([max(t0[i], t0[i+1]) + t for i,t in enumerate(t1)]) return tri[0][0]     data = """ 55 94 48 95 30 96 77 71 26 67 ...
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:...
#Kotlin
Kotlin
// version 1.0.6   import java.security.MessageDigest   fun main(args: Array<String>) { val text = "The quick brown fox jumped over the lazy dog's back" val bytes = text.toByteArray() val md = MessageDigest.getInstance("MD5") val digest = md.digest(bytes) for (byte in digest) print("%02x".format(by...
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,...
#zkl
zkl
class MagicSquareSinglyEven{ fcn init(n){ var result=magicSquareSinglyEven(n) } fcn toString{ sink,n:=Sink(String),result.len(); // num collumns fmt:="%2s "; foreach row in (result) { sink.write(row.apply('wrap(n){ fmt.fmt(n) }).concat(),"\n") } sink.write("\nMagic constant: %d"....
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 .
#Brace
Brace
#!/usr/bin/env bx use b   Main(): num outside = 16, ox = -0.5, oy = 0, r = 1.5 long i, max_i = 100, rb_i = 30 space() uint32_t *px = pixel() num d = 2*r/h, x0 = ox-d*w_2, y0 = oy+d*h_2 for(y, 0, h): cmplx c = x0 + (y0-d*y)*I repeat(w): cmplx w = 0 for i=0; i < max_i && cabs(w) < outside; ++i w = w*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...
#C.2B.2B
C++
  #include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std;   class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); }   void display() { cout << "Odd Magic Square: " << sz << " x...
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Common_Lisp
Common Lisp
(defun matrix-multiply (a b) (flet ((col (mat i) (mapcar #'(lambda (row) (elt row i)) mat)) (row (mat i) (elt mat i))) (loop for row from 0 below (length a) collect (loop for col from 0 below (length (row b 0)) collect (apply #'+ (mapcar #'* (row a row) (col b col)))))))...
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...
#JavaScript
JavaScript
(() => { 'use strict';   // doublyEvenMagicSquare :: Int -> [[Int]] const doublyEvenMagicSquare = n => 0 === n % 4 ? (() => { const sqr = n * n, power = Math.log2(sqr), scale = replicate(n / 4); return chunksOf(n)( ...
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...
#Fantom
Fantom
  class ManOrBoy { Void main() { echo(A(10, |->Int|{1}, |->Int|{-1}, |->Int|{-1}, |->Int|{1}, |->Int|{0})); }   static Int A(Int k, |->Int| x1, |->Int| x2, |->Int| x3, |->Int| x4, |->Int| x5) { |->Int|? b b = |->Int| { k--; return A(k, b, x1, x2, x3, x4) } return k <= 0 ? x4() + x5() : b() }...
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...
#Forth
Forth
: A {: w^ k x1 x2 x3 xt: x4 xt: x5 | w^ B :} recursive k @ 0<= IF x4 x5 f+ ELSE B k x1 x2 x3 action-of x4 [{: B k x1 x2 x3 x4 :}L -1 k +! k @ B @ x1 x2 x3 x4 A ;] dup B ! execute THEN ; 10 [: 1e ;] [: -1e ;] 2dup swap [: 0e ;] A f.
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...
#Wren
Wren
import "/fmt" for Conv, Fmt import "/math" for Int   var isMagnanimous = Fn.new { |n| if (n < 10) return true var p = 10 while (true) { var q = (n/p).floor var r = n % p if (!Int.isPrime(q + r)) return false if (q < 10) break p = p * 10 } return true }   var l...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#CoffeeScript
CoffeeScript
transpose = (matrix) -> (t[i] for t in matrix) for i in [0...matrix[0].length]
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "bytes" "fmt" "math/rand" "time" )   type maze struct { c []byte // cell contents h []byte // horizontal walls above cells v []byte // vertical walls to the left of cells c2 [][]byte // cells by row h2 [][]byte // horizontal walls by row (ignore f...
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.
#R
R
library(Biodem) m <- matrix(c(3,2,2,1), nrow=2) mtx.exp(m, 0) # [,1] [,2] # [1,] 1 0 # [2,] 0 1 mtx.exp(m, 1) # [,1] [,2] # [1,] 3 2 # [2,] 2 1 mtx.exp(m, 2) # [,1] [,2] # [1,] 13 8 # [2,] 8 5 mtx.exp(m, 3) # [,1] [,2] # [1,] 55 34 # [2,] 34 21 mtx.exp(m, 1...
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...
#FreeBASIC
FreeBASIC
Function MapRange(s As Integer, a1 As Integer, a2 As Integer, b1 As Integer, b2 As Integer) As Double Return b1+(s-a1)*(b2-b1)/(a2-a1) End Function   For i As Integer = 0 To 10 Print Using "## maps to ##.#"; i; MapRange(i,0,10,-1,0) Next i Sleep
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...
#Frink
Frink
mapRange[s, a1, a2, b1, b2] := b1 + (s-a1)(b2-b1)/(a2-a1)   for a = 0 to 10 println["$a\t" + mapRange[a, 0, 10, -1, 0]]
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Racket
Racket
#lang racket (require math/number-theory)   (define (trinv n) ; OEIS A002024 (exact-floor (/ (+ 1 (sqrt (* 1 (* 8 n)))) 2)))   (define (triangle-neighbour-bl n) (define row (trinv n)) (+ n (- (triangle-number row) (triangle-number (- row 1)))))   (define (maximum-triangle-path-sum T) (define n-rows (trinv (vect...
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:...
#Lasso
Lasso
Encrypt_MD5('Welcome all Rhinos!') //80ba88ee2600e9e9b36e739458c39ebd
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 .
#Brainf.2A.2A.2A
Brainf***
  A mandelbrot set fractal viewer in brainf*ck written by Erik Bosman +++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[ >>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+ <<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>> >+...
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...
#CLU
CLU
magic_square = cluster is create, unparse, magic_number rep = array[array[int]]   create = proc (order: int) returns (cvt) signals (invalid) if order<1 cor order//2 = 0 then signal invalid end sq: rep := rep$fill_copy(1, order, array[int]$fill(1, order, 0)) x: int := (order+1)/2 ...
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...
#Common_Lisp
Common Lisp
(defun magic-square (n) (loop for i from 1 to n collect (loop for j from 1 to n collect (+ (* n (mod (+ i j (floor n 2) -1) n)) (mod (+ i (* 2 j) -2) n) 1))))   ...
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.
#D
D
import std.stdio, std.string, std.conv, std.numeric, std.array, std.algorithm;   bool isRectangular(T)(in T[][] M) pure nothrow { return M.all!(row => row.length == M[0].length); }   T[][] matrixMul(T)(in T[][] A, in T[][] B) pure nothrow in { assert(A.isRectangular && B.isRectangular && !A.em...
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...
#jq
jq
def lpad($len): def l: tostring | ($len - length) as $l | (" " * $l)[:$l] + .; if type == "array" then map(l) else l end;   def magicSquareDoublyEven: if . < 4 or .%4 != 0 then "Base must be a positive multiple of 4" | error else . end | . as $n # pattern of count-up vs count-down zones | [1,0,0,1,0,1,1,0,0...
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...
#Julia
Julia
using Printf   function magicsquaredoubleeven(order::Int) if order % 4 != 0; error("the order must be divisible by 4") end   sqr = Matrix{Int}(order, order) mul = div(order, 4) ext = vcat(1:mul, order-mul+1:order) isext(i::Int, j::Int) = (i in ext) == (j in ext) boolsqr = collect(isext(i, j) 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...
#Fortran
Fortran
module man_or_boy   implicit none   contains   recursive integer function A(k,x1,x2,x3,x4,x5) result(res) integer, intent(in) :: k interface recursive integer function x1() end function recursive integer function x2() end function recursive integer function x3() end functio...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Common_Lisp
Common Lisp
(defun transpose (m) (apply #'mapcar #'list m))
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Go
Go
package main   import ( "bytes" "fmt" "math/rand" "time" )   type maze struct { c []byte // cell contents h []byte // horizontal walls above cells v []byte // vertical walls to the left of cells c2 [][]byte // cells by row h2 [][]byte // horizontal walls by row (ignore f...
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.
#Racket
Racket
  #lang racket (require math)   (define a (matrix ((3 2) (2 1))))   ;; Using the builtin matrix exponentiation (for ([i 11]) (printf "a^~a = ~s\n" i (matrix-expt a i)))   ;; Output: ;; a^0 = (array #[#[1 0] #[0 1]]) ;; a^1 = (array #[#[3 2] #[2 1]]) ;; a^2 = (array #[#[13 8] #[8 5]]) ;; a^3 = (array #[#[55 34] #[34 2...
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.
#Raku
Raku
subset SqMat of Array where { .elems == all(.[]».elems) }   multi infix:<*>(SqMat $a, SqMat $b) {[ for ^$a -> $r {[ for ^$b[0] -> $c { [+] ($a[$r][] Z* $b[].map: *[$c]) } ]} ]}   multi infix:<**> (SqMat $m, Int $n is copy where { $_ >= 0 }) { my $tmp = $m; my $out = [for ^$m ...
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...
#FutureBasic
FutureBasic
  include "NSLog.incl"   local fn MapRange( s as double, a1 as double, a2 as double, b1 as double, b2 as double ) as double end fn = b1+(s-a1)*(b2-b1)/(a2-a1)   NSInteger i   for i = 0 to 10 NSLog( @"%2d maps to %5.1f", i, fn MapRange( i, 0, 10, -1, 0 ) ) next   HandleEvents  
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...
#GDScript
GDScript
func mapRange(s:float, a1:float, a2:float, b1:float, b2:float) -> float : return b1 + ((b2-b1)/(a2-a1))*(s-a1)   for i in 11 : print( "%2d %+.1f" % [i,mapRange(i,0.0,10.0,-1.0,0.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...
#Raku
Raku
my $triangle = q| 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 ...
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:...
#Liberty_BASIC
Liberty BASIC
'[RC]MD5 'from tsh73's January 2008 code   text$="The quick brown fox jumps over the lazy dog" checkSum$="9e107d9d372bb6826bd81d3542a419d6"   print text$ print checkSum$   test$=md5$(text$)   if test$=checkSum$ then print "passed" print test$ else print "failed" ...
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#C
C
/* c program: -------------------------------- 1. draws Mandelbrot set for Fc(z)=z*z +c using Mandelbrot algorithm ( boolean escape time ) ------------------------------- 2. technique of creating ppm file is based on the code of Claudio Rocchini http://en.wikipedia.org/wiki/Image:Color_complex_plot...
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...
#Cowgol
Cowgol
include "cowgol.coh";   sub magic(n: uint16) is sub f(x: uint16, y: uint16): (r: uint16) is r := (x + y*2 + 1) % n; end sub;   sub cell(x: uint16, y: uint16): (c: uint16) is c := f(n-x-1, y)*n + f(x, y) + 1; end sub;   var y: uint16 := 0; while y < n loop var x: uint16 :=...
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...
#D
D
void main(in string[] args) { import std.stdio, std.conv, std.range, std.algorithm, std.exception;   immutable n = args.length == 2 ? args[1].to!uint : 5; enforce(n > 0 && n % 2 == 1, "Only odd n > 1"); immutable len = text(n ^^ 2).length.text; // writeln(len);   foreach (immutable r; 1 .. n + 1)...
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.
#Delphi
Delphi
  program Matrix_multiplication;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TMatrix = record values: array of array of Double; Rows, Cols: Integer; constructor Create(Rows, Cols: Integer); class operator Multiply(a: TMatrix; b: TMatrix): TMatrix; function ToString: string; end;   { TM...
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...
#Kotlin
Kotlin
// version 1.1.0   fun magicSquareDoublyEven(n: Int): Array<IntArray> { if ( n < 4 || n % 4 != 0) throw IllegalArgumentException("Base must be a positive multiple of 4")   // pattern of count-up vs count-down zones val bits = 0b1001_0110_0110_1001 val size = n * n val mult = n / 4 // how m...
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...
#Go
Go
package main import "fmt"   func a(k int, x1, x2, x3, x4, x5 func() int) int { var b func() int b = func() int { k-- return a(k, b, x1, x2, x3, x4) } if k <= 0 { return x4() + x5() } return b() }   func main() { x := func(i int) func() int { return func() int { return i } } fmt.Println(a(10, x(1), x(-1), ...
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#D
D
void main() { import std.stdio, std.range;   /*immutable*/ auto M = [[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]]; writefln("%(%(%2d %)\n%)", M.transposed); }
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...
#Haskell
Haskell
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-}   import Data.Array.ST (STArray, freeze, newArray, readArray, writeArray) import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef) import System.Random (Random(..), getStdGen, StdGen) import Control.Monad (forM_, unless) import Control.Monad.ST (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.
#Ruby
Ruby
$ irb irb(main):001:0> require 'matrix' => true irb(main):002:0> m=Matrix[[3,2],[2,1]] => Matrix[[3, 2], [2, 1]] irb(main):003:0> m**0 => Matrix[[1, 0], [0, 1]] irb(main):004:0> m ** 1 => Matrix[[3, 2], [2, 1]] irb(main):005:0> m ** 2 => Matrix[[13, 8], [8, 5]] irb(main):006:0> m ** 5 => Matrix[[987, 610], [610, 377]] ...
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.
#Rust
Rust
use std::fmt; use std::ops; const WIDTH: usize = 6;   #[derive(Clone)] struct SqMat { data: Vec<Vec<i64>>, }   impl fmt::Debug for SqMat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut row = "".to_string(); for i in &self.data { for j in i { row +...
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...
#Go
Go
  include "NSLog.incl"   local fn MapRange( s as double, a1 as double, a2 as double, b1 as double, b2 as double ) as double end fn = b1+(s-a1)*(b2-b1)/(a2-a1)   NSInteger i   for i = 0 to 10 NSLog( @"%2d maps to %5.1f", i, fn MapRange( i, 0, 10, -1, 0 ) ) next   HandleEvents  
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...
#Go_2
Go
package main   import "fmt"   type rangeBounds struct { b1, b2 float64 }   func mapRange(x, y rangeBounds, n float64) float64 { return y.b1 + (n - x.b1) * (y.b2 - y.b1) / (x.b2 - x.b1) }   func main() { r1 := rangeBounds{0, 10} r2 := rangeBounds{-1, 0} for n := float64(0); n <= 10; n += 2 { ...