task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Idris | Idris | Idris> transpose [[1,2],[3,4],[5,6]]
[[1, 3, 5], [2, 4, 6]] : List (List Integer) |
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.
| #Raku | Raku | constant mapping = :OPEN(' '),
:N< ╵ >,
:E< ╶ >,
:NE< └ >,
:S< ╷ >,
:NS< │ >,
:ES< ┌ >,
:NES< ├ >,
:W< ╴ >,
:NW< ┘ >,
:EW< ─ >,
:NEW< ┴ >,
:SW< ┐ >,
:NSW< ┤ >,
:ESW< ┬ >,
:NESW< ┼ >,
:TODO< x >,
:TRIED< · >;
enum Sym (mapping.map: *.key);
my @ch = mapping.map: *.value;
enum Direction <DeadEnd Up Right Down Left>;
sub gen_maze ( $X,
$Y,
$start_x = (^$X).pick * 2 + 1,
$start_y = (^$Y).pick * 2 + 1 )
{
my @maze;
push @maze, $[ flat ES, -N, (ESW, EW) xx $X - 1, SW ];
push @maze, $[ flat (NS, TODO) xx $X, NS ];
for 1 ..^ $Y {
push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ];
push @maze, $[ flat (NS, TODO) xx $X, NS ];
}
push @maze, $[ flat NE, (EW, NEW) xx $X - 1, -NS, NW ];
@maze[$start_y][$start_x] = OPEN;
my @stack;
my $current = [$start_x, $start_y];
loop {
if my $dir = pick_direction( $current ) {
@stack.push: $current;
$current = move( $dir, $current );
}
else {
last unless @stack;
$current = @stack.pop;
}
}
return @maze;
sub pick_direction([$x,$y]) {
my @neighbors =
(Up if @maze[$y - 2][$x]),
(Down if @maze[$y + 2][$x]),
(Left if @maze[$y][$x - 2]),
(Right if @maze[$y][$x + 2]);
@neighbors.pick or DeadEnd;
}
sub move ($dir, @cur) {
my ($x,$y) = @cur;
given $dir {
when Up { @maze[--$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y--][$x+1] -= W; }
when Down { @maze[++$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y++][$x+1] -= W; }
when Left { @maze[$y][--$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x--] -= N; }
when Right { @maze[$y][++$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x++] -= N; }
}
@maze[$y][$x] = 0;
[$x,$y];
}
}
sub display (@maze) {
for @maze -> @y {
for @y.rotor(2) -> ($w, $c) {
print @ch[abs $w];
if $c >= 0 { print @ch[$c] x 3 }
else { print ' ', @ch[abs $c], ' ' }
}
say @ch[@y[*-1]];
}
}
display gen_maze( 29, 19 ); |
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.
| #Stata | Stata | program define maprange
version 15.1
syntax varname(numeric) [if] [in], ///
from(numlist min=2 max=2) to(numlist min=2 max=2) ///
GENerate(name) [REPLACE]
tempname a b c d h
sca `a'=`:word 1 of `from''
sca `b'=`:word 2 of `from''
sca `c'=`:word 1 of `to''
sca `d'=`:word 2 of `to''
sca `h'=(`d'-`c')/(`b'-`a')
cap confirm variable `generate'
if "`replace'"=="replace" & !_rc {
qui replace `generate'=(`varlist'-`a')*`h'+`c' `if' `in'
}
else {
if "`replace'"=="replace" {
di in gr `"(note: variable `generate' not found)"'
}
qui gen `generate'=(`varlist'-`a')*`h'+`c' `if' `in'
}
end |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Swift | Swift | import Foundation
func mapRanges(_ r1: ClosedRange<Double>, _ r2: ClosedRange<Double>, to: Double) -> Double {
let num = (to - r1.lowerBound) * (r2.upperBound - r2.lowerBound)
let denom = r1.upperBound - r1.lowerBound
return r2.lowerBound + num / denom
}
for i in 0...10 {
print(String(format: "%2d maps to %5.2f", i, mapRanges(0...10, -1...0, to: Double(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.
| #PowerShell | PowerShell | $string = "The quick brown fox jumped over the lazy dog's back"
$data = [Text.Encoding]::UTF8.GetBytes($string)
$hash = [Security.Cryptography.MD5]::Create().ComputeHash($data)
([BitConverter]::ToString($hash) -replace '-').ToLower() |
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 .
| #Furor | Furor |
###sysinclude X.uh
$ff0000 sto szin
300 sto maxiter
maxypixel sto YRES
maxxpixel sto XRES
myscreen "Mandelbrot" @YRES @XRES graphic
@YRES 2 / (#d) sto y2
@YRES 2 / (#d) sto x2
#g 0. @XRES (#d) 1. i: {#d
#g 0. @YRES (#d) 1. {#d
#d
{#d}§i 400. - @x2 - @x2 /
sto x
{#d} @y2 - @y2 /
sto y
zero#d xa zero#d ya zero iter
(( #d
@x @xa dup* @ya dup* -+
@y @xa *2 @ya *+ sto ya
sto xa #g inc iter
@iter @maxiter >= then((>))
#d ( @xa dup* @ya dup* + 4. > )))
#g @iter @maxiter == { #d
myscreen {d} {d}§i @szin [][]
}{ #d
myscreen {d} {d}§i #g @iter 64 * [][]
}
#d}
#d}
(( ( myscreen key? 10000 usleep )))
myscreen !graphic
end
{ „x” }
{ „x2” }
{ „y” }
{ „y2” }
{ „xa” }
{ „ya” }
{ „iter” }
{ „maxiter” }
{ „szin” }
{ „YRES” }
{ „XRES” }
{ „myscreen” }
|
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)
| #Rust | Rust | fn main() {
let n = 9;
let mut square = vec![vec![0; n]; n];
for (i, row) in square.iter_mut().enumerate() {
for (j, e) in row.iter_mut().enumerate() {
*e = n * (((i + 1) + (j + 1) - 1 + (n >> 1)) % n) + (((i + 1) + (2 * (j + 1)) - 2) % n) + 1;
print!("{:3} ", e);
}
println!("");
}
let sum = n * (((n * n) + 1) / 2);
println!("The sum of the square is {}.", sum);
} |
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)
| #Scala | Scala | def magicSquare( n:Int ) : Option[Array[Array[Int]]] = {
require(n % 2 != 0, "n must be an odd number")
val a = Array.ofDim[Int](n,n)
// Make the horizontal by starting in the middle of the row and then taking a step back every n steps
val ii = Iterator.continually(0 to n-1).flatten.drop(n/2).sliding(n,n-1).take(n*n*2).toList.flatten
// Make the vertical component by moving up (subtracting 1) but every n-th step, step down (add 1)
val jj = Iterator.continually(n-1 to 0 by -1).flatten.drop(n-1).sliding(n,n-2).take(n*n*2).toList.flatten
// Combine the horizontal and vertical components to create the path
val path = (ii zip jj) take (n*n)
// Fill the array by following the path
for( i<-1 to (n*n); p=path(i-1) ) { a(p._1)(p._2) = i }
Some(a)
}
def output() : Unit = {
def printMagicSquare(n: Int): Unit = {
val ms = magicSquare(n)
val magicsum = (n * n + 1) / 2
assert(
if( ms.isDefined ) {
val a = ms.get
a.forall(_.sum == magicsum) &&
a.transpose.forall(_.sum == magicsum) &&
(for(i<-0 until n) yield { a(i)(i) }).sum == magicsum
}
else { false }
)
if( ms.isDefined ) {
val a = ms.get
for (y <- 0 to n * 2; x <- 0 until n) (x, y) match {
case (0, 0) => print("╔════╤")
case (i, 0) if i == n - 1 => print("════╗\n")
case (i, 0) => print("════╤")
case (0, j) if j % 2 != 0 => print("║ " + f"${ a(0)((j - 1) / 2) }%2d" + " │")
case (i, j) if j % 2 != 0 && i == n - 1 => print(" " + f"${ a(i)((j - 1) / 2) }%2d" + " ║\n")
case (i, j) if j % 2 != 0 => print(" " + f"${ a(i)((j - 1) / 2) }%2d" + " │")
case (0, j) if j == (n * 2) => print("╚════╧")
case (i, j) if j == (n * 2) && i == n - 1 => print("════╝\n")
case (i, j) if j == (n * 2) => print("════╧")
case (0, _) => print("╟────┼")
case (i, _) if i == n - 1 => print("────╢\n")
case (i, _) => print("────┼")
}
}
}
printMagicSquare(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.
| #Java | Java | public static double[][] mult(double a[][], double b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new double[0][0];
if(a[0].length != b.length) return null; //invalid dims
int n = a[0].length;
int m = a.length;
int p = b[0].length;
double ans[][] = new double[m][p];
for(int i = 0;i < m;i++){
for(int j = 0;j < p;j++){
for(int k = 0;k < n;k++){
ans[i][j] += a[i][k] * b[k][j];
}
}
}
return ans;
} |
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
| #Swift | Swift | func A(_ k: Int,
_ x1: @escaping () -> Int,
_ x2: @escaping () -> Int,
_ x3: @escaping () -> Int,
_ x4: @escaping () -> Int,
_ x5: @escaping () -> Int) -> Int {
var k1 = k
func B() -> Int {
k1 -= 1
return A(k1, B, x1, x2, x3, x4)
}
if k1 <= 0 {
return x4() + x5()
} else {
return B()
}
}
print(A(10, {1}, {-1}, {-1}, {1}, {0})) |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to 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
| #Tcl | Tcl | proc A {k x1 x2 x3 x4 x5} {
expr {$k<=0 ? [eval $x4]+[eval $x5] : [B \#[info level]]}
}
proc B {level} {
upvar $level k k x1 x1 x2 x2 x3 x3 x4 x4
incr k -1
A $k [info level 0] $x1 $x2 $x3 $x4
}
proc C {val} {return $val}
interp recursionlimit {} 1157
A 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.
| #J | J | ]matrix=: (^/ }:) >:i.5 NB. make and show example matrix
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
|: matrix
1 2 3 4 5
1 4 9 16 25
1 8 27 64 125
1 16 81 256 625 |
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.
| #Rascal | Rascal | import IO;
import util::Math;
import List;
public void make_maze(int w, int h){
vis = [[0 | _ <- [1..w]] | _ <- [1..h]];
ver = [["| "| _ <- [1..w]] + ["|"] | _ <- [1..h]] + [[]];
hor = [["+--"| _ <- [1..w]] + ["+"] | _ <- [1..h + 1]];
void walk(int x, int y){
vis[y][x] = 1;
d = [<x - 1, y>, <x, y + 1>, <x + 1, y>, <x, y - 1>];
while (d != []){
<<xx, yy>, d> = takeOneFrom(d);
if (xx < 0 || yy < 0 || xx >= w || yy >= w) continue;
if (vis[yy][xx] == 1) continue;
if (xx == x) hor[max([y, yy])][x] = "+ ";
if (yy == y) ver[y][max([x, xx])] = " ";
walk(xx, yy);
}
}
walk(arbInt(w), arbInt(h));
for (<a, b> <- zip(hor, ver)){
println(("" | it + "<z>" | z <- a));
println(("" | it + "<z>" | z <- 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.
| #Tcl | Tcl | package require Tcl 8.5
proc rangemap {rangeA rangeB value} {
lassign $rangeA a1 a2
lassign $rangeB b1 b2
expr {$b1 + ($value - $a1)*double($b2 - $b1)/($a2 - $a1)}
} |
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.
| #Ursala | Ursala | #import flo
f((("a1","a2"),("b1","b2")),"s") = plus("b1",div(minus("s","a1"),minus("a2","a1")))
#cast %eL
test = f* ((0.,10.),(-1.,0.))-* ari11/0. 10. |
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.
| #PureBasic | PureBasic | UseMD5Fingerprint() ; register the MD5 fingerprint plugin
test$ = "The quick brown fox jumped over the lazy dog's back"
; Call StringFingerprint() function and display MD5 result in Debug window
Debug StringFingerprint(test$, #PB_Cipher_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 .
| #Futhark | Futhark |
default(f32)
type complex = (f32, f32)
fun dot(c: complex): f32 =
let (r, i) = c
in r * r + i * i
fun multComplex(x: complex, y: complex): complex =
let (a, b) = x
let (c, d) = y
in (a*c - b * d,
a*d + b * c)
fun addComplex(x: complex, y: complex): complex =
let (a, b) = x
let (c, d) = y
in (a + c,
b + d)
fun divergence(depth: int, c0: complex): int =
loop ((c, i) = (c0, 0)) = while i < depth && dot(c) < 4.0 do
(addComplex(c0, multComplex(c, c)),
i + 1)
in i
fun mandelbrot(screenX: int, screenY: int, depth: int, view: (f32,f32,f32,f32)): [screenX][screenY]int =
let (xmin, ymin, xmax, ymax) = view
let sizex = xmax - xmin
let sizey = ymax - ymin
in map (fn (x: int): [screenY]int =>
map (fn (y: int): int =>
let c0 = (xmin + (f32(x) * sizex) / f32(screenX),
ymin + (f32(y) * sizey) / f32(screenY))
in divergence(depth, c0))
(iota screenY))
(iota screenX)
fun main(screenX: int, screenY: int, depth: int, xmin: f32, ymin: f32, xmax: f32, ymax: f32): [screenX][screenY]int =
mandelbrot(screenX, screenY, depth, (xmin, ymin, xmax, ymax))
|
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)
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: succ (in integer: num, in integer: max) is
return succ(num mod max);
const func integer: pred (in integer: num, in integer: max) is
return succ((num - 2) mod max);
const proc: main is func
local
var integer: size is 3;
var array array integer: magic is 0 times 0 times 0;
var integer: row is 1;
var integer: column is 1;
var integer: number is 0;
begin
if length(argv(PROGRAM)) >= 1 then
size := integer parse (argv(PROGRAM)[1]);
end if;
magic := size times size times 0;
column := succ(size div 2);
for number range 1 to size ** 2 do
magic[row][column] := number;
if magic[pred(row, size)][succ(column, size)] = 0 then
row := pred(row, size);
column := succ(column, size);
else
row := succ(row, size);
end if;
end for;
for key row range magic do
for key column range magic[row] do
write(magic[row][column] lpad 4);
end for;
writeln;
end for;
end func; |
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)
| #Sidef | Sidef | func magic_square(n {.is_pos && .is_odd}) {
var i = 0
var j = int(n/2)
var magic_square = []
for l in (1 .. n**2) {
magic_square[i][j] = l
if (magic_square[i.dec % n][j.inc % n]) {
i = (i.inc % n)
}
else {
i = (i.dec % n)
j = (j.inc % n)
}
}
return magic_square
}
func print_square(sq) {
var f = "%#{(sq.len**2).len}d";
for row in sq {
say row.map{ f % _ }.join(' ')
}
}
var(n=5) = ARGV»to_i»()...
var sq = magic_square(n)
print_square(sq)
say "\nThe magic number is: #{sq[0].sum}" |
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.
| #JavaScript | JavaScript | // returns a new matrix
Matrix.prototype.mult = function(other) {
if (this.width != other.height) {
throw "error: incompatible sizes";
}
var result = [];
for (var i = 0; i < this.height; i++) {
result[i] = [];
for (var j = 0; j < other.width; j++) {
var sum = 0;
for (var k = 0; k < this.width; k++) {
sum += this.mtx[i][k] * other.mtx[k][j];
}
result[i][j] = sum;
}
}
return new Matrix(result);
}
var a = new Matrix([[1,2],[3,4]])
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
print(a.mult(b)); |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to 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
| #TSQL | TSQL |
CREATE PROCEDURE dbo.LAMBDA_WRAP_INTEGER
@v INT
AS
DECLARE @name NVARCHAR(MAX) = 'LAMBDA_' + UPPER(REPLACE(NEWID(), '-', '_'))
DECLARE @SQL NVARCHAR(MAX) = '
CREATE PROCEDURE dbo.' + @name + '
AS
RETURN ' + CAST(@v AS NVARCHAR(MAX))
EXEC(@SQL)
RETURN OBJECT_ID(@name)
GO
CREATE PROCEDURE dbo.LAMBDA_EXEC
@id INT
AS
DECLARE @name SYSNAME = OBJECT_NAME(@id)
, @retval INT
EXEC @retval = @name
RETURN @retval
GO
-- B-procedure
CREATE PROCEDURE dbo.LAMBDA_B
@name_out SYSNAME OUTPUT
, @q INT
AS
BEGIN
DECLARE @SQL NVARCHAR(MAX)
, @name NVARCHAR(MAX) = 'LAMBDA_B_' + UPPER(REPLACE(NEWID(), '-', '_'))
SELECT @SQL = N'
CREATE PROCEDURE dbo.' + @name + N'
AS
DECLARE @retval INT, @k INT, @x1 INT, @x2 INT, @x3 INT, @x4 INT
SELECT @k = k - 1, @x1 = x1, @x2 = x2, @x3 = x3, @x4 = x4
FROM #t_args t
WHERE t.i = ' + CAST(@q AS NVARCHAR(MAX)) + '
UPDATE t
SET k = k -1
FROM #t_args t
WHERE t.i = ' + CAST(@q AS NVARCHAR(MAX)) + '
EXEC @retval = LAMBDA_A @k, @@PROCID, @x1, @x2, @x3, @x4
RETURN @retval'
EXEC(@SQL)
SELECT @name_out = @name
END
GO
-- A-procedure
CREATE PROCEDURE dbo.LAMBDA_A
(
@k INT
, @x1 INT
, @x2 INT
, @x3 INT
, @x4 INT
, @x5 INT
)
AS
SET NOCOUNT ON;
DECLARE @res1 INT
, @res2 INT
, @Name SYSNAME
, @q INT
-- First add the arguments to the "stack"
INSERT INTO #t_args (k, x1, x2, x3, x4, x5
)
SELECT @k, @x1, @x2, @x3, @x4, @x5
SELECT @q = SCOPE_IDENTITY()
IF @k <= 0
BEGIN
EXEC @res1 = dbo.LAMBDA_EXEC @x4
EXEC @res2 = dbo.LAMBDA_EXEC @x5
RETURN @res1 + @res2
END
ELSE
BEGIN
EXEC dbo.LAMBDA_B @name_out = @Name OUTPUT, @q = @q
EXEC @res1 = @Name
RETURN @res1
END
GO
-------------------------------------------------------------
-- Test script
-------------------------------------------------------------
DECLARE @x1 INT
, @x2 INT
, @x0 INT
, @x4 INT
, @x5 INT
, @K INT
, @retval INT
-------------------------------------------------------------
-- Create wrapped integers to pass as arguments
-------------------------------------------------------------
EXEC @x1 = LAMBDA_WRAP_INTEGER 1
EXEC @x2 = LAMBDA_WRAP_INTEGER -1
EXEC @x0 = LAMBDA_WRAP_INTEGER 0
-------------------------------------------------------------
-- Argument storage table
-------------------------------------------------------------
CREATE TABLE #t_args (
k INT
, x1 INT
, x2 INT
, x3 INT
, x4 INT
, x5 INT
, i INT IDENTITY
)
SELECT @K = 1
-- Anything above 5 blows up the stack
WHILE @K <= 4
BEGIN
EXEC @retval = dbo.LAMBDA_A @K, @x1, @x2, @x2, @x1, @x0
PRINT 'For k=' + CAST(@K AS VARCHAR) + ', result=' + CAST(@retval AS VARCHAR)
SELECT @K = @K + 1
END
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Java | Java | import java.util.Arrays;
public class Transpose{
public static void main(String[] args){
double[][] m = {{1, 1, 1, 1},
{2, 4, 8, 16},
{3, 9, 27, 81},
{4, 16, 64, 256},
{5, 25, 125, 625}};
double[][] ans = new double[m[0].length][m.length];
for(int rows = 0; rows < m.length; rows++){
for(int cols = 0; cols < m[0].length; cols++){
ans[cols][rows] = m[rows][cols];
}
}
for(double[] i:ans){//2D arrays are arrays of arrays
System.out.println(Arrays.toString(i));
}
}
} |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-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.
| #Red | Red | Red ["Maze generation"]
size: as-pair to-integer ask "Maze width: " to-integer ask "Maze height: "
random/seed now/time
offsetof: function [pos] [pos/y * size/x + pos/x + 1]
visited?: function [pos] [find visited pos]
newneighbour: function [pos][
nnbs: collect [
if all [pos/x > 0 not visited? p: pos - 1x0] [keep p]
if all [pos/x < (size/x - 1) not visited? p: pos + 1x0] [keep p]
if all [pos/y > 0 not visited? p: pos - 0x1] [keep p]
if all [pos/y < (size/y - 1) not visited? p: pos + 0x1] [keep p]
]
pick nnbs random length? nnbs
]
expand: function [pos][
insert visited pos
either npos: newneighbour pos [
insert exploring npos
do select [
0x-1 [o: offsetof npos walls/:o/y: 0]
1x0 [o: offsetof pos walls/:o/x: 0]
0x1 [o: offsetof pos walls/:o/y: 0]
-1x0 [o: offsetof npos walls/:o/x: 0]
] npos - pos
][
remove exploring
]
]
visited: []
walls: append/dup [] 1x1 size/x * size/y
exploring: reduce [random size - 1x1]
until [
expand exploring/1
empty? exploring
]
print append/dup "" " _" size/x
repeat j size/y [
prin "|"
repeat i size/x [
p: pick walls (j - 1 * size/x + i)
prin rejoin [pick " _" 1 + p/y pick " |" 1 + p/x]
]
print ""
] |
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.
| #Vala | Vala | double map_range(double s, int a1, int a2, int b1, int b2) {
return b1+(s-a1)*(b2-b1)/(a2-a1);
}
void main() {
for (int s = 0; s < 11; s++){
print("%2d maps to %5.2f\n", s, map_range(s, 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.
| #WDTE | WDTE | let mapRange r1 r2 s =>
+
(at r2 0)
(/
(*
(-
s
(at r1 0)
)
(-
(at r2 1)
(at r2 0)
)
)
(-
(at r1 1)
(at r1 0)
)
)
;
let s => import 'stream';
let str => import 'strings';
s.range 10
-> s.map (@ enum v => [v; mapRange [0; 10] [-1; 0] v])
-> s.map (@ print v => str.format '{} -> {}' (at v 0) (at v 1) -- io.writeln io.stdout)
-> s.drain
; |
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.
| #Python | Python | >>> import hashlib
>>> # RFC 1321 test suite:
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>> |
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 .
| #FutureBasic | FutureBasic |
_xmin = -8601
_xmax = 2867
_ymin = -4915
_ymax = 4915
_maxiter = 32
_dx = ( _xmax - _xmin ) / 79
_dy = ( _ymax - _ymin ) / 24
void local fn MandelbrotSet
printf @"\n"
SInt32 cy = _ymin
while ( cy <= _ymax )
SInt32 cx = _xmin
while ( cx <= _xmax )
SInt32 x = 0
SInt32 y = 0
SInt32 x2 = 0
SInt32 y2 = 0
SInt32 iter = 0
while ( iter < _maxiter )
if ( x2 + y2 > 16384 ) then break
y = ( ( x * y ) >> 11 ) + (SInt32)cy
x = x2 - y2 + (SInt32)cx
x2 = ( x * x ) >> 12
y2 = ( y * y ) >> 12
iter++
wend
print fn StringWithFormat( @"%3c", iter + 32 );
cx += _dx
wend
printf @"\n"
cy += _dy
wend
end fn
window 1, @"Mandelbrot Set", ( 0, 0, 820, 650 )
WindowSetBackgroundColor( 1, fn ColorBlack )
text @"Impact", 10.0, fn ColorWithRGB( 1.000, 0.800, 0.000, 1.0 )
fn MandelbrotSet
HandleEvents
|
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)
| #Stata | Stata | . mata magic(5)
1 2 3 4 5
+--------------------------+
1 | 17 24 1 8 15 |
2 | 23 5 7 14 16 |
3 | 4 6 13 20 22 |
4 | 10 12 19 21 3 |
5 | 11 18 25 2 9 |
+--------------------------+ |
http://rosettacode.org/wiki/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)
| #Swift | Swift | extension String: Error {}
struct Point: CustomStringConvertible {
var x: Int
var y: Int
init(_ _x: Int,
_ _y: Int) {
self.x = _x
self.y = _y
}
var description: String {
return "(\(x), \(y))\n"
}
}
extension Point: Equatable,Comparable {
static func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
static func < (lhs: Point, rhs: Point) -> Bool {
return lhs.y != rhs.y ? lhs.y < rhs.y : lhs.x < rhs.x
}
}
class MagicSquare: CustomStringConvertible {
var grid:[Int:Point] = [:]
var number: Int = 1
init(base n:Int) {
grid = [:]
number = n
}
func createOdd() throws -> MagicSquare {
guard number < 1 || number % 2 != 0 else {
throw "Must be odd and >= 1, try again"
return self
}
var x = 0
var y = 0
let middle = Int(number/2)
x = middle
grid[1] = Point(x,y)
for i in 2 ... number*number {
let oldXY = Point(x,y)
x += 1
y -= 1
if x >= number {x -= number}
if y < 0 {y += number}
var tempCoord = Point(x,y)
if let _ = grid.firstIndex(where: { (k,v) -> Bool in
v == tempCoord
})
{
x = oldXY.x
y = oldXY.y + 1
if y >= number {y -= number}
tempCoord = Point(x,y)
}
grid[i] = tempCoord
}
print(self)
return self
}
fileprivate func gridToText(_ result: inout String) {
let sorted = sortedGrid()
let sc = sorted.count
var i = 0
for c in sorted {
result += " \(c.key)"
if c.key < 10 && sc > 10 { result += " "}
if c.key < 100 && sc > 100 { result += " "}
if c.key < 1000 && sc > 1000 { result += " "}
if i%number==(number-1) { result += "\n"}
i += 1
}
result += "\nThe magic number is \(number * (number * number + 1) / 2)"
result += "\nRows and Columns are "
result += checkRows() == checkColumns() ? "Equal" : " Not Equal!"
result += "\nRows and Columns and Diagonals are "
let allEqual = (checkDiagonals() == checkColumns() && checkDiagonals() == checkRows())
result += allEqual ? "Equal" : " Not Equal!"
result += "\n"
}
var description: String {
var result = "base \(number)\n"
gridToText(&result)
return result
}
}
extension MagicSquare {
private func sortedGrid()->[(key:Int,value:Point)] {
return grid.sorted(by: {$0.1 < $1.1})
}
private func checkRows() -> (Bool, Int?)
{
var result = Set<Int>()
var index = 0
var rowtotal = 0
for (cell, _) in sortedGrid()
{
rowtotal += cell
if index%number==(number-1)
{
result.insert(rowtotal)
rowtotal = 0
}
index += 1
}
return (result.count == 1, result.first ?? nil)
}
private func checkColumns() -> (Bool, Int?)
{
var result = Set<Int>()
var sorted = sortedGrid()
for i in 0 ..< number {
var rowtotal = 0
for cell in stride(from: i, to: sorted.count, by: number) {
rowtotal += sorted[cell].key
}
result.insert(rowtotal)
}
return (result.count == 1, result.first)
}
private func checkDiagonals() -> (Bool, Int?)
{
var result = Set<Int>()
var sorted = sortedGrid()
var rowtotal = 0
for cell in stride(from: 0, to: sorted.count, by: number+1) {
rowtotal += sorted[cell].key
}
result.insert(rowtotal)
rowtotal = 0
for cell in stride(from: number-1, to: sorted.count-(number-1), by: number-1) {
rowtotal += sorted[cell].key
}
result.insert(rowtotal)
return (result.count == 1, result.first)
}
}
try MagicSquare(base: 3).createOdd()
try MagicSquare(base: 5).createOdd()
try MagicSquare(base: 7).createOdd()
|
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.
| #jq | jq | def dot_product(a; b):
a as $a | b as $b
| reduce range(0;$a|length) as $i (0; . + ($a[$i] * $b[$i]) );
# transpose/0 expects its input to be a rectangular matrix (an array of equal-length arrays)
def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ;
# A and B should both be numeric matrices, A being m by n, and B being n by p.
def multiply(A; B):
A as $A | B as $B
| ($B[0]|length) as $p
| ($B|transpose) as $BT
| reduce range(0; $A|length) as $i
([]; reduce range(0; $p) as $j
(.; .[$i][$j] = dot_product( $A[$i]; $BT[$j] ) )) ; |
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
| #TXR | TXR | (defun A (k x1 x2 x3 x4 x5)
(labels ((B ()
(dec k)
[A k B x1 x2 x3 x4]))
(if (<= k 0) (+ [x4] [x5]) (B))))
(prinl (A 10 (ret 1) (ret -1) (ret -1) (ret 1) (ret 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
| #Visual_Prolog | Visual Prolog |
implement main
open core
clauses
run():-
console::init(),
stdio::write(a(10, {() = 1}, {() = -1}, {() = -1}, {() = 1}, {() = 0})).
class predicates
a : (integer K, function{integer} X1, function{integer} X2, function{integer} X3, function{integer} X4, function{integer} X5) -> integer Result.
clauses
a(K, X1, X2, X3, X4, X5) = R :-
KM = varM::new(K),
BM = varM{function{integer}}::new({() = 0}),
BM:value :=
{ () = BR :-
KM:value := KM:value-1,
BR = a(KM:value, BM:value, X1, X2, X3, X4)
},
R = if KM:value <= 0 then X4() + X5() else BM:value() end if.
end implement main |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #JavaScript | JavaScript | function Matrix(ary) {
this.mtx = ary
this.height = ary.length;
this.width = ary[0].length;
}
Matrix.prototype.toString = function() {
var s = []
for (var i = 0; i < this.mtx.length; i++)
s.push( this.mtx[i].join(",") );
return s.join("\n");
}
// returns a new matrix
Matrix.prototype.transpose = function() {
var transposed = [];
for (var i = 0; i < this.width; i++) {
transposed[i] = [];
for (var j = 0; j < this.height; j++) {
transposed[i][j] = this.mtx[j][i];
}
}
return new Matrix(transposed);
}
var m = new Matrix([[1,1,1,1],[2,4,8,16],[3,9,27,81],[4,16,64,256],[5,25,125,625]]);
print(m);
print();
print(m.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.
| #REXX | REXX | /*REXX program generates and displays a rectangular solvable maze (of any size). */
parse arg rows cols seed . /*allow user to specify the maze size. */
if rows='' | rows==',' then rows= 19 /*No rows given? Then use the default.*/
if cols='' | cols==',' then cols= 19 /* " cols " ? " " " " */
if datatype(seed, 'W') then call random ,,seed /*use a random seed for repeatability.*/
ht=0; @.=0 /*HT= # rows in grid; @.: default cell*/
call makeRow '┌'copies("~┬", cols - 1)'~┐' /*construct the top edge of the maze. */
/* [↓] construct the maze's grid. */
do r=1 for rows; _=; __=; hp= "|"; hj= '├'
do c=1 for cols; _= _ || hp'1'; __= __ || hj"~"; hj= '┼'; hp= "│"
end /*c*/
call makeRow _'│' /*construct the right edge of the cells*/
if r\==rows then call makeRow __'┤' /* " " " " " " maze.*/
end /*r*/ /* [↑] construct the maze's grid. */
call makeRow '└'copies("~┴", cols - 1)'~┘' /*construct the bottom edge of the maze*/
r!= random(1, rows) *2; c!= random(1, cols) *2; @.r!.c!= 0 /*choose 1st cell.*/
/* [↓] traipse through the maze. */
do forever; n= hood(r!, c!); if n==0 then if \fCell() then leave /*¬freecell?*/
call ?; @._r._c= 0 /*get the (next) maze direction to go. */
ro= r!; co= c!; r!= _r; c!= _c /*save original maze cell coordinates. */
?.zr= ?.zr % 2; ?.zc= ?.zc % 2 /*get the maze row and cell directions.*/
rw= ro + ?.zr; cw= co + ?.zc /*calculate the next row and column. */
@.rw.cw= . /*mark the maze cell as being visited. */
end /*forever*/
/* [↓] display maze to the terminal. */
do r=1 for ht; _=
do c=1 for cols*2 + 1; _= _ || @.r.c; end /*c*/
if \(r//2) then _= translate(_, '\', .) /*trans to backslash*/
@.r= _ /*save the row in @.*/
end /*r*/
do #=1 for ht; _= @.# /*display the maze to the terminal. */
call makeNice /*prettify cell corners and dead─ends. */
_= changestr( 1 , _ , 111 ) /*──────these four ────────────────────*/
_= changestr( 0 , _ , 000 ) /*───────── statements are ────────────*/
_= changestr( . , _ , " " ) /*────────────── used for preserving ──*/
_= changestr('~', _ , "───" ) /*────────────────── the aspect ratio. */
say translate( _ , '─│' , "═|\10" ) /*make it presentable for the screen. */
end /*#*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg _r,_c; return @._r._c /*a fast way to reference a maze cell. */
makeRow: parse arg z; ht= ht+1; do c=1 for length(z); @.ht.c=substr(z,c,1); end; return
hood: parse arg rh,ch; return @(rh+2,ch) + @(rh-2,ch) + @(rh,ch-2) + @(rh,ch+2)
/*──────────────────────────────────────────────────────────────────────────────────────*/
?: do forever; ?.= 0; ?= random(1, 4); if ?==1 then ?.zc= -2 /*north*/
if ?==2 then ?.zr= 2 /* east*/
if ?==3 then ?.zc= 2 /*south*/
if ?==4 then ?.zr= -2 /* west*/
_r= r! + ?.zr; _c= c! + ?.zc; if @._r._c == 1 then return
end /*forever*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
fCell: do r=1 for rows; rr= r + r
do c=1 for cols; cc= c + c
if hood(rr,cc)==1 then do; r!= rr; c!= cc; @.r!.c!= 0; return 1; end
end /*c*/ /* [↑] r! and c! are used by invoker.*/
end /*r*/; return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
makeNice: width= length(_); old= # - 1; new= # + 1; old_= @.old; new_= @.new
if left(_, 2)=='├.' then _= translate(_, "|", '├')
if right(_,2)=='.┤' then _= translate(_, "|", '┤')
do k=1 for width while #==1; z= substr(_, k, 1) /*maze top row.*/
if z\=='┬' then iterate
if substr(new_, k, 1)=='\' then _= overlay("═", _, k)
end /*k*/
do k=1 for width while #==ht; z= substr(_, k, 1) /*maze bot row.*/
if z\=='┴' then iterate
if substr(old_, k, 1)=='\' then _= overlay("═", _, k)
end /*k*/
do k=3 to width-2 by 2 while #//2; z= substr(_, k, 1) /*maze mid rows*/
if z\=='┼' then iterate
le= substr(_ , k-1, 1)
ri= substr(_ , k+1, 1)
up= substr(old_, k , 1)
dw= substr(new_, k , 1)
select
when le== . & ri== . & up=='│' & dw=="│" then _= overlay('|', _, k)
when le=='~' & ri=="~" & up=='\' & dw=="\" then _= overlay('═', _, k)
when le=='~' & ri=="~" & up=='\' & dw=="│" then _= overlay('┬', _, k)
when le=='~' & ri=="~" & up=='│' & dw=="\" then _= overlay('┴', _, k)
when le=='~' & ri== . & up=='\' & dw=="\" then _= overlay('═', _, k)
when le== . & ri=="~" & up=='\' & dw=="\" then _= overlay('═', _, k)
when le== . & ri== . & up=='│' & dw=="\" then _= overlay('|', _, k)
when le== . & ri== . & up=='\' & dw=="│" then _= overlay('|', _, k)
when le== . & ri=="~" & up=='\' & dw=="│" then _= overlay('┌', _, k)
when le== . & ri=="~" & up=='│' & dw=="\" then _= overlay('└', _, k)
when le=='~' & ri== . & up=='\' & dw=="│" then _= overlay('┐', _, k)
when le=='~' & ri== . & up=='│' & dw=="\" then _= overlay('┘', _, k)
when le=='~' & ri== . & up=='│' & dw=="│" then _= overlay('┤', _, k)
when le== . & ri=="~" & up=='│' & dw=="│" then _= overlay('├', _, k)
otherwise nop
end /*select*/
end /*k*/; return |
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.
| #Wren | Wren | import "/fmt" for Fmt
var mapRange = Fn.new { |a, b, s| b.from + (s - a.from) * (b.to - b.from) / (a.to - a.from) }
var a = 0..10
var b = -1..0
for (s in a) {
var t = mapRange.call(a, b, s)
var f = (t >= 0) ? " " : ""
System.print("%(Fmt.d(2, s)) maps to %(f)%(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.
| #R | R | library(digest)
hexdigest <- digest("The quick brown fox jumped over the lazy dog's back",
algo="md5", serialize=FALSE) |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
const int MaxIterations = 1000;
const vec2 Focus = vec2(-0.51, 0.54);
const float Zoom = 1.0;
vec3
color(int iteration, float sqLengthZ) {
// If the point is within the mandlebrot set
// just color it black
if(iteration == MaxIterations)
return vec3(0.0);
// Else we give it a smoothed color
float ratio = (float(iteration) - log2(log2(sqLengthZ))) / float(MaxIterations);
// Procedurally generated colors
return mix(vec3(1.0, 0.0, 0.0), vec3(1.0, 1.0, 0.0), sqrt(ratio));
}
void
mainImage(out vec4 fragColor, in vec2 fragCoord) {
// C is the aspect-ratio corrected UV coordinate.
vec2 c = (-1.0 + 2.0 * fragCoord / iResolution.xy) * vec2(iResolution.x / iResolution.y, 1.0);
// Apply scaling, then offset to get a zoom effect
c = (c * exp(-Zoom)) + Focus;
vec2 z = c;
int iteration = 0;
while(iteration < MaxIterations) {
// Precompute for efficiency
float zr2 = z.x * z.x;
float zi2 = z.y * z.y;
// The larger the square length of Z,
// the smoother the shading
if(zr2 + zi2 > 32.0) break;
// Complex multiplication, then addition
z = vec2(zr2 - zi2, 2.0 * z.x * z.y) + c;
++iteration;
}
// Generate the colors
fragColor = vec4(color(iteration, dot(z,z)), 1.0);
// Apply gamma correction
fragColor.rgb = pow(fragColor.rgb, vec3(0.5));
}
|
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)
| #Tcl | Tcl | proc magicSquare {order} {
if {!($order & 1) || $order < 0} {
error "order must be odd and positive"
}
set s [lrepeat $order [lrepeat $order 0]]
set x [expr {$order / 2}]
set y 0
for {set i 1} {$i <= $order**2} {incr i} {
lset s $y $x $i
set x [expr {($x + 1) % $order}]
set y [expr {($y - 1) % $order}]
if {[lindex $s $y $x]} {
set x [expr {($x - 1) % $order}]
set y [expr {($y + 2) % $order}]
}
}
return $s
} |
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.
| #Jsish | Jsish | /* Matrix multiplication, in Jsish */
require('Matrix');
if (Interp.conf('unitTest')) {
var a = new Matrix([[1,2],[3,4]]);
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
; a;
; b;
; a.mult(b);
}
/*
=!EXPECTSTART!=
a ==> { height:2, mtx:[ [ 1, 2 ], [ 3, 4 ] ], width:2 }
b ==> { height:2, mtx:[ [ -3, -8, 3 ], [ -2, 1, 4 ] ], width:3 }
a.mult(b) ==> { height:2, mtx:[ [ -7, -6, 11 ], [ -17, -20, 25 ] ], width:3 }
=!EXPECTEND!=
*/ |
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
| #Vorpal | Vorpal | self.a = method(k, x1, x2, x3, x4, x5){
b = method(){
code.k = code.k - 1
return( self.a(code.k, code, code.x1, code.x2, code.x3, code.x4) )
}
b.k = k
b.x1 = x1
b.x2 = x2
b.x3 = x3
b.x4 = x4
b.x5 = x5
if(k <= 0){
return(self.apply(x4) + self.apply(x5))
}
else{
return(self.apply(b))
}
}
self.K = method(n){
f = method(){
return(code.n)
}
f.n = n
return(f)
}
self.a(10, self.K(1), self.K(-1), self.K(-1), self.K(1), self.K(0)).print() |
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
| #Wren | Wren | import "/fmt" for Fmt
var a
a = Fn.new { |k, x1, x2, x3, x4, x5|
var b
b = Fn.new {
k = k - 1
return a.call(k, b, x1, x2, x3, x4)
}
return (k <= 0) ? x4.call() + x5.call() : b.call()
}
System.print(" k a")
for (k in 0..20) {
Fmt.print("$2d : $ d", k, a.call(k, Fn.new { 1 }, Fn.new { -1 }, Fn.new { -1 }, Fn.new { 1 }, Fn.new { 0 }))
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Joy | Joy | DEFINE transpose == [ [null] [true] [[null] some] ifte ]
[ pop [] ]
[ [[first] map] [[rest] map] cleave ]
[ cons ]
linrec . |
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.
| #Ruby | Ruby | class Maze
DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]
def initialize(width, height)
@width = width
@height = height
@start_x = rand(width)
@start_y = 0
@end_x = rand(width)
@end_y = height - 1
# Which walls do exist? Default to "true". Both arrays are
# one element bigger than they need to be. For example, the
# @vertical_walls[x][y] is true if there is a wall between
# (x,y) and (x+1,y). The additional entry makes printing easier.
@vertical_walls = Array.new(width) { Array.new(height, true) }
@horizontal_walls = Array.new(width) { Array.new(height, true) }
# Path for the solved maze.
@path = Array.new(width) { Array.new(height) }
# "Hack" to print the exit.
@horizontal_walls[@end_x][@end_y] = false
# Generate the maze.
generate
end
# Print a nice ASCII maze.
def print
# Special handling: print the top line.
puts @width.times.inject("+") {|str, x| str << (x == @start_x ? " +" : "---+")}
# For each cell, print the right and bottom wall, if it exists.
@height.times do |y|
line = @width.times.inject("|") do |str, x|
str << (@path[x][y] ? " * " : " ") << (@vertical_walls[x][y] ? "|" : " ")
end
puts line
puts @width.times.inject("+") {|str, x| str << (@horizontal_walls[x][y] ? "---+" : " +")}
end
end
private
# Reset the VISITED state of all cells.
def reset_visiting_state
@visited = Array.new(@width) { Array.new(@height) }
end
# Is the given coordinate valid and the cell not yet visited?
def move_valid?(x, y)
(0...@width).cover?(x) && (0...@height).cover?(y) && !@visited[x][y]
end
# Generate the maze.
def generate
reset_visiting_state
generate_visit_cell(@start_x, @start_y)
end
# Depth-first maze generation.
def generate_visit_cell(x, y)
# Mark cell as visited.
@visited[x][y] = true
# Randomly get coordinates of surrounding cells (may be outside
# of the maze range, will be sorted out later).
coordinates = DIRECTIONS.shuffle.map { |dx, dy| [x + dx, y + dy] }
for new_x, new_y in coordinates
next unless move_valid?(new_x, new_y)
# Recurse if it was possible to connect the current and
# the cell (this recursion is the "depth-first" part).
connect_cells(x, y, new_x, new_y)
generate_visit_cell(new_x, new_y)
end
end
# Try to connect two cells. Returns whether it was valid to do so.
def connect_cells(x1, y1, x2, y2)
if x1 == x2
# Cells must be above each other, remove a horizontal wall.
@horizontal_walls[x1][ [y1, y2].min ] = false
else
# Cells must be next to each other, remove a vertical wall.
@vertical_walls[ [x1, x2].min ][y1] = false
end
end
end
# Demonstration:
maze = Maze.new 20, 10
maze.print |
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.
| #XPL0 | XPL0 | include c:\cxpl\codes;
func real Map(A1, A2, B1, B2, S);
real A1, A2, B1, B2, S;
return B1 + (S-A1)*(B2-B1)/(A2-A1);
int I;
[for I:= 0 to 10 do
[if I<10 then ChOut(0, ^ ); IntOut(0, I);
RlOut(0, Map(0., 10., -1., 0., float(I)));
CrLf(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.
| #Yabasic | Yabasic | sub MapRange(s, a1, a2, b1, b2)
return b1+(s-a1)*(b2-b1)/(a2-a1)
end sub
for i = 0 to 10 step 2
print i, " : ", MapRange(i,0,10,-1,0)
next |
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.
| #Racket | Racket |
#lang racket
(require file/md5)
(md5 "")
(md5 "a")
(md5 "abc")
(md5 "message digest")
(md5 "abcdefghijklmnopqrstuvwxyz")
(md5 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
(md5 "12345678901234567890123456789012345678901234567890123456789012345678901234567890")
|
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 .
| #GLSL | GLSL |
const int MaxIterations = 1000;
const vec2 Focus = vec2(-0.51, 0.54);
const float Zoom = 1.0;
vec3
color(int iteration, float sqLengthZ) {
// If the point is within the mandlebrot set
// just color it black
if(iteration == MaxIterations)
return vec3(0.0);
// Else we give it a smoothed color
float ratio = (float(iteration) - log2(log2(sqLengthZ))) / float(MaxIterations);
// Procedurally generated colors
return mix(vec3(1.0, 0.0, 0.0), vec3(1.0, 1.0, 0.0), sqrt(ratio));
}
void
mainImage(out vec4 fragColor, in vec2 fragCoord) {
// C is the aspect-ratio corrected UV coordinate.
vec2 c = (-1.0 + 2.0 * fragCoord / iResolution.xy) * vec2(iResolution.x / iResolution.y, 1.0);
// Apply scaling, then offset to get a zoom effect
c = (c * exp(-Zoom)) + Focus;
vec2 z = c;
int iteration = 0;
while(iteration < MaxIterations) {
// Precompute for efficiency
float zr2 = z.x * z.x;
float zi2 = z.y * z.y;
// The larger the square length of Z,
// the smoother the shading
if(zr2 + zi2 > 32.0) break;
// Complex multiplication, then addition
z = vec2(zr2 - zi2, 2.0 * z.x * z.y) + c;
++iteration;
}
// Generate the colors
fragColor = vec4(color(iteration, dot(z,z)), 1.0);
// Apply gamma correction
fragColor.rgb = pow(fragColor.rgb, vec3(0.5));
}
|
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)
| #TI-83_BASIC | TI-83 BASIC | 9→N
DelVar [A]:{N,N}→dim([A])
For(I,1,N)
For(J,1,N)
Remainder(I*2-J+N-1,N)*N+Remainder(I*2+J-2,N)+1→[A](I,J)
End
End
[A] |
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)
| #uBasic.2F4tH | uBasic/4tH | ' ------=< MAIN >=------
Proc _magicsq(5)
Proc _magicsq(11)
End
_magicsq Param (1) Local (4)
' reset the array
For b@ = 0 to 255
@(b@) = 0
Next
If ((a@ % 2) = 0) + (a@ < 3) + (a@ > 15) Then
Print "error: size is not odd or size is smaller then 3 or bigger than 15"
Return
EndIf
' start in the middle of the first row
b@ = 1
c@ = a@ - (a@ / 2)
d@ = 1
e@ = a@ * a@
' main loop for creating magic square
Do
If @(c@*a@+d@) = 0 Then
@(c@*a@+d@) = b@
If (b@ % a@) = 0 Then
d@ = d@ + 1
Else
c@ = c@ + 1
d@ = d@ - 1
EndIf
b@ = b@ + 1
EndIf
If c@ > a@ Then
c@ = 1
Do While @(c@*a@+d@) # 0
c@ = c@ + 1
Loop
EndIf
If d@ < 1 Then
d@ = a@
Do While @(c@*a@+d@) # 0
d@ = d@ - 1
Loop
EndIf
Until b@ > e@
Loop
Print "Odd magic square size: "; a@; " * "; a@
Print "The magic sum = "; ((e@+1) / 2) * a@
Print
For d@ = 1 To a@
For c@ = 1 To a@
Print Using "____"; @(c@*a@+d@);
Next
Print
Next
Print
Return
|
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.
| #Julia | Julia | julia> [1 2 3 ; 4 5 6] * [1 2 ; 3 4 ; 5 6] # product of a 2x3 by a 3x2
2x2 Array{Int64,2}:
22 28
49 64
julia> [1 2 3] * [1,2,3] # product of a row vector by a column vector
1-element Array{Int64,1}:
14
|
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
| #zkl | zkl | fcn A(k, x1, x2, x3, x4, x5){ // -->1,0,-2,0,1,0,1,-1,-10,-30,-67,-138
B:=CB(k, x1, x2, x3, x4, x5);
if(k <= 0) x4()+x5() else B.B();
}
foreach k in (12){
println("k=%2d A=%d".fmt(k, A(k, 1, -1, -1, 1, 0)))
}
class CB{ var k, x1, x2, x3, x4, x5;
fcn init{ k, x1, x2, x3, x4, x5 = vm.arglist; }
fcn B{
k= k - 1;
A(k, B, x1, x2, x3, x4);
}
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #jq | jq | def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ; |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Rust | Rust | use rand::{thread_rng, Rng, rngs::ThreadRng};
const WIDTH: usize = 16;
const HEIGHT: usize = 16;
#[derive(Clone, Copy)]
struct Cell {
col: usize,
row: usize,
}
impl Cell {
fn from(col: usize, row: usize) -> Cell {
Cell {col, row}
}
}
struct Maze {
cells: [[bool; HEIGHT]; WIDTH], //cell visited/non visited
walls_h: [[bool; WIDTH]; HEIGHT + 1], //horizontal walls existing/removed
walls_v: [[bool; WIDTH + 1]; HEIGHT], //vertical walls existing/removed
thread_rng: ThreadRng, //Random numbers generator
}
impl Maze {
///Inits the maze, with all the cells unvisited and all the walls active
fn new() -> Maze {
Maze {
cells: [[true; HEIGHT]; WIDTH],
walls_h: [[true; WIDTH]; HEIGHT + 1],
walls_v: [[true; WIDTH + 1]; HEIGHT],
thread_rng: thread_rng(),
}
}
///Randomly chooses the starting cell
fn first(&mut self) -> Cell {
Cell::from(self.thread_rng.gen_range(0, WIDTH), self.thread_rng.gen_range(0, HEIGHT))
}
///Opens the enter and exit doors
fn open_doors(&mut self) {
let from_top: bool = self.thread_rng.gen();
let limit = if from_top { WIDTH } else { HEIGHT };
let door = self.thread_rng.gen_range(0, limit);
let exit = self.thread_rng.gen_range(0, limit);
if from_top {
self.walls_h[0][door] = false;
self.walls_h[HEIGHT][exit] = false;
} else {
self.walls_v[door][0] = false;
self.walls_v[exit][WIDTH] = false;
}
}
///Removes a wall between the two Cell arguments
fn remove_wall(&mut self, cell1: &Cell, cell2: &Cell) {
if cell1.row == cell2.row {
self.walls_v[cell1.row][if cell1.col > cell2.col { cell1.col } else { cell2.col }] = false;
} else {
self.walls_h[if cell1.row > cell2.row { cell1.row } else { cell2.row }][cell1.col] = false;
};
}
///Returns a random non-visited neighbor of the Cell passed as argument
fn neighbor(&mut self, cell: &Cell) -> Option<Cell> {
self.cells[cell.col][cell.row] = false;
let mut neighbors = Vec::new();
if cell.col > 0 && self.cells[cell.col - 1][cell.row] { neighbors.push(Cell::from(cell.col - 1, cell.row)); }
if cell.row > 0 && self.cells[cell.col][cell.row - 1] { neighbors.push(Cell::from(cell.col, cell.row - 1)); }
if cell.col < WIDTH - 1 && self.cells[cell.col + 1][cell.row] { neighbors.push(Cell::from(cell.col + 1, cell.row)); }
if cell.row < HEIGHT - 1 && self.cells[cell.col][cell.row + 1] { neighbors.push(Cell::from(cell.col, cell.row + 1)); }
if neighbors.is_empty() {
None
} else {
let next = neighbors.get(self.thread_rng.gen_range(0, neighbors.len())).unwrap();
self.remove_wall(cell, next);
Some(*next)
}
}
///Builds the maze (runs the Depth-first search algorithm)
fn build(&mut self) {
let mut cell_stack: Vec<Cell> = Vec::new();
let mut next = self.first();
loop {
while let Some(cell) = self.neighbor(&next) {
cell_stack.push(cell);
next = cell;
}
match cell_stack.pop() {
Some(cell) => next = cell,
None => break,
}
}
}
///Displays a wall
fn paint_wall(h_wall: bool, active: bool) {
if h_wall {
print!("{}", if active { "+---" } else { "+ " });
} else {
print!("{}", if active { "| " } else { " " });
}
}
///Displays a final wall for a row
fn paint_close_wall(h_wall: bool) {
if h_wall { println!("+") } else { println!() }
}
///Displays a whole row of walls
fn paint_row(&self, h_walls: bool, index: usize) {
let iter = if h_walls { self.walls_h[index].iter() } else { self.walls_v[index].iter() };
for &wall in iter {
Maze::paint_wall(h_walls, wall);
}
Maze::paint_close_wall(h_walls);
}
///Paints the maze
fn paint(&self) {
for i in 0 .. HEIGHT {
self.paint_row(true, i);
self.paint_row(false, i);
}
self.paint_row(true, HEIGHT);
}
}
fn main() {
let mut maze = Maze::new();
maze.build();
maze.open_doors();
maze.paint();
} |
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.
| #zkl | zkl | fcn mapRange([(a1,a2)], [(b1,b2)], s) // a1a2 is List(a1,a2)
{ b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) }
r1:=T(0.0, 10.0); r2:=T(-1.0, 0.0);
foreach s in ([0.0 .. 10]){
"%2d maps to %5.2f".fmt(s,mapRange(r1,r2, s)).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.
| #Raku | Raku | use Digest::MD5;
say Digest::MD5.md5_hex: "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 .
| #gnuplot | gnuplot | set terminal png
set output 'mandelbrot.png' |
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)
| #VBA | VBA | Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Next j
Next i
Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub 'magicsquare
|
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)
| #VBScript | VBScript |
Sub magic_square(n)
Dim ms()
ReDim ms(n-1,n-1)
inc = 0
count = 1
row = 0
col = Int(n/2)
Do While count <= n*n
ms(row,col) = count
count = count + 1
If inc < n-1 Then
inc = inc + 1
row = row - 1
col = col + 1
If row >= 0 Then
If col > n-1 Then
col = 0
End If
Else
row = n-1
End If
Else
inc = 0
row = row + 1
End If
Loop
For i = 0 To n-1
For j = 0 To n-1
If j = n-1 Then
WScript.StdOut.Write ms(i,j)
Else
WScript.StdOut.Write ms(i,j) & vbTab
End If
Next
WScript.StdOut.WriteLine
Next
End Sub
magic_square(5)
|
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.
| #K | K | (1 2;3 4)_mul (5 6;7 8)
(19 22
43 50) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Jsish | Jsish | /* Matrix transposition, multiplication, identity, and exponentiation, in Jsish */
function Matrix(ary) {
this.mtx = ary;
this.height = ary.length;
this.width = ary[0].length;
}
Matrix.prototype.toString = function() {
var s = [];
for (var i = 0; i < this.mtx.length; i++) s.push(this.mtx[i].join(","));
return s.join("\n");
};
// returns a transposed matrix
Matrix.prototype.transpose = function() {
var transposed = [];
for (var i = 0; i < this.width; i++) {
transposed[i] = [];
for (var j = 0; j < this.height; j++) transposed[i][j] = this.mtx[j][i];
}
return new Matrix(transposed);
};
// returns a matrix as the product of two others
Matrix.prototype.mult = function(other) {
if (this.width != other.height) throw "error: incompatible sizes";
var result = [];
for (var i = 0; i < this.height; i++) {
result[i] = [];
for (var j = 0; j < other.width; j++) {
var sum = 0;
for (var k = 0; k < this.width; k++) sum += this.mtx[i][k] * other.mtx[k][j];
result[i][j] = sum;
}
}
return new Matrix(result);
};
// IdentityMatrix is a "subclass" of Matrix
function IdentityMatrix(n) {
this.height = n;
this.width = n;
this.mtx = [];
for (var i = 0; i < n; i++) {
this.mtx[i] = [];
for (var j = 0; j < n; j++) this.mtx[i][j] = (i == j ? 1 : 0);
}
}
IdentityMatrix.prototype = Matrix.prototype;
// the Matrix exponentiation function
Matrix.prototype.exp = function(n) {
var result = new IdentityMatrix(this.height);
for (var i = 1; i <= n; i++) result = result.mult(this);
return result;
};
provide('Matrix', '0.60'); |
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.
| #Scala | Scala | import scala.util.Random
object MazeTypes {
case class Direction(val dx: Int, val dy: Int)
case class Loc(val x: Int, val y: Int) {
def +(that: Direction): Loc = Loc(x + that.dx, y + that.dy)
}
case class Door(val from: Loc, to: Loc)
val North = Direction(0,-1)
val South = Direction(0,1)
val West = Direction(-1,0)
val East = Direction(1,0)
val directions = Set(North, South, West, East)
}
object MazeBuilder {
import MazeTypes._
def shuffle[T](set: Set[T]): List[T] = Random.shuffle(set.toList)
def buildImpl(current: Loc, grid: Grid): Grid = {
var newgrid = grid.markVisited(current)
val nbors = shuffle(grid.neighbors(current))
nbors.foreach { n =>
if (!newgrid.isVisited(n)) {
newgrid = buildImpl(n, newgrid.markVisited(current).addDoor(Door(current, n)))
}
}
newgrid
}
def build(width: Int, height: Int): Grid = {
val exit = Loc(width-1, height-1)
buildImpl(exit, new Grid(width, height, Set(), Set()))
}
}
class Grid(val width: Int, val height: Int, val doors: Set[Door], val visited: Set[Loc]) {
def addDoor(door: Door): Grid =
new Grid(width, height, doors + door, visited)
def markVisited(loc: Loc): Grid =
new Grid(width, height, doors, visited + loc)
def isVisited(loc: Loc): Boolean =
visited.contains(loc)
def neighbors(current: Loc): Set[Loc] =
directions.map(current + _).filter(inBounds(_)) -- visited
def printGrid(): List[String] = {
(0 to height).toList.flatMap(y => printRow(y))
}
private def inBounds(loc: Loc): Boolean =
loc.x >= 0 && loc.x < width && loc.y >= 0 && loc.y < height
private def printRow(y: Int): List[String] = {
val row = (0 until width).toList.map(x => printCell(Loc(x, y)))
val rightSide = if (y == height-1) " " else "|"
val newRow = row :+ List("+", rightSide)
List.transpose(newRow).map(_.mkString)
}
private val entrance = Loc(0,0)
private def printCell(loc: Loc): List[String] = {
if (loc.y == height)
List("+--")
else List(
if (openNorth(loc)) "+ " else "+--",
if (openWest(loc) || loc == entrance) " " else "| "
)
}
def openNorth(loc: Loc): Boolean = openInDirection(loc, North)
def openWest(loc: Loc): Boolean = openInDirection(loc, West)
private def openInDirection(loc: Loc, dir: Direction): Boolean =
doors.contains(Door(loc, loc + dir)) || doors.contains(Door(loc + dir, loc))
} |
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.
| #REBOL | REBOL | >> checksum/method "The quick brown fox jumped over the lazy dog" 'md5
== #{08A008A01D498C404B0C30852B39D3B8} |
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 .
| #Go | Go | package main
import "fmt"
import "math/cmplx"
func mandelbrot(a complex128) (z complex128) {
for i := 0; i < 50; i++ {
z = z*z + a
}
return
}
func main() {
for y := 1.0; y >= -1.0; y -= 0.05 {
for x := -2.0; x <= 0.5; x += 0.0315 {
if cmplx.Abs(mandelbrot(complex(x, y))) < 2 {
fmt.Print("*")
} else {
fmt.Print(" ")
}
}
fmt.Println("")
}
} |
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)
| #Visual_Basic | Visual Basic | Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i As Integer, j As Integer, v As Integer
Debug.Print "The square order is: " & n
For i = 1 To n
For j = 1 To n
v = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Debug.Print Right(Space(5) & v, 5);
Next j
Debug.Print
Next i
Debug.Print "The magic number is: " & n * (n * n + 1) \ 2
End Sub 'magicsquare
|
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.
| #Klong | Klong | mul::{[a b];b::+y;{a::x;+/'{a*x}'b}'x}
[[1 2] [3 4]] mul [[5 6] [7 8]]
[[19 22]
[43 50]] |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Julia | Julia | julia> [1 2 3 ; 4 5 6] # a 2x3 matrix
2x3 Array{Int64,2}:
1 2 3
4 5 6
julia> [1 2 3 ; 4 5 6]' # note the quote
3x2 LinearAlgebra.Adjoint{Int64,Array{Int64,2}}:
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.
| #Sidef | Sidef | var(w:5, h:5) = ARGV.map{.to_i}...
var avail = (w * h)
# cell is padded by sentinel col and row, so I don't check array bounds
var cell = (1..h -> map {([true] * w) + [false]} + [[false] * w+1])
var ver = (1..h -> map {["| "] * w })
var hor = (0..h -> map {["+--"] * w })
func walk(x, y) {
cell[y][x] = false;
avail-- > 0 || return; # no more bottles, er, cells
var d = [[-1, 0], [0, 1], [1, 0], [0, -1]]
while (!d.is_empty) {
var i = d.pop_rand
var (x1, y1) = (x + i[0], y + i[1])
cell[y1][x1] || next
if (x == x1) { hor[[y1, y].max][x] = '+ ' }
if (y == y1) { ver[y][[x1, x].max] = ' ' }
walk(x1, y1)
}
}
walk(w.rand.int, h.rand.int) # generate
for i in (0 .. h) {
say (hor[i].join('') + '+')
if (i < h) {
say (ver[i].join('') + '|')
}
} |
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.
| #REXX | REXX | /*REXX program tests the MD5 procedure (below) as per a test suite the IETF RFC (1321).*/
msg.1 = /*─────MD5 test suite [from above doc].*/
msg.2 = 'a'
msg.3 = 'abc'
msg.4 = 'message digest'
msg.5 = 'abcdefghijklmnopqrstuvwxyz'
msg.6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
msg.7 = 12345678901234567890123456789012345678901234567890123456789012345678901234567890
msg.0 = 7 /* [↑] last value doesn't need quotes.*/
do m=1 for msg.0; say /*process each of the seven messages. */
say ' in =' msg.m /*display the in message. */
say 'out =' MD5(msg.m) /* " " out " */
end /*m*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
MD5: procedure; parse arg !; numeric digits 20 /*insure there's enough decimal digits.*/
a='67452301'x; b="efcdab89"x; c='98badcfe'x; d="10325476"x; x00='0'x; x80="80"x
#=length(!) /*length in bytes of the input message.*/
L=#*8//512; if L<448 then plus=448 - L /*is the length less than 448 ? */
if L>448 then plus=960 - L /* " " " greater " " */
if L=448 then plus=512 /* " " " equal to " */
/* [↓] a little of this, ··· */
$=! || x80 || copies(x00, plus%8 -1)reverse(right(d2c(8 * #), 4, x00)) || '00000000'x
/* [↑] ··· and a little of that.*/
do j=0 to length($) % 64 - 1 /*process the message (lots of steps).*/
a_=a; b_=b; c_=c; d_=d /*save the original values for later.*/
chunk=j*64 /*calculate the size of the chunks. */
do k=1 for 16 /*process the message in chunks. */
!.k=reverse( substr($, chunk + 1 + 4*(k-1), 4) ) /*magic stuff.*/
end /*k*/ /*────step────*/
a = .part1( a, b, c, d, 0, 7, 3614090360) /*■■■■ 1 ■■■■*/
d = .part1( d, a, b, c, 1, 12, 3905402710) /*■■■■ 2 ■■■■*/
c = .part1( c, d, a, b, 2, 17, 606105819) /*■■■■ 3 ■■■■*/
b = .part1( b, c, d, a, 3, 22, 3250441966) /*■■■■ 4 ■■■■*/
a = .part1( a, b, c, d, 4, 7, 4118548399) /*■■■■ 5 ■■■■*/
d = .part1( d, a, b, c, 5, 12, 1200080426) /*■■■■ 6 ■■■■*/
c = .part1( c, d, a, b, 6, 17, 2821735955) /*■■■■ 7 ■■■■*/
b = .part1( b, c, d, a, 7, 22, 4249261313) /*■■■■ 8 ■■■■*/
a = .part1( a, b, c, d, 8, 7, 1770035416) /*■■■■ 9 ■■■■*/
d = .part1( d, a, b, c, 9, 12, 2336552879) /*■■■■ 10 ■■■■*/
c = .part1( c, d, a, b, 10, 17, 4294925233) /*■■■■ 11 ■■■■*/
b = .part1( b, c, d, a, 11, 22, 2304563134) /*■■■■ 12 ■■■■*/
a = .part1( a, b, c, d, 12, 7, 1804603682) /*■■■■ 13 ■■■■*/
d = .part1( d, a, b, c, 13, 12, 4254626195) /*■■■■ 14 ■■■■*/
c = .part1( c, d, a, b, 14, 17, 2792965006) /*■■■■ 15 ■■■■*/
b = .part1( b, c, d, a, 15, 22, 1236535329) /*■■■■ 16 ■■■■*/
a = .part2( a, b, c, d, 1, 5, 4129170786) /*■■■■ 17 ■■■■*/
d = .part2( d, a, b, c, 6, 9, 3225465664) /*■■■■ 18 ■■■■*/
c = .part2( c, d, a, b, 11, 14, 643717713) /*■■■■ 19 ■■■■*/
b = .part2( b, c, d, a, 0, 20, 3921069994) /*■■■■ 20 ■■■■*/
a = .part2( a, b, c, d, 5, 5, 3593408605) /*■■■■ 21 ■■■■*/
d = .part2( d, a, b, c, 10, 9, 38016083) /*■■■■ 22 ■■■■*/
c = .part2( c, d, a, b, 15, 14, 3634488961) /*■■■■ 23 ■■■■*/
b = .part2( b, c, d, a, 4, 20, 3889429448) /*■■■■ 24 ■■■■*/
a = .part2( a, b, c, d, 9, 5, 568446438) /*■■■■ 25 ■■■■*/
d = .part2( d, a, b, c, 14, 9, 3275163606) /*■■■■ 26 ■■■■*/
c = .part2( c, d, a, b, 3, 14, 4107603335) /*■■■■ 27 ■■■■*/
b = .part2( b, c, d, a, 8, 20, 1163531501) /*■■■■ 28 ■■■■*/
a = .part2( a, b, c, d, 13, 5, 2850285829) /*■■■■ 29 ■■■■*/
d = .part2( d, a, b, c, 2, 9, 4243563512) /*■■■■ 30 ■■■■*/
c = .part2( c, d, a, b, 7, 14, 1735328473) /*■■■■ 31 ■■■■*/
b = .part2( b, c, d, a, 12, 20, 2368359562) /*■■■■ 32 ■■■■*/
a = .part3( a, b, c, d, 5, 4, 4294588738) /*■■■■ 33 ■■■■*/
d = .part3( d, a, b, c, 8, 11, 2272392833) /*■■■■ 34 ■■■■*/
c = .part3( c, d, a, b, 11, 16, 1839030562) /*■■■■ 35 ■■■■*/
b = .part3( b, c, d, a, 14, 23, 4259657740) /*■■■■ 36 ■■■■*/
a = .part3( a, b, c, d, 1, 4, 2763975236) /*■■■■ 37 ■■■■*/
d = .part3( d, a, b, c, 4, 11, 1272893353) /*■■■■ 38 ■■■■*/
c = .part3( c, d, a, b, 7, 16, 4139469664) /*■■■■ 39 ■■■■*/
b = .part3( b, c, d, a, 10, 23, 3200236656) /*■■■■ 40 ■■■■*/
a = .part3( a, b, c, d, 13, 4, 681279174) /*■■■■ 41 ■■■■*/
d = .part3( d, a, b, c, 0, 11, 3936430074) /*■■■■ 42 ■■■■*/
c = .part3( c, d, a, b, 3, 16, 3572445317) /*■■■■ 43 ■■■■*/
b = .part3( b, c, d, a, 6, 23, 76029189) /*■■■■ 44 ■■■■*/
a = .part3( a, b, c, d, 9, 4, 3654602809) /*■■■■ 45 ■■■■*/
d = .part3( d, a, b, c, 12, 11, 3873151461) /*■■■■ 46 ■■■■*/
c = .part3( c, d, a, b, 15, 16, 530742520) /*■■■■ 47 ■■■■*/
b = .part3( b, c, d, a, 2, 23, 3299628645) /*■■■■ 48 ■■■■*/
a = .part4( a, b, c, d, 0, 6, 4096336452) /*■■■■ 49 ■■■■*/
d = .part4( d, a, b, c, 7, 10, 1126891415) /*■■■■ 50 ■■■■*/
c = .part4( c, d, a, b, 14, 15, 2878612391) /*■■■■ 51 ■■■■*/
b = .part4( b, c, d, a, 5, 21, 4237533241) /*■■■■ 52 ■■■■*/
a = .part4( a, b, c, d, 12, 6, 1700485571) /*■■■■ 53 ■■■■*/
d = .part4( d, a, b, c, 3, 10, 2399980690) /*■■■■ 54 ■■■■*/
c = .part4( c, d, a, b, 10, 15, 4293915773) /*■■■■ 55 ■■■■*/
b = .part4( b, c, d, a, 1, 21, 2240044497) /*■■■■ 56 ■■■■*/
a = .part4( a, b, c, d, 8, 6, 1873313359) /*■■■■ 57 ■■■■*/
d = .part4( d, a, b, c, 15, 10, 4264355552) /*■■■■ 58 ■■■■*/
c = .part4( c, d, a, b, 6, 15, 2734768916) /*■■■■ 59 ■■■■*/
b = .part4( b, c, d, a, 13, 21, 1309151649) /*■■■■ 60 ■■■■*/
a = .part4( a, b, c, d, 4, 6, 4149444226) /*■■■■ 61 ■■■■*/
d = .part4( d, a, b, c, 11, 10, 3174756917) /*■■■■ 62 ■■■■*/
c = .part4( c, d, a, b, 2, 15, 718787259) /*■■■■ 63 ■■■■*/
b = .part4( b, c, d, a, 9, 21, 3951481745) /*■■■■ 64 ■■■■*/
a = .a(a_, a); b=.a(b_, b); c=.a(c_, c); d=.a(d_, d)
end /*j*/
return c2x( reverse(a) )c2x( reverse(b) )c2x( reverse(c) )c2x( reverse(d) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
.a: return right( d2c( c2d( arg(1) ) + c2d( arg(2) ) ), 4, '0'x)
.h: return bitxor( bitxor( arg(1), arg(2) ), arg(3) )
.i: return bitxor( arg(2), bitor(arg(1), bitxor(arg(3), 'ffffffff'x)))
.f: return bitor( bitand(arg(1),arg(2)), bitand(bitxor(arg(1), 'ffffffff'x), arg(3)))
.g: return bitor( bitand(arg(1),arg(3)), bitand(arg(2), bitxor(arg(3), 'ffffffff'x)))
.Lr: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/
?=x2b(c2x(_)); return x2c( b2x( right(? || left(?, #), length(?) )))
.part1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
return .a(.Lr(right(d2c(_+c2d(w) +c2d(.f(x,y,z))+c2d(!.n)),4,'0'x),m),x)
.part2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
return .a(.Lr(right(d2c(_+c2d(w) +c2d(.g(x,y,z))+c2d(!.n)),4,'0'x),m),x)
.part3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
return .a(.Lr(right(d2c(_+c2d(w) +c2d(.h(x,y,z))+c2d(!.n)),4,'0'x),m),x)
.part4: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1
return .a(.Lr(right(d2c(c2d(w) +c2d(.i(x,y,z))+c2d(!.n)+_),4,'0'x),m),x) |
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 .
| #Golfscript | Golfscript | 20{40{0.1{.{;..*2$.*\-
20/3$-@@*10/3$-..*2$.*+1600<}*}32*'
*'=\;\;@@(}60*;(n\}40*;]''+ |
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)
| #Visual_Basic_.NET | Visual Basic .NET | Sub magicsquare()
'Magic squares of odd order
Const n = 9
Dim i, j, v As Integer
Console.WriteLine("The square order is: " & n)
For i = 1 To n
For j = 1 To n
v = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
Console.Write(" " & Right(Space(5) & v, 5))
Next j
Console.WriteLine("")
Next i
Console.WriteLine("The magic number is: " & n * (n * n + 1) \ 2)
End Sub 'magicsquare |
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.
| #Kotlin | Kotlin | // version 1.1.3
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
operator fun Matrix.times(other: Matrix): Matrix {
val rows1 = this.size
val cols1 = this[0].size
val rows2 = other.size
val cols2 = other[0].size
require(cols1 == rows2)
val result = Matrix(rows1) { Vector(cols2) }
for (i in 0 until rows1) {
for (j in 0 until cols2) {
for (k in 0 until rows2) {
result[i][j] += this[i][k] * other[k][j]
}
}
}
return result
}
fun printMatrix(m: Matrix) {
for (i in 0 until m.size) println(m[i].contentToString())
}
fun main(args: Array<String>) {
val m1 = arrayOf(
doubleArrayOf(-1.0, 1.0, 4.0),
doubleArrayOf( 6.0, -4.0, 2.0),
doubleArrayOf(-3.0, 5.0, 0.0),
doubleArrayOf( 3.0, 7.0, -2.0)
)
val m2 = arrayOf(
doubleArrayOf(-1.0, 1.0, 4.0, 8.0),
doubleArrayOf( 6.0, 9.0, 10.0, 2.0),
doubleArrayOf(11.0, -4.0, 5.0, -3.0)
)
printMatrix(m1 * m2)
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #K | K | {x^\:-1_ x}1+!:5
(1 1 1 1.0
2 4 8 16.0
3 9 27 81.0
4 16 64 256.0
5 25 125 625.0)
+{x^\:-1_ x}1+!:5
(1 2 3 4 5.0
1 4 9 16 25.0
1 8 27 64 125.0
1 16 81 256 625.0) |
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.
| #SuperCollider | SuperCollider |
// some useful functions
(
~grid = { 0 ! 60 } ! 60;
~at = { |coord|
var col = ~grid.at(coord[0]);
if(col.notNil) { col.at(coord[1]) }
};
~put = { |coord, value|
var col = ~grid.at(coord[0]);
if(col.notNil) { col.put(coord[1], value) }
};
~coord = ~grid.shape.rand;
~next = { |p|
var possible = [p] + [[0, 1], [1, 0], [-1, 0], [0, -1]];
possible = possible.select { |x|
var c = ~at.(x);
c.notNil and: { c == 0 }
};
possible.choose
};
~walkN = { |p, scale|
var next = ~next.(p);
if(next.notNil) {
~put.(next, 1);
Pen.lineTo(~topoint.(next, scale));
~walkN.(next, scale);
~walkN.(next, scale);
Pen.moveTo(~topoint.(p, scale));
};
};
~topoint = { |c, scale| (c + [1, 1] * scale).asPoint };
)
// do the drawing
(
var b, w;
b = Rect(100, 100, 700, 700);
w = Window("so-a-mazing", b);
w.view.background_(Color.black);
w.drawFunc = {
var p = ~grid.shape.rand;
var scale = b.width / ~grid.size * 0.98;
Pen.moveTo(~topoint.(p, scale));
~walkN.(p, scale);
Pen.width = scale / 4;
Pen.color = Color.white;
Pen.stroke;
};
w.front.refresh;
)
|
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.
| #Ring | Ring |
See MD5("my string!") + nl
# output : a83a049fbe50cf7334caa86bf16a3520
|
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 .
| #Hare | Hare | use fmt;
use math;
type complex = struct {
re: f64,
im: f64
};
export fn main() void = {
for (let y = -1.2; y < 1.2; y += 0.05) {
for (let x = -2.05; x < 0.55; x += 0.03) {
let z = complex {re = 0.0, im = 0.0};
for (let m = 0z; m < 100; m += 1) {
let tz = z;
z.re = tz.re*tz.re - tz.im*tz.im;
z.im = tz.re*tz.im + tz.im*tz.re;
z.re += x;
z.im += y;
};
fmt::print(if (abs(z) < 2f64) '#' else '.')!;
};
fmt::println()!;
};
};
fn abs(z: complex) f64 = {
return math::sqrtf64(z.re*z.re + z.im*z.im);
}; |
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)
| #VTL-2 | VTL-2 | 10 N=1
20 ?="Magic square of order ";
30 ?=N
40 ?=" with constant ";
50 ?=N*N+1/2*N
60 ?=":"
70 Y=0
80 X=0
90 ?=Y*2+N-X/N*0+%*N+(Y*2+X+1/N*0+%+1
100 $=9
110 X=X+1
120 #=X<N*90
130 ?=""
140 Y=Y+1
150 #=Y<N*80
160 ?=""
170 N=N+2
180 #=7>N*20 |
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)
| #Wren | Wren | import "/fmt" for Fmt
var ms = Fn.new { |n|
var M = Fn.new { |x| (x + n - 1) % n }
if (n <= 0 || n&1 == 0) {
n = 5
System.print("forcing size %(n)")
}
var m = List.filled(n * n, 0)
var i = 0
var j = (n/2).floor
for (k in 1..n*n) {
m[i*n + j] = k
if (m[M.call(i)*n + M.call(j)] != 0) {
i = (i + 1) % n
} else {
i = M.call(i)
j = M.call(j)
}
}
return [n, m]
}
var res = ms.call(5)
var n = res[0]
var m = res[1]
for (i in 0...n) {
for (j in 0...n) System.write(Fmt.d(4, m[i*n+j]))
System.print()
}
System.print("\nMagic number : %(((n*n + 1)/2).floor * 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.
| #Lambdatalk | Lambdatalk |
{require lib_matrix}
1) applying a matrix to a vector
{def M
{M.new [[1,2,3],
[4,5,6],
[7,8,-9]]}}
-> M
{def V {M.new [1,2,3]} }
-> V
{M.multiply {M} {V}}
-> [14,32,-4]
2) matrix multiplication
{M.multiply {M} {M}}
-> [[ 30, 36,-12],
[ 66, 81,-12],
[-24,-18,150]]
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Klong | Klong | [5 5]:^!25
[[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]]
+[5 5]:^!25
[[0 5 10 15 20]
[1 6 11 16 21]
[2 7 12 17 22]
[3 8 13 18 23]
[4 9 14 19 24]] |
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.
| #Swift | Swift | import Foundation
extension Array {
mutating func shuffle() {
guard count > 1 else { return }
for i in 0..<self.count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
enum Direction:Int {
case north = 1
case south = 2
case east = 4
case west = 8
static var allDirections:[Direction] {
return [Direction.north, Direction.south, Direction.east, Direction.west]
}
var opposite:Direction {
switch self {
case .north:
return .south
case .south:
return .north
case .east:
return .west
case .west:
return .east
}
}
var diff:(Int, Int) {
switch self {
case .north:
return (0, -1)
case .south:
return (0, 1)
case .east:
return (1, 0)
case .west:
return (-1, 0)
}
}
var char:String {
switch self {
case .north:
return "N"
case .south:
return "S"
case .east:
return "E"
case .west:
return "W"
}
}
}
class MazeGenerator {
let x:Int
let y:Int
var maze:[[Int]]
init(_ x:Int, _ y:Int) {
self.x = x
self.y = y
let column = [Int](repeating: 0, count: y)
self.maze = [[Int]](repeating: column, count: x)
generateMaze(0, 0)
}
private func generateMaze(_ cx:Int, _ cy:Int) {
var directions = Direction.allDirections
directions.shuffle()
for direction in directions {
let (dx, dy) = direction.diff
let nx = cx + dx
let ny = cy + dy
if inBounds(nx, ny) && maze[nx][ny] == 0 {
maze[cx][cy] |= direction.rawValue
maze[nx][ny] |= direction.opposite.rawValue
generateMaze(nx, ny)
}
}
}
private func inBounds(_ testX:Int, _ testY:Int) -> Bool {
return inBounds(value:testX, upper:self.x) && inBounds(value:testY, upper:self.y)
}
private func inBounds(value:Int, upper:Int) -> Bool {
return (value >= 0) && (value < upper)
}
func display() {
let cellWidth = 3
for j in 0..<y {
// Draw top edge
var topEdge = ""
for i in 0..<x {
topEdge += "+"
topEdge += String(repeating: (maze[i][j] & Direction.north.rawValue) == 0 ? "-" : " ", count: cellWidth)
}
topEdge += "+"
print(topEdge)
// Draw left edge
var leftEdge = ""
for i in 0..<x {
leftEdge += (maze[i][j] & Direction.west.rawValue) == 0 ? "|" : " "
leftEdge += String(repeating: " ", count: cellWidth)
}
leftEdge += "|"
print(leftEdge)
}
// Draw bottom edge
var bottomEdge = ""
for _ in 0..<x {
bottomEdge += "+"
bottomEdge += String(repeating: "-", count: cellWidth)
}
bottomEdge += "+"
print(bottomEdge)
}
func displayInts() {
for j in 0..<y {
var line = ""
for i in 0..<x {
line += String(maze[i][j]) + "\t"
}
print(line)
}
}
func displayDirections() {
for j in 0..<y {
var line = ""
for i in 0..<x {
line += getDirectionsAsString(maze[i][j]) + "\t"
}
print(line)
}
}
private func getDirectionsAsString(_ value:Int) -> String {
var line = ""
for direction in Direction.allDirections {
if (value & direction.rawValue) != 0 {
line += direction.char
}
}
return line
}
}
let x = 20
let y = 10
let maze = MazeGenerator(x, y)
maze.display() |
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.
| #RLaB | RLaB | >> x = "The quick brown fox jumped over the lazy dog's back"
The quick brown fox jumped over the lazy dog's back
>> hash("md5", x)
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 .
| #Haskell | Haskell | import Data.Bool
import Data.Complex (Complex((:+)), magnitude)
mandelbrot
:: RealFloat a
=> Complex a -> Complex a
mandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50
main :: IO ()
main =
mapM_
putStrLn
[ [ bool ' ' '*' (2 > magnitude (mandelbrot (x :+ y)))
| x <- [-2,-1.9685 .. 0.5] ]
| y <- [1,0.95 .. -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)
| #zkl | zkl | fcn rmod(n,m){ n=n%m; if (n<0) n+=m; n } // Ruby: -5%3-->1
fcn odd_magic_square(n){ //-->list of n*n numbers, row order
if (n.isEven or n <= 0) throw(Exception.ValueError("Need odd positive number"));
[[(i,j); n; n; '{ n*((i+j+1+n/2):rmod(_,n)) + ((i+2*j-5):rmod(_,n)) + 1 }]]
}
T(3, 5, 9).pump(Void,fcn(n){
"\nSize %d, magic sum %d".fmt(n,(n*n+1)/2*n).println();
fmt := "%%%dd".fmt((n*n).toString().len() + 1) * n;
odd_magic_square(n).pump(Console.println,T(Void.Read,n-1),fmt.fmt);
}); |
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.
| #Lang5 | Lang5 | [[1 2 3] [4 5 6]] 'm dress
[[1 2] [3 4] [5 6]] 'm dress * . |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Kotlin | Kotlin | // version 1.1.3
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
fun Matrix.transpose(): Matrix {
val rows = this.size
val cols = this[0].size
val trans = Matrix(cols) { Vector(rows) }
for (i in 0 until cols) {
for (j in 0 until rows) trans[i][j] = this[j][i]
}
return trans
}
// Alternate version
typealias Matrix<T> = List<List<T>>
fun <T> Matrix<T>.transpose(): Matrix<T> {
return (0 until this[0].size).map { x ->
(this.indices).map { y ->
this[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.
| #Tcl | Tcl | package require TclOO; # Or Tcl 8.6
# Helper to pick a random number
proc rand n {expr {int(rand() * $n)}}
# Helper to pick a random element of a list
proc pick list {lindex $list [rand [llength $list]]}
# Helper _function_ to index into a list of lists
proc tcl::mathfunc::idx {v x y} {lindex $v $x $y}
oo::class create maze {
variable x y horiz verti content
constructor {width height} {
set y $width
set x $height
set n [expr {$x * $y - 1}]
if {$n < 0} {error "illegal maze dimensions"}
set horiz [set verti [lrepeat $x [lrepeat $y 0]]]
# This matrix holds the output for the Maze Solving task; not used for generation
set content [lrepeat $x [lrepeat $y " "]]
set unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]]
# Helper to write into a list of lists (with offsets)
proc unvisited= {x y value} {
upvar 1 unvisited u
lset u [expr {$x+1}] [expr {$y+1}] $value
}
lappend stack [set here [list [rand $x] [rand $y]]]
for {set j 0} {$j < $x} {incr j} {
for {set k 0} {$k < $y} {incr k} {
unvisited= $j $k [expr {$here ne [list $j $k]}]
}
}
while {0 < $n} {
lassign $here hx hy
set neighbours {}
foreach {dx dy} {1 0 0 1 -1 0 0 -1} {
if {idx($unvisited, $hx+$dx+1, $hy+$dy+1)} {
lappend neighbours [list [expr {$hx+$dx}] [expr {$hy+$dy}]]
}
}
if {[llength $neighbours]} {
lassign [set here [pick $neighbours]] nx ny
unvisited= $nx $ny 0
if {$nx == $hx} {
lset horiz $nx [expr {min($ny, $hy)}] 1
} else {
lset verti [expr {min($nx, $hx)}] $ny 1
}
lappend stack $here
incr n -1
} else {
set here [lindex $stack end]
set stack [lrange $stack 0 end-1]
}
}
rename unvisited= {}
}
# Maze displayer; takes a maze dictionary, returns a string
method view {} {
set text {}
for {set j 0} {$j < $x*2+1} {incr j} {
set line {}
for {set k 0} {$k < $y*4+1} {incr k} {
if {$j%2 && $k%4==2} {
# At the centre of the cell, put the "content" of the cell
append line [expr {idx($content, $j/2, $k/4)}]
} elseif {$j%2 && ($k%4 || $k && idx($horiz, $j/2, $k/4-1))} {
append line " "
} elseif {$j%2} {
append line "|"
} elseif {0 == $k%4} {
append line "+"
} elseif {$j && idx($verti, $j/2-1, $k/4)} {
append line " "
} else {
append line "-"
}
}
if {!$j} {
lappend text [string replace $line 1 3 " "]
} elseif {$x*2-1 == $j} {
lappend text [string replace $line end end " "]
} else {
lappend text $line
}
}
return [join $text \n]
}
}
# Demonstration
maze create m 11 8
puts [m view] |
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.
| #RPG | RPG | **FREE
Ctl-opt MAIN(Main);
Ctl-opt DFTACTGRP(*NO) ACTGRP(*NEW);
dcl-pr QDCXLATE EXTPGM('QDCXLATE');
dataLen packed(5 : 0) CONST;
data char(32767) options(*VARSIZE);
conversionTable char(10) CONST;
end-pr;
dcl-pr Qc3CalculateHash EXTPROC('Qc3CalculateHash');
inputData pointer value;
inputDataLen int(10) const;
inputDataFormat char(8) const;
algorithmDscr char(16) const;
algorithmFormat char(8) const;
cryptoServiceProvider char(1) const;
cryptoDeviceName char(1) const options(*OMIT);
hash char(64) options(*VARSIZE : *OMIT);
errorCode char(32767) options(*VARSIZE);
end-pr;
dcl-c HEX_CHARS CONST('0123456789ABCDEF');
dcl-proc Main;
dcl-s inputData char(45);
dcl-s inputDataLen int(10) INZ(0);
dcl-s outputHash char(16);
dcl-s outputHashHex char(32);
dcl-ds algorithmDscr QUALIFIED;
hashAlgorithm int(10) INZ(0);
end-ds;
dcl-ds ERRC0100_NULL QUALIFIED;
bytesProvided int(10) INZ(0); // Leave at zero
bytesAvailable int(10);
end-ds;
dow inputDataLen = 0;
DSPLY 'Input: ' '' inputData;
inputData = %trim(inputData);
inputDataLen = %len(%trim(inputData));
DSPLY ('Input=' + inputData);
DSPLY ('InputLen=' + %char(inputDataLen));
if inputDataLen = 0;
DSPLY 'Input must not be blank';
endif;
enddo;
// Convert from EBCDIC to ASCII
QDCXLATE(inputDataLen : inputData : 'QTCPASC');
algorithmDscr.hashAlgorithm = 1; // MD5
// Calculate hash
Qc3CalculateHash(%addr(inputData) : inputDataLen : 'DATA0100' : algorithmDscr
: 'ALGD0500' : '0' : *OMIT : outputHash : ERRC0100_NULL);
// Convert to hex
CVTHC(outputHashHex : outputHash : 32);
DSPLY ('MD5: ' + outputHashHex);
return;
end-proc;
// This procedure is actually a MI, but I couldn't get it to bind so I wrote my own version
dcl-proc CVTHC;
dcl-pi *N;
target char(65534) options(*VARSIZE);
srcBits char(32767) options(*VARSIZE) CONST;
targetLen int(10) value;
end-pi;
dcl-s i int(10);
dcl-s lowNibble ind INZ(*OFF);
dcl-s inputOffset int(10) INZ(1);
dcl-ds dataStruct QUALIFIED;
numField int(5) INZ(0);
// IBM i is big-endian
charField char(1) OVERLAY(numField : 2);
end-ds;
for i = 1 to targetLen;
if lowNibble;
dataStruct.charField = %BitAnd(%subst(srcBits : inputOffset : 1) : X'0F');
inputOffset += 1;
else;
dataStruct.charField = %BitAnd(%subst(srcBits : inputOffset : 1) : X'F0');
dataStruct.numField /= 16;
endif;
%subst(target : i : 1) = %subst(HEX_CHARS : dataStruct.numField + 1 : 1);
lowNibble = NOT lowNibble;
endfor;
return;
end-proc; |
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 .
| #Haxe | Haxe | haxe -swf mandelbrot.swf -main Mandelbrot |
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.
| #LFE | LFE |
(defun matrix* (matrix-1 matrix-2)
(list-comp
((<- a matrix-1))
(list-comp
((<- b (transpose matrix-2)))
(lists:foldl #'+/2 0
(lists:zipwith #'*/2 a b)))))
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Lang5 | Lang5 | 12 iota [3 4] reshape 1 + dup .
1 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.
| #TXR | TXR | @(bind (width height) (15 15))
@(do
(defvar *r* (make-random-state nil))
(defvar vi)
(defvar pa)
(defun neigh (loc)
(let ((x (from loc))
(y (to loc)))
(list (- x 1)..y (+ x 1)..y
x..(- y 1) x..(+ y 1))))
(defun make-maze-rec (cu)
(set [vi cu] t)
(each ((ne (shuffle (neigh cu))))
(cond ((not [vi ne])
(push ne [pa cu])
(push cu [pa ne])
(make-maze-rec ne)))))
(defun make-maze (w h)
(let ((vi (hash :equal-based))
(pa (hash :equal-based)))
(each ((x (range -1 w)))
(set [vi x..-1] t)
(set [vi x..h] t))
(each ((y (range* 0 h)))
(set [vi -1..y] t)
(set [vi w..y] t))
(make-maze-rec 0..0)
pa))
(defun print-tops (pa w j)
(each ((i (range* 0 w)))
(if (memqual i..(- j 1) [pa i..j])
(put-string "+ ")
(put-string "+----")))
(put-line "+"))
(defun print-sides (pa w j)
(let ((str ""))
(each ((i (range* 0 w)))
(if (memqual (- i 1)..j [pa i..j])
(set str `@str `)
(set str `@str| `)))
(put-line `@str|\n@str|`)))
(defun print-maze (pa w h)
(each ((j (range* 0 h)))
(print-tops pa w j)
(print-sides pa w j))
(print-tops pa w h)))
@;;
@(bind m @(make-maze width height))
@(do (print-maze m width height)) |
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.
| #Ruby | Ruby | require 'digest'
Digest::MD5.hexdigest("The quick brown fox jumped over the lazy dog's back")
# => "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 .
| #Huginn | Huginn | #! /bin/sh
exec huginn -E "${0}" "${@}"
#! huginn
import Algorithms as algo;
import Mathematics as math;
import Terminal as term;
mandelbrot( x, y ) {
c = math.Complex( x, y );
z = math.Complex( 0., 0. );
s = -1;
for ( i : algo.range( 50 ) ) {
z = z * z + c;
if ( | z | > 2. ) {
s = i;
break;
}
}
return ( s );
}
main( argv_ ) {
imgSize = term_size( argv_ );
yRad = 1.2;
yScale = 2. * yRad / real( imgSize[0] );
xScale = 3.3 / real( imgSize[1] );
glyphTab = [ ".", ":", "-", "+", "+" ].resize( 12, "*" ).resize( 26, "%" ).resize( 50, "@" ).push( " " );
for ( y : algo.range( imgSize[0] ) ) {
line = "";
for ( x : algo.range( imgSize[1] ) ) {
line += glyphTab[ mandelbrot( xScale * real( x ) - 2.3, yScale * real( y ) - yRad ) ];
}
print( line + "\n" );
}
return ( 0 );
}
term_size( argv_ ) {
lines = 25;
columns = 80;
if ( size( argv_ ) == 3 ) {
lines = integer( argv_[1] );
columns = integer( argv_[2] );
} else {
lines = term.lines();
columns = term.columns();
if ( ( lines % 2 ) == 0 ) {
lines -= 1;
}
}
lines -= 1;
columns -= 1;
return ( ( lines, columns ) );
} |
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.
| #Liberty_BASIC | Liberty BASIC |
MatrixA$ ="4, 4, 1, 1, 1, 1, 2, 4, 8, 16, 3, 9, 27, 81, 4, 16, 64, 256"
MatrixB$ ="4, 4, 4, -3, 4/3, -1/4 , -13/3, 19/4, -7/3, 11/24, 3/2, -2, 7/6, -1/4, -1/6, 1/4, -1/6, 1/24"
print "Product of two matrices"
call DisplayMatrix MatrixA$
print " *"
call DisplayMatrix MatrixB$
print " ="
MatrixP$ =MatrixMultiply$( MatrixA$, MatrixB$)
call DisplayMatrix MatrixP$
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #LFE | LFE |
(defun transpose (matrix)
(transpose matrix '()))
(defun transpose (matrix acc)
(cond
((lists:any
(lambda (x) (== x '()))
matrix)
acc)
('true
(let ((heads (lists:map #'car/1 matrix))
(tails (lists:map #'cdr/1 matrix)))
(transpose tails (++ acc `(,heads)))))))
|
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.
| #XPL0 | XPL0 | code Ran=1, CrLf=9, Text=12; \intrinsic routines
def Cols=20, Rows=6; \dimensions of maze (cells)
int Cell(Cols+1, Rows+1, 3); \cells (plus right and bottom borders)
def LeftWall, Ceiling, Connected; \attributes of each cell (= 0, 1 and 2)
proc ConnectFrom(X, Y); \Connect cells starting from cell X,Y
int X, Y;
int Dir, Dir0;
[Cell(X, Y, Connected):= true; \mark current cell as connected
Dir:= Ran(4); \randomly choose a direction
Dir0:= Dir; \save this initial direction
repeat case Dir of \try to connect to cell at Dir
0: if X+1<Cols & not Cell(X+1, Y, Connected) then \go right
[Cell(X+1, Y, LeftWall):= false; ConnectFrom(X+1, Y)];
1: if Y+1<Rows & not Cell(X, Y+1, Connected) then \go down
[Cell(X, Y+1, Ceiling):= false; ConnectFrom(X, Y+1)];
2: if X-1>=0 & not Cell(X-1, Y, Connected) then \go left
[Cell(X, Y, LeftWall):= false; ConnectFrom(X-1, Y)];
3: if Y-1>=0 & not Cell(X, Y-1, Connected) then \go up
[Cell(X, Y, Ceiling):= false; ConnectFrom(X, Y-1)]
other []; \(never occurs)
Dir:= Dir+1 & $03; \next direction
until Dir = Dir0;
];
int X, Y;
[for Y:= 0 to Rows do
for X:= 0 to Cols do
[Cell(X, Y, LeftWall):= true; \start with all walls and
Cell(X, Y, Ceiling):= true; \ ceilings in place
Cell(X, Y, Connected):= false; \ and all cells disconnected
];
Cell(0, 0, LeftWall):= false; \make left and right doorways
Cell(Cols, Rows-1, LeftWall):= false;
ConnectFrom(Ran(Cols), Ran(Rows)); \randomly pick a starting cell
for Y:= 0 to Rows do \display the maze
[CrLf(0);
for X:= 0 to Cols do
Text(0, if X#Cols & Cell(X, Y, Ceiling) then "+--" else "+ ");
CrLf(0);
for X:= 0 to Cols do
Text(0, if Y#Rows & Cell(X, Y, LeftWall) then "| " else " ");
];
] |
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.
| #Rust | Rust |
[dependencies]
rust-crypto = "0.2"
|
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 .
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main()
width := 750
height := 600
limit := 100
WOpen("size="||width||","||height)
every x:=1 to width & y:=1 to height do
{
z:=complex(0,0)
c:=complex(2.5*x/width-2.0,(2.0*y/height-1.0))
j:=0
while j<limit & cAbs(z)<2.0 do
{
z := cAdd(cMul(z,z),c)
j+:= 1
}
Fg(mColor(j,limit))
DrawPoint(x,y)
}
WriteImage("./mandelbrot.gif")
WDone()
end
procedure mColor(x,limit)
max_color := 2^16-1
color := integer(max_color*(real(x)/limit))
return(if x=limit
then "black"
else color||","||color||",0")
end
record complex(r,i)
procedure cAdd(x,y)
return complex(x.r+y.r,x.i+y.i)
end
procedure cMul(x,y)
return complex(x.r*y.r-x.i*y.i,x.r*y.i+x.i*y.r)
end
procedure cAbs(x)
return sqrt(x.r*x.r+x.i*x.i)
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.
| #Logo | Logo | TO LISTVMD :A :F :C :NV
;PROCEDURE LISTVMD
;A = LIST
;F = ROWS
;C = COLS
;NV = NAME OF MATRIX / VECTOR NEW
;this procedure transform a list in matrix / vector square or rect
(LOCAL "CF "CC "NV "T "W)
MAKE "CF 1
MAKE "CC 1
MAKE "NV (MDARRAY (LIST :F :C) 1)
MAKE "T :F * :C
FOR [Z 1 :T][MAKE "W ITEM :Z :A
MDSETITEM (LIST :CF :CC) :NV :W
MAKE "CC :CC + 1
IF :CC = :C + 1 [MAKE "CF :CF + 1 MAKE "CC 1]]
OUTPUT :NV
END
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
TO XX
; MAIN PROGRAM
;LRCVS 10.04.12
; THIS PROGRAM multiplies two "square" matrices / vector ONLY!!!
; THE RECTANGULAR NOT WORK!!!
CT CS HT
; FIRST DATA MATRIX / VECTOR
MAKE "A [1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49]
MAKE "FA 5 ;"ROWS
MAKE "CA 5 ;"COLS
; SECOND DATA MATRIX / VECTOR
MAKE "B [2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50]
MAKE "FB 5 ;"ROWS
MAKE "CB 5 ;"COLS
IF (OR :FA <> :CA :FB <>:CB) [PRINT "Las_matrices/vector_no_son_cuadradas THROW
"TOPLEVEL ]
IFELSE (OR :CA <> :FB :FA <> :CB) [PRINT
"Las_matrices/vector_no_son_compatibles THROW "TOPLEVEL ][MAKE "MA LISTVMD :A
:FA :CA "MA MAKE "MB LISTVMD :B :FB :CB "MB] ;APPLICATION <<< "LISTVMD"
PRINT (LIST "THIS_IS: "ROWS "X "COLS)
PRINT []
PRINT (LIST :MA "=_M1 :FA "ROWS "X :CA "COLS)
PRINT []
PRINT (LIST :MB "=_M2 :FA "ROWS "X :CA "COLS)
PRINT []
MAKE "T :FA * :CB
MAKE "RE (ARRAY :T 1)
MAKE "CO 0
FOR [AF 1 :CA][
FOR [AC 1 :CA][
MAKE "TEMP 0
FOR [I 1 :CA ][
MAKE "TEMP :TEMP + (MDITEM (LIST :I :AF) :MA) * (MDITEM (LIST :AC :I) :MB)]
MAKE "CO :CO + 1
SETITEM :CO :RE :TEMP]]
PRINT []
PRINT (LIST "THIS_IS: :FA "ROWS "X :CB "COLS)
SHOW LISTVMD :RE :FA :CB "TO ;APPLICATION <<< "LISTVMD"
END
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\
M1 * M2 RESULT / SOLUTION
1 3 5 7 9 2 4 6 8 10 830 1880 2930 3980 5030
11 13 15 17 19 12 14 16 18 20 890 2040 3190 4340 5490
21 23 25 27 29 X 22 24 26 28 30 = 950 2200 3450 4700 5950
31 33 35 37 39 32 34 36 38 40 1010 2360 3710 5060 6410
41 43 45 47 49 42 44 46 48 50 1070 2520 3970 5420 6870
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\
NOW IN LOGO!!!!
THIS_IS: ROWS X COLS
{{1 3 5 7 9} {11 13 15 17 19} {21 23 25 27 29} {31 33 35 37 39} {41 43 45 47
49}} =_M1 5 ROWS X 5 COLS
{{2 4 6 8 10} {12 14 16 18 20} {22 24 26 28 30} {32 34 36 38 40} {42 44 46 48
50}} =_M2 5 ROWS X 5 COLS
THIS_IS: 5 ROWS X 5 COLS
{{830 1880 2930 3980 5030} {890 2040 3190 4340 5490} {950 2200 3450 4700 5950}
{1010 2360 3710 5060 6410} {1070 2520 3970 5420 6870}} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Liberty_BASIC | Liberty BASIC | MatrixC$ ="4, 3, 0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10"
print "Transpose of matrix"
call DisplayMatrix MatrixC$
print " ="
MatrixT$ =MatrixTranspose$( MatrixC$)
call DisplayMatrix MatrixT$ |
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.