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/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... | #REXX | REXX | /*REXX program finds the maximum sum of a path of numbers in a pyramid of numbers. */
@.=.; @.1 = 55
@.2 = 94 48
@.3 = 95 30 96
@.4 = ... |
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:... | #Lingo | Lingo | put cx_md5_string(str) |
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.23 | C# | using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Windows.Forms;
/// <summary>
/// Generates bitmap of Mandelbrot Set and display it on the form.
/// </summary>
public class MandelbrotSetForm : Form
{
const double MaxValueExtent = 2.0;
Thread thread;
... |
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... | #Delphi | Delphi | proc inc(word n, order) word: if n=order-1 then 0 else n+1 fi corp
proc dec(word n, order) word: if n=0 then order-1 else n-1 fi corp
proc odd_magic_square([*,*]word square) void:
word order, x, nx, y, ny, i;
order := dim(square,1);
for x from 0 upto order-1 do
for y from 0 upto order-1 do
... |
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... | #Draco | Draco | proc inc(word n, order) word: if n=order-1 then 0 else n+1 fi corp
proc dec(word n, order) word: if n=0 then order-1 else n-1 fi corp
proc odd_magic_square([*,*]word square) void:
word order, x, nx, y, ny, i;
order := dim(square,1);
for x from 0 upto order-1 do
for y from 0 upto order-1 do
... |
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.
| #EGL | EGL |
program Matrix_multiplication type BasicProgram {}
function main()
a float[][] = [[1,2,3],[4,5,6]];
b float[][] = [[1,2],[3,4],[5,6]];
c float[][] = mult(a, b);
end
function mult(a float[][], b float[][]) returns(float[][])
if(a.getSize() == 0)
return (new float[0][0]);
end
if(a[1].getSize() != ... |
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... | #Lua | Lua | import bitops, sequtils, strutils
type Square = seq[seq[int]]
func magicSquareDoublyEven(n: int): Square =
## Build a magic square of doubly even order.
assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4."
result = newSeqWith(n, newSeq[int](n))
const bits = 0b1001_0110_0110_1001 #... |
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... | #Nim | Nim | import bitops, sequtils, strutils
type Square = seq[seq[int]]
func magicSquareDoublyEven(n: int): Square =
## Build a magic square of doubly even order.
assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4."
result = newSeqWith(n, newSeq[int](n))
const bits = 0b1001_0110_0110_1001 #... |
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... | #Gosu | Gosu | function A(in_k: int, x1(): int, x2(): int, x3(): int, x4(): int, x5(): int): int {
var k = in_k
var B(): int // B is a function variable
B = \ -> {
k = k-1;
return A(k, B, x1, x2, x3, x4)
}
return k<=0 ? x4()+x5() : B()
}
print(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... | #Groovy | Groovy | def a; a = { k, x1, x2, x3, x4, x5 ->
def b; b = {
a (--k, b, x1, x2, x3, x4)
}
k <= 0 ? x4() + x5() : b()
}
def x = { n -> { it -> n } } |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Delphi | Delphi |
(lib 'matrix)
(define M (list->array (iota 6) 3 2))
(array-print M)
0 1
2 3
4 5
(array-print (matrix-transpose M))
0 2 4
1 3 5
|
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... | #Huginn | Huginn | import Algorithms as algo;
import Mathematics as math;
import Terminal as term;
class Maze {
_rows = none;
_cols = none;
_data = none;
constructor( rows_, cols_ ) {
_rows = ( rows_ / 2 ) * 2 - 1;
_cols = ( cols_ / 2 ) * 2 - 1;
_data = [].resize( _rows + 2, [].resize( _cols + 2, false ) );
x = 0;
y = 0;
... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Scala | Scala | class Matrix[T](matrix:Array[Array[T]])(implicit n: Numeric[T], m: ClassManifest[T])
{
import n._
val rows=matrix.size
val cols=matrix(0).size
def row(i:Int)=matrix(i)
def col(i:Int)=matrix map (_(i))
def *(other: Matrix[T]):Matrix[T] = new Matrix(
Array.tabulate(rows, other.cols)((row, col) =>
... |
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... | #Groovy | Groovy |
def mapRange(a1, a2, b1, b2, s) {
b1 + ((s - a1) * (b2 - b1)) / (a2 - a1)
}
(0..10).each { s ->
println(s + " in [0, 10] maps to " + mapRange(0, 10, -1, 0, s) + " in [-1, 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... | #Haskell | Haskell | import Data.Ratio
import Text.Printf (PrintfType, printf)
-- Map a value from the range [a1,a2] to the range [b1,b2]. We don't check
-- for empty ranges.
mapRange
:: Fractional a
=> (a, a) -> (a, a) -> a -> a
mapRange (a1, a2) (b1, b2) s = b1 + (s - a1) * (b2 - b1) / (a2 - a1)
main :: IO ()
main
-- Perform the... |
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... | #Ring | Ring |
# Project : Maximum triangle path sum
load "stdlib.ring"
ln = list(19)
ln[1] = " 55"
ln[2] = " 94 48"
ln[3] = " 95 30 96"
ln[4] = " 77 71 26 67"
ln[5] = " 97 13 76 38 45"
ln[6] = " 07 36 79 16 37 68"
ln[7] = " 48 07 ... |
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:... | #LiveCode | LiveCode | function md5sum hashtext
local md5, mdhex
put md5Digest(hashtext) into md5
get binaryDecode("H*",md5,mdhex)
return mdhex
end md5sum |
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.2B.2B | C++ | #include <cstdlib>
#include <complex>
// get dimensions for arrays
template<typename ElementType, std::size_t dim1, std::size_t dim2>
std::size_t get_first_dimension(ElementType (&a)[dim1][dim2])
{
return dim1;
}
template<typename ElementType, std::size_t dim1, std::size_t dim2>
std::size_t get_second_dimension... |
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... | #EchoLisp | EchoLisp |
(lib 'matrix)
;; compute next i,j = f(move,i,j)
(define-syntax-rule (path imove jmove)
(begin (set! i (imove i n)) (set! j (jmove j n))))
;; We define the ordinary and break moves
;; (1 , -1), (0, 1) King's move
(define (inext i n) (modulo (1+ i) n))
(define (jnext j n) (modulo (1- j) n))
(define (ibreak i n) 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.
| #Ela | Ela | open list
mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
[[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 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... | #PARI.2FGP | PARI/GP | magicsquare(n)=matrix(n,n,i,j,k=i+j*n-n;if(bitand(38505,2^((j-1)%4*4+(i-1)%4)),k,n*n+1-k)) |
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... | #Perl | Perl | |
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... | #Haskell | Haskell | import Data.IORef (modifyIORef, newIORef, readIORef)
a
:: (Enum a, Num b, Num a, Ord a)
=> a -> IO b -> IO b -> IO b -> IO b -> IO b -> IO b
a k x1 x2 x3 x4 x5 = do
r <- newIORef k
let b = do
k <- pred ! r
a k b x1 x2 x3 x4
if k <= 0
then (+) <$> x4 <*> x5
else b
where
f !r = m... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #EchoLisp | EchoLisp |
(lib 'matrix)
(define M (list->array (iota 6) 3 2))
(array-print M)
0 1
2 3
4 5
(array-print (matrix-transpose M))
0 2 4
1 3 5
|
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... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main(A) # generate rows x col maze
/mh := \A[1] | 12 # or take defaults 12 x 16
/mw := \A[2] | 16
mz := DisplayMaze(GenerateMaze(mh,mw))
WriteImage(mz.filename) # save file
WAttrib(mz.window,"canvas=norm... |
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.
| #Scheme | Scheme |
(define (dec x)
(- x 1))
(define (halve x)
(/ x 2))
(define (row*col row col)
(apply + (map * row col)))
(define (matrix-multiply m1 m2)
(map
(lambda (row)
(apply map (lambda col (row*col row col))
m2))
m1))
(define (matrix-exp mat exp)
(cond ((= exp 1) mat)
((even?... |
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... | #Icon_and_Unicon | Icon and Unicon |
record Range(a, b)
# note, we force 'n' to be real, which means recalculation will
# be using real numbers, not integers
procedure remap (range1, range2, n : real)
if n < range2.a | n > range2.b then fail # n out of given range
return range1.a + (n - range2.a) * (range1.b - range1.a) / (range2.b - range2.a)
en... |
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... | #Ruby | Ruby | triangle =
" 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 4... |
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:... | #Lua | Lua | require "md5"
--printing a sum:
print(md5.sumhexa"The quick brown fox jumps over the lazy dog")
--running the test suite:
local function test(msg,sum) assert(md5.sumhexa(msg)==sum) end
test("","d41d8cd98f00b204e9800998ecf8427e")
test("a","0cc175b9c0f1b6a831c399e269772661")
test("abc","900150983cd24fb0d6963f7d28... |
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 .
| #C3 | C3 | module mandelbrot;
extern fn int atoi(char *s);
extern fn int printf(char *s, ...);
extern fn void putchar(int c);
fn void main(int argc, char **argv)
{
int w = atoi(argv[1]);
int h = w;
const LIMIT = 2.0;
const SQUARE_LIMIT = LIMIT * LIMIT;
printf("P4\n%d %d\n", w, h);
int iter = 50;
int bit_nu... |
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... | #Elixir | Elixir | defmodule RC do
def odd_magic_square(n) when rem(n,2)==1 do
for i <- 0..n-1 do
for j <- 0..n-1, do: n * rem(i+j+1+div(n,2),n) + rem(i+2*j+2*n-5,n) + 1
end
end
def print_square(sq) do
width = List.flatten(sq) |> Enum.max |> to_char_list |> length
fmt = String.duplicate(" ~#{width}w", length... |
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.
| #Elixir | Elixir |
def mult(m1, m2) do
Enum.map m1, fn (x) -> Enum.map t(m2), fn (y) -> Enum.zip(x, y)
|> Enum.map(fn {x, y} -> x * y end)
|> Enum.sum
end
end
end
def t(m) do # transpose
List.zip(m) |> Enum.map(&Tuple.to_list(&1))
end
|
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... | #Phix | Phix | with javascript_semantics
constant t = {{1,1,0,0},
{1,1,0,0},
{0,0,1,1},
{0,0,1,1}}
function magic_square(integer n)
if n<4 or mod(n,4)!=0 then return false end if
sequence square = repeat(repeat(0,n),n)
integer i = 0
for r=1 to n do
for c=1 to n do
... |
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... | #Icon_and_Unicon | Icon and Unicon | record mutable(value) # we need mutable integers
# ... be obvious when we break normal scope rules
procedure main(arglist) # supply the initial k value
k := integer(arglist[1])|10 ... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #EDSAC_order_code | EDSAC order code |
[Demo of matrix transposition. Not in place, creates a new matrix.
EDSAC, Initial Orders 2.]
..PZ [blank tape and terminator]
T 50 K [to call matrix transpose subroutine with 'G X']
P 200 F [address of matrix transpose subroutine]
T 47 K [to call 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... | #J | J | maze=:4 :0
assert.0<:n=.<:x*y
horiz=. 0$~x,y-1
verti=. 0$~(x-1),y
path=.,:here=. ?x,y
unvisited=.0 (<here+1)} 0,0,~|:0,0,~1$~y,x
while.n do.
neighbors=. here+"1 (,-)=0 1
neighbors=. neighbors #~ (<"1 neighbors+1) {unvisited
if.#neighbors do.
n=.n-1
next=. ({~ ?@#) neighbors
unv... |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const type: matrix is array array float;
const func string: str (in matrix: mat) is func
result
var string: stri is "";
local
var integer: row is 0;
var integer: column is 0;
begin
for row range 1 to length(mat) do
for column range 1 to 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.
| #Sidef | Sidef | class Array {
method ** (Number n { .>= 0 }) {
var tmp = self
var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }}
loop {
out = (out `mmul` tmp) if n.is_odd
n >>= 1 || break
tmp = (tmp `mmul` tmp)
}
return out
}
}
var 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... | #J | J | maprange=:2 :0
'a1 a2'=.m
'b1 b2'=.n
b1+((y-a1)*b2-b1)%a2-a1
)
NB. this version defers all calculations to runtime, but mirrors exactly the task formulation |
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... | #Java | Java | public class Range {
public static void main(String[] args){
for(float s = 0;s <= 10; s++){
System.out.println(s + " in [0, 10] maps to "+
mapRange(0, 10, -1, 0, s)+" in [-1, 0].");
}
}
public static double mapRange(double a1, double a2, double b1, double b2, double s){
return b1 + ((s - a1)*(b2 - b... |
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... | #Rust | Rust | use std::cmp::max;
fn max_path(vector: &mut Vec<Vec<u32>>) -> u32 {
while vector.len() > 1 {
let last = vector.pop().unwrap();
let ante = vector.pop().unwrap();
let mut new: Vec<u32> = Vec::new();
for (i, value) in ante.iter().enumerate() {
new.push(max(last[i],... |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Maple | Maple |
> with( StringTools ):
> Hash( "" );
"d41d8cd98f00b204e9800998ecf8427e"
> Hash( "a" );
"0cc175b9c0f1b6a831c399e269772661"
> Hash( "abc" );
"900150983cd24fb0d6963f7d28e17f72"
> Hash( "message digest" );
"f96b697d7cb7938d525a2f31aaf161d0"
> Hash( "abcdefghijklmnopqrstuvwxyz" ... |
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 .
| #Cixl | Cixl |
use: cx;
define: max 4.0;
define: max-iter 570;
let: (max-x max-y) screen-size;
let: max-cx $max-x 2.0 /;
let: max-cy $max-y 2.0 /;
let: rows Stack<Str> new;
let: buf Buf new;
let: zoom 0 ref;
func: render()()
$rows clear
$max-y 2 / {
let: y;
$buf 0 seek
$max-x {
let: x;
let: (zx... |
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... | #ERRE | ERRE |
PROGRAM MAGIC_SQUARE
!$INTEGER
PROCEDURE Magicsq(size,filename$)
LOCAL DIM sq[25,25] ! array to hold square
IF (size AND 1)=0 OR size<3 THEN
PRINT PRINT(CHR$(7)) ! beep
PRINT("error: size is not odd or size is smaller then 3")
PAUSE(3)
EXIT PROCEDURE
END IF
! filename$ <> "" then save ma... |
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... | #Factor | Factor | USING: formatting io kernel math math.matrices math.ranges
sequences sequences.extras ;
IN: rosetta-code.magic-squares-odd
: inc-matrix ( n -- matrix )
[ 0 ] dip dup [ 1 + dup ] make-matrix nip ;
: rotator ( n -- seq ) 2/ dup [ neg ] dip [a,b] ;
: odd-magic-square ( n -- matrix )
[ inc-matrix ] [ rotator ... |
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.
| #ELLA | ELLA | MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
[INT k = 1..n](vector1[k], vector2[k]).
MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
[INT i = 1..m] [INT j = 1..n] matrix[j][i].
MAC INNER_PRODUCT{FN * = [2]TYPE t -> TYPE s, FN + = [2]s -> s}
= ([INT n][2]t: vector) -> s:
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... | #PureBasic | PureBasic | Procedure.i MagicN(n.i)
ProcedureReturn n*(n*n+1)/2
EndProcedure
Procedure.i MaxN(mx.i,n.i)
If mx>n : ProcedureReturn mx : Else : ProcedureReturn n : EndIf
EndProcedure
Procedure.i MaxL(mx.i)
Define.i i
While mx
mx/10 : i+1
Wend
ProcedureReturn i
EndProcedure
Procedure.b DblEvenMagicSquare(n.i)
... |
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... | #Io | Io | Range
a := method(k, xs,
b := block(
k = k -1
a(k, list(b, xs slice(0,4)) flatten))
if(k <= 0,
(xs at(3) call) + (xs at(4) call),
b call))
f := method(x, block(x))
1 to(500) foreach(k,
(k .. " ") print
a(k, list(1, -1, -1, 1, 0) map (x, f(x))) println) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Elixir | Elixir | m = [[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25,125, 625]]
transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end
IO.inspect transpose.(m) |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #Java | Java | package org.rosettacode;
import java.util.Collections;
import java.util.Arrays;
/*
* recursive backtracking algorithm
* shamelessly borrowed from the ruby at
* http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking
*/
public class MazeGenerator {
private final int x;
private final int y... |
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.
| #SPAD | SPAD | (1) -> A:=matrix [[0,-%i],[%i,0]]
+0 - %i+
(1) | |
+%i 0 +
Type: Matrix(Complex(Integer))
(2) -> A^4
+1 0+
(2) | |
+0 1+
Type: Matrix(Complex(Integer))
(3) -> A^(-1)... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Stata | Stata | real matrix matpow(real matrix a, real scalar n) {
real matrix p, x
real scalar i, s
s = n<0
n = abs(n)
x = a
p = I(rows(a))
for (i=n; i>0; i=floor(i/2)) {
if (mod(i,2)==1) p = p*x
x = x*x
}
return(s?luinv(p):p)
} |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #JavaScript | JavaScript | // Javascript doesn't have built-in support for ranges
// Insted we use arrays of two elements to represent ranges
var mapRange = function(from, to, s) {
return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]);
};
var range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0; i < range.length; i++) {
... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Scala | Scala | object MaximumTrianglePathSum extends App {
// Solution:
def sum(triangle: Array[Array[Int]]) =
triangle.reduceRight((upper, lower) =>
upper zip (lower zip lower.tail)
map {case (above, (left, right)) => above + Math.max(left, right)}
).head
// Tests:
def triang... |
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:... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Hash["The quick brown fox jumped over the lazy dog's back","MD5","HexString"] |
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 .
| #Clojure | Clojure | (ns mandelbrot
(:refer-clojure :exclude [+ * <])
(:use (clojure.contrib complex-numbers)
(clojure.contrib.generic [arithmetic :only [+ *]]
[comparison :only [<]]
[math-functions :only [abs]])))
(defn mandelbrot? [z]
(loop [c 1
m (i... |
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... | #Fortran | Fortran | program Magic_Square
implicit none
integer, parameter :: order = 15
integer :: i, j
write(*, "(a, i0)") "Magic Square Order: ", order
write(*, "(a)") "----------------------"
do i = 1, order
do j = 1, order
write(*, "(i4)", advance = "no") f1(order, i, j)
end do
write(*,*)
end do... |
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.
| #Erlang | Erlang |
%% Multiplies two matrices. Usage example:
%% $ matrix:multiply([[1,2,3],[4,5,6]], [[4,4],[0,0],[1,4]])
%% If the dimentions are incompatible, an error is thrown.
%%
%% The erl shell may encode the lists output as strings. In order to prevent such
%% behaviour, BEFORE running matrix:multiply, run shell:strings(fals... |
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... | #Python | Python |
def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
... |
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... | #J | J | A=:4 :0
L=.cocreate'' NB. L is context where names are defined.
k__L=:x
'`x1__L x2__L x3__L x4__L x5__L'=:y
if.k__L<:0 do.a__L=:(x4__L + x5__L)f.'' else. L B '' end.
(coerase L)]]]a__L
)
B=:4 :0
L=.x
k__L=:k__L-1
a__L=:k__L A L&B`(x1__L f.)`(x2__L f.)`(x3__L f.)`(x4__L f.)
) |
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... | #Java | Java | import java.util.function.DoubleSupplier;
public class ManOrBoy {
static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
DoubleSupplier B = new DoubleSupplier() {
int m = k;
public double getAsDou... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #ELLA | ELLA | MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
[INT i = 1..m] [INT j = 1..n] matrix[j][i]. |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #JavaScript | JavaScript | function maze(x,y) {
var n=x*y-1;
if (n<0) {alert("illegal maze dimensions");return;}
var horiz =[]; for (var j= 0; j<x+1; j++) horiz[j]= [],
verti =[]; for (var j= 0; j<x+1; j++) verti[j]= [],
here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)],
path = [here],
unvisited = [];
for ... |
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.
| #Tcl | Tcl | package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
proc matrix_exp {m pow} {
if { ! [string is int -strict $pow]} {
error "non-integer exponents not implemented"
}
if {$pow < 0} {
error "negative exponents not implemented"
}
lassign [size $m] rows cols
# ass... |
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... | #jq | jq | # The input is the value to be mapped.
# The ranges, a and b, should each be an array defining the
# left-most and right-most points of the range.
def maprange(a; b):
b[0] + (((. - a[0]) * (b[1] - b[0])) / (a[1] - a[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... | #Julia | Julia | function maprange(s, a, b)
a₁, a₂ = minimum(a), maximum(a)
b₁, b₂ = minimum(b), maximum(b)
return b₁ + (s - a₁) * (b₂ - b₁) / (a₂ - a₁)
end
@show maprange(6, 1:10, -1:0)
@show maprange(0:10, 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... | #Sidef | Sidef | var sum = [0]
ARGF.each { |line|
var x = line.words.map{.to_n}
sum = [
x.first + sum.first,
1 ..^ x.end -> map{|i| x[i] + [sum[i-1, i]].max}...,
x.last + sum.last,
]
}
say sum.max |
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:... | #MATLAB | MATLAB | function digest = md5(message)
% digest = md5(message)
% Compute the MD5 digest of the message, as a hexadecimal digest.
% Follow the MD5 algorithm from RFC 1321 [1] and Wikipedia [2].
% [1] http://tools.ietf.org/html/rfc1321
% [2] http://en.wikipedia.org/wiki/MD5
% m is the modulus for 3... |
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 .
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. MANDELBROT-SET-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 COMPLEX-ARITHMETIC.
05 X PIC S9V9(9).
05 Y PIC S9V9(9).
05 X-A PIC S9V9(6).
05 X-B PIC S9V9(6).
05 Y-A PIC S9V9(6).
05 X-A-SQUA... |
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... | #FreeBASIC | FreeBASIC | ' version 23-06-2015
' compile with: fbc -s console
Sub magicsq(size As Integer, filename As String ="")
If (size And 1) = 0 Or size < 3 Then
Print : Beep ' alert
Print "error: size is not odd or size is smaller then 3"
Sleep 3000,1 'wait 3 seconds, ignore key press
Exit Sub
... |
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.
| #ERRE | ERRE |
PROGRAM MAT_PROD
DIM A[3,1],B[1,2],ANS[3,2]
BEGIN
DATA(1,2,3,4,5,6,7,8)
DATA(1,2,3,4,5,6)
FOR I=0 TO 3 DO
FOR J=0 TO 1 DO
READ(A[I,J])
END FOR
END FOR
FOR I=0 TO 1 DO
FOR J=0 TO 2 DO
READ(B[I,J])
END FOR
END FOR
FOR I=0 TO UBOUND(ANS,1) DO
FOR J=0 TO UBOUND(ANS,2) DO
FOR K=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... | #R | R | magic <- function(n) {
if (n %% 2 == 1) {
p <- (n + 1) %/% 2 - 2
ii <- seq(n)
outer(ii, ii, function(i, j) n * ((i + j + p) %% n) + (i + 2 * (j - 1)) %% n + 1)
} else if (n %% 4 == 0) {
p <- n * (n + 1) + 1
ii <- seq(n)
outer(ii, ii, function(i, j) ifelse((i %/% 2 - j %/% 2) %% 2 == 0, p - n... |
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... | #Raku | Raku | 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
The magic number is 260 |
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... | #JavaScript | JavaScript | function a(k, x1, x2, x3, x4, x5) {
function b() {
k -= 1;
return a(k, b, x1, x2, x3, x4);
}
return (k > 0) ? b() : x4() + x5();
}
// this uses lambda wrappers around the numeric arguments
function x(n) {
return function () {
return n;
};
}
alert(a(10, x(1), x(-1), x(-1), x(1), x(0))); |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Emacs_Lisp | Emacs Lisp | (require 'cl-lib)
(defun transpose (m)
(apply #'cl-mapcar #'list m))
;;test for transposition function
(transpose '((2 3 4 5) (3 5 6 9) (9 9 9 9))) |
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... | #Julia | Julia | using Random
check(bound::Vector) = cell -> all([1, 1] .≤ cell .≤ bound)
neighbors(cell::Vector, bound::Vector, step::Int=2) =
filter(check(bound), map(dir -> cell + step * dir, [[0, 1], [-1, 0], [0, -1], [1, 0]]))
function walk(maze::Matrix, nxtcell::Vector, visited::Vector=[])
push!(visited, nxtcell)
fo... |
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.
| #TI-89_BASIC | TI-89 BASIC | [3,2;4,1]^4 |
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.
| #Ursala | Ursala | #import nat
#import lin
id = @h ^|CzyCK33/1.! 0.!*
mex = ||id@l mmult:-0^|DlS/~& iota |
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... | #K | K | f:{[a1;a2;b1;b2;s] b1+(s-a1)*(b2-b1)%(a2-a1)}
+(a; f[0;10;-1;0]'a:!11)
((0;-1.0)
(1;-0.9)
(2;-0.8)
(3;-0.7)
(4;-0.6)
(5;-0.5)
(6;-0.4)
(7;-0.3)
(8;-0.2)
(9;-0.1)
(10;0.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... | #Kotlin | Kotlin | // version 1.0.6
class FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange<Float>
fun mapRange(range1: FloatRange, range2: FloatRange, value: Float): Float {
if (value !in range1) throw IllegalArgumentException("value is not within the first range")
if (range1.endInclusive ... |
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... | #Stata | Stata | import delimited triangle.txt, delim(" ") clear
mata
a = st_data(.,.)
n = rows(a)
for (i=n-1; i>=1; i--) {
for (j=1; j<=i; j++) {
a[i,j] = a[i,j]+max((a[i+1,j],a[i+1,j+1]))
}
}
a[1,1]
end |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #min | min | "The quick brown fox jumps over the lazy dog" md5 puts! |
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 .
| #Common_Lisp | Common Lisp | (defpackage #:mandelbrot
(:use #:cl))
(in-package #:mandelbrot)
(deftype pixel () '(unsigned-byte 8))
(deftype image () '(array pixel))
(defun write-pgm (image filespec)
(declare (image image))
(with-open-file (s filespec :direction :output :element-type 'pixel :if-exists :supersede)
(let* ((width (arr... |
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... | #Frink | Frink | order = length[ARGS] > 0 ? eval[ARGS@0] : undef
until isInteger[order] and order mod 2 == 1
order = eval[input["Enter order (must be odd): ", 3]]
a = new array[[order, order], undef]
x = order div 2
y = 0
for i = 1 to order^2
{
ny = (y - 1) mod order
nx = (x + 1) mod order
if a@ny@nx != undef
{
... |
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... | #Go | Go | package main
import (
"fmt"
"log"
)
func ms(n int) (int, []int) {
M := func(x int) int { return (x + n - 1) % n }
if n <= 0 || n&1 == 0 {
n = 5
log.Println("forcing size", n)
}
m := make([]int, n*n)
i, j := 0, n/2
for k := 1; k <= n*n; k++ {
m[i*n+j] = k
... |
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.
| #Euphoria | Euphoria | function matrix_mul(sequence a, sequence b)
sequence c
if length(a[1]) != length(b) then
return 0
else
c = repeat(repeat(0,length(b[1])),length(a))
for i = 1 to length(a) do
for j = 1 to length(b[1]) do
for k = 1 to length(a[1]) do
c[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... | #REXX | REXX | /*REXX program constructs a magic square of doubly even sides (a size divisible by 4).*/
n= 8; s= n%4; L= n%2-s+1; w= length(n**2) /*size; small sq; low middle; # width*/
@.= 0; H= n%2+s /*array default; high middle. */
call gen ... |
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... | #Jsish | Jsish | /* Knuth's Man or boy test (local references in recursion), in Jsish */
/* As noted, needs a fair sized stack depth, default is 200 in jsish v2.8.24 */
Interp.conf({maxDepth:2048});
function a(k, x1, x2, x3, x4, x5) {
function b() {
k -= 1;
return a(k, b, x1, x2, x3, x4);
}
return (k > 0) ? b() : x4() +... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Erlang | Erlang |
-module(transmatrix).
-export([trans/1,transL/1]).
% using built-ins hd = head, tl = tail
trans([[]|_]) -> [];
trans(M) ->
[ lists:map(fun hd/1, M) | transpose( lists:map(fun tl/1, M) ) ].
% Purist version
transL( [ [Elem | Rest] | List] ) ->
[ [Elem | [H || [H | _] <- List] ] |
transL( [Rest |
... |
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... | #Kotlin | Kotlin | import java.util.*
class MazeGenerator(val x: Int, val y: Int) {
private val maze = Array(x) { IntArray(y) }
fun generate(cx: Int, cy: Int) {
Direction.values().shuffle().forEach {
val nx = cx + it.dx
val ny = cy + it.dy
if (between(nx, x) && between(ny, y) && maz... |
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.
| #VBA | VBA | Option Base 1
Private Function Identity(n As Integer) As Variant
Dim I() As Variant
ReDim I(n, n)
For j = 1 To n
For k = 1 To n
I(j, k) = 0
Next k
Next j
For j = 1 To n
I(j, j) = 1
Next j
Identity = I
End Function
Function MatrixExponentiation(ByVal x As ... |
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... | #Lambdatalk | Lambdatalk |
{def maprange
{lambda {:a0 :a1 :b0 :b1 :s}
{+ :b0 {/ {* {- :s :a0} {- :b1 :b0}} {- :a1 :a0}}}}}
-> maprange
{maprange 0 10 -1 0 5}
-> -0.5
{S.map {maprange 0 10 -1 0} {S.serie 0 10}}
->
0 maps to -1
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3... |
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... | #Tcl | Tcl | package require Tcl 8.6
proc maxTrianglePathSum {definition} {
# Parse the definition, stripping whitespace and leading zeroes.
set lines [lmap line [split [string trim $definition] "\n"] {
lmap val $line {scan $val %d}
}]
# Paths are bit strings (0 = go left, 1 = go right).
# Enumerate the possi... |
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:... | #MOO | MOO | string = "The quick brown fox jumped over the lazy dog's back";
player:tell(string_hash(string)); |
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 .
| #Cowgol | Cowgol | include "cowgol.coh";
const xmin := -8601;
const xmax := 2867;
const ymin := -4915;
const ymax := 4915;
const maxiter := 32;
const dx := (xmax-xmin)/79;
const dy := (ymax-ymin)/24;
var cy: int16 := ymin;
while cy <= ymax loop
var cx: int16 := xmin;
while cx <= xmax loop
var x: int32 := 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... | #Haskell | Haskell | -- as a translation from imperative code, this is probably not a "good" implementation
import Data.List
type Var = (Int, Int, Int, Int) -- sx sy sz c
magicSum :: Int -> Int
magicSum x = ((x * x + 1) `div` 2) * x
wrapInc :: Int -> Int -> Int
wrapInc max x
| x + 1 == max = 0
| otherwise = x + 1
wra... |
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.
| #Excel | Excel |
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let result_row = (matrix1.GetLength 0)
let result_column = (matrix2.GetLength 1)
let ret = Array2D.create result_row result_column 0
for x in 0 .. result_row - 1 do
for y in 0 .. result_column - 1 do
let mutable acc = 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... | #Ruby | Ruby | def double_even_magic_square(n)
raise ArgumentError, "Need multiple of four" if n%4 > 0
block_size, max = n/4, n*n
pre_pat = [true, false, false, true,
false, true, true, false]
pre_pat += pre_pat.reverse
pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size
flat_ar = pattern.each_with_... |
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... | #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.")
{
Ok(arg) if arg >= 4 && arg % 4 == 0 => arg,
Err(e) => panic!(e),
_ => panic... |
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... | #Julia | Julia | function a(k, x1, x2, x3, x4, x5)
b = ()-> a(k-=1, b, x1, x2, x3, x4);
k <= 0 ? (x4() + x5()) : b();
end
println(a(10, ()->1, ()->-1, ()->-1, ()->1, ()->0)); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.