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/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
| #Kotlin | Kotlin | // version 1.1.3
typealias Func = () -> Int
fun a(k: Int, x1: Func, x2: Func, x3: Func, x4: Func, x5: Func): Int {
var kk = k
fun b(): Int = a(--kk, ::b, x1, x2, x3, x4)
return if (kk <= 0) x4() + x5() else b()
}
fun main(args: Array<String>) {
println(" k a")
for (k in 0..12) {
println("${"%2d".format(k)}: ${a(k, { 1 }, { -1 }, { -1 }, { 1 }, { 0 })}")
}
}
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Euphoria | Euphoria | function transpose(sequence in)
sequence out
out = repeat(repeat(0,length(in)),length(in[1]))
for n = 1 to length(in) do
for m = 1 to length(in[1]) do
out[m][n] = in[n][m]
end for
end for
return out
end function
sequence m
m = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
}
? 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.
| #Lua | Lua |
math.randomseed( os.time() )
-- Fisher-Yates shuffle from http://santos.nfshost.com/shuffling.html
function shuffle(t)
for i = 1, #t - 1 do
local r = math.random(i, #t)
t[i], t[r] = t[r], t[i]
end
end
-- builds a width-by-height grid of trues
function initialize_grid(w, h)
local a = {}
for i = 1, h do
table.insert(a, {})
for j = 1, w do
table.insert(a[i], true)
end
end
return a
end
-- average of a and b
function avg(a, b)
return (a + b) / 2
end
dirs = {
{x = 0, y = -2}, -- north
{x = 2, y = 0}, -- east
{x = -2, y = 0}, -- west
{x = 0, y = 2}, -- south
}
function make_maze(w, h)
w = w or 16
h = h or 8
local map = initialize_grid(w*2+1, h*2+1)
function walk(x, y)
map[y][x] = false
local d = { 1, 2, 3, 4 }
shuffle(d)
for i, dirnum in ipairs(d) do
local xx = x + dirs[dirnum].x
local yy = y + dirs[dirnum].y
if map[yy] and map[yy][xx] then
map[avg(y, yy)][avg(x, xx)] = false
walk(xx, yy)
end
end
end
walk(math.random(1, w)*2, math.random(1, h)*2)
local s = {}
for i = 1, h*2+1 do
for j = 1, w*2+1 do
if map[i][j] then
table.insert(s, '#')
else
table.insert(s, ' ')
end
end
table.insert(s, '\n')
end
return table.concat(s)
end
print(make_maze())
|
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var m = Matrix.new([[0, 1], [1, 1]])
System.print("Original:\n")
Fmt.mprint(m, 2, 0)
System.print("\nRaised to power of 10:\n")
Fmt.mprint(m ^ 10, 3, 0) |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\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.
| #Lasso | Lasso | define map_range(
a1,
a2,
b1,
b2,
number
) => (decimal(#b1) + (decimal(#number) - decimal(#a1)) * (decimal(#b2) - decimal(#b1)) / (decimal(#a2) - decimal(#a1))) -> asstring(-Precision = 1)
with number in generateSeries(1,10) do {^
#number
': '
map_range( 0, 10, -1, 0, #number)
'<br />'
^}' |
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.
| #Liberty_BASIC | Liberty BASIC | For i = 0 To 10
Print "f(";i;") maps to ";mapToRange(i, 0, 10, -1, 0)
Next i
End
Function mapToRange(value, inputMin, inputMax, outputMin, outputMax)
mapToRange = (((value - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin
End Function
|
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #VBScript | VBScript |
'Solution derived from http://stackoverflow.com/questions/8002252/euler-project-18-approach.
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\triangle.txt",1,False)
row = Split(objinfile.ReadAll,vbCrLf)
For i = UBound(row) To 0 Step -1
row(i) = Split(row(i)," ")
If i < UBound(row) Then
For j = 0 To UBound(row(i))
If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))
Else
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))
End If
Next
End If
Next
WScript.Echo row(0)(0)
objinfile.Close
Set objfso = Nothing
|
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.
| #Neko | Neko | /**
MD5 in Neko
Tectonics:
nekoc md5.neko
neko md5
*/
var MD5 = $loader.loadprim("std@make_md5", 1);
var base_encode = $loader.loadprim("std@base_encode", 2);
var result = MD5("The quick brown fox jumps over the lazy dog");
/* Output in lowercase hex */
$print(base_encode(result, "0123456789abcdef")); |
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 .
| #D | D | void main() {
import std.stdio, std.complex;
for (real y = -1.2; y < 1.2; y += 0.05) {
for (real x = -2.05; x < 0.55; x += 0.03) {
auto z = 0.complex;
foreach (_; 0 .. 100)
z = z ^^ 2 + complex(x, y);
write(z.abs < 2 ? '#' : '.');
}
writeln;
}
} |
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)
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
n := integer(!A) | 3
write("Magic number: ",n*(n*n+1)/2)
sq := buildSquare(n)
showSquare(sq)
end
procedure buildSquare(n)
sq := [: |list(n)\n :]
r := 0
c := n/2
every i := !(n*n) do {
/sq[r+1,c+1] := i
nr := (n+r-1)%n
nc := (c+1)%n
if /sq[nr+1,nc+1] then (r := nr,c := nc) else r := (r+1)%n
}
return sq
end
procedure showSquare(sq)
n := *sq
s := *(n*n)+2
every r := !sq do every writes(right(!r,s)|"\n")
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.
| #F.23 | F# |
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let result_row = (matrix1.GetLength 0)
let result_column = (matrix2.GetLength 1)
let ret = Array2D.create result_row result_column 0
for x in 0 .. result_row - 1 do
for y in 0 .. result_column - 1 do
let mutable acc = 0
for z in 0 .. (matrix1.GetLength 1) - 1 do
acc <- acc + matrix1.[x,z] * matrix2.[z,y]
ret.[x,y] <- acc
ret
|
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Scala | Scala | object MagicSquareDoublyEven extends App {
private val n = 8
private def magicSquareDoublyEven(n: Int): Array[Array[Int]] = {
require(n >= 4 || n % 4 == 0, "Base must be a positive multiple of 4.")
// pattern of count-up vs count-down zones
val (bits, mult, result, size) = (38505, n / 4, Array.ofDim[Int](n, n), n * n)
var i = 0
for (r <- result.indices; c <- result(0).indices) {
def bitPos = c / mult + (r / mult) * 4
result(r)(c) = if ((bits & (1 << bitPos)) != 0) i + 1 else size - i
i += 1
}
result
}
magicSquareDoublyEven(n).foreach(row => println(row.map(x => f"$x%2s ").mkString))
println(f"---%nMagic constant: ${(n * n + 1) * n / 2}%d")
} |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Sidef | Sidef | func double_even_magic_square(n) {
assert(n%4 == 0, "Need multiple of four")
var (bsize, max) = (n/4, n*n)
var pre_pat = [true, false, false, true,
false, true, true, false]
pre_pat += pre_pat.flip
var pattern = (pre_pat.map{|b| bsize.of(b)... } * bsize)
pattern.map_kv{|k,v| v ? k+1 : max-k }.slices(n)
}
func format_matrix(a) {
var fmt = "%#{a.len**2 -> len}s"
a.map { .map { fmt % _ }.join(' ') }.join("\n")
}
say format_matrix(double_even_magic_square(8)) |
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
| #Lox | Lox | fun A (k, xa, xb, xc, xd, xe) {
print k;
fun B() {
k = k - 1;
return A(k, B, xa, xb, xc, xd);
}
if (k <= 0) {
return xd() + xe();
} else {
return B();
}
}
fun I0() { return 0; }
fun I1() { return 1; }
fun I_1() { return -1; }
print A(10, I1, I_1, I_1, I1, I0); |
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
| #Lua | Lua | function a(k,x1,x2,x3,x4,x5)
local function b()
k = k - 1
return a(k,b,x1,x2,x3,x4)
end
if k <= 0 then return x4() + x5() else return b() end
end
function K(n)
return function()
return n
end
end
print(a(10, K(1), K(-1), K(-1), K(1), K(0))) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Excel | Excel | let transpose (mtx : _ [,]) = Array2D.init (mtx.GetLength 1) (mtx.GetLength 0) (fun x y -> mtx.[y,x]) |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Maze {
width% = 40
height% = 20
\\ we can use DIM maze$(0 to width%,0 to height%)="#"
\\ so we can delete the two For loops
DIM maze$(0 to width%,0 to height%)
FOR x% = 0 TO width%
FOR y% = 0 TO height%
maze$(x%, y%) = "#"
NEXT y%
NEXT x%
currentx% = INT(RND * (width% - 1))
currenty% = INT(RND * (height% - 1))
IF currentx% MOD 2 = 0 THEN currentx%++
IF currenty% MOD 2 = 0 THEN currenty%++
maze$(currentx%, currenty%) = " "
done% = 0
WHILE done% = 0 {
FOR i% = 0 TO 99
oldx% = currentx%
oldy% = currenty%
SELECT CASE INT(RND * 4)
CASE 0
IF currentx% + 2 < width% THEN currentx%+=2
CASE 1
IF currenty% + 2 < height% THEN currenty%+=2
CASE 2
IF currentx% - 2 > 0 THEN currentx%-=2
CASE 3
IF currenty% - 2 > 0 THEN currenty%-=2
END SELECT
IF maze$(currentx%, currenty%) = "#" Then {
maze$(currentx%, currenty%) = " "
maze$(INT((currentx% + oldx%) / 2), ((currenty% + oldy%) / 2)) = " "
}
NEXT i%
done% = 1
FOR x% = 1 TO width% - 1 STEP 2
FOR y% = 1 TO height% - 1 STEP 2
IF maze$(x%, y%) = "#" THEN done% = 0
NEXT y%
NEXT x%
}
FOR y% = 0 TO height%
FOR x% = 0 TO width%
PRINT maze$(x%, y%);
NEXT x%
PRINT
NEXT y%
}
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.
| #Logo | Logo | to interpolate :s :a1 :a2 :b1 :b2
output (:s-:a1) / (:a2-:a1) * (:b2-:b1) + :b1
end
for [i 0 10] [print interpolate :i 0 10 -1 0] |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\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.
| #Lua | Lua | function map_range( a1, a2, b1, b2, s )
return b1 + (s-a1)*(b2-b1)/(a2-a1)
end
for i = 0, 10 do
print( string.format( "f(%d) = %f", i, map_range( 0, 10, -1, 0, i ) ) )
end |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #Wren | Wren | var lines = [
" 55",
" 94 48",
" 95 30 96",
" 77 71 26 67",
" 97 13 76 38 45",
" 07 36 79 16 37 68",
" 48 07 09 18 70 26 06",
" 18 72 79 46 59 79 29 90",
" 20 76 87 11 32 07 07 49 18",
" 27 83 58 35 71 11 25 57 29 85",
" 14 64 36 96 27 11 58 56 92 18 55",
" 02 90 03 60 48 49 41 46 33 36 47 23",
" 92 50 48 02 36 59 42 79 72 20 82 77 42",
" 56 78 38 80 39 75 02 71 66 66 01 03 55 72",
" 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36",
" 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52",
" 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15",
"27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"
]
var f = lines[-1].split(" ")
var d = f.map { |s| Num.fromString(s) }.toList
for (row in lines.count-2..0) {
var l = d[0]
var i = 0
for (s in lines[row].trimStart().split(" ")) {
var u = Num.fromString(s)
var r = d[i+1]
d[i] = (l > r) ? u + l : u + r
l = r
i = i + 1
}
}
System.print(d[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.
| #Nemerle | Nemerle | using System;
using System.Console;
using System.Text;
using System.Security.Cryptography;
using Nemerle.Collections;
using Nemerle.Collections.NCollectionsExtensions;
module Md5
{
HashMD5(input : string) : string
{
BitConverter.ToString
(MD5.Create().ComputeHash(Encoding.Default.GetBytes(input))).Replace("-", "").ToLower()
}
IsValidMD5(text : string, hash : string) : bool
{
HashMD5(text) == hash.ToLower()
}
Main() : void
{
def examples = ["The quick brown fox jumped over the lazy dog's back", "", "a", "abc", "message digest",
"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"];
def hashes = ["e38ca1d920c4b8b8d3946b2c72f01680", "d41d8cd98f00b204e9800998ecf8427e",
"0cc175b9c0f1b6a831c399e269772661", "900150983cd24fb0d6963f7d28e17f72",
"f96b697d7cb7938d525a2f31aaf161d0", "c3fcd3d76192e4007dfb496cca67e13b",
"d174ab98d277d9f5a5611c2c9f419d9f", "57edf4a22be3c955ac49da2e2107b67a"];
def tests = Hashtable(ZipLazy(examples, hashes));
foreach (test in tests)
Write($"$(IsValidMD5(test.Key, test.Value)) ");
}
} |
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 .
| #Dart | Dart | class Complex {
double _r,_i;
Complex(this._r,this._i);
double get r => _r;
double get i => _i;
String toString() => "($r,$i)";
Complex operator +(Complex other) => new Complex(r+other.r,i+other.i);
Complex operator *(Complex other) =>
new Complex(r*other.r-i*other.i,r*other.i+other.r*i);
double abs() => r*r+i*i;
}
void main() {
double start_x=-1.5;
double start_y=-1.0;
double step_x=0.03;
double step_y=0.1;
for(int y=0;y<20;y++) {
String line="";
for(int x=0;x<70;x++) {
Complex c=new Complex(start_x+step_x*x,start_y+step_y*y);
Complex z=new Complex(0.0, 0.0);
for(int i=0;i<100;i++) {
z=z*(z)+c;
if(z.abs()>2) {
break;
}
}
line+=z.abs()>2 ? " " : "*";
}
print(line);
}
} |
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)
| #J | J | ms=: i:@<.@-: |."_1&|:^:2 >:@i.@,~ |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) 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)
| #Java | Java | public class MagicSquare {
public static void main(String[] args) {
int n = 5;
for (int[] row : magicSquareOdd(n)) {
for (int x : row)
System.out.format("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int base) {
if (base % 2 == 0 || base < 3)
throw new IllegalArgumentException("base must be odd and > 2");
int[][] grid = new int[base][base];
int r = 0, number = 0;
int size = base * base;
int c = base / 2;
while (number++ < size) {
grid[r][c] = number;
if (r == 0) {
if (c == base - 1) {
r++;
} else {
r = base - 1;
c++;
}
} else {
if (c == base - 1) {
r--;
c = 0;
} else {
if (grid[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
}
}
return grid;
}
} |
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.
| #Factor | Factor | ( scratchpad ) USE: math.matrices
{ { 1 2 } { 3 4 } } { { -3 -8 3 } { -2 1 4 } } m. .
{ { -7 -6 11 } { -17 -20 25 } }
|
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Stata | Stata | mata
function magic(n) {
if (mod(n,2)==1) {
p = (n+1)/2-2
a = J(n,n,.)
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++) {
a[i,j] = n*mod(i+j+p,n)+mod(i+2*j-2,n)+1
}
}
} else if (mod(n,4)==0) {
p = n^2+n+1
a = J(n,n,.)
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++) {
a[i,j] = mod(floor(i/2)-floor(j/2),2)==0 ? p-n*i-j : n*(i-1)+j
}
}
} else {
p = n/2
q = p*p
k = (n-2)/4+1
a = magic(p)
a = a,a:+2*q\a:+3*q,a:+q
i = 1..p
j = 1..k-1
if (k>2) j = j,n-k+3..n
m = a[i,j]; a[i,j] = a[i:+p,j]; a[i:+p,j] = m
j = 1,k
m = a[k,j]; a[k,j] = a[k:+p,j]; a[k:+p,j] = m
}
return(a)
}
end |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #VBScript | VBScript | ' Magic squares of doubly even order
n=8 'multiple of 4
pattern="1001011001101001"
size=n*n: w=len(size)
mult=n\4 'how many multiples of 4
wscript.echo "Magic square : " & n & " x " & n
i=0
For r=0 To n-1
l=""
For c=0 To n-1
bit=Mid(pattern, c\mult+(r\mult)*4+1, 1)
If bit="1" Then t=i+1 Else t=size-i
l=l & Right(Space(w) & t, w) & " "
i=i+1
Next 'c
wscript.echo l
Next 'r
wscript.echo "Magic constant=" & (n*n+1)*n/2 |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | $RecursionLimit = 1665; (* anything less fails for k0 = 10 *)
a[k0_, x1_, x2_, x3_, x4_, x5_] := Module[{k, b },
k = k0;
b = (k--; a[k, b, x1, x2, x3, x4]) &;
If[k <= 0, x4[] + x5[], b[]]]
a[10, 1 &, -1 &, -1 &, 1 &, 0 &] |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to 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
| #Modula-3 | Modula-3 | MODULE Main;
IMPORT IO;
TYPE Function = PROCEDURE ():INTEGER;
PROCEDURE A(k: INTEGER; x1, x2, x3, x4, x5: Function): INTEGER =
PROCEDURE B(): INTEGER =
BEGIN
DEC(k);
RETURN A(k, B, x1, x2, x3, x4);
END B;
BEGIN
IF k <= 0 THEN
RETURN x4() + x5();
ELSE
RETURN B();
END;
END A;
PROCEDURE F0(): INTEGER = BEGIN RETURN 0; END F0;
PROCEDURE F1(): INTEGER = BEGIN RETURN 1; END F1;
PROCEDURE Fn1(): INTEGER = BEGIN RETURN -1; END Fn1;
BEGIN
IO.PutInt(A(10, F1, Fn1, Fn1, F1, F0));
IO.Put("\n");
END Main. |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #F.23 | F# | let transpose (mtx : _ [,]) = Array2D.init (mtx.GetLength 1) (mtx.GetLength 0) (fun x y -> mtx.[y,x]) |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | MazeGraphics[m_, n_] :=
Block[{$RecursionLimit = Infinity,
unvisited = Tuples[Range /@ {m, n}], maze},
maze = Graphics[{Line[{{#, # - {0, 1}}, {#, # - {1, 0}}}] & /@
unvisited,
Line[{{0, n}, {0, 0}, {m, 0}}]}]; {unvisited =
DeleteCases[unvisited, #];
Do[If[MemberQ[unvisited, neighbor],
maze = DeleteCases[
maze, {#,
neighbor - {1, 1}} | {neighbor, # - {1, 1}}, {5}]; #0@
neighbor], {neighbor,
RandomSample@{# + {0, 1}, # - {0, 1}, # + {1, 0}, # - {1,
0}}}]} &@RandomChoice@unvisited; maze];
maze = MazeGraphics[21, 13] |
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.
| #Maple | Maple |
Map:=proc(a1,a2,b1,b2,s);
return (b1+((s-a1)*(b2-b1)/(a2-a1)));
end proc;
for i from 0 to 10 do
printf("%a maps to ",i);
printf("%a\n",Map(0,10,-1,0,i));
end do;
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Rescale[#,{0,10},{-1,0}]&/@Range[0,10] |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #zkl | zkl | tri:=File("triangle.txt").pump(List,fcn(s){ s.strip().split(" ").apply("toInt") }).copy();
while(tri.len()>1){
t0:=tri.pop();
t1:=tri.pop();
tri.append( [[(it); t1.enumerate();
'wrap([(i,t)]){ t + t0[i].max(t0[i+1]) }]])
}
tri[0][0].println(); |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: 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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
import java.security.MessageDigest
MD5('The quick brown fox jumps over the lazy dog', '9e107d9d372bb6826bd81d3542a419d6')
-- RFC 1321 MD5 test suite:
MD5("", 'd41d8cd98f00b204e9800998ecf8427e')
MD5("a", '0cc175b9c0f1b6a831c399e269772661')
MD5("abc", '900150983cd24fb0d6963f7d28e17f72')
MD5("message digest", 'f96b697d7cb7938d525a2f31aaf161d0')
MD5("abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b')
MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f')
MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a')
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method MD5(messageText, verifyCheck) public static
algorithm = 'MD5'
digestSum = getDigest(messageText, algorithm)
say '<Message>'messageText'</Message>'
say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>'
say Rexx('<Verify>').right(12) || verifyCheck'</Verify>'
if digestSum == verifyCheck then say algorithm 'Confirmed'
else say algorithm 'Failed'
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx
algorithm = algorithm.upper
encoding = encoding.upper
message = String(messageText)
messageBytes = byte[]
digestBytes = byte[]
digestSum = Rexx ''
do
messageBytes = message.getBytes(encoding)
md = MessageDigest.getInstance(algorithm)
md.update(messageBytes)
digestBytes = md.digest
loop b_ = 0 to digestBytes.length - 1
bb = Rexx(digestBytes[b_]).d2x(2)
if lowercase then digestSum = digestSum || bb.lower
else digestSum = digestSum || bb.upper
end b_
catch ex = Exception
ex.printStackTrace
end
return digestSum
|
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 .
| #Dc | Dc | _2.1 sx # xmin = -2.1
0.7 sX # xmax = 0.7
_1.2 sy # ymin = -1.2
1.2 sY # ymax = 1.2
32 sM # maxiter = 32
80 sW # image width
25 sH # image height
8 k # precision
[ q ] sq # quitter helper macro
# for h from 0 to H-1
0 sh
[
lh lH =q # quit if H reached
# for w from 0 to W-1
0 sw
[
lw lW =q # quit if W reached
# (w,h) -> (R,I)
# | |
# | ymin + h*(ymax-ymin)/(height-1)
# xmin + w*(xmax-xmin)/(width-1)
lX lx - lW 1 - / lw * lx + sR
lY ly - lH 1 - / lh * ly + sI
# iterate for (R,I)
0 sr # r:=0
0 si # i:=0
0 sa # a:=0 (r squared)
0 sb # b:=0 (i squared)
0 sm # m:=0
# do while m!=M and a+b=<4
[
lm lM =q # exit if m==M
la lb + 4<q # exit if >4
2 lr * li * lI + si # i:=2*r*i+I
la lb - lR + sr # r:=a-b+R
lm 1 + sm # m+=1
lr 2 ^ sa # a:=r*r
li 2 ^ sb # b:=i*i
l0 x # loop
] s0
l0 x
lm 32 + P # print "pixel"
lw 1 + sw # w+=1
l1 x # loop
] s1
l1 x
A P # linefeed
lh 1 + sh # h+=1
l2 x # loop
] s2
l2 x |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) 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)
| #JavaScript | JavaScript | (function () {
// n -> [[n]]
function magic(n) {
return n % 2 ? rotation(
transposed(
rotation(
table(n)
)
)
) : null;
}
// [[a]] -> [[a]]
function rotation(lst) {
return lst.map(function (row, i) {
return rotated(
row, ((row.length + 1) / 2) - (i + 1)
);
})
}
// [[a]] -> [[a]]
function transposed(lst) {
return lst[0].map(function (col, i) {
return lst.map(function (row) {
return row[i];
})
});
}
// [a] -> n -> [a]
function rotated(lst, n) {
var lng = lst.length,
m = (typeof n === 'undefined') ? 1 : (
n < 0 ? lng + n : (n > lng ? n % lng : n)
);
return m ? (
lst.slice(-m).concat(lst.slice(0, lng - m))
) : lst;
}
// n -> [[n]]
function table(n) {
var rngTop = rng(1, n);
return rng(0, n - 1).map(function (row) {
return rngTop.map(function (x) {
return row * n + x;
});
});
}
// [m..n]
function rng(m, n) {
return Array.apply(null, Array(n - m + 1)).map(
function (x, i) {
return m + i;
});
}
/******************** TEST WITH 3, 5, 11 ***************************/
// Results as right-aligned wiki tables
function wikiTable(lstRows, blnHeaderRow, strStyle) {
var css = strStyle ? 'style="' + strStyle + '"' : '';
return '{| class="wikitable" ' + css + lstRows.map(
function (lstRow, iRow) {
var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|'),
strDbl = strDelim + strDelim;
return '\n|-\n' + strDelim + ' ' + lstRow.join(' ' + strDbl + ' ');
}).join('') + '\n|}';
}
return [3, 5, 11].map(
function (n) {
var w = 2.5 * n;
return 'magic(' + n + ')\n\n' + wikiTable(
magic(n), false, 'text-align:center;width:' + w + 'em;height:' + w + 'em;table-layout:fixed;'
)
}
).join('\n\n')
})(); |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Fantom | Fantom |
class Main
{
// multiply two matrices (with no error checking)
public static Int[][] multiply (Int[][] m1, Int[][] m2)
{
Int[][] result := [,]
m1.each |Int[] row1|
{
Int[] row := [,]
m2[0].size.times |Int colNumber|
{
Int value := 0
m2.each |Int[] row2, Int index|
{
value += row1[index] * row2[colNumber]
}
row.add (value)
}
result.add (row)
}
return result
}
public static Void main ()
{
m1 := [[1,2,3],[4,5,6]]
m2 := [[1,2],[3,4],[5,6]]
echo ("${m1} times ${m2} = ${multiply(m1,m2)}")
}
}
|
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Visual_Basic_.NET | Visual Basic .NET | Module MagicSquares
Function MagicSquareDoublyEven(n As Integer) As Integer(,)
If n < 4 OrElse n Mod 4 <> 0 Then
Throw New ArgumentException("base must be a positive multiple of 4")
End If
'pattern of count-up vs count-down zones
Dim bits = Convert.ToInt32("1001011001101001", 2)
Dim size = n * n
Dim mult As Integer = n / 4 ' how many multiples of 4
Dim result(n - 1, n - 1) As Integer
Dim i = 0
For r = 0 To n - 1
For c = 0 To n - 1
Dim bitPos As Integer = Math.Floor(c / mult) + Math.Floor(r / mult) * 4
Dim test = (bits And (1 << bitPos)) <> 0
If test Then
result(r, c) = i + 1
Else
result(r, c) = size - i
End If
i = i + 1
Next
Console.WriteLine()
Next
Return result
End Function
Sub Main()
Dim n = 8
Dim result = MagicSquareDoublyEven(n)
For i = 0 To result.GetLength(0) - 1
For j = 0 To result.GetLength(1) - 1
Console.Write("{0,2} ", result(i, j))
Next
Console.WriteLine()
Next
Console.WriteLine()
Console.WriteLine("Magic constant: {0} ", (n * n + 1) * n / 2)
Console.ReadLine()
End Sub
End Module |
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
| #Nim | Nim | import sugar
proc a(k: int; x1, x2, x3, x4, x5: proc(): int): int =
var k = k
proc b(): int =
dec k
a(k, b, x1, x2, x3, x4)
if k <= 0: x4() + x5()
else: b()
echo 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
| #Objeck | Objeck | interface Arg {
method : virtual : public : Run() ~ Int;
}
class ManOrBoy {
New() {}
function : A(mb : ManOrBoy, k : Int, x1 : Arg, x2 : Arg, x3 : Arg, x4 : Arg, x5 : Arg) ~ Int {
if(k <= 0) {
return x4->Run() + x5->Run();
};
return Base->New(mb, k, x1, x2, x3, x4) implements Arg {
@mb : ManOrBoy; @k : Int; @x1 : Arg; @x2 : Arg; @x3 : Arg; @x4 : Arg; @m : Int;
New(mb : ManOrBoy, k : Int, x1 : Arg, x2 : Arg, x3 : Arg, x4 : Arg) {
@mb := mb; @k := k; @x1 := x1; @x2 := x2; @x3 := x3; @x4 := x4; @m := @k;
}
method : public : Run() ~ Int {
@m -= 1;
return @mb->A(@mb, @m, @self, @x1, @x2, @x3, @x4);
}
}->Run();
}
function : C(i : Int) ~ Arg {
return Base->New(i) implements Arg {
@i : Int;
New(i : Int) {
@i := i;
}
method : public : Run() ~ Int {
return @i;
}
};
}
function : Main(args : String[]) ~ Nil {
mb := ManOrBoy->New();
mb->A(mb, 10, C(1), C(-1), C(-1), C(1), C(0))->PrintLine();
}
}
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Factor | Factor | ( scratchpad ) { { 1 2 3 } { 4 5 6 } } flip .
{ { 1 4 } { 2 5 } { 3 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.
| #MATLAB_.2F_Octave | MATLAB / Octave | function M = makeMaze(n)
showProgress = false;
colormap([1,1,1;1,1,1;0,0,0]);
set(gcf,'color','w');
NoWALL = 0;
WALL = 2;
NotVISITED = -1;
VISITED = -2;
m = 2*n+3;
M = NotVISITED(ones(m));
offsets = [-1, m, 1, -m];
M([1 2:2:end end],:) = WALL;
M(:,[1 2:2:end end]) = WALL;
currentCell = sub2ind(size(M),3,3);
M(currentCell) = VISITED;
S = currentCell;
while (~isempty(S))
moves = currentCell + 2*offsets;
unvistedNeigbors = find(M(moves)==NotVISITED);
if (~isempty(unvistedNeigbors))
next = unvistedNeigbors(randi(length(unvistedNeigbors),1));
M(currentCell + offsets(next)) = NoWALL;
newCell = currentCell + 2*offsets(next);
if (any(M(newCell+2*offsets)==NotVISITED))
S = [S newCell];
end
currentCell = newCell;
M(currentCell) = VISITED;
else
currentCell = S(1);
S = S(2:end);
end
if (showProgress)
image(M-VISITED);
axis equal off;
drawnow;
pause(.01);
end
end
image(M-VISITED);
axis equal off; |
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.
| #Maxima | Maxima | maprange(a, b, c, d) := buildq([e: ratsimp(('x - a)*(d - c)/(b - a) + c)],
lambda([x], e))$
f: maprange(0, 10, -1, 0); |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\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.
| #Nemerle | Nemerle | using System;
using System.Console;
module Maprange
{
Maprange(a : double * double, b : double * double, s : double) : double
{
def (a1, a2) = a; def (b1, b2) = b;
b1 + (((s - a1) * (b2 - b1))/(a2 - a1))
}
Main() : void
{
foreach (i in [0 .. 10])
WriteLine("{0, 2:f0} maps to {1:f1}", i, Maprange((0.0, 10.0), (-1.0, 0.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.
| #NewLISP | NewLISP | ;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html
;; (import native functions from the crypto library, provided by OpenSSL)
(module "crypto.lsp")
(crypto:md5 "The quick brown fox jumped over the lazy dog's back") |
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 .
| #Delphi | Delphi | const maxIter = 256;
var x, y, i : Integer;
for y:=-39 to 39 do begin
for x:=-39 to 39 do begin
var c := Complex(y/40-0.5, x/40);
var z := Complex(0, 0);
for i:=1 to maxIter do begin
z := z*z + c;
if Abs(z)>=4 then Break;
end;
if i>=maxIter then
Print('#')
else Print('.');
end;
PrintLn('');
end; |
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)
| #jq | jq | def odd_magic_square:
if type != "number" or . % 2 == 0 or . <= 0
then error("odd_magic_square requires an odd positive integer")
else
. as $n
| reduce range(1; 1 + ($n*$n)) as $i
( [0, (($n-1)/2), []];
.[0] as $x | .[1] as $y
| .[2]
| setpath([$x, $y]; $i )
| if getpath([(($x+$n-1) % $n), (($y+$n+1) % $n)])
then [(($x+$n+1) % $n), $y, .]
else [ (($x+$n-1) % $n), (($y+$n+1) % $n), .]
end ) | .[2]
end ; |
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)
| #Julia | Julia | # v0.6.0
function magicsquareodd(base::Int)
if base & 1 == 0 || base < 3; error("base must be odd and >3") end
square = fill(0, base, base)
r, number = 1, 1
size = base * base
c = div(base, 2) + 1
while number ≤ size
square[r, c] = number
fr = r == 1 ? base : r - 1
fc = c == base ? 1 : c + 1
if square[fr, fc] != 0
fr = r == base ? 1 : r + 1
fc = c
end
r, c = fr, fc
number += 1
end
return square
end
for n in 3:2:7
println("Magic square with size $n - magic constant = ", div(n ^ 3 + n, 2))
println("----------------------------------------------------")
square = magicsquareodd(n)
for i in 1:n
println(square[i, :])
end
println()
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.
| #Fermat | Fermat |
Array a[3,2]
Array b[2,3]
[a]:=[(2,3,5,7,11,13)]
[b]:=[(1,1,2,3,5,8)]
[a]*[b]
|
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Wren | Wren | import "/fmt" for Conv, Fmt
var magicSquareDoublyEven = Fn.new { |n|
if (n < 4 || n%4 != 0) Fiber.abort("Base must be a positive multiple of 4")
// pattern of count-up vs count-down zones
var bits = Conv.atoi("1001011001101001", 2)
var size = n * n
var mult = (n/4).floor // how many multiples of 4
var result = List.filled(n, null)
for (i in 0...n) result[i] = List.filled(n, 0)
var i = 0
for (r in 0...n) {
for (c in 0...n) {
var bitPos = (c/mult).floor + (r/mult).floor * 4
result[r][c] = ((bits & (1<<bitPos)) != 0) ? i + 1 : size - i
i = i + 1
}
}
return result
}
var n = 8
for (ia in magicSquareDoublyEven.call(n)) {
for (i in ia) Fmt.write("$2d ", i)
System.print()
}
System.print("\nMagic constant %((n * n + 1) * n / 2)") |
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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
typedef NSInteger (^IntegerBlock)(void);
NSInteger A (NSInteger kParam, IntegerBlock x1, IntegerBlock x2, IntegerBlock x3, IntegerBlock x4, IntegerBlock x5) {
__block NSInteger k = kParam;
__block __weak IntegerBlock weak_B;
IntegerBlock B;
weak_B = B = ^ {
return A(--k, weak_B, x1, x2, x3, x4);
};
return k <= 0 ? x4() + x5() : B();
}
IntegerBlock K (NSInteger n) {
return ^{return n;};
}
int main (int argc, const char * argv[]) {
@autoreleasepool {
NSInteger result = A(10, K(1), K(-1), K(-1), K(1), K(0));
NSLog(@"%d\n", result);
}
return 0;
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Fermat | Fermat |
Array a[3,1]
[a]:=[(1,2,3)]
[b]:=Trans([a])
[a]
[b]
|
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.
| #Nim | Nim | import random, sequtils, strutils
randomize()
iterator randomCover[T](xs: openarray[T]): T =
var js = toSeq 0..xs.high
for i in countdown(js.high, 0):
let j = random(i)
swap(js[i], js[j])
for j in js:
yield xs[j]
const
w = 14
h = 10
var
vis = newSeqWith(h, newSeq[bool](w))
hor = newSeqWith(h+1, newSeqWith(w, "+---"))
ver = newSeqWith(h, newSeqWith(w, "| ") & "|")
proc walk(x, y: int) =
vis[y][x] = true
for p in [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover:
if p[0] notin 0 ..< w or p[1] notin 0 ..< h or vis[p[1]][p[0]]: continue
if p[0] == x: hor[max(y, p[1])][x] = "+ "
if p[1] == y: ver[y][max(x, p[0])] = " "
walk p[0], p[1]
walk rand(0..<w), rand(0..<h)
for a,b in zip(hor, ver & @[""]).items:
echo join(a & "+\n" & b) |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
A = [ 0.0, 10.0 ]
B = [ -1.0, 0.0 ]
incr = 1.0
say 'Mapping ['A[0]',' A[1]'] to ['B[0]',' B[1]'] in increments of' incr':'
loop sVal = A[0] to A[1] by incr
say ' f('sVal.format(3, 3)') =' mapRange(A, B, sVal).format(4, 3)
end sVal
return
method mapRange(a = Rexx[], b = Rexx[], s_) public static
return mapRange(a[0], a[1], b[0], b[1], s_)
method mapRange(a1, a2, b1, b2, s_) public static
t_ = b1 + ((s_ - a1) * (b2 - b1) / (a2 - a1))
return t_
|
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.
| #Nim | Nim | import md5
echo toMD5("The quick brown fox jumped over the lazy dog's back") |
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 .
| #DWScript | DWScript | const maxIter = 256;
var x, y, i : Integer;
for y:=-39 to 39 do begin
for x:=-39 to 39 do begin
var c := Complex(y/40-0.5, x/40);
var z := Complex(0, 0);
for i:=1 to maxIter do begin
z := z*z + c;
if Abs(z)>=4 then Break;
end;
if i>=maxIter then
Print('#')
else Print('.');
end;
PrintLn('');
end; |
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)
| #Kotlin | Kotlin | // version 1.0.6
fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n
fun main(args: Array<String>) {
var n: Int
while (true) {
print("Enter the order of the magic square : ")
n = readLine()!!.toInt()
if (n < 1 || n % 2 == 0) println("Must be odd and >= 1, try again")
else break
}
println()
for (i in 0 until n) {
for (j in 0 until n) print("%4d".format(f(n, n - j - 1, i) * n + f(n, j, i) + 1))
println()
}
println("\nThe magic constant is ${(n * n + 1) / 2 * n}")
} |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Forth | Forth | S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
: FSQR ( F: r1 -- r2 ) FDUP F* ;
S" fsl/gaussj.seq" REQUIRED
3 3 float matrix A{{
1e 2e 3e 4e 5e 6e 7e 8e 9e 3 3 A{{ }}fput
3 3 float matrix B{{
3e 3e 3e 2e 2e 2e 1e 1e 1e 3 3 B{{ }}fput
float dmatrix C{{ \ result
A{{ 3 3 B{{ 3 3 & C{{ mat*
3 3 C{{ }}fprint |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #zkl | zkl | class MagicSquareDoublyEven{
fcn init(n){ var result=magicSquareDoublyEven(n) }
fcn toString{
sink,n:=Sink(String),result.len(); // num collumns
fmt:="%2s ";
foreach row in (result)
{ sink.write(row.apply('wrap(n){ fmt.fmt(n) }).concat(),"\n") }
sink.write("\nMagic constant: %d".fmt((n*n + 1)*n/2));
sink.close();
}
fcn magicSquareDoublyEven(n){
if (n<4 or n%4!=0 or n>16)
throw(Exception.ValueError("base must be a positive multiple of 4"));
bits,size,mult:=0b1001011001101001, n*n, n/4;
result:=n.pump(List(),n.pump(List(),0).copy); // array[n,n] of zero
foreach i in (size){
bitsPos:=(i%n)/mult + (i/(n*mult)*4);
value:=(bits.bitAnd((2).pow(bitsPos))) and i+1 or size-i;
result[i/n][i%n]=value;
}
result;
}
}
MagicSquareDoublyEven(8).println(); |
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
| #OCaml | OCaml | let rec a k x1 x2 x3 x4 x5 =
if k <= 0 then
x4 () + x5 ()
else
let m = ref k in
let rec b () =
decr m;
a !m b x1 x2 x3 x4
in
b ()
let () =
Printf.printf "%d\n" (a 10 (fun () -> 1) (fun () -> -1) (fun () -> -1) (fun () -> 1) (fun () -> 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
| #Ol | Ol |
; Because argument "k" is a small number, it's a value, not an object.
; So we must 'pack' it in object - 'box' it; And 'unbox' when we try to get value.
(define (box x) (list x))
(define (unbox x) (car x))
(define (copy x) (box (unbox x)))
(define (A k x1 x2 x3 x4 x5)
(define (B)
(set-car! k (- (unbox k) 1))
(A (copy k) B x1 x2 x3 x4))
(if (<= (unbox k) 0)
(+ (x4) (x5))
(B)))
(define (man-or-boy N)
(A (box N)
(lambda () 1)
(lambda () -1)
(lambda () -1)
(lambda () 1)
(lambda () 0)))
(print (man-or-boy 10))
(print (man-or-boy 15))
(print (man-or-boy 20))
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Forth | Forth | S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
: FSQR ( F: r1 -- r2 ) FDUP F* ;
S" fsl/gaussj.seq" REQUIRED
5 3 float matrix a{{
1e 2e 3e 4e 5e 6e 7e 8e 9e 10e 11e 12e 13e 14e 15e 5 3 a{{ }}fput
float dmatrix b{{
a{{ 5 3 & b{{ transpose
3 5 b{{ }}fprint |
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.
| #Node.js | Node.js |
'use strict';
/*
* Imported from http://rosettacode.org/wiki/Maze_generation#JavaScript
* Added asynchronous behaviour to the maze generation.
*
* Port by sigmasoldier
*/
/**
* Generates the maze asynchronously.
* @param {Number} x Width of the maze.
* @param {Number} y Height of the maze.
* @returns {Promise} finished when resolved.
*/
function maze(x,y) {
return new Promise((resolve, reject) => {
let n=x*y-1;
if (n<0) {
reject(new Error(`illegal maze dimensions (${x} x ${y} < 1)`));
} else {
let horiz =[]; for (let j= 0; j<x+1; j++) horiz[j]= [];
let verti =[]; for (let j= 0; j<x+1; j++) verti[j]= [];
let here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)];
let path = [here];
let unvisited = [];
for (let j = 0; j<x+2; j++) {
unvisited[j] = [];
for (let k= 0; k<y+1; k++)
unvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1));
}
while (0<n) {
let potential = [[here[0]+1, here[1]], [here[0],here[1]+1],
[here[0]-1, here[1]], [here[0],here[1]-1]];
let neighbors = [];
for (let j = 0; j < 4; j++)
if (unvisited[potential[j][0]+1][potential[j][1]+1])
neighbors.push(potential[j]);
if (neighbors.length) {
n = n-1;
let next= neighbors[Math.floor(Math.random()*neighbors.length)];
unvisited[next[0]+1][next[1]+1]= false;
if (next[0] == here[0])
horiz[next[0]][(next[1]+here[1]-1)/2]= true;
else
verti[(next[0]+here[0]-1)/2][next[1]]= true;
path.push(here = next);
} else
here = path.pop();
}
resolve({x: x, y: y, horiz: horiz, verti: verti});
}
});
}
/**
* A mere way of generating text.
* The text (Since it can be large) is generated in a non-blocking way.
* @param {Object} m Maze object.
* @param {Stream} writeTo Optinally, include here a function to write to.
* @returns {Promise} finished when the text is generated.
*/
function display(m, writeTo) {
return new Promise((resolve, reject) => {
let text = [];
for (let j= 0; j<m.x*2+1; j++) {
let line = [];
if (0 == j%2)
for (let k=0; k<m.y*4+1; k++)
if (0 == k%4)
line[k] = '+';
else
if (j>0 && m.verti[j/2-1][Math.floor(k/4)])
line[k] = ' ';
else
line[k] = '-';
else
for (let k=0; k<m.y*4+1; k++)
if (0 == k%4)
if (k>0 && m.horiz[(j-1)/2][k/4-1])
line[k] = ' ';
else
line[k] = '|';
else
line[k] = ' ';
if (0 == j) line[1] = line[2] = line[3] = ' ';
if (m.x*2-1 == j) line[4*m.y]= ' ';
text.push(line.join('')+'\r\n');
}
const OUTPUT = text.join('');
if (typeof writeTo === 'function')
writeTo(OUTPUT);
resolve(OUTPUT);
});
}
module.exports = {
maze: maze,
display: display
}
|
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.
| #Nim | Nim | import strformat
type FloatRange = tuple[s, e: float]
proc mapRange(a, b: FloatRange; s: float): float =
b.s + (s - a.s) * (b.e - b.s) / (a.e - a.s)
for i in 0..10:
let m = mapRange((0.0,10.0), (-1.0, 0.0), float(i))
echo &"{i:>2} maps to {m:4.1f}" |
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.
| #Objeck | Objeck |
bundle Default {
class Range {
function : MapRange(a1:Float, a2:Float, b1:Float, b2:Float, s:Float) ~ Float {
return b1 + (s-a1)*(b2-b1)/(a2-a1);
}
function : Main(args : String[]) ~ Nil {
"Mapping [0,10] to [-1,0] at intervals of 1:"->PrintLine();
for(i := 0.0; i <= 10.0; i += 1;) {
IO.Console->Print("f(")->Print(i->As(Int))->Print(") = ")->PrintLine(MapRange(0.0, 10.0, -1.0, 0.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.
| #Oberon-2 | Oberon-2 |
MODULE MD5;
IMPORT
Crypto:MD5,
Crypto:Utils,
Strings,
Out;
VAR
h: MD5.Hash;
str: ARRAY 128 OF CHAR;
BEGIN
h := MD5.NewHash();
h.Initialize;
str := "The quick brown fox jumped over the lazy dog's back";
h.Update(str,0,Strings.Length(str));
h.GetHash(str,0);
Out.String("MD5: ");Utils.PrintHex(str,0,h.size);Out.Ln
END MD5.
|
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 .
| #EasyLang | EasyLang | for y0 range 300
cy = (y0 - 150) / 120
for x0 range 300
cx = (x0 - 220) / 120
x = 0
y = 0
color3 0 0 0
for n range 128
if x * x + y * y > 4
color3 n / 16 0 0
break 1
.
h = x * x - y * y + cx
y = 2 * x * y + cy
x = h
.
move x0 / 3 y0 / 3
rect 0.4 0.4
.
. |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) 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)
| #Liberty_BASIC | Liberty BASIC |
Dim m(1,1)
Call magicSquare 5
Call magicSquare 17
End
Sub magicSquare n
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
'Arbitrary limit to fit width of A4 paper
If n < 23 Then
Print n;" x ";n;" Magic Square --- ";
Print "Magic constant is ";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
Else
Notice "Magic Square will not fit on one sheet of paper."
End If
End Sub
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Fortran | Fortran | real, dimension(n,m) :: a = reshape( [ (i, i=1, n*m) ], [ n, m ] )
real, dimension(m,k) :: b = reshape( [ (i, i=1, m*k) ], [ m, k ] )
real, dimension(size(a,1), size(b,2)) :: c ! C is an array whose first dimension (row) size
! is the same as A's first dimension size, and
! whose second dimension (column) size is the same
! as B's second dimension size.
c = matmul( a, b )
print *, 'A'
do i = 1, n
print *, a(i,:)
end do
print *,
print *, 'B'
do i = 1, m
print *, b(i,:)
end do
print *,
print *, 'C = AB'
do i = 1, n
print *, c(i,:)
end do |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to 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
| #Oz | Oz | declare
fun {A K X1 X2 X3 X4 X5}
ReturnA = {NewCell undefined}
fun {B}
ReturnB = {NewCell undefined}
in
K := @K - 1
ReturnA := {A {NewCell @K} B X1 X2 X3 X4}
ReturnB := @ReturnA
@ReturnB
end
in
if @K =< 0 then ReturnA := {X4} + {X5} else _ = {B} end
@ReturnA
end
fun {C V}
fun {$} V end
end
in
{Show {A {NewCell 10} {C 1} {C ~1} {C ~1} {C 1} {C 0}}} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Fortran | Fortran | integer, parameter :: n = 3, m = 5
real, dimension(n,m) :: a = reshape( (/ (i,i=1,n*m) /), (/ n, m /) )
real, dimension(m,n) :: b
b = transpose(a)
do i = 1, n
print *, a(i,:)
end do
do j = 1, m
print *, b(j,:)
end do |
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.
| #OCaml | OCaml | let seen = Hashtbl.create 7
let mark t = Hashtbl.add seen t true
let marked t = Hashtbl.mem seen t
let walls = Hashtbl.create 7
let ord a b = if a <= b then (a,b) else (b,a)
let join a b = Hashtbl.add walls (ord a b) true
let joined a b = Hashtbl.mem walls (ord a b)
let () =
let nx = int_of_string Sys.argv.(1) in
let ny = int_of_string Sys.argv.(2) in
let shuffle lst =
let nl = List.map (fun c -> (Random.bits (), c)) lst in
List.map snd (List.sort compare nl) in
let get_neighbours (x,y) =
let lim n k = (0 <= k) && (k < n) in
let bounds (x,y) = lim nx x && lim ny y in
List.filter bounds [(x-1,y);(x+1,y);(x,y-1);(x,y+1)] in
let rec visit cell =
mark cell;
let check k =
if not (marked k) then (join cell k; visit k) in
List.iter check (shuffle (get_neighbours cell)) in
let print_maze () =
begin
for i = 1 to nx do print_string "+---";done; print_endline "+";
let line n j k l s t u =
for i = 0 to n do print_string (if joined (i,j) (i+k,j+l) then s else t) done;
print_endline u in
for j = 0 to ny-2 do
print_string "| ";
line (nx-2) j 1 0 " " "| " "|";
line (nx-1) j 0 1 "+ " "+---" "+";
done;
print_string "| ";
line (nx-2) (ny-1) 1 0 " " "| " "|";
for i = 1 to nx do print_string "+---";done; print_endline "+";
end in
Random.self_init();
visit (Random.int nx, Random.int ny);
print_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.
| #OCaml | OCaml | let map_range (a1, a2) (b1, b2) s =
b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1))
let () =
print_endline "Mapping [0,10] to [-1,0] at intervals of 1:";
for i = 0 to 10 do
Printf.printf "f(%d) = %g\n" i (map_range (0.0, 10.0) (-1.0, 0.0) (float i))
done |
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.
| #Oforth | Oforth | : mapRange(p1, p2, s)
s p1 first - p2 second p2 first - * p1 second p1 first - asFloat /
p2 first + ; |
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.
| #Objeck | Objeck |
class MD5 {
function : Main(args : String[]) ~ Nil {
in := "The quick brown fox jumped over the lazy dog's back"->ToByteArray();
hash := Encryption.Hash->MD5(in);
hash->ToHexString()->PrintLine();
}
}
|
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 .
| #eC | eC | void drawMandelbrot(Bitmap bmp, float range, Complex center, ColorAlpha * palette, int nPalEntries, int nIterations, float scale)
{
int x, y;
int w = bmp.width, h = bmp.height;
ColorAlpha * picture = (ColorAlpha *)bmp.picture;
double logOf2 = log(2);
Complex d
{
w > h ? range : range * w / h,
h > w ? range : range * h / w
};
Complex C0 { center.a - d.a/2, center.b - d.b/2 };
Complex C = C0;
double delta = d.a / w;
for(y = 0; y < h; y++, C.a = C0.a, C.b += delta)
{
for(x = 0; x < w; x++, picture++, C.a += delta)
{
Complex Z { };
int i;
double ii = 0;
bool out = false;
double Za2 = Z.a * Z.a, Zb2 = Z.b * Z.b;
for(i = 0; i < nIterations; i++)
{
double z2;
Z = { Za2 - Zb2, 2*Z.a*Z.b };
Z.a += C.a;
Z.b += C.b;
Za2 = Z.a * Z.a, Zb2 = Z.b * Z.b;
z2 = Za2 + Zb2;
if(z2 >= 2*2)
{
ii = (double)(i + 1 - log(0.5 * log(z2)) / logOf2);
out = true;
break;
}
}
if(out)
{
float si = (float)(ii * scale);
int i0 = ((int)si) % nPalEntries;
*picture = palette[i0];
}
else
*picture = black;
}
}
} |
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)
| #Lua | Lua | rp[v_, pos_] := RotateRight[v, (Length[v] + 1)/2 - pos];
rho[m_] := MapIndexed[rp, m];
magic[n_] :=
rho[Transpose[rho[Table[i*n + j, {i, 0, n - 1}, {j, 1, n}]]]];
square = magic[11] // Grid
Print["Magic number is ", Total[square[[1, 1]]]] |
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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | rp[v_, pos_] := RotateRight[v, (Length[v] + 1)/2 - pos];
rho[m_] := MapIndexed[rp, m];
magic[n_] :=
rho[Transpose[rho[Table[i*n + j, {i, 0, n - 1}, {j, 1, n}]]]];
square = magic[11] // Grid
Print["Magic number is ", Total[square[[1, 1]]]] |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #FreeBASIC | FreeBASIC | type Matrix
dim as double m( any , any )
declare constructor ( )
declare constructor ( byval x as uinteger , byval y as uinteger )
end type
constructor Matrix ( )
end constructor
constructor Matrix ( byval x as uinteger , byval y as uinteger )
redim this.m( x - 1 , y - 1 )
end constructor
operator * ( byref a as Matrix , byref b as Matrix ) as Matrix
dim as Matrix ret
dim as uinteger i, j, k
if ubound( a.m , 2 ) = ubound( b.m , 1 ) and ubound( a.m , 1 ) = ubound( b.m , 2 ) then
redim ret.m( ubound( a.m , 1 ) , ubound( b.m , 2 ) )
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( b.m , 2 )
for k = 0 to ubound( b.m , 1 )
ret.m( i , j ) += a.m( i , k ) * b.m( k , j )
next k
next j
next i
end if
return ret
end operator
'some garbage matrices for demonstration
dim as Matrix a = Matrix(4 , 2)
a.m(0 , 0) = 1 : a.m(0 , 1) = 0
a.m(1 , 0) = 0 : a.m(1 , 1) = 1
a.m(2 , 0) = 2 : a.m(2 , 1) = 3
a.m(3 , 0) = 0.75 : a.m(3 , 1) = -0.5
dim as Matrix b = Matrix( 2 , 4 )
b.m(0 , 0) = 3.1 : b.m(0 , 1) = 1.6 : b.m(0 , 2) = -99 : b.m (0, 3) = -8
b.m(1 , 0) = 2.7 : b.m(1 , 1) = 0.6 : b.m(1 , 2) = 0 : b.m(1,3) = 21
dim as Matrix c = a * b
print c.m(0, 0), c.m(0, 1), c.m(0, 2), c.m(0, 3)
print c.m(1, 0), c.m(1, 1), c.m(1, 2), c.m(1, 3)
print c.m(2, 0), c.m(2, 1), c.m(2, 2), c.m(2, 3)
print c.m(3, 0), c.m(3, 1), c.m(3, 2), c.m(3, 3)
|
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
| #Pascal | Pascal | program manorboy(output);
function zero: integer; begin zero := 0 end;
function one: integer; begin one := 1 end;
function negone: integer; begin negone := -1 end;
function A(
k: integer;
function x1: integer;
function x2: integer;
function x3: integer;
function x4: integer;
function x5: integer
): integer;
function B: integer;
begin k := k - 1;
B := A(k, B, x1, x2, x3, x4)
end;
begin if k <= 0 then A := x4 + x5 else A := B
end;
begin writeln(A(10, one, negone, negone, one, zero))
end. |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #FreeBASIC | FreeBASIC | Dim matriz(0 To 3, 0 To 4) As Integer = {{78,19,30,12,36},_
{49,10,65,42,50},_
{30,93,24,78,10},_
{39,68,27,64,29}}
Dim As Integer mtranspuesta(Lbound(matriz, 2) To Ubound(matriz, 2), Lbound(matriz, 1) To Ubound(matriz, 1))
Dim As Integer fila, columna
For fila = Lbound(matriz,1) To Ubound(matriz,1)
For columna = Lbound(matriz,2) To Ubound(matriz,2)
mtranspuesta(columna, fila) = matriz(fila, columna)
Print ; matriz(fila,columna); " ";
Next columna
Print
Next fila
Print
For fila = Lbound(mtranspuesta,1) To Ubound(mtranspuesta,1)
For columna = Lbound(mtranspuesta,2) To Ubound(mtranspuesta,2)
Print ; mtranspuesta(fila,columna); " ";
Next columna
Print
Next fila
Sleep |
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.
| #Ol | Ol |
; maze generation
(import (otus random!))
(define WIDTH 30)
(define HEIGHT 8)
(define maze
(map (lambda (?)
(repeat #b01111 WIDTH)) ; 0 - unvisited, 1111 - all walls exists
(iota HEIGHT)))
(define (at x y)
(list-ref (list-ref maze y) x))
(define (unvisited? x y)
(if (and (< -1 x WIDTH) (< -1 y HEIGHT))
(zero? (band (at x y) #b10000))))
(define neighbors '((-1 . 0) (0 . -1) (+1 . 0) (0 . +1)))
(define walls '( #b10111 #b11011 #b11101 #b11110))
(define antiwalls '( #b11101 #b11110 #b10111 #b11011))
(let loop ((x (rand! WIDTH)) (y (rand! HEIGHT)))
(list-set! (list-ref maze y) x (bor (at x y) #b10000))
(let try ()
(if (or
(unvisited? (- x 1) y) ; left
(unvisited? x (- y 1)) ; top
(unvisited? (+ x 1) y) ; right
(unvisited? x (+ y 1))) ; bottom
(let*((p (rand! 4))
(neighbor (list-ref neighbors p)))
(let ((nx (+ x (car neighbor)))
(ny (+ y (cdr neighbor))))
(if (unvisited? nx ny)
(let ((ncell (at nx ny)))
(list-set! (list-ref maze y) x (band (at x y) (list-ref walls p)))
(list-set! (list-ref maze ny) nx (band ncell (list-ref antiwalls p)))
(loop nx ny)))
(try))))))
|
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.
| #PARI.2FGP | PARI/GP | map(r1,r2,x)=r2[1]+(x-r1[1])*(r2[2]-r2[1])/(r1[2]-r1[1]) |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\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.
| #Pascal | Pascal | Program Map(output);
function MapRange(fromRange, toRange: array of real; value: real): real;
begin
MapRange := (value-fromRange[0]) * (toRange[1]-toRange[0]) / (fromRange[1]-fromRange[0]) + toRange[0];
end;
var
i: integer;
begin
for i := 0 to 10 do
writeln (i, ' maps to: ', MapRange([0.0, 10.0], [-1.0, 0.0], i):4:2);
end. |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: 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.
| #Objective-C | Objective-C | NSString *myString = @"The quick brown fox jumped over the lazy dog's back";
NSData *digest = [[myString dataUsingEncoding:NSUTF8StringEncoding] md5Digest]; // or another encoding of your choosing
NSLog(@"%@", [digest hexadecimalRepresentation]); |
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 .
| #EchoLisp | EchoLisp |
(lib 'math) ;; fractal function
(lib 'plot)
;; (fractal z zc n) iterates z := z^2 + c, n times
;; 100 iterations
(define (mset z) (if (= Infinity (fractal 0 z 100)) Infinity z))
;; plot function argument inside square (-2 -2), (2,2)
(plot-z-arg mset -2 -2)
;; result here [http://www.echolalie.org/echolisp/help.html#fractal]
|
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)
| #Maxima | Maxima | wrap1(i):= if i>%n% then 1 else if i<1 then %n% else i;
wrap(P):=maplist('wrap1, P);
uprigth(P):= wrap(P + [-1, 1]);
down(P):= wrap(P + [1, 0]);
magic(n):=block([%n%: n,
M: zeromatrix (n, n),
P: [1, (n + 1)/2],
m: 1, Pc],
do (
M[P[1],P[2]]: m,
m: m + 1,
if m>n^2 then return(M),
Pc: uprigth(P),
if M[Pc[1],Pc[2]]=0 then P: Pc
else while(M[P[1],P[2]]#0) do P: down(P))); |
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)
| #Nim | Nim | import strutils
proc magic(n: int) =
let length = len($(n * n))
for row in 1 .. n:
for col in 1 .. n:
let cell = (n * ((row + col - 1 + n div 2) mod n) +
((row + 2 * col - 2) mod n) + 1)
stdout.write ($cell).align(length), ' '
echo ""
echo "\nAll sum to magic number ", (n * n + 1) * n div 2
for n in [3, 5, 7]:
echo "\nOrder ", n, "\n======="
magic(n) |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Frink | Frink | matprod[a is array, b is array] :=
{
c = makeArray[[length[a], length[b@0]], 0]
a_row = length[a]-1
a_col = length[a@0]-1
b_col = length[b]-1
for row = 0 to a_row
for col = 0 to b_col
for inc = 0 to a_col
c@row@col = c@row@col + (a@row@inc * b@inc@col)
return c
} |
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
| #Perl | Perl | sub A {
my ($k, $x1, $x2, $x3, $x4, $x5) = @_;
my($B);
$B = sub { A(--$k, $B, $x1, $x2, $x3, $x4) };
$k <= 0 ? &$x4 + &$x5 : &$B;
}
print A(10, sub{1}, sub {-1}, sub{-1}, sub{1}, sub{0} ), "\n"; |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Frink | Frink |
a = [[1,2,3],
[4,5,6],
[7,8,9]]
join["\n",a.transpose[]]
|
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.
| #Perl | Perl | use List::Util 'max';
my ($w, $h) = @ARGV;
$w ||= 26;
$h ||= 127;
my $avail = $w * $h;
# cell is padded by sentinel col and row, so I don't check array bounds
my @cell = (map([(('1') x $w), 0], 1 .. $h), [('') x ($w + 1)]);
my @ver = map([("| ") x $w], 1 .. $h);
my @hor = map([("+--") x $w], 0 .. $h);
sub walk {
my ($x, $y) = @_;
$cell[$y][$x] = '';
$avail-- or return; # no more bottles, er, cells
my @d = ([-1, 0], [0, 1], [1, 0], [0, -1]);
while (@d) {
my $i = splice @d, int(rand @d), 1;
my ($x1, $y1) = ($x + $i->[0], $y + $i->[1]);
$cell[$y1][$x1] or next;
if ($x == $x1) { $hor[ max($y1, $y) ][$x] = '+ ' }
if ($y == $y1) { $ver[$y][ max($x1, $x) ] = ' ' }
walk($x1, $y1);
}
}
walk(int rand $w, int rand $h); # generate
for (0 .. $h) { # display
print @{$hor[$_]}, "+\n";
print @{$ver[$_]}, "|\n" if $_ < $h;
} |
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.
| #Perl | Perl | #!/usr/bin/perl -w
use strict ;
sub mapValue {
my ( $range1 , $range2 , $number ) = @_ ;
return ( $range2->[ 0 ] +
(( $number - $range1->[ 0 ] ) * ( $range2->[ 1 ] - $range2->[ 0 ] ) ) / ( $range1->[ -1 ]
- $range1->[ 0 ] ) ) ;
}
my @numbers = 0..10 ;
my @interval = ( -1 , 0 ) ;
print "The mapped value for $_ is " . mapValue( \@numbers , \@interval , $_ ) . " !\n" foreach @numbers ;
|
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.
| #OCaml | OCaml | # Digest.to_hex(Digest.string "The quick brown fox jumped over the lazy dog's back") ;;
- : string = "e38ca1d920c4b8b8d3946b2c72f01680" |
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 .
| #Elixir | Elixir | defmodule Mandelbrot do
def set do
xsize = 59
ysize = 21
minIm = -1.0
maxIm = 1.0
minRe = -2.0
maxRe = 1.0
stepX = (maxRe - minRe) / xsize
stepY = (maxIm - minIm) / ysize
Enum.each(0..ysize, fn y ->
im = minIm + stepY * y
Enum.map(0..xsize, fn x ->
re = minRe + stepX * x
62 - loop(0, re, im, re, im, re*re+im*im)
end) |> IO.puts
end)
end
defp loop(n, _, _, _, _, _) when n>=30, do: n
defp loop(n, _, _, _, _, v) when v>4.0, do: n-1
defp loop(n, re, im, zr, zi, _) do
a = zr * zr
b = zi * zi
loop(n+1, re, im, a-b+re, 2*zr*zi+im, a+b)
end
end
Mandelbrot.set |
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)
| #Oforth | Oforth | : magicSquare(n)
| i j wd |
n sq log asInteger 1+ ->wd
n loop: i [
n loop: j [
i j + 1- n 2 / + n mod n *
i j + j + 2 - n mod 1 + +
System.Out swap <<w(wd) " " << drop
]
printcr
]
System.Out "Magic constant is : " << n sq 1 + 2 / n * << cr ; |
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)
| #PARI.2FGP | PARI/GP | magicSquare(n)={
my(M=matrix(n,n),j=n\2+1,i=1);
for(l=1,n^2,
M[i,j]=l;
if(M[(i-2)%n+1,j%n+1],
i=i%n+1
,
i=(i-2)%n+1;
j=j%n+1
)
);
M;
}
magicSquare(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.
| #Futhark | Futhark |
fun main(x: [n][m]int, y: [m][p]int): [n][p]int =
map (fn xr => map (fn yc => reduce (+) 0 (zipWith (*) xr yc))
(transpose y))
x
|
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
| #Phix | Phix | without js -- allocate()
forward function A(integer k, object x1, x2, x3, x4, x5)
function B(sequence s)
object {kptr,x1,x2,x3,x4} = s
integer k = peek4s(kptr)-1
poke4(kptr,k)
return A(k,{kptr,x1,x2,x3,x4},x1,x2,x3,x4)
end function
function A(integer k, object x1, x2, x3, x4, x5)
if k<=0 then
return iff(sequence(x4)?B(x4):x4)+
iff(sequence(x5)?B(x5):x5)
end if
atom kptr = allocate(4,1)
poke4(kptr,k)
return B({kptr,x1,x2,x3,x4})
end function
for k=0 to 23 do
printf(1,"A(%d) = %d\n",{k,A(k,1,-1,-1,1,0)})
end for
|
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.