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-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Class cArray {
a=(,)
Function Power(n as integer){
cArr=This ' create a copy
dim new()
new()=cArr.a ' get a pointer from a to new()
Let cArr.a=new() ' now new() return a copy
cArr.a*=0 ' make zero all elements
link cArr.a to v()
for i=dimension(cArr.a,1,0) to dimension(cArr.a, 1,1) : v(i,i)=1: next i
while n>0
let cArr=cArr*this ' * is the operator "*"
n--
end while
=cArr
}
Operator "*"{
Read cArr
b=cArr.a
if dimension(.a)<>2 or dimension(b)<>2 then Error "Need two 2D arrays "
let a2=dimension(.a,2), b1=dimension(b,1)
if a2<>b1 then Error "Need columns of first array equal to rows of second array"
let a1=dimension(.a,1), b2=dimension(b,2)
let aBase=dimension(.a,1,0)-1, bBase=dimension(b,1,0)-1
let aBase1=dimension(.a,2,0)-1, bBase1=dimension(b,2,0)-1
link .a,b to a(), b() ' change interface for arrays
dim base 1, c(a1, b2)
for i=1 to a1 : let ia=i+abase : for j=1 to b2 : let jb=j+bBase1 : for k=1 to a2
c(i,j)+=a(ia,k+aBase1)*b(k+bBase,jb)
next k : next j : next i
\\ redim to base 0
dim base 0, c(a1, b2)
.a<=c()
}
Module Print {
link .a to v()
for i=dimension(.a,1,0) to dimension(.a, 1,1)
for j=dimension(.a,2,0) to dimension(.a, 2,1)
print v(i,j),: next j: print : next i
}
Class:
\\ this module used as constructor, and not returned to final group (user object in M2000)
Module cArray (r) {
c=r
Dim a(r,c)
For i=0 to r-1 : For j=0 to c-1: Read a(i,j): Next j : Next i
.a<=a()
}
}
Print "matrix():"
P=cArray(2,3,2,2,1)
P.Print
For i=0 to 9
Print "matrix()^"+str$(i,0)+"="
K=P.Power(i)
K.Print
next i
}
Checkit
|
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Maple | Maple | > M := <<1,2>|<3,4>>;
> M ^ 2; |
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.
| #Delphi | Delphi |
(lib 'plot) ;; interpolation functions
(lib 'compile)
;; rational version
(define (q-map-range x xmin xmax ymin ymax) (+ ymin (/ ( * (- x xmin) (- ymax ymin)) (- xmax xmin))))
;; float version
(define (map-range x xmin xmax ymin ymax) (+ ymin (// ( * (- x xmin) (- ymax ymin)) (- xmax xmin))))
; accelerate it
(compile 'map-range "-vf")
(q-map-range 4 0 10 -1 0)
→ -3/5
(map-range 4 0 10 -1 0)
→ -0.6
(linear 4 0 10 -1 0) ;; native
→ -0.6
(for [(x (in-range 0 10))] (writeln x (q-map-range x 0 10 -1 0) (map-range x 0 10 -1 0)))
0 -1 -1
1 -9/10 -0.9
2 -4/5 -0.8
3 -7/10 -0.7
4 -3/5 -0.6
5 -1/2 -0.5
6 -2/5 -0.4
7 -3/10 -0.3
8 -1/5 -0.2
9 -1/10 -0.1
|
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #Yabasic | Yabasic | open window 640,512,"swiss12"
backcolor 0,0,0
clear window
mx=50
my=42
dim scr(mx,my)
for y=0 to my
for x=0 to mx
scr(x,y)=int(ran(96)+33)
next x
next y
ms=50
dim sx(ms)
dim sy(ms)
for a=1 to ms
sx(a)=int(ran(mx))
sy(a)=int(ran(my))
next a
do
for s=1 to ms
x=sx(s)
y=sy(s)
letter(0,255,0)
y=y-1
letter(0,200,0)
y=y-1
letter(0,150,0)
y=y-1
color 0,0,0
fill rect x*12.8-1,y*12.8+4 to x*12.8+12,y*12.8-10
letter(0,70,0)
y=y-24
color 0,0,0
fill rect x*12.8-1,y*12.8+4 to x*12.8+12,y*12.8-10
next s
for s=1 to ms
if int(ran(5)+1)=1 sy(s)=sy(s)+1
if sy(s)>my+25 then
sy(s)=0
sx(s)=int(ran(mx))
end if
next s
loop
sub letter(r,g,b)
if y<0 or y>my return
c=scr(x,y)
color r,g,b
text x*12.8,y*12.8,chr$(c)
end sub |
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #zkl | zkl | var [const] codes=Walker.chain( // a bunch of UTF non ascii chars
[0x0391..0x03a0], [0x03a3..0x0475], [0x0400..0x0475],
[0x048a..0x052f], [0x03e2..0x03ef], [0x2c80..0x2ce9],
[0x2200..0x2217], [0x2100..0x213a], [0x2a00..0x2aff])
.apply(fcn(utf){ utf.toString(-8) }), // jeez this is lame
codeSz=codes.len(), // 970
c=L("\e[38;2;255;255;255m",[255..30,-15].apply("\e[38;2;0;%d;0m".fmt),
(250).pump(List,T(Void,"\e[38;2;0;25;0m"))).flatten(),
csz=c.len(); // 267, c is ANSI escape code fg colors: 38;2;<r;g;b>m
// query the ANSI terminal
rows,cols := System.popen("stty size","r").readln().split().apply("toInt");
o,s,fg := buildScreen(rows,cols);
ssz:=s.len();
print("\e[?25l\e[48;5;232m"); // hide the cursor, set background color to dark
while(1){ // ignore screen resizes
print("\e[1;1H"); // move cursor to 1,1
foreach n in (ssz){ // print a screen full
print( c[fg[n]], s[n] ); // forground color, character
fg[n]=(fg[n] + 1)%csz; // fade to black
}
do(100){ s[(0).random(ssz)]=codes[(0).random(codeSz)] } // some new chars
Atomic.sleep(0.1); // frame rate for my system, up to 200x41 terminal
}
fcn buildScreen(rows,cols){ // build a row major array as list
// s --> screen full of characters
s:=(rows*cols).pump(List(), fcn{ codes[(0).random(codeSz)]});
// array fb-->( fg color, fg ..) where fg is an ANSI term 48;5;<n>m color
fg:=List.createLong(s.len(),0);
o:=csz.pump(List()).shuffle()[0,cols]; // cols random #s
foreach row in (rows){ // set fg indices
foreach col in (cols){ fg[row*cols + col] = o[col] }
o=o.apply(fcn(n){ n-=1; if(n<0) n=csz-1; n%csz }); // fade out
}
return(o,s,fg);
} |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (computer program) game should display all the player guesses and the results of that guess.
Display (just an idea):
Feature
Graphic Version
Text Version
Player guess
Colored circles
Alphabet letters
Correct color & position
Black circle
X
Correct color
White circle
O
None
Gray circle
-
A text version example: 1. ADEF - XXO-
Translates to:
the first guess;
the four colors (ADEF);
result:
two correct colors and spot,
one correct color/wrong spot, one color isn't in the code.
Happy coding!
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
| #SQL | SQL |
-- Create Table
-- Distinct combination
--- R :Red, B :Blue, G: Green, V: Violet, O: Orange, Y: Yellow
DROP TYPE IF EXISTS color cascade;CREATE TYPE color AS ENUM ('R', 'B', 'G', 'V', 'O', 'Y');
DROP TABLE IF EXISTS guesses cascade ; CREATE TABLE guesses (
FIRST color,
SECOND color,
third color ,
fourth color
);
CREATE TABLE mastermind () inherits (guesses);
INSERT INTO mastermind VALUES ('G', 'B', 'R', 'V');
INSERT INTO guesses VALUES ('Y', 'Y', 'B', 'B');
INSERT INTO guesses VALUES ('V', 'R', 'R', 'Y');
INSERT INTO guesses VALUES ('G', 'V', 'G', 'Y');
INSERT INTO guesses VALUES ('R', 'R', 'V', 'Y');
INSERT INTO guesses VALUES ('B', 'R', 'G', 'V');
INSERT INTO guesses VALUES ('G', 'B', 'R', 'V');
--- Matches Black
CREATE OR REPLACE FUNCTION check_black(guesses, mastermind) RETURNS INTEGER AS $$
SELECT (
($1.FIRST = $2.FIRST)::INT +
($1.SECOND = $2.SECOND)::INT +
($1.third = $2.third)::INT +
($1.fourth = $2.fourth)::INT
);
$$ LANGUAGE SQL;
--- Matches White
CREATE OR REPLACE FUNCTION check_white(guesses, mastermind) RETURNS INTEGER AS $$
SELECT (
CASE WHEN ($1.FIRST = $2.FIRST) THEN 0 ELSE 0 END +
CASE WHEN ($1.SECOND = $2.SECOND) THEN 0 ELSE 0 END +
CASE WHEN ($1.third = $2.third) THEN 0 ELSE 0 END +
CASE WHEN ($1.fourth = $2.fourth) THEN 0 ELSE 0 END +
CASE WHEN ($1.FIRST != $2.FIRST) THEN (
$1.FIRST = $2.SECOND OR
$1.FIRST = $2.third OR
$1.FIRST = $2.fourth
)::INT ELSE 0 END +
CASE WHEN ($1.SECOND != $2.SECOND) THEN (
$1.SECOND = $2.FIRST OR
$1.SECOND = $2.third OR
$1.SECOND = $2.fourth
)::INT ELSE 0 END +
CASE WHEN ($1.third != $2.third) THEN (
$1.third = $2.FIRST OR
$1.third = $2.SECOND OR
$1.third = $2.fourth
)::INT ELSE 0 END +
CASE WHEN ($1.fourth != $2.fourth) THEN (
$1.fourth = $2.FIRST OR
$1.fourth = $2.SECOND OR
$1.fourth = $2.third
)::INT ELSE 0 END
) FROM guesses
$$ LANGUAGE SQL;
SELECT guesses,
check_black(guesses.*, mastermind.*),
check_white(guesses.*, mastermind.*)
FROM guesses, mastermind
|
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #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]];
}
}
sub solve (@maze is copy, @from = [1, 1], @to = [@maze[0] - 2, @maze - 2]) {
my ($x, $y) = @from;
my ($xto, $yto) = @to;
my @stack;
sub drop-crumb($x,$y,$c) { @maze[$y][$x] = -$c }
drop-crumb($x,$y,N);
loop {
my $dir = pick_direction([$x,$y]);
if $dir {
($x, $y) = move($dir, [$x,$y]);
return @maze if $x == $xto and $y == $yto;
}
else {
@maze[$y][$x] = -TRIED;
($x,$y) = @stack.pop;
@maze[$y][$x] = -TRIED;
($x,$y) = @stack.pop;
}
}
sub pick_direction([$x,$y]) {
my @neighbors =
(Up unless @maze[$y - 1][$x]),
(Down unless @maze[$y + 1][$x]),
(Left unless @maze[$y][$x - 1]),
(Right unless @maze[$y][$x + 1]);
@neighbors.pick or DeadEnd;
}
sub move ($dir, @cur) {
my ($x,$y) = @cur;
given $dir {
when Up { for ^2 { push @stack, $[$x,$y--]; drop-crumb $x,$y,S; } }
when Down { for ^2 { push @stack, $[$x,$y++]; drop-crumb $x,$y,N; } }
when Left { for ^2 { push @stack, $[$x--,$y]; drop-crumb $x,$y,E; } }
when Right { for ^2 { push @stack, $[$x++,$y]; drop-crumb $x,$y,W; } }
}
$x,$y;
}
}
display solve gen_maze( 29, 19 ); |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #Pascal | Pascal | program TriSum;
{'triangle.txt'
* one element per line
55
94
48
95
30
96
...}
const
cMaxTriHeight = 18;
cMaxTriElemCnt = (cMaxTriHeight+1)*cMaxTriHeight DIV 2 +1;
type
tElem = longint;
tbaseRow = array[0..cMaxTriHeight] of tElem;
tmyTri = array[0..cMaxTriElemCnt] of tElem;
function ReadTri( fname:string;
out t:tmyTri):integer;
{read triangle values into t and returns height}
var
f : text;
s : string;
i : integer;
ValCode : word;
begin
i := 0;
fillchar(t,Sizeof(t),#0);
Assign(f,fname);
{$I-}
reset(f);
IF ioResult <> 0 then
begin
writeln('IO-Error ',ioResult);
close(f);
ReadTri := i;
EXIT;
end;
{$I+}
while NOT(EOF(f)) AND (i<cMaxTriElemCnt) do
begin
readln(f,s);
val(s,t[i],ValCode);
inc(i);
IF ValCode <> 0 then
begin
writeln(ValCode,' conversion error at line ',i);
fillchar(t,Sizeof(t),#0);
i := 0;
BREAK;
end;
end;
close(f);
ReadTri := round(sqrt(2*(i-1)));
end;
function TriMaxSum(var t: tmyTri;hei:integer):integer;
{sums up higher values bottom to top}
var
i,r,h,tmpMax : integer;
idxN : integer;
sumrow : tbaseRow;
begin
h := hei;
idxN := (h*(h+1)) div 2 -1;
{copy base row}
move(t[idxN-h+1],sumrow[0],SizeOf(tElem)*h);
dec(h);
{ for r := 0 to h do write(sumrow[r]:4);writeln;}
idxN := idxN-h;
while idxN >0 do
begin
i := idxN-h;
r := 0;
while r < h do
begin
tmpMax:= sumrow[r];
IF tmpMax<sumrow[r+1] then
tmpMax:=sumrow[r+1];
sumrow[r]:= tmpMax+t[i];
inc(i);
inc(r);
end;
idxN := idxN-h;
dec(h);
{ for r := 0 to h do write(sumrow[r]:4);writeln;}
end;
TriMaxSum := sumrow[0];
end;
var
h : integer;
triangle : tmyTri;
Begin
{ writeln(TriMaxSum(triangle,ReadTri('triangle.txt',triangle))); -> 1320}
h := ReadTri('triangle.txt',triangle);
writeln('height sum');
while h > 0 do
begin
writeln(h:4,TriMaxSum(triangle,h):7);
dec(h);
end;
end. |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Haxe | Haxe | import haxe.crypto.Md5;
class Main {
static function main() {
var md5 = Md5.encode("The quick brown fox jumped over the lazy dog's back");
Sys.println(md5);
}
} |
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #J | J |
odd =: i:@<.@-: |."0 1&|:^:2 >:@i.@,~
t =: ((*: * i.@4:) +"0 2 odd)@-:
l =: (f=:$~ # , #)@((<. , >.)@%&4 # (1: , 0:))
sh =: <:@-: * (bn=:-: # 2:) #: (2: ^ <.@%&4)
lm =: sh |."0 1 l
rm =: f@bn #: <:@(2: ^ <:@<.@%&4)
a =: ((-.@lm * {.@t) + lm * {:@t)
b =: ((-.@rm * 1&{@t) + rm * 2&{@t)
c =: ((rm * 1&{@t) + -.@rm * 2&{@t)
d =: ((lm * {.@t) + -.@lm * {:@t)
m =: (a ,"1 c) , d ,"1 b
|
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Java | Java | public class MagicSquareSinglyEven {
public static void main(String[] args) {
int n = 6;
for (int[] row : magicSquareSinglyEven(n)) {
for (int x : row)
System.out.printf("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int n) {
if (n < 3 || n % 2 == 0)
throw new IllegalArgumentException("base must be odd and > 2");
int value = 0;
int gridSize = n * n;
int c = n / 2, r = 0;
int[][] result = new int[n][n];
while (++value <= gridSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
static int[][] magicSquareSinglyEven(final int n) {
if (n < 6 || (n - 2) % 4 != 0)
throw new IllegalArgumentException("base must be a positive "
+ "multiple of 4 plus 2");
int size = n * n;
int halfN = n / 2;
int subSquareSize = size / 4;
int[][] subSquare = magicSquareOdd(halfN);
int[] quadrantFactors = {0, 2, 3, 1};
int[][] result = new int[n][n];
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int quadrant = (r / halfN) * 2 + (c / halfN);
result[r][c] = subSquare[r % halfN][c % halfN];
result[r][c] += quadrantFactors[quadrant] * subSquareSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
} |
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 .
| #Amazing_Hopper | Amazing Hopper |
#!/usr/bin/hopper
#include <hopper.h>
main:
ancho=500
alto=500
min real=-2
minReal=minreal
min complex=-2
max real = 2
max complex = 2
mandel=0,{ancho,alto}nanarray(mandel)
i=1,a2=0,b2=0,a=0,b=0,t1=0,t2=0
{","}toksep
tic(t1)
for(i=1,{i} le than (ancho),++i)
for(j=1,{j} le than (alto),++j)
{minreal} PLUS ( {max real}, minus (minReal), MUL BY ({i}minus(1)), DIV BY ({ancho}minus(1))),mov(a)
{min complex} PLUS ( {maxcomplex}, minus (mincomplex), MULBY ({j} minus(1)),DIVBY ({alto} minus (1)) ),mov(b)
a2=a,b2=b,brillo=1
k=100
__iterador__:
sqrdiff(a,b), plus (a2)
{2} mulby (a), mulby (b), plus (b2)
mov(b),mov(a)
if( {a,b} sqr add, gthan (4))
brillo=0, jmp(__out__)
endif
k--,jnz(__iterador__)
__out__:
[j,i]{brillo}put(mandel)
next
next
toc(t1,t2)
{"TIME = ",t2,"\n"}print
{mandel,"mandel.dat"}save
{0}return
|
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)
| #Arturo | Arturo | oddMagicSquare: function [n][
ensure -> and? odd? n
n >= 0
map 1..n 'i [
map 1..n 'j [
(n * ((i + (j - 1) + n / 2) % n)) +
(((i - 2) + 2 * j) % n) + 1
]
]
]
loop [3 5 7] 'n [
print ["Size:" n ", Magic sum:" n*(1+n*n)/2 "\n"]
loop oddMagicSquare n 'row [
loop row 'item [
prints pad to :string item 3
]
print ""
]
print ""
] |
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.
| #Burlesque | Burlesque |
blsq ) {{1 2}{3 4}{5 6}{7 8}}{{1 2 3}{4 5 6}}mmsp
9 12 15
19 26 33
29 40 51
39 54 69
|
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Rust | Rust | use std::fs;
fn main() {
fs::create_dir_all("./path/to/dir").expect("An Error Occured!")
} |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Scala | Scala | new java.io.File("/path/to/dir").mkdirs |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "cli_cmds.s7i";
const proc: main is func
begin
doMkdirCmd(argv(PROGRAM), TRUE);
end func; |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Sidef | Sidef | Dir.new(Dir.cwd, "path", "to", "dir").make_path; # works cross-platform |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Tcl | Tcl | file mkdir ./path/to/dir |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #UNIX_Shell | UNIX Shell | function mkdirp() { mkdir -p "$1"; } |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #C.2B.2B | C++ | #include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
class magicSqr
{
public:
magicSqr( int d ) {
while( d % 4 > 0 ) { d++; }
sz = d;
sqr = new int[sz * sz];
fillSqr();
}
~magicSqr() { delete [] sqr; }
void display() const {
cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr; cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ ) {
int yy = y * sz;
for( int x = 0; x < sz; x++ ) {
cout << setw( l + 2 ) << sqr[yy + x];
}
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr() {
static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };
int i = 0;
for( int curRow = 0; curRow < sz; curRow++ ) {
for( int curCol = 0; curCol < sz; curCol++ ) {
sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;
i++;
}
}
}
int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }
int* sqr;
int sz;
};
int main( int argc, char* argv[] ) {
magicSqr s( 8 );
s.display();
return 0;
} |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Delphi | Delphi | type
TFunc<T> = reference to function: T;
function C(x: Integer): TFunc<Integer>;
begin
Result := function: Integer
begin
Result := x;
end;
end;
function A(k: Integer; x1, x2, x3, x4, x5: TFunc<Integer>): Integer;
var
b: TFunc<Integer>;
begin
b := function: Integer
begin
Dec(k);
Result := A(k, b, x1, x2, x3, x4);
end;
if k <= 0 then
Result := x4 + x5
else
Result := b;
end;
begin
Writeln(A(10, C(1), C(-1), C(-1), C(1), C(0))); // -67 output
end. |
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #Racket | Racket |
#lang racket
(define k8 (bytes 14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7))
(define k7 (bytes 15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10))
(define k6 (bytes 10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8))
(define k5 (bytes 7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15))
(define k4 (bytes 2 12 4 1 7 10 11 6 8 5 3 15 13 0 14 9))
(define k3 (bytes 12 1 10 15 9 2 6 8 0 13 3 4 14 7 5 11))
(define k2 (bytes 4 11 2 14 15 0 8 13 3 12 9 7 5 10 6 1))
(define k1 (bytes 13 2 8 4 6 15 11 1 10 9 3 14 5 0 12 7))
(define (mk-k k2 k1)
(list->bytes (for*/list ([i 16] [j 16]) (+ (* (bytes-ref k2 i) 16) (bytes-ref k1 j)))))
(define k87 (mk-k k8 k7))
(define k65 (mk-k k6 k5))
(define k43 (mk-k k4 k3))
(define k21 (mk-k k2 k1))
(define (f x)
(define bs (integer->integer-bytes x 4 #f #f))
(define x*
(bitwise-and #xFFFFFFFF
(integer-bytes->integer
(bytes (bytes-ref k21 (bytes-ref bs 0))
(bytes-ref k43 (bytes-ref bs 1))
(bytes-ref k65 (bytes-ref bs 2))
(bytes-ref k87 (bytes-ref bs 3)))
#f #f)))
(bitwise-ior (bitwise-and #xFFFFFFFF (arithmetic-shift x* 11))
(arithmetic-shift x* (- 11 32))))
|
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #Raku | Raku | # sboxes from http://en.wikipedia.org/wiki/GOST_(block_cipher)
constant sbox =
[4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
[6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
[4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
[13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
[1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12];
sub infix:<rol³²>(\y, \n) { (y +< n) % 2**32 +| (y +> (32 - n)) }
sub ГОСТ-round(\R, \K) {
my \a = (R + K) % 2**32;
my \b = :16[ sbox[$_][(a +> (4 * $_)) % 16] for 7...0 ];
b rol³² 11;
}
sub feistel-step(&F, \L, \R, \K) { R, L +^ F(R, K) }
my @input = 0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04;
my @key = 0xF9, 0x04, 0xC1, 0xE2;
my ($L,$R) = @input.reverse.map: { :256[$^a,$^b,$^c,$^d] }
my ($K ) = @key .reverse.map: { :256[$^a,$^b,$^c,$^d] }
($L,$R) = feistel-step(&ГОСТ-round, $L, $R, $K);
say [ ($L +< 32 + $R X+> (0, 8 ... 56)) X% 256 ].fmt('%02X'); |
http://rosettacode.org/wiki/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.
Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).
There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.
Task
Write a routine (procedure, function, whatever) to find magnanimous numbers.
Use that function to find and display, here on this page the first 45 magnanimous numbers.
Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers
See also
OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory 'is_prime';
sub magnanimous {
my($n) = @_;
my $last;
for my $c (1 .. length($n) - 1) {
++$last and last unless is_prime substr($n,0,$c) + substr($n,$c)
}
not $last;
}
my @M;
for ( my $i = 0, my $count = 0; $count < 400; $i++ ) {
++$count and push @M, $i if magnanimous($i);
}
say "First 45 magnanimous numbers\n".
(sprintf "@{['%4d' x 45]}", @M[0..45-1]) =~ s/(.{60})/$1\n/gr;
say "241st through 250th magnanimous numbers\n" .
join ' ', @M[240..249];
say "\n391st through 400th magnanimous numbers\n".
join ' ', @M[390..399]; |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #BASIC256 | BASIC256 | arraybase 1
dim matriz= {{78,19,30,12,36}, {49,10,65,42,50}, {30,93,24,78,10}, {39,68,27,64,29}}
dim mtranspuesta(matriz[,?], matriz[?,])
for fila = 1 to matriz[?,]
for columna = 1 to matriz[,?]
print matriz[fila, columna]; " ";
mtranspuesta[columna, fila] = matriz[fila, columna]
next columna
print
next fila
print
for fila = 1 to mtranspuesta[?,]
for columna = 1 to mtranspuesta[,?]
print mtranspuesta[fila, columna]; " ";
next columna
print
next fila
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.
| #Elixir | Elixir | defmodule Maze do
def generate(w, h) do
maze = (for i <- 1..w, j <- 1..h, into: Map.new, do: {{:vis, i, j}, true})
|> walk(:rand.uniform(w), :rand.uniform(h))
print(maze, w, h)
maze
end
defp walk(map, x, y) do
Enum.shuffle( [[x-1,y], [x,y+1], [x+1,y], [x,y-1]] )
|> Enum.reduce(Map.put(map, {:vis, x, y}, false), fn [i,j],acc ->
if acc[{:vis, i, j}] do
{k, v} = if i == x, do: {{:hor, x, max(y, j)}, "+ "},
else: {{:ver, max(x, i), y}, " "}
walk(Map.put(acc, k, v), i, j)
else
acc
end
end)
end
defp print(map, w, h) do
Enum.each(1..h, fn j ->
IO.puts Enum.map_join(1..w, fn i -> Map.get(map, {:hor, i, j}, "+---") end) <> "+"
IO.puts Enum.map_join(1..w, fn i -> Map.get(map, {:ver, i, j}, "| ") end) <> "|"
end)
IO.puts String.duplicate("+---", w) <> "+"
end
end
Maze.generate(20, 10) |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | a = {{3, 2}, {4, 1}};
MatrixPower[a, 0]
MatrixPower[a, 1]
MatrixPower[a, -1]
MatrixPower[a, 4]
MatrixPower[a, 1/2]
MatrixPower[a, Pi] |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #MATLAB | MATLAB | function [output] = matrixexponentiation(matrixA, exponent)
output = matrixA^(exponent); |
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.
| #EchoLisp | EchoLisp |
(lib 'plot) ;; interpolation functions
(lib 'compile)
;; rational version
(define (q-map-range x xmin xmax ymin ymax) (+ ymin (/ ( * (- x xmin) (- ymax ymin)) (- xmax xmin))))
;; float version
(define (map-range x xmin xmax ymin ymax) (+ ymin (// ( * (- x xmin) (- ymax ymin)) (- xmax xmin))))
; accelerate it
(compile 'map-range "-vf")
(q-map-range 4 0 10 -1 0)
→ -3/5
(map-range 4 0 10 -1 0)
→ -0.6
(linear 4 0 10 -1 0) ;; native
→ -0.6
(for [(x (in-range 0 10))] (writeln x (q-map-range x 0 10 -1 0) (map-range x 0 10 -1 0)))
0 -1 -1
1 -9/10 -0.9
2 -4/5 -0.8
3 -7/10 -0.7
4 -3/5 -0.6
5 -1/2 -0.5
6 -2/5 -0.4
7 -3/10 -0.3
8 -1/5 -0.2
9 -1/10 -0.1
|
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 CLEAR 61999
20 BORDER 0: POKE 23624,4: POKE 23693,0: CLS: REM easier than "bright 0: flash 0: ink 0: paper 0"
30 PRINT INK 4; FLASH 1;"Initialising": GO SUB 9000: LET m=USR 62000: CLS: REM set up and run machine code; USR is the call function
40 DIM s(32,2): REM current top and bottom of character sequence for each of the 32 spaces across the screen
50 FOR x=1 TO 32: REM main loop
60 IF s(x,1)=0 AND RND>.95 THEN LET s(x,1)=1: LET s(x,2)=2: GO SUB 4000: GO SUB 3000: GO TO 80: REM start a new column; decrease the .95 modifier for a busier - but slower - screen
70 IF s(x,2)>0 THEN GO SUB 1000
80 NEXT x
90 FOR l=1 TO 10: REM matrix code switches existing glyphs occasionally
100 LET x=INT (RND*22): LET y=INT (RND*32)
110 IF PEEK (22528+32*x+y)=0 THEN GO TO 140: REM no point updating a blank space
120 GO SUB 4000
130 PRINT AT x,y; INK 8; BRIGHT 8;CHR$ (33+RND*95): REM ink 8 and bright 8 tells it to keep the cell's existing ink and bright values
140 NEXT l
150 GO TO 50
999 REM continue an existing column
1000 LET s(x,2)=s(x,2)+1
1010 IF s(x,2)<21 THEN GO SUB 3000
1020 IF s(x,2)>12 THEN LET s(x,1)=s(x,1)+1
1030 LET k=2
1040 GO SUB 2000
1050 LET k=6
1060 GO SUB 2000
1070 LET k=12
1080 GO SUB 2000
1090 IF s(x,1)=22 THEN LET s(x,1)=0: LET s(x,2)=0
1100 RETURN
1999 REM update colour
2000 LET a=22527+x+32*(s(x,2)-k)
2010 LET c=PEEK a
2020 IF c=4 THEN POKE a,0
2030 IF c=68 THEN POKE a,4
2040 IF c=71 THEN POKE a,68: REM this poke could be done with 'print at s(x,2)-k-1,x-1; ink 4; bright 1; over 1; " " ' but poking is FAR easier, especially considering the above pokes would be similar
2050 RETURN
2999 REM new character at bottom of column
3000 PRINT AT s(x,2)-1,x-1; INK 7; BRIGHT 1;CHR$ (33+RND*95)
3010 RETURN
3999 REM select character set
4000 POKE 23607,242+3*INT (RND*4): REM the spectrum character set is pointed to by the two-byte system value CHARS at 23606 and 23607, so repoking this selects a new character set - the machine code below has created four copies of the character set at suitable locations
4010 RETURN
8999 REM machine code routine to create multiple character sets
9000 RESTORE 9800
9010 LET h$="0123456789ABCDEF"
9020 LET o=62000
9030 IF PEEK o=33 AND PEEK 62121=201 THEN RETURN: REM saves storing it all again if the machine code is already there
9040 READ a$
9050 IF a$="eof" THEN RETURN
9060 FOR x=1 TO 8
9070 LET n=0
9080 LET s=(x*2)-1
9090 LET t=s+1
9100 FOR m=1 TO 16
9110 IF h$(m)=a$(s) THEN LET n=n+16*(m-1)
9120 IF h$(m)=a$(t) THEN LET n=n+m-1
9130 NEXT m
9140 POKE o,n
9150 LET o=o+1
9160 NEXT x
9170 GO TO 9040
9800 DATA "21003D1100F30100"
9810 DATA "03EDB02100F31100"
9820 DATA "F6010009EDB01100"
9830 DATA "F901FF051A6F0707"
9840 DATA "ADE6AAAD6F070707"
9850 DATA "CB0DADE666AD1213"
9860 DATA "0B78B120E721FFF5"
9870 DATA "010000E5CD8BF2E1"
9880 DATA "E5CD8BF2E1E5CD8B"
9890 DATA "F2E1CD8BF2232323"
9900 DATA "23AF470C79FEC0C2"
9910 DATA "6BF2C9E5D1043E09"
9920 DATA "90835F8A93577885"
9930 DATA "6F8C95671AE521AA"
9940 DATA "F277E17E123AAAF2"
9950 DATA "77C9000000000000"
9960 DATA "eof"
9999 POKE 23606,0: POKE 23607,60: INK 4: REM reset to default character set and colour if you get lost |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (computer program) game should display all the player guesses and the results of that guess.
Display (just an idea):
Feature
Graphic Version
Text Version
Player guess
Colored circles
Alphabet letters
Correct color & position
Black circle
X
Correct color
White circle
O
None
Gray circle
-
A text version example: 1. ADEF - XXO-
Translates to:
the first guess;
the four colors (ADEF);
result:
two correct colors and spot,
one correct color/wrong spot, one color isn't in the code.
Happy coding!
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
| #Wren | Wren | import "random" for Random
import "/ioutil" for Input
import "/str" for Str
var Rand = Random.new()
class Mastermind {
construct new(codeLen, colorsCnt, guessCnt, repeatClr) {
var color = "ABCDEFGHIJKLMNOPQRST"
_codeLen = codeLen.clamp(4, 10)
var cl = colorsCnt
if (!repeatClr && cl < _codeLen) cl = _codeLen
_colorsCnt = cl.clamp(2, 20)
_guessCnt = guessCnt.clamp(7, 20)
_repeatClr = repeatClr
_colors = color.take(_colorsCnt).join()
_combo = ""
_guesses = []
_results = []
}
play() {
var win = false
_combo = getCombo_()
while (_guessCnt != 0) {
showBoard_()
if (checkInput_(getInput_())) {
win = true
break
}
_guessCnt = _guessCnt - 1
}
System.print("\n\n--------------------------------")
if (win) {
System.print("Very well done!\nYou found the code: %(_combo)")
} else {
System.print("I am sorry, you couldn't make it!\nThe code was: %(_combo)")
}
System.print("--------------------------------\n")
}
showBoard_() {
for (x in 0..._guesses.count) {
System.print("\n--------------------------------")
System.write("%(x + 1): ")
for (y in _guesses[x]) System.write("%(y) ")
System.write(" : ")
for (y in _results[x]) System.write("%(y) ")
var z = _codeLen - _results[x].count
if (z > 0) System.write("- " * z)
}
System.print("\n")
}
getInput_() {
while (true) {
var a = Str.upper(Input.text("Enter your guess (%(_colors)): ", 1)).take(_codeLen)
if (a.all { |c| _colors.contains(c) } ) return a.join()
}
}
checkInput_(a) {
_guesses.add(a.toList)
var black = 0
var white = 0
var gmatch = List.filled(_codeLen, false)
var cmatch = List.filled(_codeLen, false)
for (i in 0..._codeLen) {
if (a[i] == _combo[i]) {
gmatch[i] = true
cmatch[i] = true
black = black + 1
}
}
for (i in 0..._codeLen) {
if (gmatch[i]) continue
for (j in 0..._codeLen) {
if (i == j || cmatch[j]) continue
if (a[i] == _combo[j]) {
cmatch[j] = true
white = white + 1
break
}
}
}
var r = []
r.addAll(("X" * black).toList)
r.addAll(("O" * white).toList)
_results.add(r)
return black == _codeLen
}
getCombo_() {
var c = ""
var clr = _colors
for (s in 0..._codeLen) {
var z = Rand.int(clr.count)
c = c + clr[z]
if (!_repeatClr) Str.delete(clr, z)
}
return c
}
}
var m = Mastermind.new(4, 8, 12, false)
m.play() |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Red | Red | Red ["Maze solver"]
do %mazegen.red
print [
"start:" start: random size - 1x1
"end:" end: random size - 1x1
]
isnew?: function [pos] [not find visited pos]
open?: function [pos d] [
o: pos/y * size/x + pos/x + 1
0 = pick walls/:o d
]
expand: function [pos][
either any [
all [pos/x > 0 isnew? p: pos - 1x0 open? p 1]
all [pos/x < (size/x - 1) isnew? p: pos + 1x0 open? pos 1]
all [pos/y > 0 isnew? p: pos - 0x1 open? p 2]
all [pos/y < (size/y - 1) isnew? p: pos + 0x1 open? pos 2]
][append visited p insert path p][remove path]
path/1
]
path: reduce [start]
visited: []
until [end = expand path/1]
print reverse path |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #Perl | Perl | use 5.10.0;
use List::Util 'max';
my @sum;
while (<>) {
my @x = split;
@sum = ($x[0] + $sum[0],
map($x[$_] + max(@sum[$_-1, $_]), 1 .. @x-2),
$x[-1] + $sum[-1]);
}
say max(@sum); |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main() # validate against the RFC test strings and more
testMD5("The quick brown fox jumps over the lazy dog", 16r9e107d9d372bb6826bd81d3542a419d6)
testMD5("The quick brown fox jumps over the lazy dog.", 16re4d909c290d0fb1ca068ffaddf22cbd0)
testMD5("", 16rd41d8cd98f00b204e9800998ecf8427e)
end
procedure testMD5(s,rh) # compute the MD5 hash and compare it to reference value
write("Message(length=",*s,") = ",image(s))
write("Digest = ",hexstring(h := MD5(s)),if h = rh then " matches reference hash" else (" does not match reference hash = " || hexstring(rh)),"\n")
end |
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Julia | Julia | function oddmagicsquare(order)
if iseven(order)
order += 1
end
q = zeros(Int, (order, order))
p = 1
i = div(order, 2) + 1
j = 1
while p <= order * order
q[i, j] = p
ti = (i + 1 > order) ? 1 : i + 1
tj = (j - 1 < 1) ? order : j - 1
if q[ti, tj] != 0
ti = i
tj = j + 1
end
i = ti
j = tj
p = p + 1
end
q, order
end
function singlyevenmagicsquare(order)
if isodd(order)
order += 1
end
if order % 4 == 0
order += 2
end
q = zeros(Int, (order, order))
z = div(order, 2)
b = z * z
c = 2 * b
d = 3 * b
sq, ord = oddmagicsquare(z)
for j in 1:z, i in 1:z
a = sq[i, j]
q[i, j] = a
q[i + z, j + z] = a + b
q[i + z, j] = a + c
q[i, j + z] = a + d
end
lc = div(z, 2)
rc = lc - 1
for j in 1:z, i in 1:order
if i <= lc || i > order - rc || (i == lc && j == lc)
if i != 0 || j != lc + 1
t = q[i, j]
q[i, j] = q[i, j + z]
q[i, j + z] = t
end
end
end
q, order
end
function check(q)
side = size(q)[1]
sums = Vector{Int}()
for n in 1:side
push!(sums, sum(q[n, :]))
push!(sums, sum(q[:, n]))
end
println(all(x->x==sums[1], sums) ?
"Checks ok: all sides add to $(sums[1])." : "Bad sum.")
end
function display(q)
r, c = size(q)
for i in 1:r, j in 1:c
nstr = lpad(string(q[i, j]), 4)
print(j % c > 0 ? nstr : "$nstr\n")
end
end
for o in (6, 10)
println("\nWith order $o:")
msq = singlyevenmagicsquare(o)[1]
display(msq)
check(msq)
end
|
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Kotlin | Kotlin | // version 1.0.6
fun magicSquareOdd(n: Int): Array<IntArray> {
if (n < 3 || n % 2 == 0)
throw IllegalArgumentException("Base must be odd and > 2")
var value = 0
val gridSize = n * n
var c = n / 2
var r = 0
val result = Array(n) { IntArray(n) }
while (++value <= gridSize) {
result[r][c] = value
if (r == 0) {
if (c == n - 1) r++
else {
r = n - 1
c++
}
}
else if (c == n - 1) {
r--
c = 0
}
else if (result[r - 1][c + 1] == 0) {
r--
c++
}
else r++
}
return result
}
fun magicSquareSinglyEven(n: Int): Array<IntArray> {
if (n < 6 || (n - 2) % 4 != 0)
throw IllegalArgumentException("Base must be a positive multiple of 4 plus 2")
val size = n * n
val halfN = n / 2
val subSquareSize = size / 4
val subSquare = magicSquareOdd(halfN)
val quadrantFactors = intArrayOf(0, 2, 3, 1)
val result = Array(n) { IntArray(n) }
for (r in 0 until n)
for (c in 0 until n) {
val quadrant = r / halfN * 2 + c / halfN
result[r][c] = subSquare[r % halfN][c % halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
val nColsLeft = halfN / 2
val nColsRight = nColsLeft - 1
for (r in 0 until halfN)
for (c in 0 until n)
if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft) continue
val tmp = result[r][c]
result[r][c] = result[r + halfN][c]
result[r + halfN][c] = tmp
}
return result
}
fun main(args: Array<String>) {
val n = 6
for (ia in magicSquareSinglyEven(n)) {
for (i in ia) print("%2d ".format(i))
println()
}
println("\nMagic constant ${(n * n + 1) * n / 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 .
| #Arturo | Arturo | inMandelbrot?: function [c][
z: to :complex [0 0]
do.times: 50 [
z: c + z*z
if 4 < abs z -> return false
]
return true
]
mandelbrot: function [settings][
y: 0
while [y < settings\height][
Y: settings\yStart + y * settings\yStep
x: 0
while [x < settings\width][
X: settings\xStart + x * settings\xStep
if? inMandelbrot? to :complex @[X Y] -> prints "*"
else -> prints " "
x: x + 1
]
print ""
y: y + 1
]
]
mandelbrot #[ yStart: 1.0 yStep: neg 0.05
xStart: neg 2.0 xStep: 0.0315
height: 40 width: 80 ] |
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)
| #AutoHotkey | AutoHotkey |
msgbox % OddMagicSquare(5)
msgbox % OddMagicSquare(7)
return
OddMagicSquare(oddN){
sq := oddN**2
obj := {}
loop % oddN
obj[A_Index] := {} ; dis is row
mid := Round((oddN+1)/2)
sum := Round(sq*(sq+1)/2/oddN)
obj[1][mid] := 1
cR := 1 , cC := mid
loop % sq-1
{
done := 0 , a := A_index+1
while !done {
nR := cR-1 , nC := cC+1
if !nR
nR := oddN
if (nC>oddN)
nC := 1
if obj[nR][nC] ;filled
cR += 1
else cR := nR , cC := nC
if !obj[cR][cC]
obj[cR][cC] := a , done := 1
}
}
str := "Magic Constant for " oddN "x" oddN " is " sum "`n"
for k,v in obj
{
for k2,v2 in v
str .= " " v2
str .= "`n"
}
return str
}
|
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.
| #C | C | #include <stdio.h>
#define MAT_ELEM(rows,cols,r,c) (r*cols+c)
//Improve performance by assuming output matrices do not overlap with
//input matrices. If this is C++, use the __restrict extension instead
#ifdef __cplusplus
typedef double * const __restrict MAT_OUT_t;
#else
typedef double * const restrict MAT_OUT_t;
#endif
typedef const double * const MAT_IN_t;
static inline void mat_mult(
const int m,
const int n,
const int p,
MAT_IN_t a,
MAT_IN_t b,
MAT_OUT_t c)
{
for (int row=0; row<m; row++) {
for (int col=0; col<p; col++) {
c[MAT_ELEM(m,p,row,col)] = 0;
for (int i=0; i<n; i++) {
c[MAT_ELEM(m,p,row,col)] += a[MAT_ELEM(m,n,row,i)]*b[MAT_ELEM(n,p,i,col)];
}
}
}
}
static inline void mat_show(
const int m,
const int p,
MAT_IN_t a)
{
for (int row=0; row<m;row++) {
for (int col=0; col<p;col++) {
printf("\t%7.3f", a[MAT_ELEM(m,p,row,col)]);
}
putchar('\n');
}
}
int main(void)
{
double a[4*4] = {1, 1, 1, 1,
2, 4, 8, 16,
3, 9, 27, 81,
4, 16, 64, 256};
double b[4*3] = { 4.0, -3.0, 4.0/3,
-13.0/3, 19.0/4, -7.0/3,
3.0/2, -2.0, 7.0/6,
-1.0/6, 1.0/4, -1.0/6};
double c[4*3] = {0};
mat_mult(4,4,3,a,b,c);
mat_show(4,3,c);
return 0;
}
|
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
System.IO.Directory.CreateDirectory("some/where")
End Sub
End Module |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #Wren | Wren | import "io" for FileSystem
class Main {
construct new() {}
init() {
FileSystem.createDirectory("path/to/dir")
}
update() {}
draw(alpha) {}
}
var Game = Main.new() |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #zkl | zkl | System.cmd("mkdir -p ../foo/bar") |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #D | D | import std.stdio;
void main() {
int n=8;
foreach(row; magicSquareDoublyEven(n)) {
foreach(col; row) {
writef("%2s ", col);
}
writeln;
}
writeln("\nMagic constant: ", (n*n+1)*n/2);
}
int[][] magicSquareDoublyEven(int n) {
import std.exception;
enforce(n>=4 && n%4 == 0, "Base must be a positive multiple of 4");
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4; // how many multiples of 4
int[][] result;
result.length = n;
foreach(i; 0..n) {
result[i].length = n;
}
for (int r=0, i=0; r<n; r++) {
for (int c=0; c<n; c++, i++) {
int bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
} |
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
| #Dyalect | Dyalect | func _C(i) {
() => i
}
func _A(k, x1, x2, x3, x4, x5) {
var b
b = () => {
k -= 1
_A(k, b, x1, x2, x3, x4)
}
if k <= 0 {
x4() + x5()
} else {
b()
}
}
for i in 1..20 {
let res = _A(i, _C(1), _C(-1), _C(-1), _C(1), _C(0))
print("\(i)\t= \(res)")
} |
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
| #Dylan | Dylan | define method a
(k :: <integer>, x1 :: <function>, x2 :: <function>, x3 :: <function>,
x4 :: <function>, x5 :: <function>)
=> (i :: <integer>)
local b() => (i :: <integer>)
k := k - 1;
a(k, b, x1, x2, x3, x4)
end;
if (k <= 0) x4() + x5() else b() end if
end method a;
define method man-or-boy
(x :: <integer>)
=> (i :: <integer>)
a(x, method() 1 end,
method() -1 end,
method() -1 end,
method() 1 end,
method() 0 end)
end method man-or-boy;
format-out("%d\n", man-or-boy(10)) |
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #REXX | REXX | /*REXX program implements main step GOST 28147-89 based on a Feistel network. */
numeric digits 12 /* ┌── a list of 4─bit S─box values used by */
/* ↓ the Central Bank of Russian Federation.*/
@.0 = 4 10 9 2 13 8 0 14 6 11 1 12 7 15 5 3
@.1 = 14 11 4 12 6 13 15 10 2 3 8 1 0 7 5 9
@.2 = 5 8 1 13 10 3 4 2 14 15 12 7 6 0 9 11
@.3 = 7 13 10 1 0 8 9 15 14 4 6 12 11 2 5 3
@.4 = 6 12 7 1 5 15 13 8 4 10 9 14 0 3 11 2
@.5 = 4 11 10 0 7 2 1 13 3 6 8 5 9 12 15 14
@.6 = 13 11 4 1 3 15 5 9 0 10 14 7 6 8 2 12
@.7 = 1 15 13 0 5 7 10 4 9 2 3 14 6 11 8 12
/* [↓] build the sub-keys array from above. */
do r=0 for 8; do c=0 for 16; !.r.c=word(@.r, c + 1); end; end
z=0
#1=x2d( 43b0421 ); #2=x2d( 4320430 ); k=#1 + x2d( 0e2c104f9 )
do while k > x2d( 7ffFFffF ); k=k - 2**32; end
do while k < x2d( 80000000 ); k=k + 2**32; end
do j=0 for 4; jj=j + j; jjp=jj + 1 /*calculate the array'a "subscripts". */
$=x2d( right( d2x( k % 2 ** (j * 8) ), 2) )
cm=$ // 16; cd=$ % 16 /*perform modulus and integer division.*/
z=z + (!.jj.cm + 16 * !.jjp.cd) * 2**(j*8)
end /*i*/ /* [↑] encryption algorithm for S-box.*/
/* [↓] encryption algorithm round. */
k = c2d( bitxor( bitor( d2c(z * 2**11, 4), d2c(z % 2**21, 4) ), d2c(#2, 4) ) )
say center(d2x(k) ' ' d2x(#1), 79) /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.
Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).
There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.
Task
Write a routine (procedure, function, whatever) to find magnanimous numbers.
Use that function to find and display, here on this page the first 45 magnanimous numbers.
Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers
See also
OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.
| #Phix | Phix | with javascript_semantics
function magnanimous(integer n)
integer p = 1, r = 0
while n>=10 do
r += remainder(n,10)*p
n = floor(n/10)
if not is_prime(n+r) then return false end if
p *= 10
end while
return true
end function
sequence mag = {}
integer n = 0
while length(mag)<400 do
if magnanimous(n) then mag &= n end if
n += 1
end while
puts(1,"First 45 magnanimous numbers: ") pp(mag[1..45],{pp_Indent,30,pp_IntCh,false,pp_Maxlen,100})
printf(1,"magnanimous numbers[241..250]: %v\n", {mag[241..250]})
printf(1,"magnanimous numbers[391..400]: %v\n", {mag[391..400]})
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"ARRAYLIB"
DIM matrix(3,4), transpose(4,3)
matrix() = 78,19,30,12,36,49,10,65,42,50,30,93,24,78,10,39,68,27,64,29
PROC_transpose(matrix(), transpose())
FOR row% = 0 TO DIM(matrix(),1)
FOR col% = 0 TO DIM(matrix(),2)
PRINT ;matrix(row%,col%) " ";
NEXT
PRINT
NEXT row%
PRINT
FOR row% = 0 TO DIM(transpose(),1)
FOR col% = 0 TO DIM(transpose(),2)
PRINT ;transpose(row%,col%) " ";
NEXT
PRINT
NEXT row% |
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.
| #Elm | Elm | import Maybe as M
import Result as R
import Matrix
import Mouse
import Random exposing (Seed)
import Matrix.Random
import Time exposing (Time, every, second)
import Set exposing (Set, fromList)
import List exposing (..)
import String exposing (join)
import Html exposing (Html, br, input, h1, h2, text, div, button)
import Html.Events as HE
import Html.Attributes as HA
import Html.App exposing (program)
import Json.Decode as JD
import Svg
import Svg.Attributes exposing (version, viewBox, cx, cy, r, x, y, x1, y1, x2, y2, fill,points, style, width, height, preserveAspectRatio)
minSide = 10
maxSide = 40
w = 700
h = 700
dt = 0.001
type alias Direction = Int
down = 0
right = 1
type alias Door = (Matrix.Location, Direction)
type State = Initial | Generating | Generated | Solved
type alias Model =
{ rows : Int
, cols : Int
, animate : Bool
, boxes : Matrix.Matrix Bool
, doors : Set Door
, current : List Matrix.Location
, state : State
, seedStarter : Int
, seed : Seed
}
initdoors : Int -> Int -> Set Door
initdoors rows cols =
let
pairs la lb = List.concatMap (\at -> List.map ((,) at) lb) la
downs = pairs (pairs [0..rows-2] [0..cols-1]) [down]
rights = pairs (pairs [0..rows-1] [0..cols-2]) [right]
in downs ++ rights |> fromList
initModel : Int -> Int -> Bool -> State -> Int -> Model
initModel rows cols animate state starter =
let rowGenerator = Random.int 0 (rows-1)
colGenerator = Random.int 0 (cols-1)
locationGenerator = Random.pair rowGenerator colGenerator
(c, s)= Random.step locationGenerator (Random.initialSeed starter)
in { rows = rows
, cols = cols
, animate = animate
, boxes = Matrix.matrix rows cols (\location -> state == Generating && location == c)
, doors = initdoors rows cols
, current = if state == Generating then [c] else []
, state = state
, seedStarter = starter -- updated every Tick until maze generated.
, seed = s
}
view model =
let
borderLineStyle = style "stroke:green;stroke-width:0.3"
wallLineStyle = style "stroke:green;stroke-width:0.1"
x1Min = x1 <| toString 0
y1Min = y1 <| toString 0
x1Max = x1 <| toString model.cols
y1Max = y1 <| toString model.rows
x2Min = x2 <| toString 0
y2Min = y2 <| toString 0
x2Max = x2 <| toString model.cols
y2Max = y2 <| toString model.rows
borders = [ Svg.line [ x1Min, y1Min, x2Max, y2Min, borderLineStyle ] []
, Svg.line [ x1Max, y1Min, x2Max, y2Max, borderLineStyle ] []
, Svg.line [ x1Max, y1Max, x2Min, y2Max, borderLineStyle ] []
, Svg.line [ x1Min, y1Max, x2Min, y2Min, borderLineStyle ] []
]
doorToLine door =
let (deltaX1, deltaY1) = if (snd door == right) then (1,0) else (0,1)
(row, column) = fst door
in Svg.line [ x1 <| toString (column + deltaX1)
, y1 <| toString (row + deltaY1)
, x2 <| toString (column + 1)
, y2 <| toString (row + 1)
, wallLineStyle ] []
doors = (List.map doorToLine <| Set.toList model.doors )
circleInBox (row,col) color =
Svg.circle [ r "0.25"
, fill (color)
, cx (toString (toFloat col + 0.5))
, cy (toString (toFloat row + 0.5))
] []
showUnvisited location box =
if box then [] else [ circleInBox location "yellow" ]
unvisited = model.boxes
|> Matrix.mapWithLocation showUnvisited
|> Matrix.flatten
|> concat
current =
case head model.current of
Nothing -> []
Just c -> [circleInBox c "black"]
maze =
if model.animate || model.state /= Generating
then [ Svg.g [] <| doors ++ borders ++ unvisited ++ current ]
else [ Svg.g [] <| borders ]
in
div
[]
[ h2 [centerTitle] [text "Maze Generator"]
, div
[floatLeft]
( slider "rows" minSide maxSide model.rows SetRows
++ [ br [] [] ]
++ slider "cols" minSide maxSide model.cols SetCols
++ [ br [] [] ]
++ checkbox "Animate" model.animate SetAnimate
++ [ br [] [] ]
++ [ button
[ HE.onClick Generate ]
[ text "Generate"]
] )
, div
[floatLeft]
[ Svg.svg
[ version "1.1"
, width (toString w)
, height (toString h)
, viewBox (join " "
[ 0 |> toString
, 0 |> toString
, model.cols |> toString
, model.rows |> toString ])
]
maze
]
]
checkbox label checked msg =
[ input
[ HA.type' "checkbox"
, HA.checked checked
, HE.on "change" (JD.map msg HE.targetChecked)
]
[]
, text label
]
slider name min max current msg =
[ input
[ HA.value (if current >= min then current |> toString else "")
, HE.on "input" (JD.map msg HE.targetValue )
, HA.type' "range"
, HA.min <| toString min
, HA.max <| toString max
]
[]
, text <| name ++ "=" ++ (current |> toString)
]
floatLeft = HA.style [ ("float", "left") ]
centerTitle = HA.style [ ( "text-align", "center") ]
unvisitedNeighbors : Model -> Matrix.Location -> List Matrix.Location
unvisitedNeighbors model (row,col) =
[(row, col-1), (row-1, col), (row, col+1), (row+1, col)]
|> List.filter (\l -> fst l >= 0 && snd l >= 0 && fst l < model.rows && snd l < model.cols)
|> List.filter (\l -> (Matrix.get l model.boxes) |> M.withDefault False |> not)
updateModel' : Model -> Int -> Model
updateModel' model t =
case head model.current of
Nothing -> {model | state = Generated, seedStarter = t }
Just prev ->
let neighbors = unvisitedNeighbors model prev
in if (length neighbors) > 0 then
let (neighborIndex, seed) = Random.step (Random.int 0 (length neighbors-1)) model.seed
next = head (drop neighborIndex neighbors) |> M.withDefault (0,0)
boxes = Matrix.set next True model.boxes
dir = if fst prev == fst next then right else down
doorCell = if ( (dir == down) && (fst prev < fst next))
|| (dir == right ) && (snd prev < snd next) then prev else next
doors = Set.remove (doorCell, dir) model.doors
in {model | boxes=boxes, doors=doors, current=next :: model.current, seed=seed, seedStarter = t}
else
let tailCurrent = tail model.current |> M.withDefault []
in updateModel' {model | current = tailCurrent} t
updateModel : Msg -> Model -> Model
updateModel msg model =
let stringToCellCount s =
let v' = String.toInt s |> R.withDefault minSide
in if v' < minSide then minSide else v'
in case msg of
Tick tf ->
let t = truncate tf
in
if (model.state == Generating) then updateModel' model t
else { model | seedStarter = t }
Generate ->
initModel model.rows model.cols model.animate Generating model.seedStarter
SetRows countString ->
initModel (stringToCellCount countString) model.cols model.animate Initial model.seedStarter
SetCols countString ->
initModel model.rows (stringToCellCount countString) model.animate Initial model.seedStarter
SetAnimate b ->
{ model | animate = b }
NoOp -> model
type Msg = NoOp | Tick Time | Generate | SetRows String | SetCols String | SetAnimate Bool
subscriptions model = every (dt * second) Tick
main =
let
update msg model = (updateModel msg model, Cmd.none)
init = (initModel 21 36 False Initial 0, Cmd.none)
in program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
} |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Maxima | Maxima | a: matrix([3, 2],
[4, 1])$
a ^^ 4;
/* matrix([417, 208],
[416, 209]) */
a ^^ -1;
/* matrix([-1/5, 2/5],
[4/5, -3/5]) */ |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Nim | Nim | import sequtils, strutils
type Matrix[N: static int; T] = array[1..N, array[1..N, T]]
func `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] =
for i in 1..N:
for j in 1..N:
for k in 1..N:
result[i][j] += a[i][k] * b[k][j]
func identityMatrix[N; T](): Matrix[N, T] =
for i in 1..N:
result[i][i] = T(1)
func `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] =
if n == 0: return identityMatrix[N, T]()
if n == 1: return m
var n = n
var m = m
result = identityMatrix[N, T]()
while n > 0:
if (n and 1) != 0:
result = result * m
n = n shr 1
m = m * m
proc `$`(m: Matrix): string =
var lg = 0
for i in 1..m.N:
for j in 1..m.N:
lg = max(lg, len($m[i][j]))
for i in 1..m.N:
echo m[i].mapIt(align($it, lg)).join(" ")
when isMainModule:
let m1: Matrix[3, int] = [[ 3, 2, -1],
[-1, 0, 5],
[ 2, -1, 3]]
echo m1^10
import math
const
C30 = sqrt(3.0) / 2
S30 = 1 / 2
let m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] # 30° rotation matrix.
echo m2^12 # Nearly the identity matrix. |
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.
| #Elixir | Elixir | defmodule RC do
def map_range(a1 .. a2, b1 .. b2, s) do
b1 + (s - a1) * (b2 - b1) / (a2 - a1)
end
end
Enum.each(0..10, fn s ->
:io.format "~2w map to ~7.3f~n", [s, RC.map_range(0..10, -1..0, s)]
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.
| #Emacs_Lisp | Emacs Lisp | (defun maprange (a1 a2 b1 b2 s)
(+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))
(dotimes (i 10)
(message "%s" (maprange 0.0 10.0 -1.0 0.0 i))) |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (computer program) game should display all the player guesses and the results of that guess.
Display (just an idea):
Feature
Graphic Version
Text Version
Player guess
Colored circles
Alphabet letters
Correct color & position
Black circle
X
Correct color
White circle
O
None
Gray circle
-
A text version example: 1. ADEF - XXO-
Translates to:
the first guess;
the four colors (ADEF);
result:
two correct colors and spot,
one correct color/wrong spot, one color isn't in the code.
Happy coding!
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
| #zkl | zkl | class MasterMind{
fcn init(code_len,guess_count){
var codeLen =code_len.max(4).min(10);
var guessCnt=guess_count.max(7).min(20);
var colors ="ABCDEFGHIJKLMNOPQRST"[0,codeLen];
}
fcn play{
guesses,win,blackWhite:=List(),False,Void;
code:=codeLen.pump(String,'wrap(_){ colors[(0).random(codeLen)] });
do(guessCnt){
str:=getInput();
win,blackWhite = checkInput(str,code);
guesses.append(T(str,blackWhite));
showBoard(guesses);
if(win) break;
}
if(win) println("--------------------------------\n",
"Very well done!\nYou found the code: ",code);
else println("--------------------------------\n",
"I am sorry, you didn't discover the code!\nThe code was: ",code);
}
fcn [private] showBoard(guesses){
foreach n,gbw in ([1..].zip(guesses)){
guess,blackWhite := gbw;
println("%2d: %s :% s %s".fmt(n,
guess.split("").concat(" "), blackWhite.split("").concat(" "),
"- "*(codeLen - blackWhite.len())));
}
}
fcn [private] getInput{
while(True){
a:=ask("Enter your guess (" + colors + "): ").toUpper()[0,codeLen];
if(not (a-colors) and a.len()>=codeLen) return(a);
}
}
fcn [private] checkInput(guess,code){
// black: guess is correct in both color and position
// white: correct color, wrong position
matched,black := guess.split("").zipWith('==,code), matched.sum(0);
// remove black from code, prepend null to make counting easy
code = L("-").extend(matched.zipWith('wrap(m,peg){ m and "-" or peg },code));
white:=0; foreach m,p in (matched.zip(guess)){
if(not m and (z:=code.find(p))){ white+=1; code[z]="-"; }
}
return(black==codeLen,"X"*black + "O"*white)
}
}(4,12).play(); |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Ruby | Ruby | class Maze
# Solve via breadth-first algorithm.
# Each queue entry is a path, that is list of coordinates with the
# last coordinate being the one that shall be visited next.
def solve
# Clean up.
reset_visiting_state
# Enqueue start position.
@queue = []
enqueue_cell([], @start_x, @start_y)
# Loop as long as there are cells to visit and no solution has
# been found yet.
path = nil
until path || @queue.empty?
path = solve_visit_cell
end
if path
# Mark the cells that make up the shortest path.
for x, y in path
@path[x][y] = true
end
else
puts "No solution found?!"
end
end
private
# Maze solving visiting method.
def solve_visit_cell
# Get the next path.
path = @queue.shift
# The cell to visit is the last entry in the path.
x, y = path.last
# Have we reached the end yet?
return path if x == @end_x && y == @end_y
# Mark cell as visited.
@visited[x][y] = true
for dx, dy in DIRECTIONS
if dx.nonzero?
# Left / Right
new_x = x + dx
if move_valid?(new_x, y) && !@vertical_walls[ [x, new_x].min ][y]
enqueue_cell(path, new_x, y)
end
else
# Top / Bottom
new_y = y + dy
if move_valid?(x, new_y) && !@horizontal_walls[x][ [y, new_y].min ]
enqueue_cell(path, x, new_y)
end
end
end
nil # No solution yet.
end
# Enqueue a new coordinate to visit.
def enqueue_cell(path, x, y)
# Add new coordinates to the current path and enqueue the new path.
@queue << path + [[x, y]]
end
end
# Demonstration:
maze = Maze.new 20, 10
maze.solve
maze.print |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #Phix | Phix | with javascript_semantics
sequence tri = {{55},
{94, 48},
{95, 30, 96},
{77, 71, 26, 67},
{97, 13, 76, 38, 45},
{ 7, 36, 79, 16, 37, 68},
{48, 7, 9, 18, 70, 26, 6},
{18, 72, 79, 46, 59, 79, 29, 90},
{20, 76, 87, 11, 32, 7, 7, 49, 18},
{27, 83, 58, 35, 71, 11, 25, 57, 29, 85},
{14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55},
{ 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23},
{92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42},
{56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72},
{44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36},
{85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52},
{ 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15},
{27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93}}
-- update each row from last but one upwards, with the larger
-- child, so the first step is to replace 6 with 6+27 or 6+2.
for r=length(tri)-1 to 1 by -1 do
for c=1 to length(tri[r]) do
tri[r][c] += max(tri[r+1][c..c+1])
end for
end for
?tri[1][1]
|
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Io | Io | Io> MD5
==> MD5_0x97663e0:
appendSeq = MD5_appendSeq()
md5 = MD5_md5()
md5String = MD5_md5String()
Io> MD5 clone appendSeq("The quick brown fox jumped over the lazy dog's back") md5String
==> e38ca1d920c4b8b8d3946b2c72f01680 |
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Lua | Lua | import sequtils, strutils
type Square = seq[seq[int]]
func magicSquareOdd(n: Positive): Square =
## Build a magic square of odd order.
assert n >= 3 and (n and 1) != 0, "base must be odd and greater than 2."
result = newSeqWith(n, newSeq[int](n))
var
r = 0
c = n div 2
value = 0
while value < n * n:
inc value
result[r][c] = value
if r == 0:
if c == n - 1:
inc r
else:
r = n - 1
inc c
elif c == n - 1:
dec r
c = 0
elif result[r - 1][c + 1] == 0:
dec r
inc c
else:
inc r
func magicSquareSinglyEven(n: int): Square =
## Build a magic square of singly even order.
assert n >= 6 and ((n - 2) and 3) == 0, "base must be a positive multiple of 4 plus 2."
result = newSeqWith(n, newSeq[int](n))
let
halfN = n div 2
subSquareSize = n * n div 4
subSquare = magicSquareOdd(halfN)
const QuadrantFactors = [0, 2, 3, 1]
for r in 0..<n:
for c in 0..<n:
let quadrant = r div halfN * 2 + c div halfN
result[r][c] = subSquare[r mod halfN][c mod halfN] + QuadrantFactors[quadrant] * subSquareSize
let
nColsLeft = halfN div 2
nColsRight = nColsLeft - 1
for r in 0..<halfN:
for c in 0..<n:
if c < nColsLeft or c >= n - nColsRight or (c == nColsLeft and r == nColsLeft):
if c != 0 or r != nColsLeft:
swap result[r][c], result[r + halfN][c]
func `$`(square: Square): string =
## Return the string representation of a magic square.
let length = len($(square.len * square.len))
for row in square:
result.add row.mapIt(($it).align(length)).join(" ") & '\n'
when isMainModule:
let n = 6
echo magicSquareSinglyEven(n)
echo "Magic constant = ", n * (n * n + 1) div 2 |
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Nim | Nim | import sequtils, strutils
type Square = seq[seq[int]]
func magicSquareOdd(n: Positive): Square =
## Build a magic square of odd order.
assert n >= 3 and (n and 1) != 0, "base must be odd and greater than 2."
result = newSeqWith(n, newSeq[int](n))
var
r = 0
c = n div 2
value = 0
while value < n * n:
inc value
result[r][c] = value
if r == 0:
if c == n - 1:
inc r
else:
r = n - 1
inc c
elif c == n - 1:
dec r
c = 0
elif result[r - 1][c + 1] == 0:
dec r
inc c
else:
inc r
func magicSquareSinglyEven(n: int): Square =
## Build a magic square of singly even order.
assert n >= 6 and ((n - 2) and 3) == 0, "base must be a positive multiple of 4 plus 2."
result = newSeqWith(n, newSeq[int](n))
let
halfN = n div 2
subSquareSize = n * n div 4
subSquare = magicSquareOdd(halfN)
const QuadrantFactors = [0, 2, 3, 1]
for r in 0..<n:
for c in 0..<n:
let quadrant = r div halfN * 2 + c div halfN
result[r][c] = subSquare[r mod halfN][c mod halfN] + QuadrantFactors[quadrant] * subSquareSize
let
nColsLeft = halfN div 2
nColsRight = nColsLeft - 1
for r in 0..<halfN:
for c in 0..<n:
if c < nColsLeft or c >= n - nColsRight or (c == nColsLeft and r == nColsLeft):
if c != 0 or r != nColsLeft:
swap result[r][c], result[r + halfN][c]
func `$`(square: Square): string =
## Return the string representation of a magic square.
let length = len($(square.len * square.len))
for row in square:
result.add row.mapIt(($it).align(length)).join(" ") & '\n'
when isMainModule:
let n = 6
echo magicSquareSinglyEven(n)
echo "Magic constant = ", n * (n * n + 1) div 2 |
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Perl | Perl | |
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 .
| #AutoHotkey | AutoHotkey | Max_Iteration := 256
Width := Height := 400
File := "MandelBrot." Width ".bmp"
Progress, b2 w400 fs9, Creating Colours ...
Gosub, CreateColours
Gosub, CreateBitmap
Progress, Off
Gui, -Caption
Gui, Margin, 0, 0
Gui, Add, Picture,, %File%
Gui, Show,, MandelBrot
Return
GuiClose:
GuiEscape:
ExitApp
;---------------------------------------------------------------------------
CreateBitmap: ; create and save a 32bit bitmap file
;---------------------------------------------------------------------------
; define header details
HeaderBMP := 14
HeaderDIB := 40
DataOffset := HeaderBMP + HeaderDIB
ImageSize := Width * Height * 4 ; 32bit
FileSize := DataOffset + ImageSize
Resolution := 3780 ; from mspaint
; create bitmap header
VarSetCapacity(IMAGE, FileSize, 0)
NumPut(Asc("B") , IMAGE, 0x00, "Char")
NumPut(Asc("M") , IMAGE, 0x01, "Char")
NumPut(FileSize , IMAGE, 0x02, "UInt")
NumPut(DataOffset , IMAGE, 0x0A, "UInt")
NumPut(HeaderDIB , IMAGE, 0x0E, "UInt")
NumPut(Width , IMAGE, 0x12, "UInt")
NumPut(Height , IMAGE, 0x16, "UInt")
NumPut(1 , IMAGE, 0x1A, "Short") ; Planes
NumPut(32 , IMAGE, 0x1C, "Short") ; Bits per Pixel
NumPut(ImageSize , IMAGE, 0x22, "UInt")
NumPut(Resolution , IMAGE, 0x26, "UInt")
NumPut(Resolution , IMAGE, 0x2A, "UInt")
; fill in Data
Gosub, CreatePixels
; save Bitmap to file
FileDelete, %File%
Handle := DllCall("CreateFile", "Str", File, "UInt", 0x40000000
, "UInt", 0, "UInt", 0, "UInt", 2, "UInt", 0, "UInt", 0)
DllCall("WriteFile", "UInt", Handle, "UInt", &IMAGE, "UInt"
, FileSize, "UInt *", Bytes, "UInt", 0)
DllCall("CloseHandle", "UInt", Handle)
Return
;---------------------------------------------------------------------------
CreatePixels: ; create pixels for [-2 < x < 1] [-1.5 < y < 1.5]
;---------------------------------------------------------------------------
Loop, % Height // 2 + 1 {
yi := A_Index - 1
y0 := -1.5 + yi / Height * 3 ; range -1.5 .. +1.5
Progress, % 200*yi // Height, % "Current line: " 2*yi " / " Height
Loop, %Width% {
xi := A_Index - 1
x0 := -2 + xi / Width * 3 ; range -2 .. +1
Gosub, Mandelbrot
p1 := DataOffset + 4 * (Width * yi + xi)
NumPut(Colour, IMAGE, p1, "UInt")
p2 := DataOffset + 4 * (Width * (Height-yi) + xi)
NumPut(Colour, IMAGE, p2, "UInt")
}
}
Return
;---------------------------------------------------------------------------
Mandelbrot: ; calculate a colour for each pixel
;---------------------------------------------------------------------------
x := y := Iteration := 0
While, (x*x + y*y <= 4) And (Iteration < Max_Iteration) {
xtemp := x*x - y*y + x0
y := 2*x*y + y0
x := xtemp
Iteration++
}
Colour := Iteration = Max_Iteration ? 0 : Colour_%Iteration%
Return
;---------------------------------------------------------------------------
CreateColours: ; borrowed from PureBasic example
;---------------------------------------------------------------------------
Loop, 64 {
i4 := (i3 := (i2 := (i1 := A_Index - 1) + 64) + 64) + 64
Colour_%i1% := RGB(4*i1 + 128, 4*i1, 0)
Colour_%i2% := RGB(64, 255, 4*i1)
Colour_%i3% := RGB(64, 255 - 4*i1, 255)
Colour_%i4% := RGB(64, 0, 255 - 4*i1)
}
Return
;---------------------------------------------------------------------------
RGB(r, g, b) { ; return 24bit color value
;---------------------------------------------------------------------------
Return, (r&0xFF)<<16 | g<<8 | b
} |
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)
| #AWK | AWK |
# syntax: GAWK -f MAGIC_SQUARES_OF_ODD_ORDER.AWK
BEGIN {
build(5)
build(3,1) # verify sum
build(7)
exit(0)
}
function build(n,check, arr,i,width,x,y) {
if (n !~ /^[0-9]*[13579]$/ || n < 3) {
printf("error: %s is invalid\n",n)
return
}
printf("\nmagic constant for %dx%d is %d\n",n,n,(n*n+1)*n/2)
x = 0
y = int(n/2)
for (i=1; i<=(n*n); i++) {
arr[x,y] = i
if (arr[(x+n-1)%n,(y+n+1)%n]) {
x = (x+n+1) % n
}
else {
x = (x+n-1) % n
y = (y+n+1) % n
}
}
width = length(n*n)
for (x=0; x<n; x++) {
for (y=0; y<n; y++) {
printf("%*s ",width,arr[x,y])
}
printf("\n")
}
if (check) { verify(arr,n) }
}
function verify(arr,n, total,x,y) { # verify sum of each row, column and diagonal
print("\nverify")
# horizontal
for (x=0; x<n; x++) {
total = 0
for (y=0; y<n; y++) {
printf("%d ",arr[x,y])
total += arr[x,y]
}
printf("\t: %d row %d\n",total,x+1)
}
# vertical
for (y=0; y<n; y++) {
total = 0
for (x=0; x<n; x++) {
printf("%d ",arr[x,y])
total += arr[x,y]
}
printf("\t: %d column %d\n",total,y+1)
}
# left diagonal
total = 0
for (x=y=0; x<n; x++ y++) {
printf("%d ",arr[x,y])
total += arr[x,y]
}
printf("\t: %d diagonal top left to bottom right\n",total)
# right diagonal
x = n - 1
total = 0
for (y=0; y<n; y++ x--) {
printf("%d ",arr[x,y])
total += arr[x,y]
}
printf("\t: %d diagonal bottom left to top right\n",total)
}
|
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.
| #C.23 | C# | public class Matrix
{
int n;
int m;
double[,] a;
public Matrix(int n, int m)
{
if (n <= 0 || m <= 0)
throw new ArgumentException("Matrix dimensions must be positive");
this.n = n;
this.m = m;
a = new double[n, m];
}
//indices start from one
public double this[int i, int j]
{
get { return a[i - 1, j - 1]; }
set { a[i - 1, j - 1] = value; }
}
public int N { get { return n; } }
public int M { get { return m; } }
public static Matrix operator*(Matrix _a, Matrix b)
{
int n = _a.N;
int m = b.M;
int l = _a.M;
if (l != b.N)
throw new ArgumentException("Illegal matrix dimensions for multiplication. _a.M must be equal b.N");
Matrix result = new Matrix(_a.N, b.M);
for(int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
double sum = 0.0;
for (int k = 0; k < l; k++)
sum += _a.a[i, k]*b.a[k, j];
result.a[i, j] = sum;
}
return result;
}
} |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Elena | Elena | import system'routines;
import extensions;
import extensions'routines;
MagicSquareDoublyEven(int n)
{
if(n < 4 || n.mod(4) != 0)
{ InvalidArgumentException.new:"base must be a positive multiple of 4".raise() };
int bits := 09669h;
int size := n * n;
int mult := n / 4;
var result := IntMatrix.allocate(n,n);
int i := 0;
for (int r := 0, r < n, r += 1)
{
for(int c := 0, c < n, c += 1, i += 1)
{
int bitPos := c / mult + (r / mult) * 4;
result[r][c] := ((bits && (1 $shl bitPos)) != 0).iif(i+1,size - i)
}
};
^ result
}
public program()
{
int n := 8;
console.printLine(MagicSquareDoublyEven(n));
console.printLine().printLine("Magic constant: ",(n * n + 1) * n / 2)
} |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Elixir | Elixir | defmodule Magic_square do
def doubly_even(n) when rem(n,4)!=0, do: raise ArgumentError, "must be even, but not divisible by 4."
def doubly_even(n) do
n2 = n * n
Enum.zip(1..n2, make_pattern(n))
|> Enum.map(fn {i,p} -> if p, do: i, else: n2 - i + 1 end)
|> Enum.chunk(n)
|> to_string(n)
|> IO.puts
end
defp make_pattern(n) do
pattern = Enum.reduce(1..4, [true], fn _,acc ->
acc ++ Enum.map(acc, &(!&1))
end) |> Enum.chunk(4)
for i <- 0..n-1, j <- 0..n-1, do: Enum.at(pattern, rem(i,4)) |> Enum.at(rem(j,4))
end
defp to_string(square, n) do
format = String.duplicate("~#{length(to_char_list(n*n))}w ", n) <> "\n"
Enum.map_join(square, fn row ->
:io_lib.format(format, row)
end)
end
end
Magic_square.doubly_even(8) |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | a k x1 x2 x3 x4 x5:
local b:
set :k -- k
a k @b @x1 @x2 @x3 @x4
if <= k 0:
+ x4 x5
else:
b
local x i:
labda:
i
!. a 10 x 1 x -1 x -1 x 1 x 0 |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #E | E | def a(var k, &x1, &x2, &x3, &x4, &x5) {
def bS; def &b := bS
bind bS {
to get() {
k -= 1
return a(k, &b, &x1, &x2, &x3, &x4)
}
}
return if (k <= 0) { x4 + x5 } else { b }
}
def p := 1
def n := -1
def z := 0
println(a(10, &p, &n, &n, &p, &z)) |
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #Rust | Rust | use std::convert::TryInto;
use std::env;
use std::num::Wrapping;
const REPLACEMENT_TABLE: [[u8; 16]; 8] = [
[4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
[6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
[4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
[13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
[1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12],
];
const KEYS: [u32; 8] = [
0xE2C1_04F9,
0xE41D_7CDE,
0x7FE5_E857,
0x0602_65B4,
0x281C_CC85,
0x2E2C_929A,
0x4746_4503,
0xE00_CE510,
];
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
let plain_text: Vec<u8> = vec![0x04, 0x3B, 0x04, 0x21, 0x04, 0x32, 0x04, 0x30];
println!(
"Before one step: {}\n",
plain_text
.iter()
.cloned()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))
);
let encoded_text = main_step(plain_text, KEYS[0]);
println!(
"After one step : {}\n",
encoded_text
.iter()
.cloned()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))
);
} else {
let mut t = args[1].clone(); // "They call him... Баба Яга"
t += &" ".repeat((8 - t.len() % 8) % 8);
let text_bytes = t.bytes().collect::<Vec<_>>();
let plain_text = text_bytes.chunks(8).collect::<Vec<_>>();
println!(
"Plain text : {}\n",
plain_text.iter().cloned().fold("".to_string(), |a, x| a
+ "["
+ &x.iter()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))[..23]
+ "]")
);
let encoded_text = plain_text
.iter()
.map(|c| encode(c.to_vec()))
.collect::<Vec<_>>();
println!(
"Encoded text: {}\n",
encoded_text.iter().cloned().fold("".to_string(), |a, x| a
+ "["
+ &x.into_iter()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))[..23]
+ "]")
);
let decoded_text = encoded_text
.iter()
.map(|c| decode(c.to_vec()))
.collect::<Vec<_>>();
println!(
"Decoded text: {}\n",
decoded_text.iter().cloned().fold("".to_string(), |a, x| a
+ "["
+ &x.into_iter()
.fold("".to_string(), |b, y| b + &format!("{:02X} ", y))[..23]
+ "]")
);
let recovered_text =
String::from_utf8(decoded_text.iter().cloned().flatten().collect::<Vec<_>>()).unwrap();
println!("Recovered text: {}\n", recovered_text);
}
}
fn encode(text_block: Vec<u8>) -> Vec<u8> {
let mut step = text_block;
for i in 0..24 {
step = main_step(step, KEYS[i % 8]);
}
for i in (0..8).rev() {
step = main_step(step, KEYS[i]);
}
step
}
fn decode(text_block: Vec<u8>) -> Vec<u8> {
let mut step = text_block[4..].to_vec();
let mut temp = text_block[..4].to_vec();
step.append(&mut temp);
for key in &KEYS {
step = main_step(step, *key);
}
for i in (0..24).rev() {
step = main_step(step, KEYS[i % 8]);
}
let mut ans = step[4..].to_vec();
let mut temp = step[..4].to_vec();
ans.append(&mut temp);
ans
}
fn main_step(text_block: Vec<u8>, key_element: u32) -> Vec<u8> {
let mut n = text_block;
let mut s = (Wrapping(
u32::from(n[0]) << 24 | u32::from(n[1]) << 16 | u32::from(n[2]) << 8 | u32::from(n[3]),
) + Wrapping(key_element))
.0;
let mut new_s: u32 = 0;
for mid in 0..4 {
let cell = (s >> (mid << 3)) & 0xFF;
new_s += (u32::from(REPLACEMENT_TABLE[(mid * 2) as usize][(cell & 0x0f) as usize])
+ (u32::from(REPLACEMENT_TABLE[(mid * 2 + 1) as usize][(cell >> 4) as usize]) << 4))
<< (mid << 3);
}
s = ((new_s << 11) + (new_s >> 21))
^ (u32::from(n[4]) << 24 | u32::from(n[5]) << 16 | u32::from(n[6]) << 8 | u32::from(n[7]));
n[4] = n[0];
n[5] = n[1];
n[6] = n[2];
n[7] = n[3];
n[0] = (s >> 24).try_into().unwrap();
n[1] = ((s >> 16) & 0xFF).try_into().unwrap();
n[2] = ((s >> 8) & 0xFF).try_into().unwrap();
n[3] = (s & 0xFF).try_into().unwrap();
n
} |
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #Tcl | Tcl | namespace eval ::GOST {
proc tcl::mathfunc::k {a b} {
variable ::GOST::replacementTable
lindex $replacementTable $a $b
}
proc mainStep {textBlock idx key} {
variable replacementTable
lassign [lindex $textBlock $idx] N0 N1
set S [expr {($N0 + $key) & 0xFFFFFFFF}]
set newS 0
for {set i 0} {$i < 4} {incr i} {
set cell [expr {$S >> ($i * 8) & 0xFF}]
incr newS [expr {
(k($i*2, $cell%15) + k($i*2+1, $cell/16) * 16) << ($i * 8)
}]
}
set S [expr {((($newS << 11) + ($newS >> 21)) & 0xFFFFFFFF) ^ $N1}]
lset textBlock $idx [list $S $N0]
return $textBlock
}
} |
http://rosettacode.org/wiki/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.
Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).
There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.
Task
Write a routine (procedure, function, whatever) to find magnanimous numbers.
Use that function to find and display, here on this page the first 45 magnanimous numbers.
Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers
See also
OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.
| #PicoLisp | PicoLisp | (de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
(de isprime (N)
(cache '(NIL) N
(if (== N 2)
T
(and
(> N 1)
(bit? 1 N)
(let (Q (dec N) N1 (dec N) K 0 X)
(until (bit? 1 Q)
(setq
Q (>> 1 Q)
K (inc K) ) )
(catch 'composite
(do 16
(loop
(setq X
(**Mod
(rand 2 (min (dec N) 1000000000000))
Q
N ) )
(T (or (=1 X) (= X N1)))
(T
(do K
(setq X (**Mod X 2 N))
(when (=1 X) (throw 'composite))
(T (= X N1) T) ) )
(throw 'composite) ) )
(throw 'composite T) ) ) ) ) ) )
(de numbers (N)
(let (P 10 Q N)
(make
(until (> 10 Q)
(link
(+
(setq Q (/ N P))
(% N P) ) )
(setq P (* P 10)) ) ) ) )
(de ismagna (N)
(or
(> 10 N)
(fully isprime (numbers N)) ) )
(let (C 0 N 0 Lst)
(setq Lst
(make
(until (== C 401)
(when (ismagna N)
(link N)
(inc 'C) )
(inc 'N) ) ) )
(println (head 45 Lst))
(println (head 10 (nth Lst 241)))
(println (head 10 (nth Lst 391))) ) |
http://rosettacode.org/wiki/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.
Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).
There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.
Task
Write a routine (procedure, function, whatever) to find magnanimous numbers.
Use that function to find and display, here on this page the first 45 magnanimous numbers.
Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers
See also
OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.
| #PL.2FM | PL/M | 100H: /* FIND SOME MAGNANIMOUS NUMBERS - THOSE WHERE INSERTING '+' BETWEEN */
/* ANY TWO OF THE DIGITS AND EVALUATING THE SUM RESULTS IN A PRIME */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PRINT$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PRINT$NL: PROCEDURE; CALL PRINT$STRING( .( 0DH, 0AH, '$' ) ); END;
PRINT$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
IF N < 100 THEN DO;
IF N < 10 THEN CALL PRINT$CHAR( ' ' );
CALL PRINT$CHAR( ' ' );
END;
CALL PRINT$STRING( .N$STR( W ) );
END PRINT$NUMBER;
/* INTEGER SQUARE ROOT: BASED ON THE ONE IN THE PL/M FROBENIUS NUMBERS */
SQRT: PROCEDURE( N )ADDRESS;
DECLARE ( N, X0, X1 ) ADDRESS;
IF N <= 3 THEN DO;
IF N = 0 THEN X0 = 0; ELSE X0 = 1;
END;
ELSE DO;
X0 = SHR( N, 1 );
DO WHILE( ( X1 := SHR( X0 + ( N / X0 ), 1 ) ) < X0 );
X0 = X1;
END;
END;
RETURN X0;
END SQRT;
DECLARE MAGNANIMOUS (251)ADDRESS; /* MAGNANIMOUS NUMBERS */
DECLARE FALSE LITERALLY '0';
DECLARE TRUE LITERALLY '0FFH';
/* TO FIND MAGNANIMOUS NUMBERS UP TO 30$000, WE NEED TO FIND PRIMES */
/* UP TO 9$999 + 9 = 10$008 */
DECLARE MAX$PRIME LITERALLY '10$008';
DECLARE DCL$PRIME LITERALLY '10$009';
/* SIEVE THE PRIMES TO MAX$PRIME */
DECLARE ( I, S ) ADDRESS;
DECLARE PRIME ( DCL$PRIME )BYTE;
PRIME( 1 ) = FALSE; PRIME( 2 ) = TRUE;
DO I = 3 TO LAST( PRIME ) BY 2; PRIME( I ) = TRUE; END;
DO I = 4 TO LAST( PRIME ) BY 2; PRIME( I ) = FALSE; END;
DO I = 3 TO SQRT( MAX$PRIME );
IF PRIME( I ) THEN DO;
DO S = I * I TO LAST( PRIME ) BY I + I;PRIME( S ) = FALSE; END;
END;
END;
/* FIND THE MAGNANIMOUS NUMBERS */
FIND$MAGNANIMOUS: PROCEDURE;
DECLARE ( D1, D2, D3, D4, D5
, D12, D123, D1234
, D23, D234, D2345
, D34, D345, D45
) ADDRESS;
DECLARE M$COUNT ADDRESS; /* COUNT OF MAGNANIMOUS NUMBERS FOUND */
STORE$MAGNANIMOUS: PROCEDURE( N )BYTE;
DECLARE N ADDRESS;
M$COUNT = M$COUNT + 1;
IF M$COUNT <= LAST( MAGNANIMOUS ) THEN MAGNANIMOUS( M$COUNT ) = N;
RETURN M$COUNT <= LAST( MAGNANIMOUS );
END STORE$MAGNANIMOUS;
M$COUNT = 0;
/* 1 DIGIT MAGNANIMOUS NUMBERS */
DO D1 = 0 TO 9; IF NOT STORE$MAGNANIMOUS( D1 ) THEN RETURN; END;
/* 2 DIGIT MAGNANIMOUS NUMBERS */
DO D1 = 1 TO 9;
DO D2 = 0 TO 9;
IF PRIME( D1 + D2 ) THEN DO;
IF NOT STORE$MAGNANIMOUS( ( D1 * 10 ) + D2 ) THEN RETURN;
END;
END;
END;
/* 3 DIGIT MAGNANIMOUS NUMBERS */
DO D1 = 1 TO 9;
DO D23 = 0 TO 99;
IF PRIME( D1 + D23 ) THEN DO;
D3 = D23 MOD 10;
D12 = ( D1 * 10 ) + ( D23 / 10 );
IF PRIME( D12 + D3 ) THEN DO;
IF NOT STORE$MAGNANIMOUS( ( D12 * 10 ) + D3 ) THEN RETURN;
END;
END;
END;
END;
/* 4 DIGIT MAGNANIMOUS NUMBERS */
DO D12 = 10 TO 99;
DO D34 = 0 TO 99;
IF PRIME( D12 + D34 ) THEN DO;
D123 = ( D12 * 10 ) + ( D34 / 10 );
D4 = D34 MOD 10;
IF PRIME( D123 + D4 ) THEN DO;
D1 = D12 / 10;
D234 = ( ( D12 MOD 10 ) * 100 ) + D34;
IF PRIME( D1 + D234 ) THEN DO;
IF NOT STORE$MAGNANIMOUS( ( D12 * 100 ) + D34 )
THEN RETURN;
END;
END;
END;
END;
END;
/* 5 DIGIT MAGNANIMOUS NUMBERS UP TO 30$000 */
DO D12 = 10 TO 30;
DO D345 = 0 TO 999;
IF PRIME( D12 + D345 ) THEN DO;
D123 = ( D12 * 10 ) + ( D345 / 100 );
D45 = D345 MOD 100;
IF PRIME( D123 + D45 ) THEN DO;
D1234 = ( D123 * 10 ) + ( D45 / 10 );
D5 = D45 MOD 10;
IF PRIME( D1234 + D5 ) THEN DO;
D1 = D12 / 10;
D2345 = ( ( D12 MOD 10 ) * 1000 ) + D345;
IF PRIME( D1 + D2345 ) THEN DO;
IF NOT STORE$MAGNANIMOUS( ( D12 * 1000 ) + D345 )
THEN RETURN;
END;
END;
END;
END;
END;
END;
END FIND$MAGNANIMOUS ;
CALL FIND$MAGNANIMOUS;
DO I = 1 TO LAST( MAGNANIMOUS );
IF I = 1 THEN DO;
CALL PRINT$STRING( .'MAGNANIMOUS NUMBERS 1-45:$' ); CALL PRINT$NL;
CALL PRINT$NUMBER( MAGNANIMOUS( I ) );
END;
ELSE IF I < 46 THEN DO;
IF I MOD 15 = 1 THEN CALL PRINT$NL; ELSE CALL PRINT$CHAR( ' ' );
CALL PRINT$NUMBER( MAGNANIMOUS( I ) );
END;
ELSE IF I = 241 THEN DO;
CALL PRINT$NL;
CALL PRINT$STRING( .'MAGANIMOUS NUMBERS 241-250:$' ); CALL PRINT$NL;
CALL PRINT$NUMBER( MAGNANIMOUS( I ) );
END;
ELSE IF I > 241 AND I <= 250 THEN DO;
CALL PRINT$CHAR( ' ' );
CALL PRINT$NUMBER( MAGNANIMOUS( I ) );
END;
END;
CALL PRINT$NL;
EOF |
http://rosettacode.org/wiki/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.
Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).
There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.
Task
Write a routine (procedure, function, whatever) to find magnanimous numbers.
Use that function to find and display, here on this page the first 45 magnanimous numbers.
Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers
See also
OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.
| #Raku | Raku | my @magnanimous = lazy flat ^10, (10 .. 1001).map( {
my int $last;
(1 ..^ .chars).map: -> \c { $last = 1 and last unless (.substr(0,c) + .substr(c)).is-prime }
next if $last;
$_
} ),
(1002 .. ∞).map: {
# optimization for numbers > 1001; First and last digit can not both be even or both be odd
next if (.substr(0,1) + .substr(*-1)) %% 2;
my int $last;
(1 ..^ .chars).map: -> \c { $last = 1 and last unless (.substr(0,c) + .substr(c)).is-prime }
next if $last;
$_
}
put 'First 45 magnanimous numbers';
put @magnanimous[^45]».fmt('%3d').batch(15).join: "\n";
put "\n241st through 250th magnanimous numbers";
put @magnanimous[240..249];
put "\n391st through 400th magnanimous numbers";
put @magnanimous[390..399]; |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Burlesque | Burlesque |
blsq ) {{78 19 30 12 36}{49 10 65 42 50}{30 93 24 78 10}{39 68 27 64 29}}tpsp
78 49 30 39
19 10 93 68
30 65 24 27
12 42 78 64
36 50 10 29
|
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.
| #Emacs_Lisp | Emacs Lisp | (require 'cl-lib)
(cl-defstruct maze rows cols data)
(defmacro maze-pt (w r c)
`(+ (* (mod ,r (maze-rows ,w)) (maze-cols ,w))
(mod ,c (maze-cols ,w))))
(defmacro maze-ref (w r c)
`(aref (maze-data ,w) (maze-pt ,w ,r ,c)))
(defun new-maze (rows cols)
(setq rows (1+ rows)
cols (1+ cols))
(let ((m (make-maze :rows rows :cols cols :data (make-vector (* rows cols) nil))))
(dotimes (r rows)
(dotimes (c cols)
(setf (maze-ref m r c) (copy-sequence '(wall ceiling)))))
(dotimes (r rows)
(maze-set m r (1- cols) 'visited))
(dotimes (c cols)
(maze-set m (1- rows) c 'visited))
(maze-unset m 0 0 'ceiling) ;; Maze Entrance
(maze-unset m (1- rows) (- cols 2) 'ceiling) ;; Maze Exit
m))
(defun maze-is-set (maze r c v)
(member v (maze-ref maze r c)))
(defun maze-set (maze r c v)
(let ((cell (maze-ref maze r c)))
(when (not (member v cell))
(setf (maze-ref maze r c) (cons v cell)))))
(defun maze-unset (maze r c v)
(setf (maze-ref maze r c) (delete v (maze-ref maze r c))))
(defun print-maze (maze &optional marks)
(dotimes (r (1- (maze-rows maze)))
(dotimes (c (1- (maze-cols maze)))
(princ (if (maze-is-set maze r c 'ceiling) "+---" "+ ")))
(princ "+")
(terpri)
(dotimes (c (1- (maze-cols maze)))
(princ (if (maze-is-set maze r c 'wall) "|" " "))
(princ (if (member (cons r c) marks) " * " " ")))
(princ "|")
(terpri))
(dotimes (c (1- (maze-cols maze)))
(princ (if (maze-is-set maze (1- (maze-rows maze)) c 'ceiling) "+---" "+ ")))
(princ "+")
(terpri))
(defun shuffle (lst)
(sort lst (lambda (a b) (= 1 (random 2)))))
(defun to-visit (maze row col)
(let (unvisited)
(dolist (p '((0 . +1) (0 . -1) (+1 . 0) (-1 . 0)))
(let ((r (+ row (car p)))
(c (+ col (cdr p))))
(unless (maze-is-set maze r c 'visited)
(push (cons r c) unvisited))))
unvisited))
(defun make-passage (maze r1 c1 r2 c2)
(if (= r1 r2)
(if (< c1 c2)
(maze-unset maze r2 c2 'wall) ; right
(maze-unset maze r1 c1 'wall)) ; left
(if (< r1 r2)
(maze-unset maze r2 c2 'ceiling) ; up
(maze-unset maze r1 c1 'ceiling)))) ; down
(defun dig-maze (maze row col)
(let (backup
(run 0))
(maze-set maze row col 'visited)
(push (cons row col) backup)
(while backup
(setq run (1+ run))
(when (> run (/ (+ row col) 3))
(setq run 0)
(setq backup (shuffle backup)))
(setq row (caar backup)
col (cdar backup))
(let ((p (shuffle (to-visit maze row col))))
(if p
(let ((r (caar p))
(c (cdar p)))
(make-passage maze row col r c)
(maze-set maze r c 'visited)
(push (cons r c) backup))
(pop backup)
(setq backup (shuffle backup))
(setq run 0))))))
(defun generate (rows cols)
(let* ((m (new-maze rows cols)))
(dig-maze m (random rows) (random cols))
(print-maze m)))
(defun parse-ceilings (line)
(let (rtn
(i 1))
(while (< i (length line))
(push (eq ?- (elt line i)) rtn)
(setq i (+ i 4)))
(nreverse rtn)))
(defun parse-walls (line)
(let (rtn
(i 0))
(while (< i (length line))
(push (eq ?| (elt line i)) rtn)
(setq i (+ i 4)))
(nreverse rtn)))
(defun parse-maze (file-name)
(let ((rtn)
(lines (with-temp-buffer
(insert-file-contents-literally file-name)
(split-string (buffer-string) "\n" t))))
(while lines
(push (parse-ceilings (pop lines)) rtn)
(push (parse-walls (pop lines)) rtn))
(nreverse rtn)))
(defun read-maze (file-name)
(let* ((raw (parse-maze file-name))
(rows (1- (/ (length raw) 2)))
(cols (length (car raw)))
(maze (new-maze rows cols)))
(dotimes (r rows)
(let ((ceilings (pop raw)))
(dotimes (c cols)
(unless (pop ceilings)
(maze-unset maze r c 'ceiling))))
(let ((walls (pop raw)))
(dotimes (c cols)
(unless (pop walls)
(maze-unset maze r c 'wall)))))
maze))
(defun find-exits (maze row col)
(let (exits)
(dolist (p '((0 . +1) (0 . -1) (-1 . 0) (+1 . 0)))
(let ((r (+ row (car p)))
(c (+ col (cdr p))))
(unless
(cond
((equal p '(0 . +1)) (maze-is-set maze r c 'wall))
((equal p '(0 . -1)) (maze-is-set maze row col 'wall))
((equal p '(+1 . 0)) (maze-is-set maze r c 'ceiling))
((equal p '(-1 . 0)) (maze-is-set maze row col 'ceiling)))
(push (cons r c) exits))))
exits))
(defun drop-visited (maze points)
(let (not-visited)
(while points
(unless (maze-is-set maze (caar points) (cdar points) 'visited)
(push (car points) not-visited))
(pop points))
not-visited))
(defun solve-maze (maze)
(let (solution
(exit (cons (- (maze-rows maze) 2) (- (maze-cols maze) 2)))
(pt (cons 0 0)))
(while (not (equal pt exit))
(maze-set maze (car pt) (cdr pt) 'visited)
(let ((exits (drop-visited maze (find-exits maze (car pt) (cdr pt)))))
(if (null exits)
(setq pt (pop solution))
(push pt solution)
(setq pt (pop exits)))))
(push pt solution)))
(defun solve (file-name)
(let* ((maze (read-maze file-name))
(solution (solve-maze maze)))
(print-maze maze solution)))
(generate 20 20) |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #OCaml | OCaml | (* identity matrix *)
let eye n =
let a = Array.make_matrix n n 0.0 in
for i=0 to n-1 do
a.(i).(i) <- 1.0
done;
(a)
;;
(* matrix dimensions *)
let dim a = Array.length a, Array.length a.(0);;
(* make matrix from list in row-major order *)
let matrix p q v =
if (List.length v) <> (p * q)
then failwith "bad dimensions"
else
let a = Array.make_matrix p q (List.hd v) in
let rec g i j = function
| [] -> a
| x::v ->
a.(i).(j) <- x;
if j+1 < q
then g i (j+1) v
else g (i+1) 0 v
in
g 0 0 v
;;
(* matrix product *)
let matmul a b =
let n, p = dim a
and q, r = dim b in
if p <> q then failwith "bad dimensions" else
let c = Array.make_matrix n r 0.0 in
for i=0 to n-1 do
for j=0 to r-1 do
for k=0 to p-1 do
c.(i).(j) <- c.(i).(j) +. a.(i).(k) *. b.(k).(j)
done
done
done;
(c)
;;
(* generic exponentiation, usual algorithm *)
let pow one mul a n =
let rec g p x = function
| 0 -> x
| i ->
g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2)
in
g a one n
;;
(* example with integers *)
pow 1 ( * ) 2 16;;
(* - : int = 65536 *) |
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.
| #Erlang | Erlang | -module(map_range).
-export([map_value/3]).
map_value({A1,A2},{B1,B2},S) ->
B1 + (S - A1) * (B2 - B1) / (A2 - A1).
|
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Rust | Rust | use rand::{thread_rng, Rng, rngs::ThreadRng};
const WIDTH: usize = 16;
const HEIGHT: usize = 16;
#[derive(Clone, Copy, PartialEq)]
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,
}
}
}
///MAZE SOLVING: Find the starting cell of the solution
fn solution_first(&self) -> Option<Cell> {
for (i, wall) in self.walls_h[0].iter().enumerate() {
if !wall {
return Some(Cell::from(i, 0));
}
}
for (i, wall) in self.walls_v.iter().enumerate() {
if !wall[0] {
return Some(Cell::from(0, i));
}
}
None
}
///MAZE SOLVING: Find the last cell of the solution
fn solution_last(&self) -> Option<Cell> {
for (i, wall) in self.walls_h[HEIGHT].iter().enumerate() {
if !wall {
return Some(Cell::from(i, HEIGHT - 1));
}
}
for (i, wall) in self.walls_v.iter().enumerate() {
if !wall[WIDTH] {
return Some(Cell::from(WIDTH - 1, i));
}
}
None
}
///MAZE SOLVING: Get the next candidate cell
fn solution_next(&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] && !self.walls_v[cell.row][cell.col] { neighbors.push(Cell::from(cell.col - 1, cell.row)); }
if cell.row > 0 && self.cells[cell.col][cell.row - 1] && !self.walls_h[cell.row][cell.col] { neighbors.push(Cell::from(cell.col, cell.row - 1)); }
if cell.col < WIDTH - 1 && self.cells[cell.col + 1][cell.row] && !self.walls_v[cell.row][cell.col + 1] { neighbors.push(Cell::from(cell.col + 1, cell.row)); }
if cell.row < HEIGHT - 1 && self.cells[cell.col][cell.row + 1] && !self.walls_h[cell.row + 1][cell.col] { 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();
Some(*next)
}
}
///MAZE SOLVING: solve the maze
///Uses self.cells to store the solution cells (true)
fn solve(&mut self) {
self.cells = [[true; HEIGHT]; WIDTH];
let mut solution: Vec<Cell> = Vec::new();
let mut next = self.solution_first().unwrap();
solution.push(next);
let last = self.solution_last().unwrap();
'main: loop {
while let Some(cell) = self.solution_next(&next) {
solution.push(cell);
if cell == last {
break 'main;
}
next = cell;
}
solution.pop().unwrap();
next = *solution.last().unwrap();
}
self.cells = [[false; HEIGHT]; WIDTH];
for cell in solution {
self.cells[cell.col][cell.row] = true;
}
}
///MAZE SOLVING: Ask if cell is part of the solution (cells[col][row] == true)
fn is_solution(&self, col: usize, row: usize) -> bool {
self.cells[col][row]
}
///Displays a wall
///MAZE SOLVING: Leave space for printing '*' if cell is part of the solution
/// (only when painting vertical walls)
///
// fn paint_wall(h_wall: bool, active: bool) {
// if h_wall {
// print!("{}", if active { "+---" } else { "+ " });
// } else {
// print!("{}", if active { "| " } else { " " });
// }
// }
fn paint_wall(h_wall: bool, active: bool, with_solution: bool) {
if h_wall {
print!("{}", if active { "+---" } else { "+ " });
} else {
print!("{}{}", if active { "|" } else { " " }, if with_solution { "" } else { " " });
}
}
///MAZE SOLVING: Paint * if cell is part of the solution
fn paint_solution(is_part: bool) {
print!("{}", if is_part { " * " } 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
///MAZE SOLVING: Displays a whole row of walls and, optionally, the included solution cells.
// 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);
// }
fn paint_row(&self, h_walls: bool, index: usize, with_solution: bool) {
let iter = if h_walls { self.walls_h[index].iter() } else { self.walls_v[index].iter() };
for (col, &wall) in iter.enumerate() {
Maze::paint_wall(h_walls, wall, with_solution);
if !h_walls && with_solution && col < WIDTH {
Maze::paint_solution(self.is_solution(col, index));
}
}
Maze::paint_close_wall(h_walls);
}
///Paints the maze
///MAZE SOLVING: Displaying the solution is an option
// fn paint(&self) {
// for i in 0 .. HEIGHT {
// self.paint_row(true, i);
// self.paint_row(false, i);
// }
// self.paint_row(true, HEIGHT);
// }
fn paint(&self, with_solution: bool) {
for i in 0 .. HEIGHT {
self.paint_row(true, i, with_solution);
self.paint_row(false, i, with_solution);
}
self.paint_row(true, HEIGHT, with_solution);
}
}
fn main() {
let mut maze = Maze::new();
maze.build();
maze.open_doors();
println!("The maze:");
maze.paint(false);
maze.solve();
println!("The maze, solved:");
maze.paint(true);
} |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #Picat | Picat | table (+,+,+,max)
pp(Row,_Column,Tri,Sum),Row>Tri.length => Sum=0.
pp(Row,Column,Tri,Sum) ?=>
pp(Row+1,Column,Tri,Sum1),
Sum = Sum1+Tri[Row,Column].
pp(Row,Column,Tri,Sum) =>
pp(Row+1,Column+1,Tri,Sum1),
Sum = Sum1+Tri[Row,Column]. |
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.
| #J | J | require 'convert/misc/md5'
md5 'The quick brown fox jumped over the lazy dog''s back'
e38ca1d920c4b8b8d3946b2c72f01680 |
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order | Magic squares of singly even order | A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
Task
Create a magic square of 6 x 6.
Related tasks
Magic squares of odd order
Magic squares of doubly even order
See also
Singly Even Magic Squares (1728.org)
| #Phix | Phix | with javascript_semantics
function swap(sequence s, integer x1, y1, x2, y2)
{s[x1,y1],s[x2,y2]} = {s[x2,y2],s[x1,y1]}
return s
end function
function se_magicsq(integer n)
if n<6 or mod(n-2,4)!=0 then
crash("illegal size (%d)",{n})
end if
sequence sq = repeat(repeat(0,n),n)
integer magic_sum = n*(n*n+1)/2,
sq_d_2 = n/2,
q2 = power(sq_d_2,2),
l = (n-2)/4,
x1 = floor(sq_d_2/2)+1, x2,
y1 = 1, y2,
r = 1
-- fill pattern a c
-- d b
-- main loop for creating magic square in section a
-- the value for b,c and d is derived from a
while true do
if sq[x1,y1]=0 then
x2 = x1+sq_d_2
y2 = y1+sq_d_2
sq[x1,y1] = r -- a
sq[x2,y2] = r+q2 -- b
sq[x2,y1] = r+q2*2 -- c
sq[x1,y2] = r+q2*3 -- d
if mod(r,sq_d_2)=0 then
y1 += 1
else
x1 += 1
y1 -= 1
end if
r += 1
end if
if x1>sq_d_2 then
x1 = 1
while sq[x1,y1] <> 0 do
x1 += 1
end while
end if
if y1<1 then
y1 = sq_d_2
while sq[x1,y1] <> 0 do
y1 -= 1
end while
end if
if r>q2 then exit end if
end while
-- swap left side
for y=1 to sq_d_2 do
y2 = y+sq_d_2
for x=1 to l do
sq = swap(sq, x,y, x,y2)
end for
end for
-- make indent
y1 = floor(sq_d_2/2) +1
y2 = y1+sq_d_2
x1 = 1
sq = swap(sq, x1,y1, x1,y2)
x1 = l+1
sq = swap(sq, x1,y1, x1,y2)
-- swap right side
for y=1 to sq_d_2 do
y2 = y+sq_d_2
for x=n-l+2 to n do
sq = swap(sq, x,y, x,y2)
end for
end for
-- check columms and rows
for y=1 to n do
r = 0
l = 0
for x=1 to n do
r += sq[x,y]
l += sq[y,x]
end for
if r<>magic_sum
or l<>magic_sum then
crash("error: value <> magic_sum")
end if
end for
-- check diagonals
r = 0
l = 0
for x=1 to n do
r += sq[x,x]
x2 = n-x+1
l += sq[x2,x2]
end for
if r<>magic_sum
or l<>magic_sum then
crash("error: value <> magic_sum")
end if
return sq
end function
pp(se_magicsq(6),{pp_Nest,1,pp_IntFmt,"%3d",pp_StrFmt,3,pp_IntCh,false,pp_Pause,0})
|
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #AWK | AWK | BEGIN {
XSize=59; YSize=21;
MinIm=-1.0; MaxIm=1.0;MinRe=-2.0; MaxRe=1.0;
StepX=(MaxRe-MinRe)/XSize; StepY=(MaxIm-MinIm)/YSize;
for(y=0;y<YSize;y++)
{
Im=MinIm+StepY*y;
for(x=0;x<XSize;x++)
{
Re=MinRe+StepX*x; Zr=Re; Zi=Im;
for(n=0;n<30;n++)
{
a=Zr*Zr; b=Zi*Zi;
if(a+b>4.0) break;
Zi=2*Zr*Zi+Im; Zr=a-b+Re;
}
printf "%c",62-n;
}
print "";
}
exit;
} |
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)
| #BASIC | BASIC |
100 :
110 REM MAGIC SQUARE OF ODD ORDER
120 :
130 DEF FN MOD(A) = A - INT (A / N) * N
140 DEF FN NR(J) = FN MOD((J + 2 * I + 1))
200 INPUT "ENTER N: ";N
210 IF N < 3 OR (N - INT (N / 2) * 2) = 0 GOTO 200
220 FOR I = 0 TO (N - 1)
230 FOR J = 0 TO (N - 1): HTAB 4 * (J + 1)
240 PRINT N * FN NR(N - J - 1) + FN NR(J) + 1;
250 NEXT J: PRINT
260 NEXT I
270 PRINT "MAGIC CONSTANT: ";N * (N * N + 1) / 2
|
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) 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)
| #Batch_File | Batch File | @echo off
rem Magic squares of odd order
setlocal EnableDelayedExpansion
set n=9
echo The square order is: %n%
for /l %%i in (1,1,%n%) do (
set w=
for /l %%j in (1,1,%n%) do (
set /a v1=%%i*2-%%j+n-1
set /a v1=v1%%n*n
set /a v2=%%i*2+%%j+n-2
set /a v2=v2%%n
set /a v=v1+v2+1
set v= !v!
set w=!w!!v:~-5!)
echo !w!)
set /a w=n*(n*n+1)/2
echo The magic number is: %w%
pause |
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.
| #C.2B.2B | C++ | #include <iostream>
#include <blitz/tinymat.h>
int main()
{
using namespace blitz;
TinyMatrix<double,3,3> A, B, C;
A = 1, 2, 3,
4, 5, 6,
7, 8, 9;
B = 1, 0, 0,
0, 1, 0,
0, 0, 1;
C = product(A, B);
std::cout << C << std::endl;
} |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Factor | Factor | USING: arrays combinators.short-circuit formatting fry
generalizations kernel math math.matrices prettyprint sequences
;
IN: rosetta-code.doubly-even-magic-squares
: top? ( loc n -- ? ) [ second ] dip 1/4 * < ;
: bottom? ( loc n -- ? ) [ second ] dip 3/4 * >= ;
: left? ( loc n -- ? ) [ first ] dip 1/4 * < ;
: right? ( loc n -- ? ) [ first ] dip 3/4 * >= ;
: corner? ( loc n -- ? )
{
[ { [ top? ] [ left? ] } ]
[ { [ top? ] [ right? ] } ]
[ { [ bottom? ] [ left? ] } ]
[ { [ bottom? ] [ right? ] } ]
} [ 2&& ] map-compose 2|| ;
: center? ( loc n -- ? )
{ [ top? ] [ bottom? ] [ left? ] [ right? ] } [ not ]
map-compose 2&& ;
: backward? ( loc n -- ? ) { [ corner? ] [ center? ] } 2|| ;
: forward ( loc n -- m ) [ first2 ] dip * 1 + + ;
: backward ( loc n -- m ) tuck forward [ sq ] dip - 1 + ;
: (doubly-even-magic-square) ( n -- matrix )
[ dup 2array matrix-coordinates flip ] [ 3 dupn ] bi
'[ dup _ backward? [ _ backward ] [ _ forward ] if ]
matrix-map ;
ERROR: invalid-order order ;
: check-order ( n -- )
dup { [ zero? not ] [ 4 mod zero? ] } 1&& [ drop ]
[ invalid-order ] if ;
: doubly-even-magic-square ( n -- matrix )
dup check-order (doubly-even-magic-square) ;
: main ( -- )
{ 4 8 12 } [
dup doubly-even-magic-square dup
[ "Order: %d\n" printf ]
[ simple-table. ]
[ first sum "Magic constant: %d\n\n" printf ] tri*
] each ;
MAIN: main |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #FreeBASIC | FreeBASIC | ' version 18-03-2016
' compile with: fbc -s console
' doubly even magic square 4, 8, 12, 16...
Sub Err_msg(msg As String)
Print msg
Beep : Sleep 5000, 1 : Exit Sub
End Sub
Sub de_magicsq(n As UInteger, filename As String = "")
' filename <> "" then save square in a file
' filename can contain directory name
' if filename exist it will be overwriten, no error checking
If n < 4 Then
Err_msg( "Error: n is to small")
Exit Sub
End If
If (n Mod 4) <> 0 Then
Err_msg "Error: not possible to make doubly" + _
" even magic square size " + Str(n)
Exit Sub
End If
Dim As UInteger sq(1 To n, 1 To n)
Dim As UInteger magic_sum = n * (n ^ 2 +1) \ 2
Dim As UInteger q = n \ 4
Dim As UInteger x, y, nr = 1
Dim As String frmt = String(Len(Str(n * n)) +1, "#")
' set up the square
For y = 1 To n
For x = q +1 To n - q
sq(x,y) = 1
Next
Next
For x = 1 To n
For y = q +1 To n - q
sq(x, y) Xor= 1
Next
Next
' fill the square
q = n * n +1
For y = 1 To n
For x = 1 To n
If sq(x,y) = 0 Then
sq(x,y) = q - nr
Else
sq(x,y) = nr
End If
nr += 1
Next
Next
' check columms and rows
For y = 1 To n
nr = 0 : q = 0
For x = 1 To n
nr += sq(x,y)
q += sq(y,x)
Next
If nr <> magic_sum Or q <> magic_sum Then
Err_msg "Error: value <> magic_sum"
Exit Sub
End If
Next
' check diagonals
nr = 0 : q = 0
For x = 1 To n
nr += sq(x, x)
q += sq(n - x +1, n - x +1)
Next
If nr <> magic_sum Or q <> magic_sum Then
Err_msg "Error: value <> magic_sum"
Exit Sub
End If
' printing square's on screen bigger when
' n > 19 results in a wrapping of the line
Print "Single even magic square size: "; n; "*"; n
Print "The magic sum = "; magic_sum
Print
For y = 1 To n
For x = 1 To n
Print Using frmt; sq(x, y);
Next
Print
Next
' output magic square to a file with the name provided
If filename <> "" Then
nr = FreeFile
Open filename For Output As #nr
Print #nr, "Single even magic square size: "; n; "*"; n
Print #nr, "The magic sum = "; magic_sum
Print #nr,
For y = 1 To n
For x = 1 To n
Print #nr, Using frmt; sq(x,y);
Next
Print #nr,
Next
Close #nr
End If
End Sub
' ------=< MAIN >=------
de_magicsq(8, "magic8de.txt") : Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #EchoLisp | EchoLisp |
;; copied from Scheme
(define (A k x1 x2 x3 x4 x5)
(define (B)
(set! k (- k 1))
(A k B x1 x2 x3 x4))
(if (<= k 0)
(+ (x4) (x5))
(B)))
(A 10 (lambda () 1) (lambda () -1) (lambda () -1) (lambda () 1) (lambda () 0))
→ -67
(A 13 (lambda () 1) (lambda () -1) (lambda () -1) (lambda () 1) (lambda () 0))
→ -642
(A 14 ..)
❗ InternalError : too much recursion - JS internal error (please, report it)-
→ stack overflow using FireFox
|
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #X86_Assembly | X86 Assembly | .386
.model flat
.code
_gost32 proc near32
public _gost32
; The inner loop of a subroutine
; 1. Beginning of the cycle, and preservation of the old N1
iloop: mov EBP,EAX
; 2. Adding to the S key modulo 2^32
add EAX,[ESI] ; add the key
add ESI,4 ; the next element of the key.
; 3. Block-replace in the rotation of S by 8 bits to the left
REPT 3
xlat ; recoding byte
ror EAX,8 ; AL <- next byte
add EBX,100h; next node changes
ENDM
xlat ; recoding byte
sub EBX,300h; BX -> 1st node changes
; 4. Complete rotation of the S at 3 bits to the left
rol EAX,3
; 5. The calculation of the new values of N1,N2
xor EAX,EDX
mov EDX,EBP
; The completion of the inner loop
loop iloop
ret
_gost32 endp
end |
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #Wren | Wren | import "/fmt" for Fmt
class GOST {
// assumes 's' is an 8 x 16 integer array
construct new(s) {
_k87 = List.filled(256, 0)
_k65 = List.filled(256, 0)
_k43 = List.filled(256, 0)
_k21 = List.filled(256, 0)
_enc = List.filled(8, 0)
for (i in 0..255) {
_k87[i] = s[7][i>>4]<<4 | s[6][i&15]
_k65[i] = s[5][i>>4]<<4 | s[4][i&15]
_k43[i] = s[3][i>>4]<<4 | s[2][i&15]
_k21[i] = s[1][i>>4]<<4 | s[0][i&15]
}
}
enc { _enc }
f(x) {
x = _k87[x>>24&255]<<24 | _k65[x>>16&255]<<16 | _k43[x>>8&255]<<8 | _k21[x&255]
return x<<11 | x>>(32-11)
}
mainStep(input, key) {
var key32 = GOST.u32(key)
var input1 = GOST.u32(input[0...4])
var input2 = GOST.u32(input[4..-1])
GOST.b4(f(key32+input1)^input2, enc)
for (i in 0..3) enc[i + 4] = input[i]
}
static u32(b) { b[0] | b[1]<<8 | b[2]<<16 | b[3]<<24 }
static b4(u, b) {
b[0] = u & 0xff
b[1] = (u >> 8) & 0xff
b[2] = (u >> 16) & 0xff
b[3] = (u >> 24) & 0xff
}
}
var cbrf = [
[ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
[ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
[ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
[13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
[ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]
]
var input = [0x21, 0x04, 0x3b, 0x04, 0x30, 0x04, 0x32, 0x04]
var key = [0xf9, 0x04, 0xc1, 0xe2]
var g = GOST.new(cbrf)
g.mainStep(input, key)
for (b in g.enc) System.write("[%(Fmt.xz(2, b))]")
System.print() |
http://rosettacode.org/wiki/Magnanimous_numbers | Magnanimous numbers | A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.
E.G.
6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.
Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).
There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.
Task
Write a routine (procedure, function, whatever) to find magnanimous numbers.
Use that function to find and display, here on this page the first 45 magnanimous numbers.
Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers
See also
OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.
| #REXX | REXX | /*REXX pgm finds/displays magnanimous #s (#s with a inserted + sign to sum to a prime).*/
parse arg bet.1 bet.2 bet.3 highP . /*obtain optional arguments from the CL*/
if bet.1=='' | bet.1=="," then bet.1= 1..45 /* " " " " " " */
if bet.2=='' | bet.2=="," then bet.2= 241..250 /* " " " " " " */
if bet.3=='' | bet.3=="," then bet.3= 391..400 /* " " " " " " */
if highP=='' | highP=="," then highP= 1000000 /* " " " " " " */
call genP /*gen primes up to highP (1 million).*/
do j=1 for 3 /*process three magnanimous "ranges". */
parse var bet.j LO '..' HI /*obtain the first range (if any). */
if HI=='' then HI= LO /*Just a single number? Then use LO. */
if HI==0 then iterate /*Is HI a zero? Then skip this range.*/
finds= 0; $= /*#: magnanimous # cnt; $: is a list*/
do k=0 until finds==HI /* [↓] traipse through the number(s). */
if \magna(k) then iterate /*Not magnanimous? Then skip this num.*/
finds= finds + 1 /*bump the magnanimous number count. */
if finds>=LO then $= $ k /*In range► Then add number ──► $ list*/
end /*k*/
say
say center(' 'LO "──►" HI 'magnanimous numbers ', 126, "─")
say strip($)
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
magna: procedure expose @. !.; parse arg x 1 L 2 '' -1 R /*obtain #, 1st & last digit.*/
len= length(x); if len==1 then return 1 /*one digit #s are magnanimous*/
if x>1001 then if L//2 == R//2 then return 0 /*Has parity? Not magnanimous*/
do s= 1 for len-1 /*traipse thru #, inserting + */
parse var x y +(s) z; sum= y + z /*parse 2 parts of #, sum 'em.*/
if !.sum then iterate /*Is sum prime? So far so good*/
else return 0 /*Nope? Then not magnanimous.*/
end /*s*/
return 1 /*Pass all the tests, it's magnanimous.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*assign low primes; # primes.*/
!.= 0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1 /* " semaphores to " */
#= 6; sq.#= @.# ** 2 /*# primes so far; P squared.*/
do j=@.#+4 by 2 to highP; parse var j '' -1 _; if _==5 then iterate /*÷ by 5?*/
if j// 3==0 then iterate; if j// 7==0 then iterate /*÷ by 3?; ÷ by 7?*/
if j//11==0 then iterate /*" " 11? " " 13?*/
do k=6 while sq.k<=j /*divide by some generated odd primes. */
if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/
end /*k*/ /* [↓] a prime (J) has been found. */
#= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump #Ps; P──►@.assign P; P^2; P flag*/
end /*j*/; return |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #C | C | #include <stdio.h>
void transpose(void *dest, void *src, int src_h, int src_w)
{
int i, j;
double (*d)[src_h] = dest, (*s)[src_w] = src;
for (i = 0; i < src_h; i++)
for (j = 0; j < src_w; j++)
d[j][i] = s[i][j];
}
int main()
{
int i, j;
double a[3][5] = {{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 1, 0, 0, 0, 42}};
double b[5][3];
transpose(b, a, 3, 5);
for (i = 0; i < 5; i++)
for (j = 0; j < 3; j++)
printf("%g%c", b[i][j], j == 2 ? '\n' : ' ');
return 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.
| #Erlang | Erlang |
-module( maze ).
-export( [cell_accessible_neighbours/1, cell_content/1, cell_content_set/2, cell_pid/3, cell_position/1, display/1, generation/2, stop/1, task/0] ).
-record( maze, {dict, max_x, max_y, start} ).
-record( state, {content=" ", controller, is_dug=false, max_x, max_y, neighbours=[], position, walls=[north, south, east, west], walk_done} ).
cell_accessible_neighbours( Pid ) -> read( Pid, accessible_neighbours ).
cell_content( Pid ) -> read( Pid, content ).
cell_content_set( Pid, Content ) -> Pid ! {content, Content, erlang:self()}.
cell_pid( X, Y, Maze ) -> dict:fetch( {X, Y}, Maze#maze.dict ).
cell_position( Pid ) -> read( Pid, position ).
display( #maze{dict=Dict, max_x=Max_x, max_y=Max_y} ) ->
Position_pids = dict:to_list( Dict ),
display( Max_x, Max_y, reads(Position_pids, content), reads(Position_pids, walls) ).
generation( Max_x, Max_y ) ->
Controller = erlang:self(),
Position_pids = cells_create( Controller, Max_x, Max_y ),
Pids = [Y || {_X, Y} <- Position_pids],
[X ! {position_pids, Position_pids} || X <- Pids],
{Position, Pid} = lists:nth( random:uniform(Max_x * Max_y), Position_pids ),
Pid ! {dig, Controller},
receive
{dig_done} -> ok
end,
#maze{dict=dict:from_list(Position_pids), max_x=Max_x, max_y=Max_y, start=Position}.
stop( #maze{dict=Dict} ) ->
Controller = erlang:self(),
Pids = [Y || {_X, Y} <- dict:to_list(Dict)],
[X ! {stop, Controller} || X <- Pids],
ok.
task() ->
Maze = generation( 16, 8 ),
io:fwrite( "Starting at ~p~n", [Maze#maze.start] ),
display( Maze ),
stop( Maze ).
cells_create( Controller, Max_x, Max_y ) -> [{{X, Y}, cell_create(Controller, Max_x, Max_y, {X, Y})} || X <- lists:seq(1, Max_x), Y<- lists:seq(1, Max_y)].
cell_create( Controller, Max_x, Max_y, {X, Y} ) -> erlang:spawn_link( fun() -> random:seed( X*1000, Y*1000, (X+Y)*1000 ), loop( #state{controller=Controller, max_x=Max_x, max_y=Max_y, position={X, Y}} ) end ).
display( Max_x, Max_y, Position_contents, Position_walls ) ->
All_rows = [display_row( Max_x, Y, Position_contents, Position_walls ) || Y <- lists:seq(Max_y, 1, -1)],
[io:fwrite("~s+~n~s|~n", [North, West]) || {North, West} <- All_rows],
io:fwrite("~s+~n", [lists:flatten(lists:duplicate(Max_x, display_row_north(true)))] ).
display_row( Max_x, Y, Position_contents, Position_walls ) ->
North_wests = [display_row_walls(proplists:get_value({X,Y}, Position_contents), proplists:get_value({X,Y}, Position_walls)) || X <- lists:seq(1, Max_x)],
North = lists:append( [North || {North, _West} <- North_wests] ),
West = lists:append( [West || {_X, West} <- North_wests] ),
{North, West}.
display_row_walls( Content, Walls ) -> {display_row_north( lists:member(north, Walls) ), display_row_west( lists:member(west, Walls), Content )}.
display_row_north( true ) -> "+---";
display_row_north( false ) -> "+ ".
display_row_west( true, Content ) -> "| " ++ Content ++ " ";
display_row_west( false, Content ) -> " " ++ Content ++ " ".
loop( State ) ->
receive
{accessible_neighbours, Pid} ->
Pid ! {accessible_neighbours, loop_accessible_neighbours( State#state.neighbours, State#state.walls ), erlang:self()},
loop( State );
{content, Pid} ->
Pid ! {content, State#state.content, erlang:self()},
loop( State );
{content, Content, _Pid} ->
loop( State#state{content=Content} );
{dig, Pid} ->
Not_dug_neighbours = loop_not_dug( State#state.neighbours ),
New_walls = loop_dig( Not_dug_neighbours, lists:delete( loop_wall_from_pid(Pid, State#state.neighbours), State#state.walls), Pid ),
loop( State#state{is_dug=true, walls=New_walls, walk_done=Pid} );
{dig_done} ->
Not_dug_neighbours = loop_not_dug( State#state.neighbours ),
New_walls = loop_dig( Not_dug_neighbours, State#state.walls, State#state.walk_done ),
loop( State#state{walls=New_walls} );
{is_dug, Pid} ->
Pid ! {is_dug, State#state.is_dug, erlang:self()},
loop( State );
{position, Pid} ->
Pid ! {position, State#state.position, erlang:self()},
loop( State );
{position_pids, Position_pids} ->
{_My_position, Neighbours} = lists:foldl( fun loop_neighbours/2, {State#state.position, []}, Position_pids ),
erlang:garbage_collect(), % Shrink process after using large Pid_positions. For memory starved systems.
loop( State#state{neighbours=Neighbours} );
{stop, Controller} when Controller =:= State#state.controller ->
ok;
{walls, Pid} ->
Pid ! {walls, State#state.walls, erlang:self()},
loop( State )
end.
loop_accessible_neighbours( Neighbours, Walls ) -> [Pid || {Direction, Pid} <- Neighbours, not lists:member(Direction, Walls)].
loop_dig( [], Walls, Pid ) ->
Pid ! {dig_done},
Walls;
loop_dig( Not_dug_neighbours, Walls, _Pid ) ->
{Dig_pid, Dig_direction} = lists:nth( random:uniform(erlang:length(Not_dug_neighbours)), Not_dug_neighbours ),
Dig_pid ! {dig, erlang:self()},
lists:delete( Dig_direction, Walls ).
loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y + 1 -> {{X, My_y}, [{north, Pid} | Acc]};
loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y - 1 -> {{X, My_y}, [{south, Pid} | Acc]};
loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x + 1 -> {{My_x, Y}, [{east, Pid} | Acc]};
loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x - 1 -> {{My_x, Y}, [{west, Pid} | Acc]};
loop_neighbours( _Position_pid, Acc ) -> Acc.
loop_not_dug( Neighbours ) ->
My_pid = erlang:self(),
[Pid ! {is_dug, My_pid} || {_Direction, Pid} <- Neighbours],
[{Pid, Direction} || {Direction, Pid} <- Neighbours, not read_receive(Pid, is_dug)].
loop_wall_from_pid( Pid, Neighbours ) -> loop_wall_from_pid_result( lists:keyfind(Pid, 2, Neighbours) ).
loop_wall_from_pid_result( {Direction, _Pid} ) -> Direction;
loop_wall_from_pid_result( false ) -> controller.
read( Pid, Key ) ->
Pid ! {Key, erlang:self()},
read_receive( Pid, Key ).
read_receive( Pid, Key ) ->
receive
{Key, Value, Pid} -> Value
end.
reads( Position_pids, Key ) ->
My_pid = erlang:self(),
[Pid ! {Key, My_pid} || {_Position, Pid} <- Position_pids],
[{Position, read_receive(Pid, Key)} || {Position, Pid} <- Position_pids].
|
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Octave | Octave | M = [ 3, 2; 2, 1 ];
M^0
M^1
M^2
M^(-1)
M^0.5 |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #PARI.2FGP | PARI/GP | M^n |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #ERRE | ERRE | PROGRAM RANGE
BEGIN
AL=0 AH=10
BL=-1 BH=0
FOR N=0 TO 10 DO
RANGE=BL+(N-AL)*(BH-BL)/(AH-AL)
WRITE("### maps to ##.##";N;RANGE)
! PRINT(N;" maps to ";RANGE)
END FOR
END PROGRAM
|
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.
| #Euphoria | Euphoria | function map_range(sequence a, sequence b, atom s)
return b[1]+(s-a[1])*(b[2]-b[1])/(a[2]-a[1])
end function
for i = 0 to 10 do
printf(1, "%2g maps to %4g\n", {i, map_range({0,10},{-1,0},i)})
end for |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Swift | Swift | enum errors: Error {
//Occurs when a start or end position is given that is outside of bounds
case IndexOutsideMazeBoundary
}
///Used to solve any maze generated by the swift implementation of maze generator at:
///https://www.rosettacode.org/wiki/Maze_generation#Swift
class MazeSolver {
///your starting index position in the maze
var startPos: (Int, Int)
/// the end index position you are trying to reach within the maze
var endPos: (Int, Int)
/// a maze of [[INT]] where each value is between 1 and 14.
/// each number representing a
var maze: [[Int]]
var visitedSpaces: [(Int, Int)]
init(maze: [[Int]]) {
self.startPos = (0, 0)
self.endPos = (0, 0)
/// a maze that consists of a array of ints from 1-14 organized to
/// create a maze like structure.
/// Each number represents where the walls and paths will be
/// ex. 2 only has a path south and 12 has paths E or W
self.maze = maze
/// spaces each branch has visited to stop from searching previously explored
/// areas of the maze
self.visitedSpaces = []
}
/// determine if the user has previously visited the given location within the maze
func visited(position: (Int, Int)) -> Bool {
return visitedSpaces.contains(where: {$0 == position})
}
/// used to translate the mazes number scheme to a list of directions available
/// for each number. DirectionDiff for N would be (0, -1) for example
func getDirections(positionValue: Int) -> [(Int, Int)] {
switch positionValue {
case 1:
return [Direction.north.diff]
case 2:
return [Direction.south.diff]
case 3:
return [Direction.north.diff, Direction.south.diff]
case 4:
return [Direction.east.diff]
case 5:
return [Direction.north.diff, Direction.east.diff]
case 6:
return [Direction.south.diff, Direction.east.diff]
case 7:
return [Direction.north.diff, Direction.east.diff, Direction.south.diff]
case 8:
return [Direction.west.diff]
case 9:
return [Direction.north.diff, Direction.west.diff]
case 10:
return [Direction.west.diff, Direction.south.diff]
case 11:
return [Direction.north.diff, Direction.south.diff, Direction.west.diff]
case 12:
return [Direction.west.diff, Direction.east.diff]
case 13:
return [Direction.north.diff, Direction.east.diff, Direction.west.diff]
case 14:
return [Direction.east.diff, Direction.south.diff, Direction.west.diff]
default:
return []
}
}
/// calculate and return all paths branching from the current position that haven't been explored yet
func availablePaths(currentPosition: (Int, Int), lastPos: (Int, Int)) -> [(Int, Int)] {
/// all available paths to be returned
var paths: [(Int, Int)] = []
/// the maze contents at the given position (ie the maze number)
let positionValue = maze[currentPosition.0][ currentPosition.1]
/// used to build the new path positions and check them before they
/// are added to paths
var workingPos: (Int, Int)
// is the maze at a dead end and not our first position
if ([1, 2, 4, 8].contains(positionValue) && currentPosition != lastPos) {
return []
}
/// the directions available based on the maze contents of our
/// current position
let directions: [(Int, Int)] = getDirections(positionValue: positionValue)
/// build the paths
for pos in directions {
workingPos = (currentPosition.0 + pos.0, currentPosition.1 + pos.1)
if (currentPosition == lastPos || (workingPos != lastPos && !visited(position: workingPos))) {
paths.append(workingPos)
}
}
return paths
}
/// prints a model of the maze with
/// O representing the start point
/// X representing the end point
/// * representing traveled space
/// NOTE: starting pos and end pos represent indexes and thus start at 0
func solveAndDisplay(startPos: (Int, Int), endPos: (Int, Int)) throws {
if (startPos.0 >= maze.count || startPos.1 >= maze[0].count) {
throw errors.IndexOutsideMazeBoundary
}
/// the position you are beginning at in the maze
self.startPos = startPos
/// the position you wish to get to within the maze
self.endPos = endPos
/// spaces each branch has visited to stop from searching previously explored
/// areas of the maze
self.visitedSpaces = []
self.displaySolvedMaze(finalPath: solveMaze(startpos: startPos, pathSoFar: [])!)
}
/// recursively solves our maze
private func solveMaze(startpos: (Int, Int), pathSoFar: [(Int, Int)]) -> [(Int, Int)]? {
/// marks our current position in the maze
var currentPos: (Int, Int) = startpos
/// saves the spaces visited on this current branch
var currVisitedSpaces : [(Int, Int)] = [startpos]
/// the final path (or the path so far if the end pos has not been reached)
/// from the start position to the end position
var finalPath: [(Int, Int)] = pathSoFar
/// all possible paths from our current position that have not been explored
var possiblePaths: [(Int, Int)] = availablePaths(currentPosition: startpos, lastPos: pathSoFar.last ?? startpos)
// move through the maze until you come to a position that has been explored, the end position, or a dead end (the
// possible paths array is empty)
while (!possiblePaths.isEmpty) {
// found the final path
guard (currentPos != self.endPos) else {
finalPath.append(contentsOf: currVisitedSpaces)
return finalPath
}
// multiple valid paths from current position found
// recursively call new branches for each valid path
if (possiblePaths.count > 1) {
visitedSpaces.append(contentsOf: currVisitedSpaces)
finalPath.append(contentsOf: currVisitedSpaces)
// for each valid path recursively call each path
// and if it contains the final path
// ie it found the endpoint, return that path
for pos in possiblePaths {
let path = solveMaze(startpos: pos, pathSoFar: finalPath)
if (path != nil) {
return path
}
}
// otherwise this branch and it's sub-branches
// are dead-ends so kill this branch
return nil
}
// continue moving along the only path available
else {
// update current path to our only available next
// position
currentPos = possiblePaths[0]
// calculate the available paths from our new
// current position
possiblePaths = availablePaths(currentPosition: currentPos, lastPos: currVisitedSpaces.last ?? currentPos)
// update the visited spaces for this branch
currVisitedSpaces.append(currentPos)
}
}
// if our new current position is the endpos return our final path
if (currentPos == self.endPos) {
finalPath.append(contentsOf: currVisitedSpaces)
return finalPath
}
else {
return nil
}
}
// Reference: https://www.rosettacode.org/wiki/Maze_generation#Swift
// adapts the display method used in the swift implementation of the maze generator we used for this app to display the maze
// solved
func displaySolvedMaze(finalPath: [(Int, Int)]) {
/// all cells are 3 wide in the x axis
let cellWidth = 3
for j in 0..<y {
// Draw top edge
// if mark corner with +, add either (cell width) spaces or - to the topedge var dependin on if it is a wall or not
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
//through the center of the cell if is a wall add | if not a space
// then if it is travelled add " * " otherwise just 3 spaces then
//cap it with a | at the end for the right most wall
var leftEdge = ""
for i in 0..<x {
leftEdge += (maze[i][j] & Direction.west.rawValue) == 0 ? "|" : " "
if (finalPath.first! == (i, j)) {
leftEdge += " O "
}
else if (finalPath.last! == (i, j)) {
leftEdge += " X "
}
else {
if (finalPath.contains(where: {$0 == (i, j)})) {
leftEdge += " * "
}
else {
leftEdge += String(repeating: " ", count: cellWidth)
}
}
}
leftEdge += "|"
print(leftEdge)
}
// Draw bottom edge
// adds + on corners and _ everywhere else
var bottomEdge = ""
for _ in 0..<x {
bottomEdge += "+"
bottomEdge += String(repeating: "-", count: cellWidth)
}
bottomEdge += "+"
print(bottomEdge)
}
}
|
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
Task
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| #PicoLisp | PicoLisp | (de maxpath (Lst)
(let (Lst (reverse Lst) R (car Lst))
(for I (cdr Lst)
(setq R
(mapcar
+
(maplist
'((L)
(and (cdr L) (max (car L) (cadr L))) )
R )
I ) ) )
(car R) ) ) |
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.
| #Java | Java | import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Digester {
public static void main(String[] args) {
System.out.println(hexDigest("Rosetta code", "MD5"));
}
static String hexDigest(String str, String digestName) {
try {
MessageDigest md = MessageDigest.getInstance(digestName);
byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
char[] hex = new char[digest.length * 2];
for (int i = 0; i < digest.length; i++) {
hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4);
hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f);
}
return new String(hex);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
} |
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.