task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | originalMatrix := [[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625]];
transposedMatrix := TransposedMat(originalMatrix); |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Phix | Phix | with javascript_semantics
--
-- grid is eg for w=3,h=2: {"+---+---+---+", -- ("wall")
-- "| ? | ? | ? |", -- ("cell")
-- "+---+---+---+", -- ("wall")
-- "| ? | ? | ? |", -- ("cell")
-- "+---+---+---+", -- ("wall")
-- ""} -- (for a trailing \n)
--
-- note those ?(x,y) are at [y*2][x*4-1], and we navigate
-- using y=2..2*h (+/-2), x=3..w*4-1 (+/-4) directly.
--
constant w = 11, h = 8
sequence wall = join(repeat("+",w+1),"---")&"\n",
cell = join(repeat("|",w+1)," ? ")&"\n",
grid = split(join(repeat(wall,h+1),cell),'\n')
procedure amaze(integer x, integer y)
grid[y][x] = ' ' -- mark cell visited
sequence p = shuffle({{x-4,y},{x,y+2},{x+4,y},{x,y-2}})
for i=1 to length(p) do
integer {nx,ny} = p[i]
if nx>1 and nx<w*4 and ny>1 and ny<=2*h and grid[ny][nx]='?' then
integer mx = (x+nx)/2
grid[(y+ny)/2][mx-1..mx+1] = ' ' -- knock down wall
amaze(nx,ny)
end if
end for
end procedure
function heads()
return rand(2)=1 -- 50:50 true(1)/false(0)
end function
integer {x,y} = {(rand(w)*4)-1,rand(h)*2}
amaze(x,y)
-- mark start pos
grid[y][x] = '*'
-- add a random door (heads=rhs/lhs, tails=top/btm)
if heads() then
grid[rand(h)*2][heads()*w*4-1] = ' '
else
x = rand(w)*4-1
grid[heads()*h*2+1][x-1..x+1] = ' '
end if
printf(1,"%s\n",join(grid,'\n'))
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Phix | Phix | with javascript_semantics
function map_range(atom s, a1, a2, b1, b2)
return b1+(s-a1)*(b2-b1)/(a2-a1)
end function
for i=0 to 10 by 2 do
printf(1,"%2d : %g\n",{i,map_range(i,0,10,-1,0)})
end for
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #PicoLisp | PicoLisp | (scl 1)
(de mapRange (Val A1 A2 B1 B2)
(+ B1 (*/ (- Val A1) (- B2 B1) (- A2 A1))) )
(for Val (range 0 10.0 1.0)
(prinl
(format (mapRange Val 0 10.0 -1.0 0) *Scl) ) ) |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Octave | Octave | s = "The quick brown fox jumped over the lazy dog's back";
hash = md5sum(s, true);
disp(hash) |
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 .
| #Emacs_Lisp | Emacs Lisp | ; === Mandelbrot ============================================
(setq mandel-size (cons 76 34))
(setq xmin -2)
(setq xmax .5)
(setq ymin -1.2)
(setq ymax 1.2)
(setq max-iter 20)
(defun mandel-iter-point (x y)
"Run the actual iteration for each point."
(let ((xp 0)
(yp 0)
(it 0)
(xt 0))
(while (and (< (+ (* xp xp) (* yp yp)) 4) (< it max-iter))
(setq xt (+ (* xp xp) (* -1 yp yp) x))
(setq yp (+ (* 2 xp yp) y))
(setq xp xt)
(setq it (1+ it)))
it))
(defun mandel-iter (p)
"Return string for point based on whether inside/outside the set."
(let ((it (mandel-iter-point (car p) (cdr p))))
(if (= it max-iter) "*" "-")))
(defun mandel-pos (x y)
"Convert screen coordinates to input coordinates."
(let ((xp (+ xmin (* (- xmax xmin) (/ (float x) (car mandel-size)))))
(yp (+ ymin (* (- ymax ymin) (/ (float y) (cdr mandel-size))))))
(cons xp yp)))
(defun mandel ()
"Plot the Mandelbrot set."
(dotimes (y (cdr mandel-size))
(dotimes (x (car mandel-size))
(if (= x 0)
(insert(format "\n%s" (mandel-iter (mandel-pos x y))))
(insert(format "%s" (mandel-iter (mandel-pos x y))))))))
(mandel) |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Pascal | Pascal | PROGRAM magic;
(* Magic squares of odd order *)
CONST
n=9;
VAR
i,j :INTEGER;
BEGIN (*magic*)
WRITELN('The square order is: ',n);
FOR i:=1 TO n DO
BEGIN
FOR j:=1 TO n DO
WRITE((i*2-j+n-1) MOD n*n + (i*2+j-2) MOD n+1:5);
WRITELN
END;
WRITELN('The magic number is: ',n*(n*n+1) DIV 2)
END (*magic*). |
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.
| #GAP | GAP | # Built-in
A := [[1, 2], [3, 4], [5, 6], [7, 8]];
B := [[1, 2, 3], [4, 5, 6]];
PrintArray(A);
# [ [ 1, 2 ],
# [ 3, 4 ],
# [ 5, 6 ],
# [ 7, 8 ] ]
PrintArray(B);
# [ [ 1, 2, 3 ],
# [ 4, 5, 6 ] ]
PrintArray(A * B);
# [ [ 9, 12, 15 ],
# [ 19, 26, 33 ],
# [ 29, 40, 51 ],
# [ 39, 54, 69 ] ] |
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #PHP | PHP | <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
$b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
return A(--$k,$b,$x1,$x2,$x3,$x4);
};
return $k <= 0 ? $x4() + $x5() : $b();
}
echo A(10, function () { return 1; },
function () { return -1; },
function () { return -1; },
function () { return 1; },
function () { return 0; }) . "\n";
?> |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #GAP | GAP | originalMatrix := [[1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625]];
transposedMatrix := TransposedMat(originalMatrix); |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #PHP | PHP | <?php
class Maze
{
protected $width;
protected $height;
protected $grid;
protected $path;
protected $horWalls;
protected $vertWalls;
protected $dirs;
protected $isDebug;
public function __construct($x, $y, $debug = false)
{
$this->width = $x;
$this->height = $y;
$this->path = [];
$this->dirs = [ [0, -1], [0, 1], [-1, 0], [1, 0]]; // array of coordinates of N,S,W,E
$this->horWalls = []; // list of removed horizontal walls (---+)
$this->vertWalls = [];// list of removed vertical walls (|)
$this->isDebug = $debug; // debug flag
// generate the maze:
$this->generate();
}
protected function generate()
{
$this->initMaze(); // init the stack and an unvisited grid
// start from a random cell and then proceed recursively
$this->walk(mt_rand(0, $this->width-1), mt_rand(0, $this->height-1));
}
/**
* Actually prints the Maze, on stdOut. Put in a separate method to allow extensibility
* For simplicity sake doors are positioned on the north wall and east wall
*/
public function printOut()
{
$this->log("Horizontal walls: %s", json_encode($this->horWalls));
$this->log("Vertical walls: %s", json_encode($this->vertWalls));
$northDoor = mt_rand(0,$this->width-1);
$eastDoor = mt_rand(0, $this->height-1);
$str = '+';
for ($i=0;$i<$this->width;$i++) {
$str .= ($northDoor == $i) ? ' +' : '---+';
}
$str .= PHP_EOL;
for ($i=0; $i<$this->height; $i++) {
for ($j=0; $j<$this->width; $j++) {
$str .= (!empty($this->vertWalls[$j][$i]) ? $this->vertWalls[$j][$i] : '| ');
}
$str .= ($i == $eastDoor ? ' ' : '|').PHP_EOL.'+';
for ($j=0; $j<$this->width; $j++) {
$str .= (!empty($this->horWalls[$j][$i]) ? $this->horWalls[$j][$i] : '---+');
}
$str .= PHP_EOL;
}
echo $str;
}
/**
* Logs to stdOut if debug flag is enabled
*/
protected function log(...$params)
{
if ($this->isDebug) {
echo vsprintf(array_shift($params), $params).PHP_EOL;
}
}
private function walk($x, $y)
{
$this->log('Entering cell %d,%d', $x, $y);
// mark current cell as visited
$this->grid[$x][$y] = true;
// add cell to path
$this->path[] = [$x, $y];
// get list of all neighbors
$neighbors = $this->getNeighbors($x, $y);
$this->log("Valid neighbors: %s", json_encode($neighbors));
if(empty($neighbors)) {
// Dead end, we need now to backtrack, if there's still any cell left to be visited
$this->log("Start backtracking along path: %s", json_encode($this->path));
array_pop($this->path);
if (!empty($this->path)) {
$next = array_pop($this->path);
return $this->walk($next[0], $next[1]);
}
} else {
// randomize neighbors, as per request
shuffle($neighbors);
foreach ($neighbors as $n) {
$nextX = $n[0];
$nextY = $n[1];
if ($nextX == $x) {
$wallY = max($nextY, $y);
$this->log("New cell is on the same column (%d,%d), removing %d, (%d-1) horizontal wall", $nextX, $nextY, $x, $wallY);
$this->horWalls[$x][min($nextY, $y)] = " +";
}
if ($nextY == $y) {
$wallX = max($nextX, $x);
$this->log("New cell is on the same row (%d,%d), removing %d,%d vertical wall", $nextX, $nextY, $wallX, $y);
$this->vertWalls[$wallX][$y] = " ";
}
return $this->walk($nextX, $nextY);
}
}
}
/**
* Initialize an empty grid of $width * $height dimensions
*/
private function initMaze()
{
for ($i=0;$i<$this->width;$i++) {
for ($j = 0;$j<$this->height;$j++) {
$this->grid[$i][$j] = false;
}
}
}
/**
* @param int $x
* @param int $y
* @return array
*/
private function getNeighbors($x, $y)
{
$neighbors = [];
foreach ($this->dirs as $dir) {
$nextX = $dir[0] + $x;
$nextY = $dir[1] + $y;
if (($nextX >= 0 && $nextX < $this->width && $nextY >= 0 && $nextY < $this->height) && !$this->grid[$nextX][$nextY]) {
$neighbors[] = [$nextX, $nextY];
}
}
return $neighbors;
}
}
$maze = new Maze(10,10);
$maze->printOut(); |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #PL.2FI | PL/I |
map: procedure options (main); /* 24/11/2011 */
declare (a1, a2, b1, b2) float;
declare d fixed decimal (3,1);
do d = 0 to 10 by 0.9, 10;
put skip edit ( d, ' maps to ', map(0, 10, -1, 0, d) ) (f(5,1), a, f(10,6));
end;
map: procedure (a1, a2, b1, b2, s) returns (float);
declare (a1, a2, b1, b2, s) float;
return (b1 + (s - a1)*(b2 - b1) / (a2 - a1) );
end map;
end map;
|
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Ol | Ol |
(import (otus ffi))
(define libcrypto (load-dynamic-library "libcrypto.so.1.0.0"))
(define MD5 (libcrypto type-vptr "MD5" type-string fft-unsigned-long type-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 .
| #Erlang | Erlang |
-module(mandelbrot).
-export([test/0]).
magnitude(Z) ->
R = complex:real(Z),
I = complex:imaginary(Z),
R * R + I * I.
mandelbrot(A, MaxI, Z, I) ->
case (I < MaxI) and (magnitude(Z) < 2.0) of
true ->
NZ = complex:add(complex:mult(Z, Z), A),
mandelbrot(A, MaxI, NZ, I + 1);
false ->
case I of
MaxI ->
$*;
_ ->
$
end
end.
test() ->
lists:map(
fun(S) -> io:format("~s",[S]) end,
[
[
begin
Z = complex:make(X, Y),
mandelbrot(Z, 50, Z, 1)
end
|| X <- seq_float(-2, 0.5, 0.0315)
] ++ "\n"
|| Y <- seq_float(-1,1, 0.05)
] ),
ok.
% **************************************************
% Copied from https://gist.github.com/andruby/241489
% **************************************************
seq_float(Min, Max, Inc, Counter, Acc) when (Counter*Inc + Min) >= Max ->
lists:reverse([Max|Acc]);
seq_float(Min, Max, Inc, Counter, Acc) ->
seq_float(Min, Max, Inc, Counter+1, [Inc * Counter + Min|Acc]).
seq_float(Min, Max, Inc) ->
seq_float(Min, Max, Inc, 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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Perl | Perl | |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Phix | Phix | with javascript_semantics
function magic_square(integer n)
if mod(n,2)!=1 or n<1 then return false end if
sequence square = repeat(repeat(0,n),n)
for i=1 to n do
for j=1 to n do
square[i,j] = n*mod(2*i-j+n-1,n) + mod(2*i+j-2,n) + 1
end for
end for
return square
end function
procedure check(sequence sq)
integer n = length(sq)
integer magic = n*(n*n+1)/2
integer bd=0, fd=0
for i=1 to length(sq) do
if sum(sq[i])!=magic then ?9/0 end if
if sum(columnize(sq,i))!=magic then ?9/0 end if
bd += sq[i,i]
fd += sq[n-i+1,n-i+1]
end for
if bd!=magic or fd!=magic then ?9/0 end if
end procedure
for i=1 to 7 by 2 do
sequence square = magic_square(i)
printf(1,"maqic square of order %d, sum: %d\n", {i,sum(square[i])})
string fmt = sprintf("%%%dd",length(sprintf("%d",i*i)))
pp(square,{pp_Nest,1,pp_IntFmt,fmt,pp_StrFmt,3,pp_IntCh,false,pp_Pause,0})
check(square)
end for
|
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.
| #Generic | Generic |
generic coordinaat
{
ecs
uuii
coordinaat() { ecs=+a uuii=+a}
coordinaat(ecs_set uuii_set) { ecs = ecs_set uuii=uuii_set }
operaator<(c)
{
iph ecs < c.ecs return troo
iph c.ecs < ecs return phals
iph uuii < c.uuii return troo
return phals
}
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals
iph connpair < this return phals
return troo
}
operaator!=(connpair)
{
iph this < connpair return troo
iph connpair < this return troo
return phals
}
too_string()
{
return "(" + ecs.too_string() + "," + uuii.too_string() + ")"
}
print()
{
str = too_string()
str.print()
}
println()
{
str = too_string()
str.println()
}
}
generic nnaatrics
{
s // this is a set of coordinaat/ualioo pairs.
iteraator // this field holds an iteraator phor the nnaatrics.
nnaatrics() // no parameters required phor nnaatrics construction.
{
s = nioo set() // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul // the iteraator is initially set to nul.
}
nnaatrics(copee) // copee the nnaatrics.
{
s = nioo set() // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul // the iteraator is initially set to nul.
r = copee.rouus
c = copee.cols
i = 0
uuiil i < r
{
j = 0
uuiil j < c
{
this[i j] = copee[i j]
j++
}
i++
}
}
begin { get { return s.begin } } // property: used to commence manual iteraashon.
end { get { return s.end } } // property: used to dephiin the end itenn of iteraashon
operaator<(a) // les than operaator is corld bii the avl tree algorithnns
{ // this operaator innpliis phor instance that you could potenshalee hav sets ou nnaatricss.
iph cees < a.cees // connpair the cee sets phurst.
return troo
els iph a.cees < cees
return phals
els // the cee sets are eecuuol thairphor connpair nnaatrics elennents.
{
phurst1 = begin
lahst1 = end
phurst2 = a.begin
lahst2 = a.end
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
iph phurst1.daata.ualioo < phurst2.daata.ualioo
return troo
els
{
iph phurst2.daata.ualioo < phurst1.daata.ualioo
return phals
els
{
phurst1 = phurst1.necst
phurst2 = phurst2.necst
}
}
}
return phals
}
}
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals
iph connpair < this return phals
return troo
}
operaator!=(connpair)
{
iph this < connpair return troo
iph connpair < this return troo
return phals
}
operaator[cee_a cee_b] // this is the nnaatrics indexer.
{
set
{
trii { s >> nioo cee_ualioo(new coordinaat(cee_a cee_b)) } catch {}
s << nioo cee_ualioo(new coordinaat(nioo integer(cee_a) nioo integer(cee_b)) ualioo)
}
get
{
d = s.get(nioo cee_ualioo(new coordinaat(cee_a cee_b)))
return d.ualioo
}
}
operaator>>(coordinaat) // this operaator reennoous an elennent phronn the nnaatrics.
{
s >> nioo cee_ualioo(coordinaat)
return this
}
iteraat() // and this is how to iterate on the nnaatrics.
{
iph iteraator.nul()
{
iteraator = s.lepht_nnohst
iph iteraator == s.heder
return nioo iteraator(phals nioo nun())
els
return nioo iteraator(troo iteraator.daata.ualioo)
}
els
{
iteraator = iteraator.necst
iph iteraator == s.heder
{
iteraator = nul
return nioo iteraator(phals nioo nun())
}
els
return nioo iteraator(troo iteraator.daata.ualioo)
}
}
couunt // this property returns a couunt ou elennents in the nnaatrics.
{
get
{
return s.couunt
}
}
ennptee // is the nnaatrics ennptee?
{
get
{
return s.ennptee
}
}
lahst // returns the ualioo of the lahst elennent in the nnaatrics.
{
get
{
iph ennptee
throuu "ennptee nnaatrics"
els
return s.lahst.ualioo
}
}
too_string() // conuerts the nnaatrics too aa string
{
return s.too_string()
}
print() // prints the nnaatrics to the consohl.
{
out = too_string()
out.print()
}
println() // prints the nnaatrics as a liin too the consohl.
{
out = too_string()
out.println()
}
cees // return the set ou cees ou the nnaatrics (a set of coordinaats).
{
get
{
k = nioo set()
phor e : s k << e.cee
return k
}
}
operaator+(p)
{
ouut = nioo nnaatrics()
phurst1 = begin
lahst1 = end
phurst2 = p.begin
lahst2 = p.end
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs phurst1.daata.cee.uuii] = phurst1.daata.ualioo + phurst2.daata.ualioo
phurst1 = phurst1.necst
phurst2 = phurst2.necst
}
return ouut
}
operaator-(p)
{
ouut = nioo nnaatrics()
phurst1 = begin
lahst1 = end
phurst2 = p.begin
lahst2 = p.end
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs phurst1.daata.cee.uuii] = phurst1.daata.ualioo - phurst2.daata.ualioo
phurst1 = phurst1.necst
phurst2 = phurst2.necst
}
return ouut
}
rouus
{
get
{
r = +a
phurst1 = begin
lahst1 = end
uuiil phurst1 != lahst1
{
iph r < phurst1.daata.cee.ecs r = phurst1.daata.cee.ecs
phurst1 = phurst1.necst
}
return r + +b
}
}
cols
{
get
{
c = +a
phurst1 = begin
lahst1 = end
uuiil phurst1 != lahst1
{
iph c < phurst1.daata.cee.uuii c = phurst1.daata.cee.uuii
phurst1 = phurst1.necst
}
return c + +b
}
}
operaator*(o)
{
iph cols != o.rouus throw "rouus-cols nnisnnatch"
reesult = nioo nnaatrics()
rouu_couunt = rouus
colunn_couunt = o.cols
loop = cols
i = +a
uuiil i < rouu_couunt
{
g = +a
uuiil g < colunn_couunt
{
sunn = +a.a
h = +a
uuiil h < loop
{
a = this[i h]
b = o[h g]
nn = a * b
sunn = sunn + nn
h++
}
reesult[i g] = sunn
g++
}
i++
}
return reesult
}
suuop_rouus(a b)
{
c = cols
i = 0
uuiil u < cols
{
suuop = this[a i]
this[a i] = this[b i]
this[b i] = suuop
i++
}
}
suuop_colunns(a b)
{
r = rouus
i = 0
uuiil i < rouus
{
suuopp = this[i a]
this[i a] = this[i b]
this[i b] = suuop
i++
}
}
transpohs
{
get
{
reesult = new nnaatrics()
r = rouus
c = cols
i=0
uuiil i < r
{
g = 0
uuiil g < c
{
reesult[g i] = this[i g]
g++
}
i++
}
return reesult
}
}
deternninant
{
get
{
rouu_couunt = rouus
colunn_count = cols
if rouu_couunt != colunn_count
throw "not a scuuair nnaatrics"
if rouu_couunt == 0
throw "the nnaatrics is ennptee"
if rouu_couunt == 1
return this[0 0]
if rouu_couunt == 2
return this[0 0] * this[1 1] -
this[0 1] * this[1 0]
temp = nioo nnaatrics()
det = 0.0
parity = 1.0
j = 0
uuiil j < rouu_couunt
{
k = 0
uuiil k < rouu_couunt-1
{
skip_col = phals
l = 0
uuiil l < rouu_couunt-1
{
if l == j skip_col = troo
if skip_col
n = l + 1
els
n = l
temp[k l] = this[k + 1 n]
l++
}
k++
}
det = det + parity * this[0 j] * temp.deeternninant
parity = 0.0 - parity
j++
}
return det
}
}
ad_rouu(a b)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] + this[b i]
i++
}
}
ad_colunn(a b)
{
c = rouus
i = 0
uuiil i < c
{
this[i a] = this[i a] + this[i b]
i++
}
}
subtract_rouu(a b)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] - this[b i]
i++
}
}
subtract_colunn(a b)
{
c = rouus
i = 0
uuiil i < c
{
this[i a] = this[i a] - this[i b]
i++
}
}
nnultiplii_rouu(rouu scalar)
{
c = cols
i = 0
uuiil i < c
{
this[rouu i] = this[rouu i] * scalar
i++
}
}
nnultiplii_colunn(colunn scalar)
{
r = rouus
i = 0
uuiil i < r
{
this[i colunn] = this[i colunn] * scalar
i++
}
}
diuiid_rouu(rouu scalar)
{
c = cols
i = 0
uuiil i < c
{
this[rouu i] = this[rouu i] / scalar
i++
}
}
diuiid_colunn(colunn scalar)
{
r = rouus
i = 0
uuiil i < r
{
this[i colunn] = this[i colunn] / scalar
i++
}
}
connbiin_rouus_ad(a b phactor)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] + phactor * this[b i]
i++
}
}
connbiin_rouus_subtract(a b phactor)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] - phactor * this[b i]
i++
}
}
connbiin_colunns_ad(a b phactor)
{
r = rouus
i = 0
uuiil i < r
{
this[i a] = this[i a] + phactor * this[i b]
i++
}
}
connbiin_colunns_subtract(a b phactor)
{
r = rouus
i = 0
uuiil i < r
{
this[i a] = this[i a] - phactor * this[i b]
i++
}
}
inuers
{
get
{
rouu_couunt = rouus
colunn_couunt = cols
iph rouu_couunt != colunn_couunt
throw "nnatrics not scuuair"
els iph rouu_couunt == 0
throw "ennptee nnatrics"
els iph rouu_couunt == 1
{
r = nioo nnaatrics()
r[0 0] = 1.0 / this[0 0]
return r
}
gauss = nioo nnaatrics(this)
i = 0
uuiil i < rouu_couunt
{
j = 0
uuiil j < rouu_couunt
{
iph i == j
gauss[i j + rouu_couunt] = 1.0
els
gauss[i j + rouu_couunt] = 0.0
j++
}
i++
}
j = 0
uuiil j < rouu_couunt
{
iph gauss[j j] == 0.0
{
k = j + 1
uuiil k < rouu_couunt
{
if gauss[k j] != 0.0 {gauss.nnaat.suuop_rouus(j k) break }
k++
}
if k == rouu_couunt throw "nnatrics is singioolar"
}
phactor = gauss[j j]
iph phactor != 1.0 gauss.diuiid_rouu(j phactor)
i = j+1
uuiil i < rouu_couunt
{
gauss.connbiin_rouus_subtract(i j gauss[i j])
i++
}
j++
}
i = rouu_couunt - 1
uuiil i > 0
{
k = i - 1
uuiil k >= 0
{
gauss.connbiin_rouus_subtract(k i gauss[k i])
k--
}
i--
}
reesult = nioo nnaatrics()
i = 0
uuiil i < rouu_couunt
{
j = 0
uuiil j < rouu_couunt
{
reesult[i j] = gauss[i j + rouu_couunt]
j++
}
i++
}
return reesult
}
}
}
|
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #PicoLisp | PicoLisp | (de a (K X1 X2 X3 X4 X5)
(let (@K (cons K) B (cons)) # Explicit frame
(set B
(curry (@K B X1 X2 X3 X4) ()
(a (dec @K) (car B) X1 X2 X3 X4) ) )
(if (gt0 (car @K)) ((car B)) (+ (X4) (X5))) ) )
(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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #PL.2FI | PL/I | morb: proc options (main) reorder;
dcl sysprint file;
put skip list(a((10), lambda1, lambdam1, lambdam1, lambda0, lambda0));
a: proc(k, x1, x2, x3, x4, x5) returns(fixed bin (31)) recursive;
dcl k fixed bin (31);
dcl (x1, x2, x3, x4, x5) entry returns(fixed bin (31));
b: proc returns(fixed bin(31)) recursive;
k = k - 1;
return(a((k), b, x1, x2, x3, x4));
end b;
if k <= 0 then
return(x4 + x5);
else
return(b);
end a;
lambdam1: proc returns(fixed bin (31)); return(-1); end lambdam1;
lambda0: proc returns(fixed bin (31)); return(1); end lambda0;
lambda1: proc returns(fixed bin (31)); return(1); end lambda1;
end morb;
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Go | Go | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.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-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Picat | Picat | main =>
gen_maze(8,8).
main([RStr,CStr]) =>
MaxR = to_int(RStr),
MaxC = to_int(CStr),
gen_maze(MaxR,MaxC).
gen_maze(MaxR,MaxC) =>
Maze = new_array(MaxR,MaxC),
foreach (R in 1..MaxR, C in 1..MaxC)
Maze[R,C] = 0
end,
gen_maze(Maze,MaxR,MaxC,1,1),
display_maze(Maze,MaxR,MaxC).
gen_maze(Maze,MaxR,MaxC,R,C) =>
Dirs = shuffle([left, right, up, down]),
foreach (Dir in Dirs)
dir(Dir,Dr,Dc,B,OB),
R1 := R+Dr,
C1 := C+Dc,
if (R1 >= 1 && R1 =< MaxR && C1 >= 1 && C1 =< MaxC && Maze[R1,C1] == 0) then
Maze[R,C] := Maze[R,C] \/ B,
Maze[R1,C1] := Maze[R1,C1] \/ OB,
gen_maze(Maze,MaxR,MaxC,R1,C1)
end
end.
% dir(direction, Dr, Dc, Bit, OppBit)
dir(left, 0, -1, 1, 2).
dir(right, 0, 1, 2, 1).
dir(up, -1, 0, 4, 8).
dir(down, 1, 0, 8, 4).
shuffle(Arr) = Res =>
foreach (_ in 1..10)
I1 = random() mod 4 + 1,
I2 = random() mod 4 + 1,
T := Arr[I1],
Arr[I1] := Arr[I2],
Arr[I2] := T
end,
Res = Arr.
display_maze(Maze,MaxR,MaxC) =>
foreach (R in 1..MaxR)
foreach (C in 1..MaxC)
printf("%s", cond(Maze[R,C] /\ 4 == 0, "+---", "+ "))
end,
println("+"),
foreach (C in 1..MaxC)
printf("%s", cond(Maze[R,C] /\ 1 == 0, "| ", " ")),
end,
println("|")
end,
foreach (C in 1..MaxC)
print("+---")
end,
println("+").
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #PowerShell | PowerShell |
function Group-Range
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[ValidateCount(2,2)]
[double[]]
$Range1,
[Parameter(Mandatory=$true,
Position=1)]
[ValidateCount(2,2)]
[double[]]
$Range2,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=2)]
[double]
$Map
)
Process
{
foreach ($number in $Map)
{
[PSCustomObject]@{
Index = $number
Mapping = $Range2[0] + ($number - $Range1[0]) * ($Range2[0] - $Range2[1]) / ($Range1[0] - $Range1[1])
}
}
}
}
|
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #OpenEdge.2FProgress | OpenEdge/Progress | MESSAGE
1 STRING( HEX-ENCODE( MD5-DIGEST( "" ) ) ) SKIP
2 STRING( HEX-ENCODE( MD5-DIGEST( "a" ) ) ) SKIP
3 STRING( HEX-ENCODE( MD5-DIGEST( "abc" ) ) ) SKIP
4 STRING( HEX-ENCODE( MD5-DIGEST( "message digest" ) ) ) SKIP
5 STRING( HEX-ENCODE( MD5-DIGEST( "abcdefghijklmnopqrstuvwxyz" ) ) ) SKIP
6 STRING( HEX-ENCODE( MD5-DIGEST( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ) ) ) SKIP
7 STRING( HEX-ENCODE( MD5-DIGEST( "12345678901234567890123456789012345678901234567890123456789012345678901234567890" ) ) )
VIEW-AS ALERT-BOX |
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 .
| #ERRE | ERRE |
PROGRAM MANDELBROT
!$KEY
!$INCLUDE="PC.LIB"
BEGIN
SCREEN(7)
GR_WINDOW(-2,1.5,2,-1.5)
FOR X0=-2 TO 2 STEP 0.01 DO
FOR Y0=-1.5 TO 1.5 STEP 0.01 DO
X=0
Y=0
ITERATION=0
MAX_ITERATION=223
WHILE (X*X+Y*Y<=(2*2) AND ITERATION<MAX_ITERATION) DO
X_TEMP=X*X-Y*Y+X0
Y=2*X*Y+Y0
X=X_TEMP
ITERATION=ITERATION+1
END WHILE
IF ITERATION<>MAX_ITERATION THEN
C=ITERATION
ELSE
C=0
END IF
PSET(X0,Y0,C)
END FOR
END FOR
END PROGRAM
|
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Picat | Picat | import util.
go =>
foreach(N in [3,5,17])
M=magic_square(N),
print_matrix(M),
check(M),
nl
end,
nl.
%
% Not as nice as the J solution.
% But I like the chaining of the functions.
%
magic_square(N) = MS =>
if N mod 2 = 0 then
printf("N (%d) is not odd!\n", N),
halt
end,
R = make_rotate_list(N), % the rotate indices
MS = make_square(N).transpose().rotate_matrix(R).transpose().rotate_matrix(R).
%
% make a square matrix of size N (containing the numbers 1..N*N)
%
make_square(N) = [[I*N+J : J in 1..N]: I in 0..N-1].
%
% rotate list:
% rotate_list(11) = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
%
make_rotate_list(N) = [I - ceiling(N / 2) : I in 1..N].
%
% rotate the matrix M according to rotate list R
%
rotate_matrix(M, R) = [rotate_n(Row,N) : {Row,N} in zip(M,R)].
%
% Rotate the list L N steps (either positive or negative N)
% rotate(1..10,3) -> [4,5,6,7,8,9,10,1,2,3]
% rotate(1..10,-3) -> [8,9,10,1,2,3,4,5,6,7]
%
rotate_n(L,N) = Rot =>
Len = L.length,
R = cond(N < 0, Len + N, N),
Rot = [L[I] : I in (R+1..Len) ++ 1..R].
%
% Check if M is a magic square
%
check(M) =>
N = M.length,
Sum = N*(N*N+1) // 2, % The correct sum.
println(sum=Sum),
Rows = [sum(Row) : Row in M],
Cols = [sum(Col) : Col in M.transpose()],
Diag1 = sum([M[I,I] : I in 1..N]),
Diag2 = sum([M[I,N-I+1] : I in 1..N]),
All = Rows ++ Cols ++ [Diag1, Diag2],
OK = true,
foreach(X in All)
if X != Sum then
printf("%d != %d\n", X, Sum),
OK := false
end
end,
if OK then
println(ok)
else
println(not_ok)
end,
nl.
% Print the matrix
print_matrix(M) =>
N = M.len,
printf("N=%d\n",N),
Format = to_fstring("%%%dd",max(flatten(M)).to_string().length+1),
foreach(Row in M)
foreach(X in Row)
printf(Format, X)
end,
nl
end,
nl. |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(de magic (A)
(let
(Grid (grid A A T T)
Sum (/ (* A (inc (** A 2))) 2))
(println 'N A 'Sum Sum)
# cut one important edge
(with (last (last Grid)) (con (: 0 1)))
(with (get Grid (inc (/ A 2)) A)
(for N (* A A)
(=: V N)
(setq This
(if
(with (setq @@ (north (east This)))
(not (: V)) )
@@
(south This) ) ) ) )
# display
(mapc
'((L)
(for This L
(prin (align 4 (: V))) )
(prinl) )
Grid )
# clean
(mapc '((L) (mapc zap L)) Grid) ) )
(magic 5)
(prinl)
(magic 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.
| #Go | Go | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
a := mat.NewDense(2, 4, []float64{
1, 2, 3, 4,
5, 6, 7, 8,
})
b := mat.NewDense(4, 3, []float64{
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12,
})
var m mat.Dense
m.Mul(a, b)
fmt.Println(mat.Formatted(&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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Pop11 | Pop11 | define A(k, x1, x2, x3, x4, x5);
define B();
k - 1 -> k;
A(k, B, x1, x2, x3, x4)
enddefine;
if k <= 0 then
x4() + x5()
else
B()
endif
enddefine;
define one(); 1 enddefine;
define minus_one(); -1 enddefine;
define zero(); 0 enddefine;
A(10, one, minus_one, minus_one, one, zero) =>
|
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Python | Python | #!/usr/bin/env python
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(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.
| #Groovy | Groovy | def matrix = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ] ]
matrix.each { println it }
println()
def transpose = matrix.transpose()
transpose.each { println it } |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(de maze (DX DY)
(let Maze (grid DX DY)
(let Fld (get Maze (rand 1 DX) (rand 1 DY))
(recur (Fld)
(for Dir (shuffle '((west . east) (east . west) (south . north) (north . south)))
(with ((car Dir) Fld)
(unless (or (: west) (: east) (: south) (: north))
(put Fld (car Dir) This)
(put This (cdr Dir) Fld)
(recurse This) ) ) ) ) )
(for (X . Col) Maze
(for (Y . This) Col
(set This
(cons
(cons
(: west)
(or
(: east)
(and (= Y 1) (= X DX)) ) )
(cons
(: south)
(or
(: north)
(and (= X 1) (= Y DY)) ) ) ) ) ) )
Maze ) )
(de display (Maze)
(disp Maze 0 '((This) " ")) ) |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #PureBasic | PureBasic | Structure RR
a.f
b.f
EndStructure
Procedure.f MapRange(*a.RR, *b.RR, s)
Protected.f a1, a2, b1, b2
a1=*a\a: a2=*a\b
b1=*b\a: b2=*b\b
ProcedureReturn b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
EndProcedure
;- Test the function
If OpenConsole()
Define.RR Range1, Range2
Range1\a=0: Range1\b=10
Range2\a=-1:Range2\b=0
;
For i=0 To 10
PrintN(RSet(Str(i),2)+" maps to "+StrF(MapRange(@Range1, @Range2, i),1))
Next
EndIf |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Python | Python | >>> def maprange( a, b, s):
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
>>> for s in range(11):
print("%2g maps to %g" % (s, maprange( (0, 10), (-1, 0), s)))
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
8 maps to -0.2
9 maps to -0.1
10 maps to 0 |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #PARI.2FGP | PARI/GP | #include <pari/pari.h>
#include <openssl/md5.h>
#define HEX(x) (((x) < 10)? (x)+'0': (x)-10+'a')
/*
* PARI/GP func: MD5 hash
*
* gp code: install("plug_md5", "s", "MD5", "<library path>");
*/
GEN plug_md5(char *text)
{
char md[MD5_DIGEST_LENGTH];
char hash[sizeof(md) * 2 + 1];
int i;
MD5((unsigned char*)text, strlen(text), (unsigned char*)md);
for (i = 0; i < sizeof(md); i++) {
hash[i+i] = HEX((md[i] >> 4) & 0x0f);
hash[i+i+1] = HEX(md[i] & 0x0f);
}
hash[sizeof(md) * 2] = 0;
return strtoGENstr(hash);
} |
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 .
| #F.23 | F# | open System.Drawing
open System.Windows.Forms
type Complex =
{
re : float;
im : float
}
let cplus (x:Complex) (y:Complex) : Complex =
{
re = x.re + y.re;
im = x.im + y.im
}
let cmult (x:Complex) (y:Complex) : Complex =
{
re = x.re * y.re - x.im * y.im;
im = x.re * y.im + x.im * y.re;
}
let norm (x:Complex) : float =
x.re*x.re + x.im*x.im
type Mandel = class
inherit Form
static member xPixels = 500
static member yPixels = 500
val mutable bmp : Bitmap
member x.mandelbrot xMin xMax yMin yMax maxIter =
let rec mandelbrotIterator z c n =
if (norm z) > 2.0 then false else
match n with
| 0 -> true
| n -> let z' = cplus ( cmult z z ) c in
mandelbrotIterator z' c (n-1)
let dx = (xMax - xMin) / (float (Mandel.xPixels))
let dy = (yMax - yMin) / (float (Mandel.yPixels))
in
for xi = 0 to Mandel.xPixels-1 do
for yi = 0 to Mandel.yPixels-1 do
let c = {re = xMin + (dx * float(xi) ) ;
im = yMin + (dy * float(yi) )} in
if (mandelbrotIterator {re=0.;im=0.;} c maxIter) then
x.bmp.SetPixel(xi,yi,Color.Azure)
else
x.bmp.SetPixel(xi,yi,Color.Black)
done
done
member public x.generate () = x.mandelbrot (-1.5) 0.5 (-1.0) 1.0 200 ; x.Refresh()
new() as x = {bmp = new Bitmap(Mandel.xPixels , Mandel.yPixels)} then
x.Text <- "Mandelbrot set" ;
x.Width <- Mandel.xPixels ;
x.Height <- Mandel.yPixels ;
x.BackgroundImage <- x.bmp;
x.generate();
x.Show();
end
let f = new Mandel()
do Application.Run(f) |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #PL.2FI | PL/I | magic: procedure options (main); /* 18 April 2014 */
declare n fixed binary;
put skip list ('What is the order of the magic square?');
get list (n);
if n < 3 | iand(n, 1) = 0 then
do; put skip list ('The value is out of range'); stop; end;
put skip list ('The order is ' || trim(n));
begin;
declare m(n, n) fixed, (i, j, k) fixed binary;
on subrg snap put data (i, j, k);
m = 0;
i = 1; j = (n+1)/2;
do k = 1 to n*n;
if m(i,j) = 0 then
m(i,j) = k;
else
do;
i = i + 2; j = j + 1;
if i > n then i = mod(i,n);
if j > n then j = 1;
m(i,j) = k;
end;
i = i - 1; j = j - 1;
if i < 1 then i = n;
if j < 1 then j = n;
end;
do i = 1 to n;
put skip edit (m(i, *)) (f(4));
end;
put skip list ('The magic number is' || sum(m(1,*)));
end;
end magic; |
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.
| #Groovy | Groovy | def assertConformable = { a, b ->
assert a instanceof List
assert b instanceof List
assert a.every { it instanceof List && it.size() == b.size() }
assert b.every { it instanceof List && it.size() == b[0].size() }
}
def matmulWOIL = { a, b ->
assertConformable(a, b)
def bt = b.transpose()
a.collect { ai ->
bt.collect { btj ->
[ai, btj].transpose().collect { it[0] * it[1] }.sum()
}
}
} |
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #R | R | n <- function(x) function()x
A <- function(k, x1, x2, x3, x4, x5) {
B <- function() A(k <<- k-1, B, x1, x2, x3, x4)
if (k <= 0) x4() + x5() else B()
}
A(10, n(1), n(-1), n(-1), n(1), n(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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Racket | Racket | #lang racket
(define (A k x1 x2 x3 x4 x5)
(define (B)
(set! k (- k 1))
(A k B x1 x2 x3 x4))
(if (<= k 0)
(+ (x4) (x5))
(B)))
(A 10 (lambda () 1) (lambda () -1) (lambda () -1) (lambda () 1) (lambda () 0)) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Haskell | Haskell | *Main> transpose [[1,2],[3,4],[5,6]]
[[1,3,5],[2,4,6]] |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #PL.2FI | PL/I | *process source attributes xref or(!);
mgg: Proc Options(main);
/* REXX ***************************************************************
* 04.09.2013 Walter Pachl translated from REXX version 3
**********************************************************************/
Dcl (MIN,MOD,RANDOM,REPEAT,SUBSTR) Builtin;
Dcl SYSIN STREAM INPUT;
Dcl print Print;
Dcl imax Bin Fixed(31) init(10);
Dcl jmax Bin Fixed(31) init(15);
Dcl seed Bin Fixed(31) init(4711);
Get File(sysin) Data(imax,jmax,seed);
Dcl ii Bin Fixed(31);
Dcl jj Bin Fixed(31);
Dcl id Bin Fixed(31);
Dcl jd Bin Fixed(31);
id=2*imax+1; /* vertical dimension of a.i.j */
jd=2*jmax+1; /* horizontal dimension of a.i.j */
Dcl c Char(2000) Var;
c=repeat('123456789'!!'abcdefghijklmnopqrstuvwxyz'!!
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',20);
Dcl x Bin Float(53);
x=random(seed);
Dcl ps Bin Fixed(31) Init(1); /* first position */
Dcl na Bin Fixed(31) Init(1); /* number of points used */
Dcl si Bin Fixed(31); /* loop to compute paths */
Begin;
Dcl a(id,jd) Bin Fixed(15);
Dcl p(imax,jmax) Char(1);
Dcl 1 pl(imax*jmax),
2 ic Bin Fixed(15),
2 jc Bin Fixed(15);
Dcl 1 np(imax*jmax),
2 ic Bin Fixed(15),
2 jc Bin Fixed(15);
Dcl 1 pos(imax*jmax),
2 ic Bin Fixed(15),
2 jc Bin Fixed(15);
Dcl npl Bin Fixed(31) Init(0);
a=1; /* mark all borders present */
p='.'; /* Initialize all grid points */
ii=rnd(imax); /* find a start position */
jj=rnd(jmax);
Do si=1 To 1000; /* Do Forever - see Leave */
Call path(ii,jj); /* compute a path starting at ii/jj */
If na=imax*jmax Then /* all points used */
Leave; /* we are done */
Call select_next(ii,jj); /* get a new start from a path*/
End;
Call show;
Return;
path: Procedure(ii,jj);
/**********************************************************************
* compute a path starting from point (ii,jj)
**********************************************************************/
Dcl ii Bin Fixed(31);
Dcl jj Bin Fixed(31);
Dcl nb Bin Fixed(31);
Dcl ch Bin Fixed(31);
Dcl pp Bin Fixed(31);
p(ii,jj)='1';
pos.ic(ps)=ii;
pos.jc(ps)=jj;
Do pp=1 to 50; /* compute a path of maximum length 50*/
nb=neighbors(ii,jj); /* number of free neighbors */
Select;
When(nb=1) /* just one */
Call advance((1),ii,jj); /* go for it */
When(nb>0) Do; /* more Than 1 */
ch=rnd(nb); /* choose one possibility */
Call advance(ch,ii,jj); /* and go for that */
End;
Otherwise /* none available */
Leave;
End;
End;
End;
neighbors: Procedure(i,j) Returns(Bin Fixed(31));
/**********************************************************************
* count the number of free neighbors of point (i,j)
**********************************************************************/
Dcl i Bin Fixed(31);
Dcl j Bin Fixed(31);
Dcl in Bin Fixed(31);
Dcl jn Bin Fixed(31);
Dcl nb Bin Fixed(31) Init(0);
in=i-1; If in>0 Then Call check(in,j,nb);
in=i+1; If in<=imax Then Call check(in,j,nb);
jn=j-1; If jn>0 Then Call check(i,jn,nb);
jn=j+1; If jn<=jmax Then Call check(i,jn,nb);
Return(nb);
End;
check: Procedure(i,j,n);
/**********************************************************************
* check if point (i,j) is free and note it as possible successor
**********************************************************************/
Dcl i Bin Fixed(31);
Dcl j Bin Fixed(31);
Dcl n Bin Fixed(31);
If p(i,j)='.' Then Do; /* point is free */
n+=1; /* number of free neighbors */
np.ic(n)=i; /* note it as possible choice */
np.jc(n)=j;
End;
End;
advance: Procedure(ch,ii,jj);
/**********************************************************************
* move to the next point of the current path
**********************************************************************/
Dcl ch Bin Fixed(31);
Dcl ii Bin Fixed(31);
Dcl jj Bin Fixed(31);
Dcl ai Bin Fixed(31);
Dcl aj Bin Fixed(31);
Dcl pii Bin Fixed(31) Init((ii));
Dcl pjj Bin Fixed(31) Init((jj));
Dcl z Bin Fixed(31);
ii=np.ic(ch);
jj=np.jc(ch);
ps+=1; /* position number */
pos.ic(ps)=ii; /* note its coordinates */
pos.jc(ps)=jj;
p(ii,jj)=substr(c,ps,1); /* mark the point as used */
ai=pii+ii; /* vertical border position */
aj=pjj+jj; /* horizontal border position */
a(ai,aj)=0; /* tear the border down */
na+=1; /* number of used positions */
z=npl+1; /* add the point to the list */
pl.ic(z)=ii; /* of follow-up start pos. */
pl.jc(z)=jj;
npl=z;
End;
show: Procedure;
/*********************************************************************
* Show the resulting maze
*********************************************************************/
Dcl i Bin Fixed(31);
Dcl j Bin Fixed(31);
Dcl ol Char(300) Var;
Put File(print) Edit('mgg',imax,jmax,seed)(Skip,a,3(f(4)));
Put File(print) Skip Data(na);
Do i=1 To id;
ol='';
Do j=1 To jd;
If mod(i,2)=1 Then Do; /* odd lines */
If a(i,j)=1 Then Do; /* border to be drawn */
If mod(j,2)=0 Then
ol=ol!!'---'; /* draw the border */
Else
ol=ol!!'+';
End;
Else Do; /* border was torn down */
If mod(j,2)=0 Then
ol=ol!!' '; /* blanks instead of border */
Else
ol=ol!!'+';
End;
End;
Else Do; /* even line */
If a(i,j)=1 Then Do;
If mod(j,2)=0 Then /* even column */
ol=ol!!' '; /* moving space */
Else /* odd column */
ol=ol!!'!'; /* draw the border */
End;
Else /* border was torn down */
ol=ol!!' '; /* blank instead of border */
End;
End;
Select;
When(i=6) substr(ol,11,1)='A';
When(i=8) substr(ol, 3,1)='B';
Otherwise;
End;
Put File(print) Edit(ol,i)(Skip,a,f(3));
End;
End;
select_next: Procedure(is,js);
/**********************************************************************
* look for a point to start the nnext path
**********************************************************************/
Dcl is Bin Fixed(31);
Dcl js Bin Fixed(31);
Dcl n Bin Fixed(31);
Dcl nb Bin Fixed(31);
Dcl s Bin Fixed(31);
Do Until(nb>0); /* loop until one is found */
n=npl; /* number of points recorded */
s=rnd(n); /* pick a random index */
is=pl.ic(s); /* its coordinates */
js=pl.jc(s);
nb=neighbors(is,js); /* count free neighbors */
If nb=0 Then Do; /* if there is none */
pl.ic(s)=pl.ic(n); /* remove this point */
pl.jc(s)=pl.jc(n);
npl-=1;
End;
End;
End;
rnd: Proc(n) Returns(Bin Fixed(31));
/*********************************************************************
* return a pseudo-random integer between 1 and n
*********************************************************************/
dcl (r,n) Bin Fixed(31);
r=min(random()*n+1,n);
Return(r);
End;
End;
End; |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #R | R | tRange <- function(aRange, bRange, s)
{
#Guard clauses. We could write some proper error messages, but this is all we really need.
stopifnot(length(aRange) == 2, length(bRange) == 2,
is.numeric(aRange), is.numeric(bRange), is.numeric(s),
s >= aRange[1], s <= aRange[2])
bRange[1] + ((s - aRange[1]) * (bRange[2] - bRange[1])) / (aRange[2] - aRange[1])
}
data.frame(s = 0:10, t = sapply(0:10, tRange, aRange = c(0, 10), bRange = c(-1, 0))) |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Pascal | Pascal |
program GetMd5;
uses md5;
var
strEncrypted : string;
begin
strEncrypted := md5Print(md5String('The quick brown fox jumped over the lazy dog''s back'));
writeln(strEncrypted);
end.
|
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 .
| #Factor | Factor |
! with ("::") or without (":") generalizations:
! : [a..b] ( steps a b -- a..b ) 2dup swap - 4 nrot 1 - / <range> ;
:: [a..b] ( steps a b -- a..b ) a b b a - steps 1 - / <range> ;
: >char ( n -- c )
dup -1 = [ drop 32 ] [ 26 mod CHAR: a + ] if ;
! iterates z' = z^2 + c, Factor does complex numbers!
: iter ( c z -- z' ) dup * + ;
: unbound ( c -- ? ) absq 4 > ;
:: mz ( c max i z -- n )
{
{ [ i max >= ] [ -1 ] }
{ [ z unbound ] [ i ] }
[ c max i 1 + c z iter mz ]
} cond ;
: mandelzahl ( c max -- n ) 0 0 mz ;
:: mandel ( w h max -- )
h -1. 1. [a..b] ! range over y
[ w -2. 1. [a..b] ! range over x
[ dupd swap rect> max mandelzahl >char ] map
>string print
drop ! old y
] each
;
70 25 1000 mandel
|
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #PureBasic | PureBasic | #N=9
Define.i i,j
If OpenConsole("Magic squares")
PrintN("The square order is: "+Str(#N))
For i=1 To #N
For j=1 To #N
Print(RSet(Str((i*2-j+#N-1) % #N*#N + (i*2+j-2) % #N+1),5))
Next
PrintN("")
Next
PrintN("The magic number is: "+Str(#N*(#N*#N+1)/2))
EndIf
Input() |
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.
| #Haskell | Haskell | import Data.List
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
mmult a b = [ [ sum $ zipWith (*) ar bc | bc <- (transpose b) ] | ar <- a ]
-- Example use:
test = [[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]] |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Raku | Raku | sub A($k is copy, &x1, &x2, &x3, &x4, &x5) {
$k <= 0
?? x4() + x5()
!! (my &B = { A(--$k, &B, &x1, &x2, &x3, &x4) })();
};
say A(10, {1}, {-1}, {-1}, {1}, {0}); |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Haxe | Haxe | class Matrix {
static function main() {
var m = [ [1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256],
[5, 25, 125, 625] ];
var t = [ for (i in 0...m[0].length)
[ for (j in 0...m.length) 0 ] ];
for(i in 0...m.length)
for(j in 0...m[0].length)
t[j][i] = m[i][j];
for(aa in [m, t])
for(a in aa) Sys.println(a);
}
} |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Processing | Processing | int g_size = 10;
color background_color = color (80, 80, 220);
color runner = color (255, 50, 50);
color visited_color = color(220, 240, 240);
color done_color = color (100, 160, 250);
int c_size;
Cell[][] cell;
ArrayList<Cell> done = new ArrayList<Cell>();
ArrayList<Cell> visit = new ArrayList<Cell>();
Cell run_cell;
void setup() {
size(600, 600);
frameRate(20);
smooth(4);
strokeCap(ROUND);
c_size = max(width/g_size, height/g_size);
cell = new Cell[g_size][g_size];
for (int i = 0; i < g_size; i++) {
for (int j = 0; j < g_size; j++) {
cell[i][j] = new Cell(i, j);
}
}
for (int i = 0; i < g_size; i++) {
for (int j = 0; j < g_size; j++) {
cell[i][j].add_neighbor();
}
}
run_cell = cell[0][0];
visit.add(run_cell);
}
void draw() {
background(background_color);
for (int i = 0; i < g_size; i++) {
for (int j = 0; j < g_size; j++) {
cell[i][j].draw_cell();
cell[i][j].draw_wall();
}
}
if (visit.size() < g_size*g_size) {
if (run_cell.check_sides()) {
Cell chosen = run_cell.pick_neighbor();
done.add(run_cell);
run_cell.stacked = true;
if (chosen.i - run_cell.i == 1) {
run_cell.wall[1] = false;
chosen.wall[3] = false;
} else if (chosen.i - run_cell.i == -1) {
run_cell.wall[3] = false;
chosen.wall[1] = false;
} else if (chosen.j - run_cell.j == 1) {
run_cell.wall[2] = false;
chosen.wall[0] = false;
} else {
run_cell.wall[0] = false;
chosen.wall[2] = false;
}
run_cell.current = false;
run_cell = chosen;
run_cell.current = true;
run_cell.visited = true;
} else if (done.size()>0) {
run_cell.current = false;
run_cell = done.remove(done.size()-1);
run_cell.stacked = false;
run_cell.current = true;
}
}
}
class Cell {
ArrayList<Cell> neighbor;
boolean visited, stacked, current;
boolean[] wall;
int i, j;
Cell(int _i, int _j) {
i = _i;
j = _j;
wall = new boolean[]{true,true,true,true};
}
Cell pick_neighbor() {
ArrayList<Cell> unvisited = new ArrayList<Cell>();
for(int i = 0; i < neighbor.size(); i++){
Cell nb = neighbor.get(i);
if(nb.visited == false) unvisited.add(nb);
}
return unvisited.get(floor(random(unvisited.size())));
}
void add_neighbor() {
neighbor = new ArrayList<Cell>();
if(i>0){neighbor.add(cell[i-1][j]);}
if(i<g_size-1){neighbor.add(cell[i+1][j]);}
if(j>0){neighbor.add(cell[i][j-1]);}
if(j<g_size-1){neighbor.add(cell[i][j+1]);}
}
boolean check_sides() {
for(int i = 0; i < neighbor.size(); i++){
Cell nb = neighbor.get(i);
if(!nb.visited) return true;
}
return false;
}
void draw_cell() {
noStroke();
noFill();
if(current) fill(runner);
else if(stacked) fill(done_color);
else if(visited) fill(visited_color);
rect(j*c_size,i*c_size,c_size,c_size);
}
void draw_wall() {
stroke(0);
strokeWeight(5);
if(wall[0]) line(j*c_size, i*c_size, j*c_size, (i+1)* c_size);
if(wall[1]) line(j*c_size, (i+1)*c_size, (j+1)*c_size, (i+1)*c_size);
if(wall[2]) line((j+1)*c_size, (i+1)*c_size, (j+1)*c_size, i*c_size);
if(wall[3]) line((j+1)*c_size, i*c_size, j*c_size, i*c_size);
}
} |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Racket | Racket |
#lang racket
(define (make-range-map a1 a2 b1 b2)
;; returns a mapping function, doing computing the differences in
;; advance so it's fast
(let ([a (- a2 a1)] [b (- b2 b1)])
(λ(s) (exact->inexact (+ b1 (/ (* (- s a1) b) a))))))
(define map (make-range-map 0 10 -1 0))
(for ([i (in-range 0 11)]) (printf "~a --> ~a\n" i (map i)))
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Raku | Raku | sub getmapper(Range $a, Range $b) {
my ($a1, $a2) = $a.bounds;
my ($b1, $b2) = $b.bounds;
return -> $s { $b1 + (($s-$a1) * ($b2-$b1) / ($a2-$a1)) }
}
my &mapper = getmapper(0 .. 10, -1 .. 0);
for ^11 -> $x {say "$x maps to &mapper($x)"} |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Perl | Perl | use Digest::MD5 qw(md5_hex);
print md5_hex("The quick brown fox jumped over the lazy dog's back"), "\n"; |
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 .
| #Fennel | Fennel |
#!/usr/bin/env fennel
(fn mandelzahl [cr ci max i tr ti tr2 ti2]
"Calculates the Mandelbrot escape number of a complex point c"
(if (>= i max) -1
(>= (+ tr2 ti2) 4) i
(let [(tr ti) (values (+ (- tr2 ti2) cr)
(+ (* tr ti 2) ci))]
(mandelzahl cr ci max (+ i 1)
tr ti (* tr tr) (* ti ti)))))
(fn mandel [w h max]
"Entry point, generate a 'graphical' representation of the Mandelbrot set"
(for [y -1.0 1.0 (/ 2.0 h)]
(var line {})
(for [x -2.0 1.0 (/ 3.0 w)]
(let [mz (mandelzahl x y max 0 0 0 0 0)]
(tset line (+ (length line) 1)
(or (and (< mz 0) " ")
(string.char (+ (string.byte :a) (% mz 26)))))))
(print (table.concat line))))
(fn arg-def [pos default]
"A helper fn to extract command line parameter with defaults"
(or (tonumber (and arg (. arg pos))) default))
(let [width (arg-def 1 140)
height (arg-def 2 50)
max (arg-def 3 1e5)]
(mandel width height max))
|
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Python | Python | >>> def magic(n):
for row in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
(n * ((row + col - 1 + n // 2) % n) +
((row + 2 * col - 2) % n) + 1
for col in range(1, n + 1))))
print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))
>>> for n in (5, 3, 7):
print('\nOrder %i\n=======' % n)
magic(n)
Order 5
=======
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
All sum to magic number 65
Order 3
=======
8 1 6
3 5 7
4 9 2
All sum to magic number 15
Order 7
=======
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
All sum to magic number 175
>>> |
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.
| #HicEst | HicEst | REAL :: m=4, n=2, p=3, a(m,n), b(n,p), res(m,p)
a = $ ! initialize to 1, 2, ..., m*n
b = $ ! initialize to 1, 2, ..., n*p
res = 0
DO i = 1, m
DO j = 1, p
DO k = 1, n
res(i,j) = res(i,j) + a(i,k) * b(k,j)
ENDDO
ENDDO
ENDDO
DLG(DefWidth=4, Text=a, Text=b,Y=0, Text=res,Y=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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #REXX | REXX | /*REXX program performs the "man or boy" test as far as possible for N. */
do n=0 /*increment N from zero forever. */
say 'n='n a(N,x1,x2,x3,x4,x5) /*display the result to the terminal. */
end /*n*/ /* [↑] do until something breaks. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
a: procedure; parse arg k, x1, x2, x3, x4, x5
if k<=0 then return f(x4) + f(x5)
else return f(b)
/*──────────────────────────────────────────────────────────────────────────────────────*/
b: k=k-1; return a(k, b, x1, x2, x3, x4)
f: interpret 'v=' arg(1)"()"; return v
x1: procedure; return 1
x2: procedure; return -1
x3: procedure; return -1
x4: procedure; return 1
x5: procedure; return 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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Ruby | Ruby | def a(k, x1, x2, x3, x4, x5)
b = lambda { k -= 1; a(k, b, x1, x2, x3, x4) }
k <= 0 ? x4[] + x5[] : b[]
end
puts a(10, lambda {1}, lambda {-1}, lambda {-1}, lambda {1}, lambda {0}) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #HicEst | HicEst | REAL :: mtx(2, 4)
mtx = 1.1 * $
WRITE() mtx
SOLVE(Matrix=mtx, Transpose=mtx)
WRITE() 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-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Prolog | Prolog | :- dynamic cell/2.
maze(Lig,Col) :-
retractall(cell(_,_)),
new(D, window('Maze')),
% creation of the grid
forall(between(0,Lig, I),
(XL is 50, YL is I * 30 + 50,
XR is Col * 30 + 50,
new(L, line(XL, YL, XR, YL)),
send(D, display, L))),
forall(between(0,Col, I),
(XT is 50 + I * 30, YT is 50,
YB is Lig * 30 + 50,
new(L, line(XT, YT, XT, YB)),
send(D, display, L))),
SX is Col * 30 + 100,
SY is Lig * 30 + 100,
send(D, size, new(_, size(SX, SY))),
% choosing a first cell
L0 is random(Lig),
C0 is random(Col),
assert(cell(L0, C0)),
\+search(D, Lig, Col, L0, C0),
send(D, open).
search(D, Lig, Col, L, C) :-
Dir is random(4),
nextcell(Dir, Lig, Col, L, C, L1, C1),
assert(cell(L1,C1)),
assert(cur(L1,C1)),
erase_line(D, L, C, L1, C1),
search(D, Lig, Col, L1, C1).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
erase_line(D, L, C, L, C1) :-
( C < C1 -> C2 = C1; C2 = C),
XT is C2 * 30 + 50,
YT is L * 30 + 51, YR is (L+1) * 30 + 50,
new(Line, line(XT, YT, XT, YR)),
send(Line, colour, white),
send(D, display, Line).
erase_line(D, L, C, L1, C) :-
XT is 51 + C * 30, XR is 50 + (C + 1) * 30,
( L < L1 -> L2 is L1; L2 is L),
YT is L2 * 30 + 50,
new(Line, line(XT, YT, XR, YT)),
send(Line, colour, white),
send(D, display, Line).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nextcell(Dir, Lig, Col, L, C, L1, C1) :-
next(Dir, Lig, Col, L, C, L1, C1);
( Dir1 is (Dir+3) mod 4,
next(Dir1, Lig, Col, L, C, L1, C1));
( Dir2 is (Dir+1) mod 4,
next(Dir2, Lig, Col, L, C, L1, C1));
( Dir3 is (Dir+2) mod 4,
next(Dir3, Lig, Col, L, C, L1, C1)).
% 0 => northward
next(0, _Lig, _Col, L, C, L1, C) :-
L > 0,
L1 is L - 1,
\+cell(L1, C).
% 1 => rightward
next(1, _Lig, Col, L, C, L, C1) :-
C < Col - 1,
C1 is C + 1,
\+cell(L, C1).
% 2 => southward
next(2, Lig, _Col, L, C, L1, C) :-
L < Lig - 1,
L1 is L + 1,
\+cell(L1, C).
% 3 => leftward
next(2, _Lig, _Col, L, C, L, C1) :-
C > 0,
C1 is C - 1,
\+cell(L, C1).
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #ReScript | ReScript | let map_range = ((a1, a2), (b1, b2), s) => {
b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1))
}
Js.log("Mapping [0,10] to [-1,0] at intervals of 1:")
for i in 0 to 10 {
Js.log("f(" ++ Js.String.make(i) ++ ") = " ++
Js.String.make(map_range((0.0, 10.0), (-1.0, 0.0), float(i))))
} |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #REXX | REXX | /*REXX program maps and displays a range of numbers from one range to another range.*/
rangeA = 0 10 /*or: rangeA = ' 0 10 ' */
rangeB = -1 0 /*or: rangeB = " -1 0 " */
parse var rangeA L H
inc= 1
do j=L to H by inc * (1 - 2 * sign(H<L) ) /*BY: either +inc or -inc */
say right(j, 9) ' maps to ' mapR(rangeA, rangeB, j)
end /*j*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
mapR: procedure; parse arg a1 a2,b1 b2,s;$=b1+(s-a1)*(b2-b1)/(a2-a1);return left('',$>=0)$ |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Phix | Phix | $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $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 .
| #FOCAL | FOCAL | 1.1 S I1=-1.2; S I2=1.2; S R1=-2; S R2=.5
1.2 S MIT=30
1.3 F Y=1,24; D 2
1.4 Q
2.1 T !
2.2 F X=1,70; D 3
3.1 S R=X*(R2-R1)/70+R1
3.2 S I=Y*(I2-I1)/24+I1
3.3 S C1=R; S C2=I
3.4 F T=1,MIT; D 4
4.1 S C3=C1
4.2 S C1=C1*C1 - C2*C2
4.3 S C2=C3*C2 + C2*C3
4.4 S C1=C1+R
4.5 S C2=C2+I
4.6 I (-FABS(C1)+2)5.1
4.7 I (-FABS(C2)+2)5.1
4.8 I (MIT-T-1)6.1
5.1 S T=MIT; T "*"; R
6.1 T " "; R |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #QB64 | QB64 | _Title "Magic Squares of Odd Order"
'$Dynamic
DefLng A-Z
Dim Shared As Long m(1, 1)
Call magicSquare(5)
Call magicSquare(15)
Sleep
System
Sub magicSquare (n As Integer)
Dim As Integer inc, count, row, col
If (n < 3) Or (n And 1) <> 1 Then n = 3
ReDim m(n, n)
inc = 1
count = 1
row = 1
col = (n + 1) / 2
While count <= n * n
m(row, col) = count
count = count + 1
If inc < n Then
inc = inc + 1
row = row - 1
col = col + 1
If row <> 0 Then
If col > n Then col = 1
Else
row = n
End If
Else
inc = 1
row = row + 1
End If
Wend
Call printSquare(n)
End Sub
Sub printSquare (n As Integer)
Dim As Integer row, col
'Arbitrary limit ensures a fit within console window
'Can be any size that fits within your computers memory limits
If n < 21 Then
Print "Order "; n; " Magic Square constant is "; Str$(Int((n * n + 1) / 2 * n))
For row = 1 To n
For col = 1 To n
Print Using "####"; m(row, col);
Next col
Print
' Print
Next row
End If
End Sub |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #R | R | > magic(5)
[,1] [,2] [,3] [,4] [,5]
[1,] 17 24 1 8 15
[2,] 23 5 7 14 16
[3,] 4 6 13 20 22
[4,] 10 12 19 21 3
[5,] 11 18 25 2 9 |
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.
| #Icon_and_Unicon | Icon and Unicon |
link matrix
procedure main ()
m1 := [[1,2,3], [4,5,6]]
m2 := [[1,2],[3,4],[5,6]]
m3 := mult_matrix (m1, m2)
write ("Multiply:")
write_matrix ("", m1) # first argument is filename, or "" for stdout
write ("by:")
write_matrix ("", m2)
write ("Result: ")
write_matrix ("", m3)
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Rust | Rust | use std::cell::Cell;
trait Arg {
fn run(&self) -> i32;
}
impl Arg for i32 {
fn run(&self) -> i32 { *self }
}
struct B<'a> {
k: &'a Cell<i32>,
x1: &'a Arg,
x2: &'a Arg,
x3: &'a Arg,
x4: &'a Arg,
}
impl<'a> Arg for B<'a> {
fn run(&self) -> i32 {
self.k.set(self.k.get() - 1);
a(self.k.get(), self, self.x1, self.x2, self.x3, self.x4)
}
}
fn a(k: i32, x1: &Arg, x2: &Arg, x3: &Arg, x4: &Arg, x5: &Arg) -> i32 {
if k <= 0 {
x4.run() + x5.run()
} else {
B{
k: &Cell::new(k),
x1, x2, x3, x4
}.run()
}
}
pub fn main() {
println!("{}", 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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Scala | Scala | def A(in_k: Int, x1: =>Int, x2: =>Int, x3: =>Int, x4: =>Int, x5: =>Int): Int = {
var k = in_k
def B: Int = {
k = k-1
A(k, B, x1, x2, x3, x4)
}
if (k<=0) x4+x5 else B
}
println(A(10, 1, -1, -1, 1, 0)) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Hope | Hope | uses lists;
dec transpose : list (list alpha) -> list (list alpha);
--- transpose ([]::_) <= [];
--- transpose n <= map head n :: transpose (map tail n); |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #PureBasic | PureBasic | Enumeration
;indexes for types of offsets from maze coordinates (x,y)
#visited ;used to index visited(x,y) in a given direction from current maze cell
#maze ;used to index maze() in a given direction from current maze cell
#wall ;used to index walls in maze() in a given direction from current maze cell
#numOffsets = #wall
;direction indexes
#dir_ID = 0 ;identity value, produces no changes
#firstDir
#dir_N = #firstDir
#dir_E
#dir_S
#dir_W
#numDirs = #dir_W
EndEnumeration
DataSection
;maze(x,y) offsets for visited, maze, & walls for each direction
Data.i 1, 1, 0, 0, 0, 0 ;ID
Data.i 1, 0, 0, -1, 0, 0 ;N
Data.i 2, 1, 1, 0, 1, 0 ;E
Data.i 1, 2, 0, 1, 0, 1 ;S
Data.i 0, 1, -1, 0, 0, 0 ;W
Data.i %00, %01, %10, %01, %10 ;wall values for ID, N, E, S, W
EndDataSection
#cellDWidth = 4
Structure mazeOutput
vWall.s
hWall.s
EndStructure
;setup reference values indexed by type and direction from current map cell
Global Dim offset.POINT(#numOffsets, #numDirs)
Define i, j
For i = 0 To #numDirs
For j = 0 To #numOffsets
Read.i offset(j, i)\x: Read.i offset(j, i)\y
Next
Next
Global Dim wallvalue(#numDirs)
For i = 0 To #numDirs: Read.i wallvalue(i): Next
Procedure makeDisplayMazeRow(Array mazeRow.mazeOutput(1), Array maze(2), y)
;modify mazeRow() to produce output of 2 strings showing the vertical walls above and horizontal walls across a given maze row
Protected x, vWall.s, hWall.s
Protected mazeWidth = ArraySize(maze(), 1), mazeHeight = ArraySize(maze(), 2)
vWall = "": hWall = ""
For x = 0 To mazeWidth
If maze(x, y) & wallvalue(#dir_N): vWall + "+ ": Else: vWall + "+---": EndIf
If maze(x, y) & wallvalue(#dir_W): hWall + " ": Else: hWall + "| ": EndIf
Next
mazeRow(0)\vWall = Left(vWall, mazeWidth * #cellDWidth + 1)
If y <> mazeHeight: mazeRow(0)\hWall = Left(hWall, mazeWidth * #cellDWidth + 1): Else: mazeRow(0)\hWall = "": EndIf
EndProcedure
Procedure displayMaze(Array maze(2))
Protected x, y, vWall.s, hWall.s, mazeHeight = ArraySize(maze(), 2)
Protected Dim mazeRow.mazeOutput(0)
For y = 0 To mazeHeight
makeDisplayMazeRow(mazeRow(), maze(), y)
PrintN(mazeRow(0)\vWall): PrintN(mazeRow(0)\hWall)
Next
EndProcedure
Procedure generateMaze(Array maze(2), mazeWidth, mazeHeight)
Dim maze(mazeWidth, mazeHeight) ;Each cell specifies walls present above and to the left of it,
;array includes an extra row and column for the right and bottom walls
Dim visited(mazeWidth + 1, mazeHeight + 1) ;Each cell represents a cell of the maze, an extra line of cells are included
;as padding around the representative cells for easy border detection
Protected i
;mark outside border as already visited (off limits)
For i = 0 To mazeWidth
visited(i + offset(#visited, #dir_N)\x, 0 + offset(#visited, #dir_N)\y) = #True
visited(i + offset(#visited, #dir_S)\x, mazeHeight - 1 + offset(#visited, #dir_S)\y) = #True
Next
For i = 0 To mazeHeight
visited(0 + offset(#visited, #dir_W)\x, i + offset(#visited, #dir_W)\y) = #True
visited(mazeWidth - 1 + offset(#visited, #dir_E)\x, i + offset(#visited, #dir_E)\y) = #True
Next
;generate maze
Protected x = Random(mazeWidth - 1), y = Random (mazeHeight - 1), cellCount, nextCell
visited(x + offset(#visited, #dir_ID)\x, y + offset(#visited, #dir_ID)\y) = #True
PrintN("Maze of size " + Str(mazeWidth) + " x " + Str(mazeHeight) + ", generation started at " + Str(x) + " x " + Str(y))
NewList stack.POINT()
Dim unvisited(#numDirs - #firstDir)
Repeat
cellCount = 0
For i = #firstDir To #numDirs
If Not visited(x + offset(#visited, i)\x, y + offset(#visited, i)\y)
unvisited(cellCount) = i: cellCount + 1
EndIf
Next
If cellCount
nextCell = unvisited(Random(cellCount - 1))
visited(x + offset(#visited, nextCell)\x, y + offset(#visited, nextCell)\y) = #True
maze(x + offset(#wall, nextCell)\x, y + offset(#wall, nextCell)\y) | wallvalue(nextCell)
If cellCount > 1
AddElement(stack())
stack()\x = x: stack()\y = y
EndIf
x + offset(#maze, nextCell)\x: y + offset(#maze, nextCell)\y
ElseIf ListSize(stack()) > 0
x = stack()\x: y = stack()\y
DeleteElement(stack())
Else
Break ;end maze generation
EndIf
ForEver
; ;mark random entry and exit point
; x = Random(mazeWidth - 1): y = Random(mazeHeight - 1)
; maze(x, 0) | wallvalue(#dir_N): maze(mazeWidth, y) | wallvalue(#dir_E)
ProcedureReturn
EndProcedure
If OpenConsole()
Dim maze(0, 0)
Define mazeWidth = Random(5) + 7: mazeHeight = Random(5) + 3
generateMaze(maze(), mazeWidth, mazeHeight)
displayMaze(maze())
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Ring | Ring |
# Project : Map range
decimals(1)
al = 0
ah = 10
bl = -1
bh = 0
for n = 0 to 10
see "" + n + " maps to " + maprange(al, bl, n) + nl
next
func maprange(al, bl, s)
return bl + (s - al) * (bh - bl) / (ah - al)
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Ruby | Ruby | def map_range(a, b, s)
af, al, bf, bl = a.first, a.last, b.first, b.last
bf + (s - af)*(bl - bf).quo(al - af)
end
(0..10).each{|s| puts "%s maps to %g" % [s, map_range(0..10, -1..0, s)]} |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #PHP | PHP | $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $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 .
| #Forth | Forth | 500 value max-iter
: mandel ( gmp F: imin imax rmin rmax -- )
0e 0e { F: imin F: imax F: rmin F: rmax F: Zr F: Zi }
dup bheight 0 do
i s>f dup bheight s>f f/ imax imin f- f* imin f+ TO Zi
dup bwidth 0 do
i s>f dup bwidth s>f f/ rmax rmin f- f* rmin f+ TO Zr
Zr Zi max-iter
begin 1- dup
while fover fdup f* fover fdup f*
fover fover f+ 4e f<
while f- Zr f+
frot frot f* 2e f* Zi f+
repeat fdrop fdrop
drop 0 \ for a pretty grayscale image, replace with: 255 max-iter */
else drop 255
then fdrop fdrop
over i j rot g!
loop
loop drop ;
80 24 graymap
dup -1e 1e -2e 1e mandel |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Racket | Racket | #lang racket
;; Using "helpful formulae" in:
;; http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order
(define (squares n) n)
(define (last-no n) (sqr n))
(define (middle-no n) (/ (add1 (sqr n)) 2))
(define (M n) (* n (middle-no n)))
(define ((Ith-row-Jth-col n) I J)
(+ (* (modulo (+ I J -1 (exact-floor (/ n 2))) n) n)
(modulo (+ I (* 2 J) -2) n)
1))
(define (magic-square n)
(define IrJc (Ith-row-Jth-col n))
(for/list ((I (in-range 1 (add1 n)))) (for/list ((J (in-range 1 (add1 n)))) (IrJc I J))))
(define (fmt-list-of-lists l-o-l width)
(string-join
(for/list ((row l-o-l))
(string-join (map (λ (x) (~a #:align 'right #:width width x)) row) " "))
"\n"))
(define (show-magic-square n)
(format "MAGIC SQUARE ORDER:~a~%~a~%MAGIC NUMBER:~a~%"
n (fmt-list-of-lists (magic-square n) (+ (order-of-magnitude (last-no n)) 1)) (M n)))
(displayln (show-magic-square 3))
(displayln (show-magic-square 5))
(displayln (show-magic-square 9)) |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Raku | Raku | 17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
The magic number is 65 |
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.
| #IDL | IDL | result = arr1 # arr2 |
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Scheme | Scheme | (define (A k x1 x2 x3 x4 x5)
(define (B)
(set! k (- k 1))
(A k B x1 x2 x3 x4))
(if (<= k 0)
(+ (x4) (x5))
(B)))
(A 10 (lambda () 1) (lambda () -1) (lambda () -1) (lambda () 1) (lambda () 0)) |
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Sidef | Sidef | func a(k, x1, x2, x3, x4, x5) {
func b { a(--k, b, x1, x2, x3, x4) };
k <= 0 ? (x4() + x5()) : b();
}
say a(10, ->{1}, ->{-1}, ->{-1}, ->{1}, ->{0}); #=> -67 |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Icon_and_Unicon | Icon and Unicon | procedure transpose_matrix (matrix)
result := []
# for each column
every (i := 1 to *matrix[1]) do {
col := []
# extract the number in each row for that column
every (row := !matrix) do put (col, row[i])
# and push that column as a row in the result matrix
put (result, col)
}
return result
end
procedure print_matrix (matrix)
every (row := !matrix) do {
every writes (!row || " ")
write ()
}
end
procedure main ()
matrix := [[1,2,3],[4,5,6]]
write ("Start:")
print_matrix (matrix)
transposed := transpose_matrix (matrix)
write ("Transposed:")
print_matrix (transposed)
end |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Python | Python | from random import shuffle, randrange
def make_maze(w = 16, h = 8):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
ver = [["| "] * w + ['|'] for _ in range(h)] + [[]]
hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
shuffle(d)
for (xx, yy) in d:
if vis[yy][xx]: continue
if xx == x: hor[max(y, yy)][x] = "+ "
if yy == y: ver[y][max(x, xx)] = " "
walk(xx, yy)
walk(randrange(w), randrange(h))
s = ""
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
if __name__ == '__main__':
print(make_maze()) |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Rust | Rust | use std::ops::{Add, Sub, Mul, Div};
fn map_range<T: Copy>(from_range: (T, T), to_range: (T, T), s: T) -> T
where T: Add<T, Output=T> +
Sub<T, Output=T> +
Mul<T, Output=T> +
Div<T, Output=T>
{
to_range.0 + (s - from_range.0) * (to_range.1 - to_range.0) / (from_range.1 - from_range.0)
}
fn main() {
let input: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
let result = input.into_iter()
.map(|x| map_range((0.0, 10.0), (-1.0, 0.0), x))
.collect::<Vec<f64>>();
print!("{:?}", result);
} |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Scala | Scala | def mapRange(a1:Double, a2:Double, b1:Double, b2:Double, x:Double):Double=b1+(x-a1)*(b2-b1)/(a2-a1)
for(i <- 0 to 10)
println("%2d in [0, 10] maps to %5.2f in [-1, 0]".format(i, mapRange(0,10, -1,0, 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: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #PicoLisp | PicoLisp | (let Str "The quick brown fox jumped over the lazy dog's back"
(pack
(mapcar '((B) (pad 2 (hex B)))
(native "libcrypto.so" "MD5" '(B . 16) Str (length Str) '(NIL (16))) ) ) ) |
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 .
| #Fortran | Fortran | program mandelbrot
implicit none
integer , parameter :: rk = selected_real_kind (9, 99)
integer , parameter :: i_max = 800
integer , parameter :: j_max = 600
integer , parameter :: n_max = 100
real (rk), parameter :: x_centre = -0.5_rk
real (rk), parameter :: y_centre = 0.0_rk
real (rk), parameter :: width = 4.0_rk
real (rk), parameter :: height = 3.0_rk
real (rk), parameter :: dx_di = width / i_max
real (rk), parameter :: dy_dj = -height / j_max
real (rk), parameter :: x_offset = x_centre - 0.5_rk * (i_max + 1) * dx_di
real (rk), parameter :: y_offset = y_centre - 0.5_rk * (j_max + 1) * dy_dj
integer, dimension (i_max, j_max) :: image
integer :: i
integer :: j
integer :: n
real (rk) :: x
real (rk) :: y
real (rk) :: x_0
real (rk) :: y_0
real (rk) :: x_sqr
real (rk) :: y_sqr
do j = 1, j_max
y_0 = y_offset + dy_dj * j
do i = 1, i_max
x_0 = x_offset + dx_di * i
x = 0.0_rk
y = 0.0_rk
n = 0
do
x_sqr = x ** 2
y_sqr = y ** 2
if (x_sqr + y_sqr > 4.0_rk) then
image (i, j) = 255
exit
end if
if (n == n_max) then
image (i, j) = 0
exit
end if
y = y_0 + 2.0_rk * x * y
x = x_0 + x_sqr - y_sqr
n = n + 1
end do
end do
end do
open (10, file = 'out.pgm')
write (10, '(a/ i0, 1x, i0/ i0)') 'P2', i_max, j_max, 255
write (10, '(i0)') image
close (10)
end program mandelbrot |
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #REXX | REXX | /*REXX program generates and displays magic squares (odd N will be a true magic square).*/
parse arg N . /*obtain the optional argument from CL.*/
if N=='' | N=="," then N=5 /*Not specified? Then use the default.*/
NN=N*N; w=length(NN) /*W: width of largest number (output).*/
r=1; c=(n+1) % 2 /*define the initial row and column.*/
@.=. /*assign a default value for entire @.*/
do j=1 for NN /* [↓] filling uses the Siamese method*/
if r<1 & c>N then do; r=r+2; c=c-1; end /*the row is under, column is over.*/
if r<1 then r=N /* " " " " make row=last. */
if r>N then r=1 /* " " " over, " " first.*/
if c>N then c=1 /* " column " over, " col=first.*/
if @.r.c\==. then do; r=min(N,r+2); c=max(1,c-1); end /*at the previous cell? */
@.r.c=j; r=r-1; c=c+1 /*assign # ───► cell; next row & column*/
end /*j*/
/* [↓] display square with aligned #'s*/
do r=1 for N; _= /*display one matrix row at a time. */
do c=1 for N; _=_ right(@.r.c, w) /*construct a row of the magic square. */
end /*c*/
say substr(_, 2) /*display a row of the magic square. */
end /*r*/
say /* [↓] If an odd square, show magic #.*/
if N//2 then say 'The magic number (or magic constant is): ' N * (NN+1) % 2
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Idris | Idris | import Data.Vect
Matrix : Nat -> Nat -> Type -> Type
Matrix m n t = Vect m (Vect n t)
multiply : Num t => Matrix m1 n t -> Matrix n m2 t -> Matrix m1 m2 t
multiply a b = multiply' a (transpose b)
where
dot : Num t => Vect n t -> Vect n t -> t
dot v1 v2 = sum $ map (\(s1, s2) => (s1 * s2)) (zip v1 v2)
multiply' : Num t => Matrix m1 n t -> Matrix m2 n t -> Matrix m1 m2 t
multiply' (a::as) b = map (dot a) b :: multiply' as b
multiply' [] _ = [] |
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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Smalltalk | Smalltalk | Number>>x1: x1 x2: x2 x3: x3 x4: x4 x5: x5
| b k |
k := self.
b := [ k := k - 1. k x1: b x2: x1 x3: x2 x4: x3 x5: x4 ].
^k <= 0 ifTrue: [ x4 value + x5 value ] ifFalse: b
10 x1: [1] x2: [-1] x3: [-1] x4: [1] x5: [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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Snap.21 | Snap! | function a(k, x1, x2, x3, x4, x5) {
let kk = { "k": k.k };
let b = function b() {
kk.k--;
return a(kk, b, x1, x2, x3, x4);
};
return kk.k <= 0 ? x4() + x5() : b();
}
function x(n) {
return function () {
return n;
};
}
print(a({ "k": 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.
| #IDL | IDL | m=[[1,1,1,1],[2, 4, 8, 16],[3, 9,27, 81],[5, 25,125, 625]]
print,transpose(m) |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Racket | Racket |
#lang racket
;; the structure representing a maze of size NxM
(struct maze (N M tbl))
;; managing cell properties
(define (connections tbl c) (dict-ref tbl c '()))
(define (connect! tbl c n)
(dict-set! tbl c (cons n (connections tbl c)))
(dict-set! tbl n (cons c (connections tbl n))))
(define (connected? tbl a b) (member a (connections tbl b)))
;; Returns a maze of a given size
;; build-maze :: Index Index -> Maze
(define (build-maze N M)
(define tbl (make-hash))
(define (visited? tbl c) (dict-has-key? tbl c))
(define (neigbours c)
(filter
(match-lambda [(list i j) (and (<= 0 i (- N 1)) (<= 0 j (- M 1)))])
(for/list ([d '((0 1) (0 -1) (-1 0) (1 0))]) (map + c d))))
; generate the maze
(let move-to-cell ([c (list (random N) (random M))])
(for ([n (shuffle (neigbours c))] #:unless (visited? tbl n))
(connect! tbl c n)
(move-to-cell n)))
; return the result
(maze N M tbl))
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: mapRange (in float: a1, in float: a2, in float: b1, in float: b2, ref float: s) is
return b1 + (s-a1)*(b2-b1)/(a2-a1);
const proc: main is func
local
var integer: number is 0;
begin
writeln("Mapping [0,10] to [-1,0] at intervals of 1:");
for number range 0 to 10 do
writeln("f(" <& number <& ") = " <& mapRange(0.0, 10.0, -1.0, 0.0, flt(number)) digits 1);
end for;
end func; |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Sidef | Sidef | func map_range(a, b, x) {
var (a1, a2, b1, b2) = (a.bounds, b.bounds);
x-a1 * b2-b1 / a2-a1 + b1;
}
var a = 0..10;
var b = -1..0;
for x in a {
say "#{x} maps to #{map_range(a, b, x)}";
} |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Pike | Pike | import String;
import Crypto.MD5;
int main(){
write( string2hex( hash( "The quick brown fox jumped over the lazy dog's back" ) ) + "\n" );
} |
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 .
| #Frink | Frink |
// Maximum levels for each pixel.
levels = 60
// Create a random color for each level.
colors = new array[[levels]]
for a = 0 to levels-1
colors@a = new color[randomFloat[0,1], randomFloat[0,1], randomFloat[0,1]]
// Make this number smaller for higher resolution.
stepsize = .005
g = new graphics
g.antialiased[false]
for im = -1.2 to 1.2 step stepsize
{
imag = i * im
for real = -2 to 1 step stepsize
{
C = real + imag
z = 0
count = -1
do
{
z = z^2 + C
count=count+1;
} while abs[z] < 4 and count < levels
g.color[colors@((count-1) mod levels)]
g.fillRectSize[real, im, stepsize, stepsize]
}
}
g.show[]
|
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Ring | Ring |
n=9
see "the square order is : " + n + nl
for i=1 to n
for j = 1 to n
x = (i*2-j+n-1) % n*n + (i*2+j-2) % n + 1
see "" + x + " "
next
see nl
next
see "the magic number is : " + n*(n*n+1) / 2 + nl
|
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) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #Ruby | Ruby | def odd_magic_square(n)
raise ArgumentError "Need odd positive number" if n.even? || n <= 0
n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} }
end
[3, 5, 9].each do |n|
puts "\nSize #{n}, magic sum #{(n*n+1)/2*n}"
fmt = "%#{(n*n).to_s.size + 1}d" * n
odd_magic_square(n).each{|row| puts fmt % row}
end
|
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.
| #J | J | mp =: +/ .* NB. Matrix product
A =: ^/~>:i. 4 NB. Same A as in other examples (1 1 1 1, 2 4 8 16, 3 9 27 81,:4 16 64 256)
B =: %.A NB. Matrix inverse of A
'6.2' 8!:2 A mp B
1.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00 |
http://rosettacode.org/wiki/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 distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Sparkling | Sparkling | function a(k, x1, x2, x3, x4, x5) {
let kk = { "k": k.k };
let b = function b() {
kk.k--;
return a(kk, b, x1, x2, x3, x4);
};
return kk.k <= 0 ? x4() + x5() : b();
}
function x(n) {
return function () {
return n;
};
}
print(a({ "k": 10 }, x(1), x(-1), x(-1), x(1), x(0))); |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Standard_ML | Standard ML | fun a (k, x1, x2, x3, x4, x5) =
if k <= 0 then
x4 () + x5 ()
else let
val m = ref k
fun b () = (
m := !m - 1;
a (!m, b, x1, x2, x3, x4)
)
in
b ()
end
val () =
print (Int.toString (a (10, fn () => 1, fn () => ~1, fn () => ~1, fn () => 1, fn () => 0)) ^ "\n") |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.