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/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.
| #AWK | AWK |
# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
BEGIN {
for (i=1; i<=ARGC-1; i++) {
path = ARGV[i]
msg = (make_dir_path(path) == 0) ? "created" : "exists"
printf("'%s' %s\n",path,msg)
}
exit(0)
}
function make_dir_path(path, cmd) {
# cmd = sprintf("mkdir -p '%s'",path) # Unix
cmd = sprintf("MKDIR \"%s\" 2>NUL",path) # MS-Windows
return system(cmd)
}
|
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
int main (int argc, char **argv) {
char *str, *s;
struct stat statBuf;
if (argc != 2) {
fprintf (stderr, "usage: %s <path>\n", basename (argv[0]));
exit (1);
}
s = argv[1];
while ((str = strtok (s, "/")) != NULL) {
if (str != s) {
str[-1] = '/';
}
if (stat (argv[1], &statBuf) == -1) {
mkdir (argv[1], 0);
} else {
if (! S_ISDIR (statBuf.st_mode)) {
fprintf (stderr, "couldn't create directory %s\n", argv[1]);
exit (1);
}
}
s = NULL;
}
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Man_Or_Boy is
function Zero return Integer is begin return 0; end Zero;
function One return Integer is begin return 1; end One;
function Neg return Integer is begin return -1; end Neg;
function A
( K : Integer;
X1, X2, X3, X4, X5 : access function return Integer
) return Integer is
M : Integer := K; -- K is read-only in Ada. Here is a mutable copy of
function B return Integer is
begin
M := M - 1;
return A (M, B'Access, X1, X2, X3, X4);
end B;
begin
if M <= 0 then
return X4.all + X5.all;
else
return B;
end if;
end A;
begin
Put_Line
( Integer'Image
( A
( 10,
One'Access, -- Returns 1
Neg'Access, -- Returns -1
Neg'Access, -- Returns -1
One'Access, -- Returns 1
Zero'Access -- Returns 0
) ) );
end Man_Or_Boy; |
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.
| #BBC_BASIC | BBC BASIC | DIM table&(7,15), test%(1)
table&() = 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
test%() = &043B0421, &04320430
key% = &E2C104F9
PROCmainstep(test%(), key%, table&())
PRINT ~ test%(0) test%(1)
END
DEF PROCmainstep(n%(), key%, t&())
LOCAL i%, s%, cell&, new_s%
s% = FN32(n%(0) + key%)
FOR i% = 0 TO 3
cell& = (s% >>> (i%*8)) AND &FF
new_s% += (t&(i%*2,cell& MOD 16) + 16*t&(i%*2+1,cell& DIV 16)) << (i%*8)
NEXT
s% = ((new_s% << 11) OR (new_s% >>> 21)) EOR n%(1)
n%(1) = n%(0) : n%(0) = s%
ENDPROC
DEF FN32(v)
WHILE v>&7FFFFFFF : v-=2^32 : ENDWHILE
WHILE v<&80000000 : v+=2^32 : ENDWHILE
= v |
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.
| #ALGOL_68 | ALGOL 68 | BEGIN # find some magnanimous numbers - numbers where inserting a + between any #
# digits ab=nd evaluatinf the sum results in a prime in all cases #
# returns the first n magnanimous numbers #
# uses global sieve prime which must include 0 and be large enough #
# for all possible sub-sequences of digits #
OP MAGNANIMOUS = ( INT n )[]INT:
BEGIN
[ 1 : n ]INT result;
INT m count := 0;
FOR i FROM 0 WHILE m count < n DO
# split the number into pairs of digit seuences and check the sums of the pairs are all prime #
INT divisor := 1;
BOOL all prime := TRUE;
WHILE divisor *:= 10;
IF INT front = i OVER divisor;
front = 0
THEN FALSE
ELSE all prime := prime[ front + ( i MOD divisor ) ]
FI
DO SKIP OD;
IF all prime THEN result[ m count +:= 1 ] := i FI
OD;
result
END; # MAGNANIMPUS #
# prints part of a seuence of magnanimous numbers #
PROC print magnanimous = ( []INT m, INT first, INT last, STRING legend )VOID:
BEGIN
print( ( legend, ":", newline ) );
FOR i FROM first TO last DO print( ( " ", whole( m[ i ], 0 ) ) ) OD;
print( ( newline ) )
END ; # print magnanimous #
# we assume the first 400 magnanimous numbers will be in 0 .. 1 000 000 #
# so we will need a sieve of 0 up to 99 999 + 9 #
[ 0 : 99 999 + 9 ]BOOL prime;
prime[ 0 ] := prime[ 1 ] := FALSE; prime[ 2 ] := TRUE;
FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD;
FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
IF prime[ i ] THEN FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD FI
OD;
# construct the sequence of magnanimous numbers #
[]INT m = MAGNANIMOUS 400;
print magnanimous( m, 1, 45, "First 45 magnanimous numbers" );
print magnanimous( m, 241, 250, "Magnanimous numbers 241-250" );
print magnanimous( m, 391, 400, "Magnanimous numbers 391-400" )
END |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #ActionScript | ActionScript | function transpose( m:Array):Array
{
//Assume each element in m is an array. (If this were production code, use typeof to be sure)
//Each element in m is a row, so this gets the length of a row in m,
//which is the same as the number of rows in m transpose.
var mTranspose = new Array(m[0].length);
for(var i:uint = 0; i < mTranspose.length; i++)
{
//create a row
mTranspose[i] = new Array(m.length);
//set the row to the appropriate values
for(var j:uint = 0; j < mTranspose[i].length; j++)
mTranspose[i][j] = m[j][i];
}
return mTranspose;
}
var m:Array = [[1, 2, 3, 10],
[4, 5, 6, 11],
[7, 8, 9, 12]];
var M:Array = transpose(m);
for(var i:uint = 0; i < M.length; i++)
trace(M[i]); |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #Befunge | Befunge | 45*28*10p00p020p030p006p0>20g30g00g*+::"P"%\"P"/6+gv>$\1v@v1::\+g02+*g00+g03-\<
0_ 1!%4+1\-\0!::\-\2%2:p<pv0<< v0p+6/"P"\%"P":\+4%4<^<v-<$>+2%\1-*20g+\1+4%::v^
#| +2%\1-*30g+\1\40g1-:v0+v2?1#<v>+:00g%!55+*>:#0>#,_^>:!|>\#%"P"v#:*+*g00g0<>1
02!:++`\0\`-1g01:\+`\< !46v3<^$$<^1,g2+1%2/2,g1+1<v%g00:\<*g01,<>:30p\:20p:v^3g
0#$g#<1#<-#<`#<\#<0#<^#_^/>#1+#4<>"P"%\"P"/6+g:2%^!>,1-:#v_$55+^|$$ "JH" $$>#<0
::"P"%\"P"/6+g40p\40g+\:#^"P"%#\<^ ::$_,#!0#:<*"|"<^," _"<:g000 <> /6+g4/2%+#^_
|
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.
| #FreeBASIC | FreeBASIC | #include once "matmult.bas"
#include once "rowech.bas"
#include once "matinv.bas"
operator ^ (byval M as Matrix, byval n as integer ) as Matrix
dim as uinteger i, j, k = ubound( M.m, 1 )
if n < 0 then return matinv(M) ^ (-n)
if n = 0 then return M * matinv(M)
return (M ^ (n-1)) * M
end operator
dim as Matrix M = Matrix(2,2), Q
dim as integer i, j, n
M.m(0,0) = 1./3 : M.m(0,1) = 2./3
M.m(1,0) = 2./7 : M.m(1,1) = 5./7
for n = -2 to 4
Q = (M ^ n)
for i = 0 to 1
for j = 0 to 1
print Q.m(i, j),
next j
print
next i
print
next 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.
| #AppleScript | AppleScript | ------------------------ MAP RANGE -----------------------
-- rangeMap :: (Num, Num) -> (Num, Num) -> Num -> Num
on rangeMap(a, b)
script
on |λ|(s)
set {a1, a2} to a
set {b1, b2} to b
b1 + ((s - a1) * (b2 - b1)) / (a2 - a1)
end |λ|
end script
end rangeMap
--------------------------- TEST -------------------------
on run
set mapping to rangeMap({0, 10}, {-1, 0})
set xs to enumFromTo(0, 10)
set ys to map(mapping, xs)
set zs to map(approxRatio(0), ys)
unlines(zipWith3(formatted, xs, ys, zs))
end run
------------------------- DISPLAY ------------------------
-- formatted :: Int -> Float -> Ratio -> String
on formatted(x, m, r)
set fract to showRatio(r)
set {n, d} to splitOn("/", fract)
(justifyRight(2, space, x as string) & " -> " & ¬
justifyRight(4, space, m as string)) & " = " & ¬
justifyRight(2, space, n) & "/" & d
end formatted
-------------------- GENERIC FUNCTIONS -------------------
-- Absolute value.
-- abs :: Num -> Num
on abs(x)
if 0 > x then
-x
else
x
end if
end abs
-- approxRatio :: Real -> Real -> Ratio
on approxRatio(epsilon)
script
on |λ|(n)
if {real, integer} contains (class of epsilon) and 0 < epsilon then
set e to epsilon
else
set e to 1 / 10000
end if
script gcde
on |λ|(e, x, y)
script _gcd
on |λ|(a, b)
if b < e then
a
else
|λ|(b, a mod b)
end if
end |λ|
end script
|λ|(abs(x), abs(y)) of _gcd
end |λ|
end script
set c to |λ|(e, 1, n) of gcde
ratio((n div c), (1 div c))
end |λ|
end script
end approxRatio
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- gcd :: Int -> Int -> Int
on gcd(a, b)
set x to abs(a)
set y to abs(b)
repeat until y = 0
if x > y then
set x to x - y
else
set y to y - x
end if
end repeat
return x
end gcd
-- justifyLeft :: Int -> Char -> String -> String
on justifyLeft(n, cFiller, strText)
if n > length of strText then
text 1 thru n of (strText & replicate(n, cFiller))
else
strText
end if
end justifyLeft
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- minimum :: Ord a => [a] -> a
on minimum(xs)
set lng to length of xs
if lng < 1 then return missing value
set m to item 1 of xs
repeat with x in xs
set v to contents of x
if v < m then set m to v
end repeat
return m
end minimum
-- ratio :: Int -> Int -> Ratio Int
on ratio(x, y)
script go
on |λ|(x, y)
if 0 ≠ y then
if 0 ≠ x then
set d to gcd(x, y)
{type:"Ratio", n:(x div d), d:(y div d)}
else
{type:"Ratio", n:0, d:1}
end if
else
missing value
end if
end |λ|
end script
go's |λ|(x * (signum(y)), abs(y))
end ratio
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- showRatio :: Ratio -> String
on showRatio(r)
(n of r as string) & "/" & (d of r as string)
end showRatio
-- signum :: Num -> Num
on signum(x)
if x < 0 then
-1
else if x = 0 then
0
else
1
end if
end signum
-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, pat}
set xs to text items of src
set my text item delimiters to dlm
return xs
end splitOn
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to xs's |λ|()
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
on zipWith3(f, xs, ys, zs)
set lng to minimum({length of xs, length of ys, length of zs})
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys, item i of zs)
end repeat
return lst
end tell
end zipWith3 |
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.
| #Julia | Julia | using Gtk, Colors, Cairo
import Base.iterate, Base.IteratorSize, Base.IteratorEltype
const caps = [c for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
startfall() = rand() < 0.2
endfall() = rand() < 0.2
startblank() = rand() < 0.1
endblank() = rand() < 0.05
bechangingchar() = rand() < 0.03
struct RainChars chars::Vector{Char} end
Base.IteratorSize(s::RainChars) = Base.IsInfinite()
Base.IteratorEltype(s::RainChars) = Char
function Base.iterate(rain::RainChars, state = (true, false, 0))
c = '\0'
isfalling, isblank, blankcount = state
if isfalling # falling, so feed the column
if isblank
c = ' '
((blankcount += 1) > 12) && (isblank = endblank())
else
c = bechangingchar() ? '~' : rand(rain.chars)
isblank, blankcount = startblank(), 0
end
endfall() && (isfalling = false)
else
isfalling = startfall()
end
return c, (isfalling, isblank, blankcount)
end
function digitalrain()
mapwidth, mapheight, fontpointsize = 800, 450, 14
windowmaxx = div(mapwidth, Int(round(fontpointsize * 0.9)))
windowmaxy = div(mapheight, fontpointsize)
basebuffer = fill(' ', windowmaxy, windowmaxx)
bkcolor, rcolor, xcolor = colorant"black", colorant"green", colorant"limegreen"
columngenerators = [Iterators.Stateful(RainChars(caps)) for _ in 1:windowmaxx]
win = GtkWindow("Digital Rain Effect", mapwidth, mapheight) |>
(GtkFrame() |> (can = GtkCanvas()))
set_gtk_property!(can, :expand, true)
draw(can) do widget
ctx = Gtk.getgc(can)
select_font_face(ctx, "Leonardo\'s mirrorwriting", Cairo.FONT_SLANT_NORMAL,
Cairo.FONT_WEIGHT_BOLD)
set_font_size(ctx, fontpointsize)
set_source(ctx, bkcolor)
rectangle(ctx, 0, 0, mapwidth, mapheight)
fill(ctx)
set_source(ctx, rcolor)
for i in 1:size(basebuffer)[1], j in 1:size(basebuffer)[2]
move_to(ctx, j * fontpointsize * 0.9, i * fontpointsize)
c = basebuffer[i, j]
if c == '~'
set_source(ctx, xcolor)
show_text(ctx, String([rand(caps)]))
set_source(ctx, rcolor)
else
show_text(ctx, String([c]))
end
end
end
while true
for col in 1:windowmaxx
c = popfirst!(columngenerators[col])
if c != '\0'
basebuffer[2:end, col] .= basebuffer[1:end-1, col]
basebuffer[1, col] = c
end
end
draw(can)
Gtk.showall(win)
sleep(0.05)
end
end
digitalrain()
|
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.
| #Locomotive_Basic | Locomotive Basic | 10 mode 0:defint a-z:randomize time:ink 0,0:ink 1,26:ink 2,19:border 0
20 dim p(20):mm=5:dim act(mm):for i=1 to mm:act(i)=rnd*19+1:next
30 md=mm-2:dim del(md):for i=1 to md:del(i)=rnd*19+1:next
40 for i=1 to mm:x=act(i):locate x,p(x)+1:pen 1:print chr$(rnd*55+145);
50 if p(x)>0 then locate x,p(x):pen 2:print chr$(rnd*55+145);
60 p(x)=p(x)+1:if p(x)=25 then locate x,25:pen 2:print chr$(rnd*55+145);:p(x)=0:act(i)=rnd*19+1
70 next
80 for i=1 to md:x=del(i):locate x,p(x)+1:print " ";
90 p(x)=p(x)+1:if p(x)=25 then p(x)=0:del(i)=rnd*19+1
100 next
110 goto 40 |
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
| #JavaScript | JavaScript |
class Mastermind {
constructor() {
this.colorsCnt;
this.rptColors;
this.codeLen;
this.guessCnt;
this.guesses;
this.code;
this.selected;
this.game_over;
this.clear = (el) => {
while (el.hasChildNodes()) {
el.removeChild(el.firstChild);
}
};
this.colors = ["🤡", "👹", "👺", "👻", "👽", "👾", "🤖", "🐵", "🐭",
"🐸", "🎃", "🤠", "☠️", "🦄", "🦇", "🛸", "🎅", "👿", "🐲", "🦋"
];
}
newGame() {
this.selected = null;
this.guessCnt = parseInt(document.getElementById("gssCnt").value);
this.colorsCnt = parseInt(document.getElementById("clrCnt").value);
this.codeLen = parseInt(document.getElementById("codeLen").value);
if (this.codeLen > this.colorsCnt) {
document.getElementById("rptClr").selectedIndex = 1;
}
this.rptColors = document.getElementById("rptClr").value === "yes";
this.guesses = 0;
this.game_over = false;
const go = document.getElementById("gameover");
go.innerText = "";
go.style.visibility = "hidden";
this.clear(document.getElementById("code"));
this.buildPalette();
this.buildPlayField();
}
buildPalette() {
const pal = document.getElementById("palette"),
z = this.colorsCnt / 5,
h = Math.floor(z) != z ? Math.floor(z) + 1 : z;
this.clear(pal);
pal.style.height = `${44 * h + 3 * h}px`;
const clrs = [];
for (let c = 0; c < this.colorsCnt; c++) {
clrs.push(c);
const b = document.createElement("div");
b.className = "bucket";
b.clr = c;
b.innerText = this.colors[c];
b.addEventListener("click", () => {
this.palClick(b);
});
pal.appendChild(b);
}
this.code = [];
while (this.code.length < this.codeLen) {
const r = Math.floor(Math.random() * clrs.length);
this.code.push(clrs[r]);
if (!this.rptColors) {
clrs.splice(r, 1);
}
}
}
buildPlayField() {
const brd = document.getElementById("board");
this.clear(brd);
const w = 49 * this.codeLen + 7 * this.codeLen + 5;
brd.active = 0;
brd.style.width = `${w}px`;
document.querySelector(".column").style.width = `${w + 20}px`;
this.addGuessLine(brd);
}
addGuessLine(brd) {
const z = document.createElement("div");
z.style.clear = "both";
brd.appendChild(z);
brd.active += 10;
for (let c = 0; c < this.codeLen; c++) {
const d = document.createElement("div");
d.className = "bucket";
d.id = `brd${brd.active+ c}`;
d.clr = -1;
d.addEventListener("click", () => {
this.playClick(d);
})
brd.appendChild(d);
}
}
palClick(bucket) {
if (this.game_over) return;
if (null === this.selected) {
bucket.classList.add("selected");
this.selected = bucket;
return;
}
if (this.selected !== bucket) {
this.selected.classList.remove("selected");
bucket.classList.add("selected");
this.selected = bucket;
return;
}
this.selected.classList.remove("selected");
this.selected = null;
}
vibrate() {
const brd = document.getElementById("board");
let timerCnt = 0;
const exp = setInterval(() => {
if ((timerCnt++) > 60) {
clearInterval(exp);
brd.style.top = "0px";
brd.style.left = "0px";
}
let x = Math.random() * 4,
y = Math.random() * 4;
if (Math.random() < .5) x = -x;
if (Math.random() < .5) y = -y;
brd.style.top = y + "px";
brd.style.left = x + "px";
}, 10);
}
playClick(bucket) {
if (this.game_over) return;
if (this.selected) {
bucket.innerText = this.selected.innerText;
bucket.clr = this.selected.clr;
} else {
this.vibrate();
}
}
check() {
if (this.game_over) return;
let code = [];
const brd = document.getElementById("board");
for (let b = 0; b < this.codeLen; b++) {
const h = document.getElementById(`brd${brd.active + b}`).clr;
if (h < 0) {
this.vibrate();
return;
}
code.push(h);
}
this.guesses++;
if (this.compareCode(code)) {
this.gameOver(true);
return;
}
if (this.guesses >= this.guessCnt) {
this.gameOver(false);
return;
}
this.addGuessLine(brd);
}
compareCode(code) {
let black = 0,
white = 0,
b_match = new Array(this.codeLen).fill(false),
w_match = new Array(this.codeLen).fill(false);
for (let i = 0; i < this.codeLen; i++) {
if (code[i] === this.code[i]) {
b_match[i] = true;
w_match[i] = true;
black++;
}
}
for (let i = 0; i < this.codeLen; i++) {
if (b_match[i]) continue;
for (let j = 0; j < this.codeLen; j++) {
if (i == j || w_match[j]) continue;
if (code[i] === this.code[j]) {
w_match[j] = true;
white++;
break;
}
}
}
const brd = document.getElementById("board");
let d;
for (let i = 0; i < black; i++) {
d = document.createElement("div");
d.className = "pin";
d.style.backgroundColor = "#a00";
brd.appendChild(d);
}
for (let i = 0; i < white; i++) {
d = document.createElement("div");
d.className = "pin";
d.style.backgroundColor = "#eee";
brd.appendChild(d);
}
return (black == this.codeLen);
}
gameOver(win) {
if (this.game_over) return;
this.game_over = true;
const cd = document.getElementById("code");
for (let c = 0; c < this.codeLen; c++) {
const d = document.createElement("div");
d.className = "bucket";
d.innerText = this.colors[this.code[c]];
cd.appendChild(d);
}
const go = document.getElementById("gameover");
go.style.visibility = "visible";
go.innerText = win ? "GREAT!" : "YOU FAILED!";
const i = setInterval(() => {
go.style.visibility = "hidden";
clearInterval(i);
}, 3000);
}
}
const mm = new Mastermind();
document.getElementById("newGame").addEventListener("click", () => {
mm.newGame()
});
document.getElementById("giveUp").addEventListener("click", () => {
mm.gameOver();
});
document.getElementById("check").addEventListener("click", () => {
mm.check()
});
|
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[optim, aux]
optim[a_List] := Module[{u, v, n, c, r, s},
n = Length[a] - 1;
u = ConstantArray[0, {n, n}];
v = ConstantArray[\[Infinity], {n, n}];
u[[All, 1]] = -1;
v[[All, 1]] = 0;
Do[
Do[
Do[
c =
v[[i, k]] + v[[i + k, j - k]] + a[[i]] a[[i + k]] a[[i + j]];
If[c < v[[i, j]],
u[[i, j]] = k;
v[[i, j]] = c;
]
,
{k, 1, j - 1}
]
,
{i, 1, n - j + 1}
]
,
{j, 2, n}
];
r = v[[1, n]];
s = aux[u, 1, n];
{r, s}
]
aux[u_, i_, j_] := Module[{k},
k = u[[i, j]];
If[k < 0,
i
,
Inactive[Times][aux[u, i, k], aux[u, i + k, j - k]]
]
]
{r, s} = optim[{1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2}];
r
s
{r, s} = optim[{1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}];
r
s |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #MATLAB | MATLAB | function [r,s] = optim(a)
n = length(a)-1;
u = zeros(n,n);
v = ones(n,n)*inf;
u(:,1) = -1;
v(:,1) = 0;
for j = 2:n
for i = 1:n-j+1
for k = 1:j-1
c = v(i,k)+v(i+k,j-k)+a(i)*a(i+k)*a(i+j);
if c<v(i,j)
u(i,j) = k;
v(i,j) = c;
end
end
end
end
r = v(1,n);
s = aux(u,1,n);
end
function s = aux(u,i,j)
k = u(i,j);
if k<0
s = sprintf("%d",i);
else
s = sprintf("(%s*%s)",aux(u,i,k),aux(u,i+k,j-k));
end
end |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | HighlightGraph[maze, PathGraph@FindShortestPath[maze, 1, 273]] |
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.
| #J | J | padTri=: 0 ". ];._2 NB. parse triangle and (implicitly) pad with zeros
maxSum=: [: {. (+ (0 ,~ 2 >./\ ]))/ NB. find max triangle path sum |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
| #Raku | Raku | sub md4($str) {
my @buf = $str.ords;
my $buflen = @buf.elems;
my \mask = (1 +< 32) - 1;
my &f = -> $x, $y, $z { ($x +& $y) +| ($x +^ mask) +& $z }
my &g = -> $x, $y, $z { ($x +& $y) +| ($x +& $z) +| ($y +& $z) }
my &h = -> $x, $y, $z { $x +^ $y +^ $z }
my &r = -> $v, $s { (($v +< $s) +& mask) +| (($v +& mask) +> (32 - $s)) }
sub pack-le (@a) {
gather for @a -> $a,$b,$c,$d { take $d +< 24 + $c +< 16 + $b +< 8 + $a }
}
my ($a, $b, $c, $d) = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476;
my $term = False;
my $last = False;
my $off = 0;
repeat until $last {
my @block = @buf[$off..$off+63]:v; $off += 64;
my @x;
given +@block {
when 64 {
@x = pack-le @block;
}
when 56..63 {
$term = True;
@block.push(0x80);
@block.push(slip 0 xx 63 - $_);
@x = pack-le @block;
}
when 0..55 {
@block.push($term ?? 0 !! 0x80);
@block.push(slip 0 xx 55 - $_);
@x = pack-le @block;
my $bit_len = $buflen +< 3;
@x.push: $bit_len +& mask, $bit_len +> 32;
$last = True;
}
default {
die "oops";
}
}
my ($aa, $bb, $cc, $dd) = $a, $b, $c, $d;
for 0, 4, 8, 12 -> \i {
$a = r($a + f($b, $c, $d) + @x[ i+0 ], 3);
$d = r($d + f($a, $b, $c) + @x[ i+1 ], 7);
$c = r($c + f($d, $a, $b) + @x[ i+2 ], 11);
$b = r($b + f($c, $d, $a) + @x[ i+3 ], 19);
}
for 0, 1, 2, 3 -> \i {
$a = r($a + g($b, $c, $d) + @x[ i+0 ] + 0x5a827999, 3);
$d = r($d + g($a, $b, $c) + @x[ i+4 ] + 0x5a827999, 5);
$c = r($c + g($d, $a, $b) + @x[ i+8 ] + 0x5a827999, 9);
$b = r($b + g($c, $d, $a) + @x[ i+12] + 0x5a827999, 13);
}
for 0, 2, 1, 3 -> \i {
$a = r($a + h($b, $c, $d) + @x[ i+0 ] + 0x6ed9eba1, 3);
$d = r($d + h($a, $b, $c) + @x[ i+8 ] + 0x6ed9eba1, 9);
$c = r($c + h($d, $a, $b) + @x[ i+4 ] + 0x6ed9eba1, 11);
$b = r($b + h($c, $d, $a) + @x[ i+12] + 0x6ed9eba1, 15);
}
$a = ($a + $aa) +& mask;
$b = ($b + $bb) +& mask;
$c = ($c + $cc) +& mask;
$d = ($d + $dd) +& mask;
}
sub b2l($n is copy) {
my $x = 0;
for ^4 {
$x +<= 8;
$x += $n +& 0xff;
$n +>= 8;
}
$x;
}
b2l($a) +< 96 +
b2l($b) +< 64 +
b2l($c) +< 32 +
b2l($d);
}
sub MAIN {
my $str = 'Rosetta Code';
say md4($str).base(16).lc;
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Wart | Wart | def (mid3 n)
withs (digits (with outstring # itoa
(pr abs.n))
max len.digits
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2) |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Wren | Wren | import "/fmt" for Fmt
var middle3 = Fn.new { |n|
if (n < 0) n = -n
var s = "%(n)"
var c = s.count
if (c < 3) return "Minimum is 3 digits, only has %(c)."
if (c%2 == 0) return "Number of digits must be odd, %(c) is even."
if (c == 3) return s
var d = (c - 3)/2
return s[d..d+2]
}
var a = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
for (e in a) {
System.print("%(Fmt.s(9, e)) -> %(middle3.call(e))")
} |
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.
| #F.23 | F# | let md5ootb (msg: string) =
use md5 = System.Security.Cryptography.MD5.Create()
msg
|> System.Text.Encoding.ASCII.GetBytes
|> md5.ComputeHash
|> Seq.map (fun c -> c.ToString("X2"))
|> Seq.reduce ( + )
md5ootb @"The quick brown fox jumped over the lazy dog's back" |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
Task
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number n which cannot be expressed with 6x + 9y + 20z = n
where x, y and z are natural numbers).
| #Quackery | Quackery | 0 temp put
100 6 / times
[ i 6 *
100 9 / times
[ dup i 9 * +
100 20 / times
[ dup i 20 * +
dup 101 < if
[ dup bit
temp take | temp put ]
drop ]
drop ]
drop ]
-1 temp take
101 times
[ dup i bit & 0 =
if
[ nip i swap
conclude ] ]
drop dup 0 < iff
[ drop
say "There are no non-McNugget numbers below 101" ]
else
[ say "The largest non-McNugget number below 101 is "
echo ]
char . emit |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
Task
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number n which cannot be expressed with 6x + 9y + 20z = n
where x, y and z are natural numbers).
| #R | R | allInputs <- expand.grid(x = 0:(100 %/% 6), y = 0:(100 %/% 9), z = 0:(100 %/% 20))
mcNuggets <- do.call(function(x, y, z) 6 * x + 9 * y + 20 * z, allInputs) |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most significant
digit at the left). This task will be using a left─to─right (horizontal) format, mostly for familiarity and
readability, and to conserve screen space (when showing the output) on this task page.
Mayan numerals
Mayan numerals (a base─20 "digit" or glyph) are written in two orientations, this
task will be using the "vertical" format (as displayed below). Using the vertical format makes
it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.)
and hyphen (-); (however, round bullets (•) and long dashes (─)
make a better presentation on Rosetta Code).
Furthermore, each Mayan numeral (for this task) is to be displayed as a
cartouche (enclosed in a box) to make it easier to parse (read); the box may be
drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers.
Mayan numerals added to Unicode
Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018 (this corresponds with
version 11.0). But since most web browsers don't support them at this time, this Rosetta Code
task will be constructing the glyphs with "simple" characters and/or ASCII art.
The "zero" glyph
The Mayan numbering system has the concept of zero, and should be shown by a glyph that represents
an upside─down (sea) shell, or an egg. The Greek letter theta (Θ) can be
used (which more─or─less, looks like an
egg). A commercial at symbol (@) could make a poor substitute.
Mayan glyphs (constructed)
The Mayan numbering system is
a [vigesimal (base 20)] positional numeral system.
The Mayan numerals (and some random numbers) shown in the vertical format would be shown as
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙ ║ ║ ║ ║
1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║
║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙∙ ║ ║ ║ ║
2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║
║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙ ║ ║ ║ ║
3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║
║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙∙║ ║ ║ ║
4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║
║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
5──► ║ ║ 15──► ║────║ 90──► ║ ║────║
║────║ ║────║ ║∙∙∙∙║────║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║∙∙∙ ║ ║ ║ ║
║ ║ ║────║ 300──► ║────║ ║
8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╦════╗
║ ║ ║∙∙∙∙║ ║ ║ ║ ║
║ ║ ║────║ 400──► ║ ║ ║ ║
9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║
║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╩════╝
╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║
║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║
╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝
Note that the Mayan numeral 13 in horizontal format would be shown as:
╔════╗
║ ││║
║ ∙││║
13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task.
║ ∙││║
╚════╝
Other forms of cartouches (boxes) can be used for this task.
Task requirements
convert the following decimal numbers to Mayan numbers:
4,005
8,017
326,205
886,205
show a unique interesting/pretty/unusual/intriguing/odd/amusing/weird Mayan number
show all output here
Related tasks
Roman numerals/Encode ─── convert numeric values into Roman numerals
Roman numerals/Decode ─── convert Roman numerals into Arabic numbers
See also
The Wikipedia entry: [Mayan numerals]
| #Raku | Raku | ### Formatting ###
my $t-style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"';
my $c-style = '"border: solid black 2px;background-color: #fffff0;border-bottom: double 6px;'~
'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'~
'vertical-align: bottom;width: 3.25em;"';
my $joiner = '<br>';
sub display ($num, @digits) { join "\n", "\{| style=$t-style", "|+ $num", '|-', (|@digits.map: {"| style=$c-style | $_"}), '|}' }
### Logic ###
sub mayan ($int) { $int.polymod(20 xx *).reverse.map: *.polymod(5) }
my @output = <4005 8017 326205 886205 16160025 1081439556 503491211079>.map: {
display $_, .&mayan.map: { [flat '' xx 3, '●' x .[0], '───' xx .[1], ('Θ' if !.[0,1].sum)].tail(4).join: $joiner }
}
say @output.join: "\n$joiner\n";
|
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #ALGOL_68 | ALGOL 68 | MODE FIELD = LONG REAL; # field type is LONG REAL #
INT default upb:=3;
MODE VECTOR = [default upb]FIELD;
MODE MATRIX = [default upb,default upb]FIELD;
# crude exception handling #
PROC VOID raise index error := VOID: GOTO exception index error;
# define the vector/matrix operators #
OP * = (VECTOR a,b)FIELD: ( # basically the dot product #
FIELD result:=0;
IF LWB a/=LWB b OR UPB a/=UPB b THEN raise index error FI;
FOR i FROM LWB a TO UPB a DO result+:= a[i]*b[i] OD;
result
);
OP * = (VECTOR a, MATRIX b)VECTOR: ( # overload vector times matrix #
[2 LWB b:2 UPB b]FIELD result;
IF LWB a/=LWB b OR UPB a/=UPB b THEN raise index error FI;
FOR j FROM 2 LWB b TO 2 UPB b DO result[j]:=a*b[,j] OD;
result
);
# this is the task portion #
OP * = (MATRIX a, b)MATRIX: ( # overload matrix times matrix #
[LWB a:UPB a, 2 LWB b:2 UPB b]FIELD result;
IF 2 LWB a/=LWB b OR 2 UPB a/=UPB b THEN raise index error FI;
FOR k FROM LWB result TO UPB result DO result[k,]:=a[k,]*b OD;
result
);
# Some sample matrices to test #
test:(
MATRIX a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256));
MATRIX b=(( 4 , -3 , 4/3, -1/4 ), # matrix B #
(-13/3, 19/4, -7/3, 11/24),
( 3/2, -2 , 7/6, -1/4 ),
( -1/6, 1/4, -1/6, 1/24));
MATRIX prod = a * b; # actual multiplication example of A x B #
FORMAT real fmt = $g(-6,2)$; # width of 6, with no '+' sign, 2 decimals #
PROC real matrix printf= (FORMAT real fmt, MATRIX m)VOID:(
FORMAT vector fmt = $"("n(2 UPB m-1)(f(real fmt)",")f(real fmt)")"$;
FORMAT matrix fmt = $x"("n(UPB m-1)(f(vector fmt)","lxx)f(vector fmt)");"$;
# finally print the result #
printf((matrix fmt,m))
);
# finally print the result #
print(("Product of a and b: ",new line));
real matrix printf(real fmt, prod)
EXIT
exception index error:
putf(stand error, $x"Exception: index error."l$)
) |
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.
| #C.23 | C# | System.IO.Directory.CreateDirectory(path) |
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.
| #C.2B.2B | C++ |
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
if(argc != 2)
{
std::cout << "usage: mkdir <path>\n";
return -1;
}
fs::path pathToCreate(argv[1]);
if (fs::exists(pathToCreate))
return 0;
if (fs::create_directories(pathToCreate))
return 0;
else
{
std::cout << "couldn't create directory: " << pathToCreate.string() << std::endl;
return -1;
}
}
|
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.
| #Clojure | Clojure | (defn mkdirp [path]
(let [dir (java.io.File. path)]
(if (.exists dir)
true
(.mkdirs dir)))) |
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
| #Aime | Aime | integer
F(list l)
{
l[1];
}
integer
eval(list l)
{
l[0](l);
}
integer A(list);
integer
B(list l)
{
A(list(B, l[1] = l[1] - 1, l, l[-5], l[-4], l[-3], l[-2]));
}
integer
A(list l)
{
integer x;
if (l[1] < 1) {
x = eval(l[-2]) + eval(l[-1]);
} else {
x = B(l);
}
x;
}
integer
main(void)
{
list f1, f0, fn1;
l_append(f1, F);
l_append(f1, 1);
l_append(f0, F);
l_append(f0, 0);
l_append(fn1, F);
l_append(fn1, -1);
o_(A(list(B, 10, f1, fn1, fn1, f1, f0)), "\n");
0;
} |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #ALGOL_60 | ALGOL 60 | begin
real procedure A (k, x1, x2, x3, x4, x5);
value k; integer k;
real x1, x2, x3, x4, x5;
begin
real procedure B;
begin k:= k - 1;
B:= A := A (k, B, x1, x2, x3, x4)
end;
if k <= 0 then A:= x4 + x5 else B
end;
outreal (A (10, 1, -1, -1, 1, 0))
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.
| #C | C | static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 };
static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 };
static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 };
static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 };
static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 };
static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 };
static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 };
static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 };
static unsigned char k87[256];
static unsigned char k65[256];
static unsigned char k43[256];
static unsigned char k21[256];
void
kboxinit(void)
{
int i;
for (i = 0; i < 256; i++) {
k87[i] = k8[i >> 4] << 4 | k7[i & 15];
k65[i] = k6[i >> 4] << 4 | k5[i & 15];
k43[i] = k4[i >> 4] << 4 | k3[i & 15];
k21[i] = k2[i >> 4] << 4 | k1[i & 15];
}
}
static word32
f(word32 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);
} |
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.
| #ALGOL_W | ALGOL W | begin
% find some Magnanimous numbers - numbers where inserting a "+" between %
% any two of the digits and evaluating the sum results in a prime number %
% implements the sieve of Eratosthenes %
procedure sieve( logical array s ( * ); integer value n ) ;
begin
% start with everything flagged as prime %
for i := 1 until n do s( i ) := true;
% sieve out the non-primes %
s( 1 ) := false;
for i := 2 until truncate( sqrt( n ) ) do begin
if s( i ) then for p := i * i step i until n do s( p ) := false
end for_i ;
end sieve ;
% construct an array of magnanimous numbers using the isPrime sieve %
procedure findMagnanimous ( logical array magnanimous, isPrime ( * ) ) ;
begin
% 1 digit magnanimous numbers %
for i := 0 until 9 do magnanimous( i ) := true;
% initially, the other magnanimous numbers are unknown %
for i := 10 until MAGNANIMOUS_MAX do magnanimous( i ) := false;
% 2 & 3 digit magnanimous numbers %
for d1 := 1 until 9 do begin
for d2 := 0 until 9 do begin
if isPrime( d1 + d2 ) then magnanimous( ( d1 * 10 ) + d2 ) := true
end for_d2 ;
for d23 := 0 until 99 do begin
if isPrime( d1 + d23 ) then begin
integer d12, d3;
d3 := d23 rem 10;
d12 := ( d1 * 10 ) + ( d23 div 10 );
if isPrime( d12 + d3 ) then magnanimous( ( d12 * 10 ) + d3 ) := true
end if_isPrime_d1_plus_d23
end for_d23
end for_d1 ;
% 4 & 5 digit magnanimous numbers %
for d12 := 10 until 99 do begin
for d34 := 0 until 99 do begin
if isPrime( d12 + d34 ) then begin
integer d123, d4;
d123 := ( d12 * 10 ) + ( d34 div 10 );
d4 := d34 rem 10;
if isPrime( d123 + d4 ) then begin
integer d1, d234;
d1 := d12 div 10;
d234 := ( ( d12 rem 10 ) * 100 ) + d34;
if isPrime( d1 + d234 ) then magnanimous( ( d12 * 100 ) + d34 ) := true
end if_isPrime_d123_plus_d4
end if_isPrime_d12_plus_d34
end for_d34 ;
for d345 := 0 until 999 do begin
if isPrime( d12 + d345 ) then begin
integer d123, d45;
d123 := ( d12 * 10 ) + ( d345 div 100 );
d45 := d345 rem 100;
if isPrime( d123 + d45 ) then begin
integer d1234, d5;
d1234 := ( d123 * 10 ) + ( d45 div 10 );
d5 := d45 rem 10;
if isPrime( d1234 + d5 ) then begin
integer d1, d2345;
d1 := d12 div 10;
d2345 := ( ( d12 rem 10 ) * 1000 ) + d345;
if isPrime( d1 + d2345 ) then magnanimous( ( d12 * 1000 ) + d345 ) := true
end if_isPrime_d1234_plus_d5
end if_isPrime_d123_plus_d45
end if_isPrime_d12_plus_d345
end for_d234
end for_d12 ;
% find 6 digit magnanimous numbers %
for d123 := 100 until 999 do begin
for d456 := 0 until 999 do begin
if isPrime( d123 + d456 ) then begin
integer d1234, d56;
d1234 := ( d123 * 10 ) + ( d456 div 100 );
d56 := d456 rem 100;
if isPrime( d1234 + d56 ) then begin
integer d12345, d6;
d12345 := ( d1234 * 10 ) + ( d56 div 10 );
d6 := d56 rem 10;
if isPrime( d12345 + d6 ) then begin
integer d12, d3456;
d12 := d123 div 10;
d3456 := ( ( d123 rem 10 ) * 1000 ) + d456;
if isPrime( d12 + d3456 ) then begin
integer d1, d23456;
d1 := d12 div 10;
d23456 := ( ( d12 rem 10 ) * 10000 ) + d3456;
if isPrime( d1 + d23456 ) then magnanimous( ( d123 * 1000 ) + d456 ) := true
end if_isPrime_d12_plus_d3456
end if_isPrime_d12345_plus_d6
end if_isPrime_d1234_plus_d56
end if_isPrime_d123_plus_d456
end for_d456
end for_d123
end findMagnanimous ;
% we look for magnanimous numbers with up to 6 digits, so we need to %
% check for primes up to 99999 + 9 = 100008 %
integer PRIME_MAX, MAGNANIMOUS_MAX;
PRIME_MAX := 100008;
MAGNANIMOUS_MAX := 1000000;
begin
logical array magnanimous ( 0 :: MAGNANIMOUS_MAX );
logical array isPrime ( 1 :: PRIME_MAX );
integer mPos;
integer lastM;
sieve( isPrime, PRIME_MAX );
findMagnanimous( magnanimous, isPrime );
% show some of the magnanimous numbers %
lastM := mPos := 0;
i_w := 3; s_w := 1; % output formatting %
for i := 0 until MAGNANIMOUS_MAX do begin
if magnanimous( i ) then begin
mPos := mPos + 1;
lastM := i;
if mPos = 1 then begin
write( "Magnanimous numbers 1-45:" );
write( i )
end
else if mPos < 46 then begin
if mPos rem 15 = 1 then write( i )
else writeon( i )
end
else if mPos = 241 then begin
write( "Magnanimous numbers 241-250:" );
write( i )
end
else if mPos > 241 and mPos <= 250 then writeon( i )
else if mPos = 391 then begin
write( "Magnanimous numbers 391-400:" );
write( i )
end
else if mPos > 391 and mPos <= 400 then writeon( i )
end if_magnanimous_i
end for_i ;
i_w := 1; s_w := 0;
write( "Last magnanimous number found: ", mPos, " = ", lastM )
end
end. |
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.
| #AWK | AWK |
# syntax: GAWK -f MAGNANIMOUS_NUMBERS.AWK
# converted from C
BEGIN {
magnanimous(1,45)
magnanimous(241,250)
magnanimous(391,400)
exit(0)
}
function is_magnanimous(n, p,q,r) {
if (n < 10) { return(1) }
for (p=10; ; p*=10) {
q = int(n/p)
r = n % p
if (!is_prime(q+r)) { return(0) }
if (q < 10) { break }
}
return(1)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (!(n % 2)) { return(n == 2) }
if (!(n % 3)) { return(n == 3) }
while (d*d <= n) {
if (!(n % d)) { return(0) }
d += 2
if (!(n % d)) { return(0) }
d += 4
}
return(1)
}
function magnanimous(start,stop, count,i) {
printf("%d-%d:",start,stop)
for (i=0; count<stop; ++i) {
if (is_magnanimous(i)) {
if (++count >= start) {
printf(" %d",i)
}
}
}
printf("\n")
}
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Ada | Ada | with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Text_IO; use Ada.Text_IO;
procedure Matrix_Transpose is
procedure Put (X : Real_Matrix) is
type Fixed is delta 0.01 range -500.0..500.0;
begin
for I in X'Range (1) loop
for J in X'Range (2) loop
Put (Fixed'Image (Fixed (X (I, J))));
end loop;
New_Line;
end loop;
end Put;
Matrix : constant Real_Matrix :=
( (0.0, 0.1, 0.2, 0.3),
(0.4, 0.5, 0.6, 0.7),
(0.8, 0.9, 1.0, 1.1)
);
begin
Put_Line ("Before Transposition:");
Put (Matrix);
New_Line;
Put_Line ("After Transposition:");
Put (Transpose (Matrix));
end Matrix_Transpose; |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define DOUBLE_SPACE 1
#if DOUBLE_SPACE
# define SPC " "
#else
# define SPC " "
#endif
wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄";
typedef unsigned char byte;
enum { N = 1, S = 2, W = 4, E = 8, V = 16 };
byte **cell;
int w, h, avail;
#define each(i, x, y) for (i = x; i <= y; i++)
int irand(int n)
{
int r, rmax = n * (RAND_MAX / n);
while ((r = rand()) >= rmax);
return r / (RAND_MAX/n);
}
void show()
{
int i, j, c;
each(i, 0, 2 * h) {
each(j, 0, 2 * w) {
c = cell[i][j];
if (c > V) printf("\033[31m");
printf("%lc", glyph[c]);
if (c > V) printf("\033[m");
}
putchar('\n');
}
}
inline int max(int a, int b) { return a >= b ? a : b; }
inline int min(int a, int b) { return b >= a ? a : b; }
static int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}};
void walk(int x, int y)
{
int i, t, x1, y1, d[4] = { 0, 1, 2, 3 };
cell[y][x] |= V;
avail--;
for (x1 = 3; x1; x1--)
if (x1 != (y1 = irand(x1 + 1)))
i = d[x1], d[x1] = d[y1], d[y1] = i;
for (i = 0; avail && i < 4; i++) {
x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1];
if (cell[y1][x1] & V) continue;
/* break walls */
if (x1 == x) {
t = (y + y1) / 2;
cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E;
} else if (y1 == y) {
t = (x + x1)/2;
cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N;
}
walk(x1, y1);
}
}
int solve(int x, int y, int tox, int toy)
{
int i, t, x1, y1;
cell[y][x] |= V;
if (x == tox && y == toy) return 1;
each(i, 0, 3) {
x1 = x + dirs[i][0], y1 = y + dirs[i][1];
if (cell[y1][x1]) continue;
/* mark path */
if (x1 == x) {
t = (y + y1)/2;
if (cell[t][x] || !solve(x1, y1, tox, toy)) continue;
cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N;
} else if (y1 == y) {
t = (x + x1)/2;
if (cell[y][t] || !solve(x1, y1, tox, toy)) continue;
cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W;
}
return 1;
}
/* backtrack */
cell[y][x] &= ~V;
return 0;
}
void make_maze()
{
int i, j;
int h2 = 2 * h + 2, w2 = 2 * w + 2;
byte **p;
p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1);
p[1] = (byte*)(p + h2 + 2) + 1;
each(i, 2, h2) p[i] = p[i-1] + w2;
p[0] = p[h2];
cell = &p[1];
each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V;
each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V;
each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W;
each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S;
each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S;
each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E;
avail = w * h;
walk(irand(2) * 2 + 1, irand(h) * 2 + 1);
/* reset visited marker (it's also used by path finder) */
each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V;
solve(1, 1, 2 * w - 1, 2 * h - 1);
show();
}
int main(int c, char **v)
{
setlocale(LC_ALL, "");
if (c < 2 || (w = atoi(v[1])) <= 0) w = 16;
if (c < 3 || (h = atoi(v[2])) <= 0) h = 8;
make_maze();
return 0;
} |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #GAP | GAP | # Matrix exponentiation is built-in
A := [[0 , 1], [1, 1]];
PrintArray(A);
# [ [ 0, 1 ],
# [ 1, 1 ] ]
PrintArray(A^10);
# [ [ 34, 55 ],
# [ 55, 89 ] ] |
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.
| #Go | Go | package main
import "fmt"
type vector = []float64
type matrix []vector
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func identityMatrix(n int) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := 0; i < n; i++ {
ident[i] = make(vector, n)
ident[i][i] = 1
}
return ident
}
func (m matrix) pow(n int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n < 0:
panic("Negative exponents not supported")
case n == 0:
return identityMatrix(le)
case n == 1:
return m
}
pow := identityMatrix(le)
base := m
e := n
for e > 0 {
if (e & 1) == 1 {
pow = pow.mul(base)
}
e >>= 1
base = base.mul(base)
}
return pow
}
func main() {
m := matrix{{3, 2}, {2, 1}}
for i := 0; i <= 10; i++ {
fmt.Println("** Power of", i, "**")
fmt.Println(m.pow(i))
fmt.Println()
}
} |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Arturo | Arturo | getMapped: function [a,b,i][
round .to:1 b\0 + ((i - a\0) * (b\1 - b\0))/(a\1 - a\0)
]
rangeA: @[0.0 10.0]
rangeB: @[0-1.0 0.0]
loop 0..10 'x [
mapped: getMapped rangeA rangeB to :floating x
print [x "maps to" mapped]
] |
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.
| #AutoHotkey | AutoHotkey |
mapRange(a1, a2, b1, b2, s)
{
return b1 + (s-a1)*(b2-b1)/(a2-a1)
}
out := "Mapping [0,10] to [-1,0] at intervals of 1:`n"
Loop 11
out .= "f(" A_Index-1 ") = " mapRange(0,10,-1,0,A_Index-1) "`n"
MsgBox % out
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SeedRandom[1234];
ClearAll[ColorFunc]
chars = RandomSample[Flatten[CharacterRange @@@ Partition[Characters["\[CapitalAlpha]\[CapitalPi]ЀѵҊԯ\:03e2\:03efヲンⲀ⳩\[ForAll]∗℀℺⨀⫿"], 2]]];
charlen = Length[chars];
fadelength = 6;
ColorFunc[fade_] := ColorFunc[fade] = Blend[{Black, Green}, fade/fadelength]
rows = 30;
cols = 50;
n = 10;
trailpos = {RandomInteger[{1, cols}, n], RandomInteger[{1, rows}, n]} // Transpose;
trailchars = RandomInteger[{1, Length[chars]}, n];
charmap = ConstantArray[".", {rows, cols}];
fade = ConstantArray[5, {rows, cols}];
indices = MapIndexed[#2 &, fade, {2}];
Dynamic[Graphics[{txts}, PlotRange -> {{1, cols}, {1, rows}}, PlotRangePadding -> 1, Background -> Black]]
Do[
trailpos[[All, 2]] += 1;
fade = Ramp[fade - 1];
trailchars = Mod[trailchars + 1, charlen, 1];
Do[
If[trailpos[[i, 2]] >= rows,
trailpos[[i, 2]] = 1;
trailpos[[i, 1]] = RandomInteger[{1, cols}];
];
charmap[[trailpos[[i, 2]], trailpos[[i, 1]]]] =
chars[[trailchars[[i]]]];
fade[[trailpos[[i, 2]], trailpos[[i, 1]]]] = fadelength
,
{i, n}
];
txts = MapThread[If[#2 > 0, Text[Style[#1, ColorFunc[#2]], {#1, rows - #2 + 1} & @@ Reverse[#3]], {}] &, {charmap, fade, indices}, 2];
Pause[0.1]
,
{1000}
] |
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
| #Julia | Julia | using Gtk, Colors, Cairo, Graphics
struct Guess
code::Vector{Color}
guess::Vector{Color}
hint::Vector{Color}
end
function Guess(code, guess)
len = length(code)
hints = fill(colorant"gray", len) # gray default
for (i, g) in enumerate(guess), (j, c) in enumerate(code)
if g == c
if i == j
hints[i] = colorant"black"
elseif hints[i] != colorant"black"
hints[i] = colorant"white"
end
end
end
g = Guess([c for c in code], [c for c in guess], [c for c in hints])
end
tovec(guess) = [x for x in [guess.code; guess.guess; guess.hint]]
function mastermindapp()
allu(s) = length(unique(s)) == length(s)
ccode(c, n, rok) = while true a = rand(c, n); if rok || allu(a) return a end end
numcolors, codelength, maxguesses, allowrep, gameover = 10, 4, 10, false, false
colors = distinguishable_colors(numcolors)
code = ccode(colors, numcolors, allowrep)
guesshistory = Vector{Guess}()
win = GtkWindow("Mastermind Game", 900, 750) |> (GtkFrame() |> (box = GtkBox(:v)))
settingsbox = GtkBox(:h)
playtoolbar = GtkToolbar()
setcolors = GtkScale(false, 4:20)
set_gtk_property!(setcolors, :hexpand, true)
adj = GtkAdjustment(setcolors)
set_gtk_property!(adj, :value, 10)
clabel = GtkLabel("Number of Colors")
setcodelength = GtkScale(false, 4:10)
set_gtk_property!(setcodelength, :hexpand, true)
adj = GtkAdjustment(setcodelength)
set_gtk_property!(adj, :value, 4)
slabel = GtkLabel("Code Length")
setnumguesses = GtkScale(false, 4:40)
set_gtk_property!(setnumguesses, :hexpand, true)
adj = GtkAdjustment(setnumguesses)
set_gtk_property!(adj, :value, 10)
nlabel = GtkLabel("Max Guesses")
allowrepeatcolor = GtkScale(false, 0:1)
set_gtk_property!(allowrepeatcolor, :hexpand, true)
rlabel = GtkLabel("Allow Repeated Colors (0 = No)")
newgame = GtkToolButton("New Game")
set_gtk_property!(newgame, :label, "New Game")
set_gtk_property!(newgame, :is_important, true)
tryguess = GtkToolButton("Submit Current Guess")
set_gtk_property!(tryguess, :label, "Submit Current Guess")
set_gtk_property!(tryguess, :is_important, true)
eraselast = GtkToolButton("Erase Last (Unsubmitted) Pick")
set_gtk_property!(eraselast, :label, "Erase Last (Unsubmitted) Pick")
set_gtk_property!(eraselast, :is_important, true)
map(w->push!(settingsbox, w),[clabel, setcolors, slabel, setcodelength,
nlabel, setnumguesses, rlabel, allowrepeatcolor])
map(w->push!(playtoolbar, w),[newgame, tryguess, eraselast])
scrwin = GtkScrolledWindow()
can = GtkCanvas()
set_gtk_property!(can, :expand, true)
map(w -> push!(box, w),[settingsbox, playtoolbar, scrwin])
push!(scrwin, can)
currentguess = RGB[]
guessesused = 0
colorpositions = Point[]
function newgame!(w)
empty!(guesshistory)
numcolors = Int(GAccessor.value(setcolors))
codelength = Int(GAccessor.value(setcodelength))
maxguesses = Int(GAccessor.value(setnumguesses))
allowrep = Int(GAccessor.value(allowrepeatcolor))
colors = distinguishable_colors(numcolors)
code = ccode(colors, codelength, allowrep == 1)
empty!(currentguess)
currentneeded = codelength
guessesused = 0
gameover = false
draw(can)
end
signal_connect(newgame!, newgame, :clicked)
function saywon!()
warn_dialog("You have WON the game!", win)
gameover = true
end
function outofguesses!()
warn_dialog("You have Run out of moves! Game over.", win)
gameover = true
end
can.mouse.button1press = @guarded (widget, event) -> begin
if !gameover && (i = findfirst(p ->
sqrt((p.x - event.x)^2 + (p.y - event.y)^2) < 20,
colorpositions)) != nothing
if length(currentguess) < codelength
if allowrep == 0 && !allu(currentguess)
warn_dialog("Please erase the duplicate color.", win)
else
push!(currentguess, colors[i])
draw(can)
end
else
warn_dialog("You need to submit this guess if ready.", win)
end
end
end
@guarded draw(can) do widget
ctx = Gtk.getgc(can)
select_font_face(ctx, "Courier", Cairo.FONT_SLANT_NORMAL, Cairo.FONT_WEIGHT_BOLD)
fontpointsize = 12
set_font_size(ctx, fontpointsize)
workcolor = colorant"black"
set_source(ctx, workcolor)
move_to(ctx, 0, fontpointsize)
show_text(ctx, "Color options: " * "-"^70)
stroke(ctx)
empty!(colorpositions)
for i in 1:numcolors
set_source(ctx, colors[i])
circle(ctx, i * 40, 40, 20)
push!(colorpositions, Point(i * 40, 40))
fill(ctx)
end
set_gtk_property!(can, :expand, false) # kludge for good text overwriting
move_to(ctx, 0, 80)
set_source(ctx, workcolor)
show_text(ctx, string(maxguesses - guessesused, pad = 2) * " moves remaining.")
stroke(ctx)
set_gtk_property!(can, :expand, true)
for i in 1:codelength
set_source(ctx, i > length(currentguess) ? colorant"lightgray" : currentguess[i])
circle(ctx, i * 40, 110, 20)
fill(ctx)
end
if length(guesshistory) > 0
move_to(ctx, 0, 155)
set_source(ctx, workcolor)
show_text(ctx, "Past Guesses: " * "-"^70)
for (i, g) in enumerate(guesshistory), (j, c) in enumerate(tovec(g)[codelength+1:end])
x = j * 40 + (j > codelength ? 20 : 0)
y = 150 + 40 * i
set_source(ctx, c)
circle(ctx, x, y, 20)
fill(ctx)
end
end
Gtk.showall(win)
end
function submitguess!(w)
if length(currentguess) == length(code)
g = Guess(code, currentguess)
push!(guesshistory, g)
empty!(currentguess)
guessesused += 1
draw(can)
if all(i -> g.code[i] == g.guess[i], 1:length(code))
saywon!()
elseif guessesused > maxguesses
outofguesses!()
end
end
end
signal_connect(submitguess!, tryguess, :clicked)
function undolast!(w)
if length(currentguess) > 0
pop!(currentguess)
draw(can)
end
end
signal_connect(undolast!, eraselast, :clicked)
newgame!(win)
Gtk.showall(win)
condition = Condition()
endit(w) = notify(condition)
signal_connect(endit, win, :destroy)
showall(win)
wait(condition)
end
mastermindapp()
|
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
| #Kotlin | Kotlin | // version 1.2.51
import java.util.Random
val rand = Random()
class Mastermind {
private val codeLen: Int
private val colorsCnt: Int
private var guessCnt = 0
private val repeatClr: Boolean
private val colors: String
private var combo = ""
private val guesses = mutableListOf<CharArray>()
private val results = mutableListOf<CharArray>()
constructor(codeLen: Int, colorsCnt: Int, guessCnt: Int, repeatClr: Boolean) {
val color = "ABCDEFGHIJKLMNOPQRST"
this.codeLen = codeLen.coerceIn(4, 10)
var cl = colorsCnt
if (!repeatClr && cl < this.codeLen) cl = this.codeLen
this.colorsCnt = cl.coerceIn(2, 20)
this.guessCnt = guessCnt.coerceIn(7, 20)
this.repeatClr = repeatClr
this.colors = color.take(this.colorsCnt)
}
fun play() {
var win = false
combo = getCombo()
while (guessCnt != 0) {
showBoard()
if (checkInput(getInput())) {
win = true
break
}
guessCnt--
}
println("\n\n--------------------------------")
if (win) {
println("Very well done!\nYou found the code: $combo")
}
else {
println("I am sorry, you couldn't make it!\nThe code was: $combo")
}
println("--------------------------------\n")
}
private fun showBoard() {
for (x in 0 until guesses.size) {
println("\n--------------------------------")
print("${x + 1}: ")
for (y in guesses[x]) print("$y ")
print(" : ")
for (y in results[x]) print("$y ")
val z = codeLen - results[x].size
if (z > 0) print("- ".repeat(z))
}
println("\n")
}
private fun getInput(): String {
while (true) {
print("Enter your guess ($colors): ")
val a = readLine()!!.toUpperCase().take(codeLen)
if (a.all { it in colors } ) return a
}
}
private fun checkInput(a: String): Boolean {
guesses.add(a.toCharArray())
var black = 0
var white = 0
val gmatch = BooleanArray(codeLen)
val cmatch = BooleanArray(codeLen)
for (i in 0 until codeLen) {
if (a[i] == combo[i]) {
gmatch[i] = true
cmatch[i] = true
black++
}
}
for (i in 0 until codeLen) {
if (gmatch[i]) continue
for (j in 0 until codeLen) {
if (i == j || cmatch[j]) continue
if (a[i] == combo[j]) {
cmatch[j] = true
white++
break
}
}
}
val r = mutableListOf<Char>()
r.addAll("X".repeat(black).toList())
r.addAll("O".repeat(white).toList())
results.add(r.toCharArray())
return black == codeLen
}
private fun getCombo(): String {
val c = StringBuilder()
val clr = StringBuilder(colors)
for (s in 0 until codeLen) {
val z = rand.nextInt(clr.length)
c.append(clr[z])
if (!repeatClr) clr.deleteCharAt(z)
}
return c.toString()
}
}
fun main(args: Array<String>) {
val m = Mastermind(4, 8, 12, false)
m.play()
} |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #Nim | Nim | import sequtils
type Optimizer = object
dims: seq[int]
m: seq[seq[Natural]]
s: seq[seq[Natural]]
proc initOptimizer(dims: openArray[int]): Optimizer =
## Create an optimizer for the given dimensions.
Optimizer(dims: @dims)
proc findMatrixChainOrder(opt: var Optimizer) =
## Find the best order for matrix chain multiplication.
let n = opt.dims.high
opt.m = newSeqWith(n, newSeq[Natural](n))
opt.s = newSeqWith(n, newSeq[Natural](n))
for lg in 1..<n:
for i in 0..<(n - lg):
let j = i + lg
opt.m[i][j] = Natural.high
for k in i..<j:
let cost = opt.m[i][k] + opt.m[k+1][j] + opt.dims[i] * opt.dims[k+1] * opt.dims[j+1]
if cost < opt.m[i][j]:
opt.m[i][j] = cost
opt.s[i][j] = k
proc optimalChainOrder(opt: Optimizer; i, j: Natural): string =
## Return the optimal chain order as a string.
if i == j:
result.add chr(i + ord('A'))
else:
result.add '('
result.add opt.optimalChainOrder(i, opt.s[i][j])
result.add opt.optimalChainOrder(opt.s[i][j] + 1, j)
result.add ')'
when isMainModule:
const
Dims1 = @[5, 6, 3, 1]
Dims2 = @[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
Dims3 = @[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
for dims in [Dims1, Dims2, Dims3]:
var opt = initOptimizer(dims)
opt.findMatrixChainOrder()
echo "Dims: ", dims
echo "Order: ", opt.optimalChainOrder(0, dims.len - 2)
echo "Cost: ", opt.m[0][dims.len - 2]
echo "" |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #Perl | Perl | use strict;
use feature 'say';
sub matrix_mult_chaining {
my(@dimensions) = @_;
my(@cp,@path);
# a matrix never needs to be multiplied with itself, so it has cost 0
$cp[$_][$_] = 0 for keys @dimensions;
my $n = $#dimensions;
for my $chain_length (1..$n) {
for my $start (0 .. $n - $chain_length - 1) {
my $end = $start + $chain_length;
$cp[$end][$start] = 10e10;
for my $step ($start .. $end - 1) {
my $new_cost = $cp[$step][$start]
+ $cp[$end][$step + 1]
+ $dimensions[$start] * $dimensions[$step+1] * $dimensions[$end+1];
if ($new_cost < $cp[$end][$start]) {
$cp[$end][$start] = $new_cost; # cost
$cp[$start][$end] = $step; # path
}
}
}
}
$cp[$n-1][0] . ' ' . find_path(0, $n-1, @cp);
}
sub find_path {
my($start,$end,@cp) = @_;
my $result;
if ($start == $end) {
$result .= 'A' . ($start + 1);
} else {
$result .= '(' .
find_path($start, $cp[$start][$end], @cp) .
find_path($cp[$start][$end] + 1, $end, @cp) .
')';
}
return $result;
}
say matrix_mult_chaining(<1 5 25 30 100 70 2 1 100 250 1 1000 2>);
say matrix_mult_chaining(<1000 1 500 12 1 700 2500 3 2 5 14 10>); |
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.
| #Nim | Nim | import random, strutils
type
Direction {.pure.} = enum None, Up, Left, Down, Right
Maze = object
cells: seq[string]
hwalls: seq[string]
vwalls: seq[string]
####################################################################################################
# Maze creation.
func initMaze(rows, cols: Positive): Maze =
## Initialize a maze description.
var h = repeat('-', cols)
var v = repeat("|", cols)
for i in 0..<rows:
result.cells.add newString(cols)
result.hwalls.add h
result.vwalls.add v
proc gen(maze: var Maze; r, c: Natural) =
## Generate a maze starting from point (r, c).
maze.cells[r][c] = ' '
var dirs = [Up, Left, Down, Right]
dirs.shuffle()
for dir in dirs:
case dir
of None:
discard
of Up:
if r > 0 and maze.cells[r-1][c] == '\0':
maze.hwalls[r][c] = chr(0)
maze.gen(r-1, c)
of Left:
if c > 0 and maze.cells[r][c-1] == '\0':
maze.vwalls[r][c] = chr(0)
maze.gen(r, c-1)
of Down:
if r < maze.cells.high and maze.cells[r+1][c] == '\0':
maze.hwalls[r+1][c] = chr(0)
maze.gen(r+1, c)
of Right:
if c < maze.cells[0].high and maze.cells[r][c+1] == '\0':
maze.vwalls[r][c+1] = chr(0)
maze.gen(r, c+1)
proc gen(maze: var Maze) =
## Generate a maze, choosing a random starting point.
maze.gen(rand(maze.cells.high), rand(maze.cells[0].high))
####################################################################################################
# Maze solving.
proc solve(maze: var Maze; ra, ca, rz, cz: Natural) =
## Solve a maze by finding the path from point (ra, ca) to point (rz, cz).
proc rsolve(maze: var Maze; r, c: Natural; dir: Direction): bool {.discardable.} =
## Recursive solver.
if r == rz and c == cz:
maze.cells[r][c] = 'F'
return true
if dir != Down and maze.hwalls[r][c] == '\0':
if maze.rSolve(r-1, c, Up):
maze.cells[r][c] = '^'
maze.hwalls[r][c] = '^'
return true
if dir != Up and r < maze.hwalls.high and maze.hwalls[r+1][c] == '\0':
if maze.rSolve(r+1, c, Down):
maze.cells[r][c] = 'v'
maze.hwalls[r+1][c] = 'v'
return true
if dir != Left and c < maze.vwalls[0].high and maze.vwalls[r][c+1] == '\0':
if maze.rSolve(r, c+1, Right):
maze.cells[r][c] = '>'
maze.vwalls[r][c+1] = '>'
return true
if dir != Right and maze.vwalls[r][c] == '\0':
if maze.rSolve(r, c-1, Left):
maze.cells[r][c] = '<'
maze.vwalls[r][c] = '<'
return true
maze.rsolve(ra, ca, None)
maze.cells[ra][ca] = 'S'
####################################################################################################
# Maze display.
func `$`(maze: Maze): string =
## Return the string representation fo a maze.
const
HWall = "+---"
HOpen = "+ "
VWall = "| "
VOpen = " "
RightCorner = "+\n"
RightWall = "|\n"
for r, hw in maze.hwalls:
for h in hw:
if h == '-' or r == 0:
result.add HWall
else:
result.add HOpen
if h notin {'-', '\0'}: result[^2] = h
result.add RightCorner
for c, vw in maze.vwalls[r]:
if vw == '|' or c == 0:
result.add VWall
else:
result.add VOpen
if vw notin {'|', '\0'}: result[^4] = vw
if maze.cells[r][c] != '\0': result[^2] = maze.cells[r][c]
result.add RightWall
for _ in 1..maze.hwalls[0].len:
result.add HWall
result.add RightCorner
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
const
Width = 8
Height = 8
randomize()
var maze = initMaze(Width, Height)
maze.gen()
var ra, rz = rand(Width - 1)
var ca, cz = rand(Height - 1)
while rz == ra and cz == ca:
# Make sur starting and ending points are different.
rz = rand(Width - 1)
cz = rand(Height - 1)
maze.solve(ra, ca , rz, cz)
echo maze |
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.
| #Java | Java | import java.nio.file.*;
import static java.util.Arrays.stream;
public class MaxPathSum {
public static void main(String[] args) throws Exception {
int[][] data = Files.lines(Paths.get("triangle.txt"))
.map(s -> stream(s.trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
for (int r = data.length - 1; r > 0; r--)
for (int c = 0; c < data[r].length - 1; c++)
data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);
System.out.println(data[0][0]);
}
} |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
| #Ruby | Ruby | require 'openssl'
puts OpenSSL::Digest::MD4.hexdigest('Rosetta Code') |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #XPL0 | XPL0 | include c:\cxpl\stdlib;
func Mid3Digits(I); \Return the middle three digits of I
int I;
int Len, Mid;
char S(10);
[ItoA(abs(I), S);
Len:= StrLen(S);
if Len<3 or (Len&1)=0 then return "Must be 3, 5, 7 or 9 digits";
Mid:= Len/2;
S:= S + Mid - 1;
S(2):= S(2) ! $80; \terminate string
return S; \WARNING: very temporary
];
int Passing, Failing, X;
[Passing:= [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345];
Failing:= [1, 2, -1, -10, 2002, -2002, 0]; \WARNING: nasty trick
for X:= 0 to 16 do
[Text(0, "Middle three digits of "); IntOut(0, Passing(X));
Text(0, " returned: ");
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
] |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Factor | Factor | USING: kernel strings io checksums checksums.md5 ;
"The quick brown fox jumps over the lazy dog"
md5 checksum-bytes hex-string print
|
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
Task
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number n which cannot be expressed with 6x + 9y + 20z = n
where x, y and z are natural numbers).
| #Racket | Racket | #lang racket
(apply max (set->list (for*/fold ((s (list->set (range 1 101))))
((x (in-range 0 101 20))
(y (in-range x 101 9))
(n (in-range y 101 6)))
(set-remove s n)))) |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
Task
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number n which cannot be expressed with 6x + 9y + 20z = n
where x, y and z are natural numbers).
| #Raku | Raku | sub Mcnugget-number (*@counts) {
return '∞' if 1 < [gcd] @counts;
my $min = min @counts;
my @meals;
my @min;
for ^Inf -> $a {
for 0..$a -> $b {
for 0..$b -> $c {
($a, $b, $c).permutations.map: { @meals[ sum $_ Z* @counts ] = True }
}
}
for @meals.grep: so *, :k {
if @min.tail and @min.tail + 1 == $_ {
@min.push: $_;
last if $min == +@min
} else {
@min = $_;
}
}
last if $min == +@min
}
@min[0] ?? @min[0] - 1 !! 0
}
for (6,9,20), (6,7,20), (1,3,20), (10,5,18), (5,17,44), (2,4,6), (3,6,15) -> $counts {
put "Maximum non-Mcnugget number using {$counts.join: ', '} is: ",
Mcnugget-number(|$counts)
} |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most significant
digit at the left). This task will be using a left─to─right (horizontal) format, mostly for familiarity and
readability, and to conserve screen space (when showing the output) on this task page.
Mayan numerals
Mayan numerals (a base─20 "digit" or glyph) are written in two orientations, this
task will be using the "vertical" format (as displayed below). Using the vertical format makes
it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.)
and hyphen (-); (however, round bullets (•) and long dashes (─)
make a better presentation on Rosetta Code).
Furthermore, each Mayan numeral (for this task) is to be displayed as a
cartouche (enclosed in a box) to make it easier to parse (read); the box may be
drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers.
Mayan numerals added to Unicode
Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018 (this corresponds with
version 11.0). But since most web browsers don't support them at this time, this Rosetta Code
task will be constructing the glyphs with "simple" characters and/or ASCII art.
The "zero" glyph
The Mayan numbering system has the concept of zero, and should be shown by a glyph that represents
an upside─down (sea) shell, or an egg. The Greek letter theta (Θ) can be
used (which more─or─less, looks like an
egg). A commercial at symbol (@) could make a poor substitute.
Mayan glyphs (constructed)
The Mayan numbering system is
a [vigesimal (base 20)] positional numeral system.
The Mayan numerals (and some random numbers) shown in the vertical format would be shown as
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙ ║ ║ ║ ║
1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║
║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙∙ ║ ║ ║ ║
2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║
║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙ ║ ║ ║ ║
3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║
║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙∙║ ║ ║ ║
4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║
║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
5──► ║ ║ 15──► ║────║ 90──► ║ ║────║
║────║ ║────║ ║∙∙∙∙║────║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║∙∙∙ ║ ║ ║ ║
║ ║ ║────║ 300──► ║────║ ║
8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╦════╗
║ ║ ║∙∙∙∙║ ║ ║ ║ ║
║ ║ ║────║ 400──► ║ ║ ║ ║
9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║
║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╩════╝
╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║
║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║
╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝
Note that the Mayan numeral 13 in horizontal format would be shown as:
╔════╗
║ ││║
║ ∙││║
13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task.
║ ∙││║
╚════╝
Other forms of cartouches (boxes) can be used for this task.
Task requirements
convert the following decimal numbers to Mayan numbers:
4,005
8,017
326,205
886,205
show a unique interesting/pretty/unusual/intriguing/odd/amusing/weird Mayan number
show all output here
Related tasks
Roman numerals/Encode ─── convert numeric values into Roman numerals
Roman numerals/Decode ─── convert Roman numerals into Arabic numbers
See also
The Wikipedia entry: [Mayan numerals]
| #REXX | REXX | /*REXX program converts decimal numbers to the Mayan numbering system (with cartouches).*/
parse arg $ /*obtain optional arguments from the CL*/
if $='' then $= 4005 8017 326205 886205, /*Not specified? Then use the default.*/
172037122592320200101 /*Morse code for MAYAN; egg is a blank.*/
do j=1 for words($) /*convert each of the numbers specified*/
#= word($, j) /*extract a number from (possible) list*/
say
say center('converting the decimal number ' # " to a Mayan number:", 90, '─')
say
call $MAYAN # '(overlap)' /*invoke the $MAYAN (REXX) subroutine.*/
say
end /*j*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most significant
digit at the left). This task will be using a left─to─right (horizontal) format, mostly for familiarity and
readability, and to conserve screen space (when showing the output) on this task page.
Mayan numerals
Mayan numerals (a base─20 "digit" or glyph) are written in two orientations, this
task will be using the "vertical" format (as displayed below). Using the vertical format makes
it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.)
and hyphen (-); (however, round bullets (•) and long dashes (─)
make a better presentation on Rosetta Code).
Furthermore, each Mayan numeral (for this task) is to be displayed as a
cartouche (enclosed in a box) to make it easier to parse (read); the box may be
drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers.
Mayan numerals added to Unicode
Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018 (this corresponds with
version 11.0). But since most web browsers don't support them at this time, this Rosetta Code
task will be constructing the glyphs with "simple" characters and/or ASCII art.
The "zero" glyph
The Mayan numbering system has the concept of zero, and should be shown by a glyph that represents
an upside─down (sea) shell, or an egg. The Greek letter theta (Θ) can be
used (which more─or─less, looks like an
egg). A commercial at symbol (@) could make a poor substitute.
Mayan glyphs (constructed)
The Mayan numbering system is
a [vigesimal (base 20)] positional numeral system.
The Mayan numerals (and some random numbers) shown in the vertical format would be shown as
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙ ║ ║ ║ ║
1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║
║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙∙ ║ ║ ║ ║
2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║
║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙ ║ ║ ║ ║
3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║
║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙∙║ ║ ║ ║
4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║
║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
5──► ║ ║ 15──► ║────║ 90──► ║ ║────║
║────║ ║────║ ║∙∙∙∙║────║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║∙∙∙ ║ ║ ║ ║
║ ║ ║────║ 300──► ║────║ ║
8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╦════╗
║ ║ ║∙∙∙∙║ ║ ║ ║ ║
║ ║ ║────║ 400──► ║ ║ ║ ║
9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║
║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╩════╝
╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║
║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║
╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝
Note that the Mayan numeral 13 in horizontal format would be shown as:
╔════╗
║ ││║
║ ∙││║
13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task.
║ ∙││║
╚════╝
Other forms of cartouches (boxes) can be used for this task.
Task requirements
convert the following decimal numbers to Mayan numbers:
4,005
8,017
326,205
886,205
show a unique interesting/pretty/unusual/intriguing/odd/amusing/weird Mayan number
show all output here
Related tasks
Roman numerals/Encode ─── convert numeric values into Roman numerals
Roman numerals/Decode ─── convert Roman numerals into Arabic numbers
See also
The Wikipedia entry: [Mayan numerals]
| #Ruby | Ruby | numbers = ARGV.map(&:to_i)
if numbers.length == 0
puts
puts("usage: #{File.basename(__FILE__)} number...")
exit
end
def maya_print(number)
digits5s1s = number.to_s(20).chars.map { |ch| ch.to_i(20) }.map { |dig| dig.divmod(5) }
puts(('+----' * digits5s1s.length) + '+')
3.downto(0) do |row|
digits5s1s.each do |d5s1s|
if row < d5s1s[0]
print('|----')
elsif row == d5s1s[0]
print("|#{[(d5s1s[0] == 0 ? ' @ ' : ' '), ' . ', ' .. ', '... ', '....'][d5s1s[1]]}")
else
print('| ')
end
end
puts('|')
end
puts(('+----' * digits5s1s.length) + '+')
end
numbers.each do |num|
puts(num)
maya_print(num)
end |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
first matrix=0, second matrix=0,a=-1
{5,2},rand array(a),mulby(10),ceil, cpy(first matrix), puts,{"\n"},puts
{2,3},rand array(a),mulby(10),ceil, cpy(second matrix), puts,{"\n"},puts
{first matrix,second matrix},mat mul, println
exit(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.
| #Common_Lisp | Common Lisp |
(ensure-directories-exist "your/path/name")
|
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.
| #D | D | import std.stdio;
void main() {
makeDir("parent/test");
}
/// Manual implementation of what mkdirRecurse in std.file does.
void makeDir(string path) out {
import std.exception : enforce;
import std.file : exists;
enforce(path.exists, "Failed to create the requested directory.");
} body {
import std.array : array;
import std.file;
import std.path : pathSplitter, chainPath;
auto workdir = "";
foreach (dir; path.pathSplitter) {
workdir = chainPath(workdir, dir).array;
if (workdir.exists) {
if (!workdir.isDir) {
import std.conv : text;
throw new FileException(text("The file ", workdir, " in the path ", path, " is not a directory."));
}
} else {
workdir.mkdir();
}
}
} |
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.
| #Delphi | Delphi |
program Make_directory_path;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils;
const
Path1 = '.\folder1\folder2\folder3'; // windows relative path (others OS formats are acepted)
Path2 = 'folder4\folder5\folder6';
begin
// "ForceDirectories" work with relative path if start with "./"
if ForceDirectories(Path1) then
Writeln('Created "', path1, '" sucessfull.');
// "TDirectory.CreateDirectory" work with any path format
// but don't return sucess, requere "TDirectory.Exists" to check
TDirectory.CreateDirectory(Path2);
if TDirectory.Exists(Path2) then
Writeln('Created "', path2, '" sucessfull.');
Readln;
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
| #ALGOL_68 | ALGOL 68 | PROC a = (INT in k, PROC INT xl, x2, x3, x4, x5) INT:(
INT k := in k;
PROC b = INT: a(k-:=1, b, xl, x2, x3, x4);
( k<=0 | x4 + x5 | b )
);
test:(
printf(($gl$,a(10, INT:1, INT:-1, INT:-1, INT:1, INT:0)))
) |
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.
| #C.2B.2B | C++ | UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)
{
UINT_64 N;
N = N1;
N = (N<<32)|N2;
return UINT_64(N);
}
UINT_32 TGost::ReplaceBlock(UINT_32 x)
{
register i;
UINT_32 res = 0UL;
for(i=7;i>=0;i--)
{
ui4_0 = x>>(i*4);
ui4_0 = BS[ui4_0][i];
res = (res<<4)|ui4_0;
}
return res;
}
UINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)
{
UINT_32 N1,N2,S=0UL;
N1=UINT_32(N);
N2=N>>32;
S = N1 + X % 0x4000000000000;
S = ReplaceBlock(S);
S = (S<<11)|(S>>21);
S ^= N2;
N2 = N1;
N1 = S;
return SWAP32(N2,N1);
} |
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.
| #D | D | import std.stdio, std.range, std.algorithm;
/// Rotate uint left.
uint rol(in uint x, in uint nBits) @safe pure nothrow @nogc {
return (x << nBits) | (x >> (32 - nBits));
}
alias Nibble = ubyte; // 4 bits used.
alias SBox = immutable Nibble[16][8];
private bool _validateSBox(in SBox data) @safe pure nothrow @nogc {
foreach (const ref row; data)
foreach (ub; row)
if (ub >= 16) // Verify it's a nibble.
return false;
return true;
}
struct GOST(s...) if (s.length == 1 && s[0]._validateSBox) {
private static generate(ubyte k)() @safe pure nothrow {
return k87.length.iota
.map!(i=> (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF])
.array;
}
private uint[2] buffer;
private static immutable ubyte[256] k87 = generate!7,
k65 = generate!5,
k43 = generate!3,
k21 = generate!1;
// Endianess problems?
private static uint f(in uint x) pure nothrow @nogc @safe {
immutable uint y = (k87[(x >> 24) & 0xFF] << 24) |
(k65[(x >> 16) & 0xFF] << 16) |
(k43[(x >> 8) & 0xFF] << 8) |
k21[ x & 0xFF];
return rol(y, 11);
}
// This performs only a step of the encoding.
public void mainStep(in uint[2] input, in uint key)
pure nothrow @nogc @safe {
buffer[0] = f(key + input[0]) ^ input[1];
buffer[1] = input[0];
}
}
void main() {
// S-boxes used by the Central Bank of Russian Federation:
// http://en.wikipedia.org/wiki/GOST_28147-89
// (This is a matrix of nibbles).
enum SBox 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]];
GOST!cbrf g;
// Example from the talk page (bytes swapped for endianess):
immutable uint[2] input = [0x_04_3B_04_21, 0x_04_32_04_30];
immutable uint key = 0x_E2_C1_04_F9;
g.mainStep(input, key);
writefln("%(%08X %)", g.buffer);
} |
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.
| #C | C | #include <stdio.h>
#include <string.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
/* OK for 'small' numbers. */
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
void ord(char *res, int n) {
char suffix[3];
int m = n % 100;
if (m >= 4 && m <= 20) {
sprintf(res,"%dth", n);
return;
}
switch(m % 10) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
sprintf(res, "%d%s", n, suffix);
}
bool is_magnanimous(ull n) {
ull p, q, r;
if (n < 10) return TRUE;
for (p = 10; ; p *= 10) {
q = n / p;
r = n % p;
if (!is_prime(q + r)) return FALSE;
if (q < 10) break;
}
return TRUE;
}
void list_mags(int from, int thru, int digs, int per_line) {
ull i = 0;
int c = 0;
char res1[13], res2[13];
if (from < 2) {
printf("\nFirst %d magnanimous numbers:\n", thru);
} else {
ord(res1, from);
ord(res2, thru);
printf("\n%s through %s magnanimous numbers:\n", res1, res2);
}
for ( ; c < thru; ++i) {
if (is_magnanimous(i)) {
if (++c >= from) {
printf("%*llu ", digs, i);
if (!(c % per_line)) printf("\n");
}
}
}
}
int main() {
list_mags(1, 45, 3, 15);
list_mags(241, 250, 1, 10);
list_mags(391, 400, 1, 10);
return 0;
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Agda | Agda | module Matrix where
open import Data.Nat
open import Data.Vec
Matrix : (A : Set) → ℕ → ℕ → Set
Matrix A m n = Vec (Vec A m) n
transpose : ∀ {A m n} → Matrix A m n → Matrix A n m
transpose [] = replicate []
transpose (xs ∷ xss) = zipWith _∷_ xs (transpose xss)
a = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ []
b = transpose a |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Drawing;
namespace MazeGeneration
{
public static class Extensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
var e = source.ToArray();
for (var i = e.Length - 1; i >= 0; i--)
{
var swapIndex = rng.Next(i + 1);
yield return e[swapIndex];
e[swapIndex] = e[i];
}
}
public static CellState OppositeWall(this CellState orig)
{
return (CellState)(((int) orig >> 2) | ((int) orig << 2)) & CellState.Initial;
}
public static bool HasFlag(this CellState cs,CellState flag)
{
return ((int)cs & (int)flag) != 0;
}
}
[Flags]
public enum CellState
{
Top = 1,
Right = 2,
Bottom = 4,
Left = 8,
Visited = 128,
Initial = Top | Right | Bottom | Left,
}
public struct RemoveWallAction
{
public Point Neighbour;
public CellState Wall;
}
public class Maze
{
private readonly CellState[,] _cells;
private readonly int _width;
private readonly int _height;
private readonly Random _rng;
public Maze(int width, int height)
{
_width = width;
_height = height;
_cells = new CellState[width, height];
for(var x=0; x<width; x++)
for(var y=0; y<height; y++)
_cells[x, y] = CellState.Initial;
_rng = new Random();
VisitCell(_rng.Next(width), _rng.Next(height));
}
public CellState this[int x, int y]
{
get { return _cells[x,y]; }
set { _cells[x,y] = value; }
}
public IEnumerable<RemoveWallAction> GetNeighbours(Point p)
{
if (p.X > 0) yield return new RemoveWallAction {Neighbour = new Point(p.X - 1, p.Y), Wall = CellState.Left};
if (p.Y > 0) yield return new RemoveWallAction {Neighbour = new Point(p.X, p.Y - 1), Wall = CellState.Top};
if (p.X < _width-1) yield return new RemoveWallAction {Neighbour = new Point(p.X + 1, p.Y), Wall = CellState.Right};
if (p.Y < _height-1) yield return new RemoveWallAction {Neighbour = new Point(p.X, p.Y + 1), Wall = CellState.Bottom};
}
public void VisitCell(int x, int y)
{
this[x,y] |= CellState.Visited;
foreach (var p in GetNeighbours(new Point(x, y)).Shuffle(_rng).Where(z => !(this[z.Neighbour.X, z.Neighbour.Y].HasFlag(CellState.Visited))))
{
this[x, y] -= p.Wall;
this[p.Neighbour.X, p.Neighbour.Y] -= p.Wall.OppositeWall();
VisitCell(p.Neighbour.X, p.Neighbour.Y);
}
}
public void Display()
{
var firstLine = string.Empty;
for (var y = 0; y < _height; y++)
{
var sbTop = new StringBuilder();
var sbMid = new StringBuilder();
for (var x = 0; x < _width; x++)
{
sbTop.Append(this[x, y].HasFlag(CellState.Top) ? "+--" : "+ ");
sbMid.Append(this[x, y].HasFlag(CellState.Left) ? "| " : " ");
}
if (firstLine == string.Empty)
firstLine = sbTop.ToString();
Debug.WriteLine(sbTop + "+");
Debug.WriteLine(sbMid + "|");
Debug.WriteLine(sbMid + "|");
}
Debug.WriteLine(firstLine);
}
}
class Program
{
static void Main(string[] args)
{
var maze = new Maze(20, 20);
maze.Display();
}
}
}
|
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.
| #Haskell | Haskell | import Data.List (transpose)
(<+>)
:: Num a
=> [a] -> [a] -> [a]
(<+>) = zipWith (+)
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a =
Mat [[a]]
deriving (Eq, Show)
instance Num a =>
Num (Mat a) where
negate (Mat x) = Mat $ map (map negate) x
Mat x + Mat y = Mat $ zipWith (<+>) x y
Mat x * Mat y =
Mat
[ [ xs Main.<*> ys -- Main prefix to distinguish fron applicative operator
| ys <- transpose y ]
| xs <- x ]
abs = undefined
fromInteger _ = undefined -- don't know dimension of the desired matrix
signum = undefined
-- TEST ----------------------------------------------------------------------
main :: IO ()
main = print $ Mat [[1, 2], [0, 1]] ^ 4 |
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.
| #AWK | AWK |
# syntax: GAWK -f MAP_RANGE.AWK
BEGIN {
a1 = 0
a2 = 10
b1 = -1
b2 = 0
for (i=a1; i<=a2; i++) {
printf("%g maps to %g\n",i,map_range(a1,a2,b1,b2,i))
}
exit(0)
}
function map_range(a1,a2,b1,b2,num) {
return b1 + ((num-a1) * (b2-b1) / (a2-a1))
}
|
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #Axiom | Axiom | )abbrev package TESTP TestPackage
TestPackage(R:Field) : with
mapRange: (Segment(R), Segment(R)) -> (R->R)
== add
mapRange(fromRange, toRange) ==
(a1,a2,b1,b2) := (lo fromRange,hi fromRange,lo toRange,hi toRange)
(x:R):R +-> b1+(x-a1)*(b2-b1)/(a2-a1) |
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.
| #Nim | Nim | import os, random, sequtils
import ncurses
const RowDelay = 40 # In milliseconds.
proc exit() {.noconv.} =
endwin()
quit QuitSuccess
proc run() =
const
Chars = "0123456789" # Characters to randomly appear in the rain sequence.
let stdscr = initscr()
noEcho()
cursSet(0)
startColor()
initPair(1, COLOR_GREEN, COLOR_BLACK)
attron(COLOR_PAIR(1).cint)
var width, height: cint
stdscr.getmaxyx(height, width)
let maxX = width - 1
let maxY = height - 1
# Create arrays of columns based on screen width.
# Array containing the current row of each column.
# Set top row as current row for all columns.
var columnsRow = repeat(cint -1, width)
# Array containing the active status of each column.
# A column draws characters on a row when active.
var columnsActive = newSeq[bool](width)
setControlCHook(exit)
while true:
for i in 0..maxX:
if columnsRow[i] == -1:
# If a column is at the top row, pick a random starting row and active status.
columnsRow[i] = cint(rand(maxY))
columnsActive[i] = bool(rand(1))
# Loop through columns and draw characters on rows.
for i in 0..maxX:
if columnsActive[i]:
# Draw a random character at this column's current row.
let charIndex = rand(Chars.high)
mvprintw(columnsRow[i], i, "%c", Chars[charIndex])
else:
# Draw an empty character if the column is inactive.
mvprintw(columnsRow[i], i, " ")
inc columnsRow[i]
# When a column reaches the bottom row, reset to top.
if columnsRow[i] > maxY: columnsRow[i] = -1
# Randomly alternate the column's active status.
if rand(999) == 0: columnsActive[i] = not columnsActive[i]
sleep(RowDelay)
refresh()
run() |
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
| #Lua | Lua |
math.randomseed( os.time() )
local black, white, none, code = "X", "O", "-"
local colors, codeLen, maxGuess, rept, alpha, opt = 6, 4, 10, false, "ABCDEFGHIJKLMNOPQRST", ""
local guesses, results
function createCode()
code = ""
local dic, a = ""
for i = 1, colors do
dic = dic .. alpha:sub( i, i )
end
for i = 1, codeLen do
a = math.floor( math.random( 1, #dic ) )
code = code .. dic:sub( a, a )
if not rept then
dic = dic:sub(1, a - 1 ) .. dic:sub( a + 1, #dic )
end
end
end
function checkInput( inp )
table.insert( guesses, inp )
local b, w, fnd, str = 0, 0, {}, ""
for bl = 1, codeLen do
if inp:sub( bl, bl ) == code:sub( bl, bl ) then
b = b + 1; fnd[bl] = true
else
for wh = 1, codeLen do
if nil == fnd[bl] and wh ~= bl and inp:sub( wh, wh ) == code:sub( bl, bl ) then
w = w + 1; fnd[bl] = true
end
end
end
end
for i = 1, b do str = str .. string.format( "%s ", black ) end
for i = 1, w do str = str .. string.format( "%s ", white ) end
for i = 1, 2 * codeLen - #str, 2 do str = str .. string.format( "%s ", none ) end
table.insert( results, str )
return b == codeLen
end
function play()
local err, win, r = true, false;
for j = 1, colors do opt = opt .. alpha:sub( j, j ) end
while( true ) do
createCode(); guesses, results = {}, {}
for i = 1, maxGuess do
err = true;
while( err ) do
io.write( string.format( "\n-------------------------------\nYour guess (%s)?", opt ) )
inp = io.read():upper();
if #inp == codeLen then
err = false;
for k = 1, #inp do
if( nil == opt:find( inp:sub( k, k ) ) ) then
err = true;
break;
end
end
end
end
if( checkInput( inp ) ) then win = true; break
else
for l = 1, #guesses do
print( string.format( "%.2d: %s : %s", l, guesses[l], results[l] ) )
end
end
end
if win then print( "\nWell done!" )
else print( string.format( "\nSorry, you did not crack the code --> %s!", code ) )
end
io.write( "Play again( Y/N )? " ); r = io.read()
if r ~= "Y" and r ~= "y" then break end
end
end
--[[ entry point ]]---
if arg[1] ~= nil and tonumber( arg[1] ) > 1 and tonumber( arg[1] ) < 21 then colors = tonumber( arg[1] ) end
if arg[2] ~= nil and tonumber( arg[2] ) > 3 and tonumber( arg[2] ) < 11 then codeLen = tonumber( arg[2] ) end
if arg[3] ~= nil and tonumber( arg[3] ) > 6 and tonumber( arg[3] ) < 21 then maxGuess = tonumber( arg[3] ) end
if arg[4] ~= nil and arg[4] == "true" or arg[4] == "false" then rept = ( arg[4] == "true" ) end
play()
|
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #Phix | Phix | with javascript_semantics
function optimal_chain_order(int i, int j, sequence s)
if i==j then
return i+'A'-1
end if
return "("&optimal_chain_order(i,s[i,j],s)
&optimal_chain_order(s[i,j]+1,j,s)&")"
end function
function optimal_matrix_chain_order(sequence dims)
integer n = length(dims)-1
sequence m = repeat(repeat(0,n),n),
s = deep_copy(m)
for len=2 to n do
for i=1 to n-len+1 do
integer j = i+len-1
m[i][j] = -1
for k=i to j-1 do
atom cost := m[i][k] + m[k+1][j] + dims[i]*dims[k+1]*dims[j+1]
if m[i][j]<0
or cost<m[i][j] then
m[i][j] = cost;
s[i][j] = k;
end if
end for
end for
end for
return {optimal_chain_order(1,n,s),m[1,n]}
end function
constant tests = {{5, 6, 3, 1},
{1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2},
{1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}}
for i=1 to length(tests) do
sequence ti = tests[i]
printf(1,"Dims : %s\n",{sprint(ti)})
printf(1,"Order : %s\nCost : %d\n",optimal_matrix_chain_order(ti))
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.
| #Perl | Perl |
#!perl
use strict;
use warnings;
my ($width, $height) = @ARGV;
$_ ||= 10 for $width, $height;
my %visited;
my $h_barrier = "+" . ("--+" x $width) . "\n";
my $v_barrier = "|" . (" |" x $width) . "\n";
my @output = ($h_barrier, $v_barrier) x $height;
push @output, $h_barrier;
my @dx = qw(-1 1 0 0);
my @dy = qw(0 0 -1 1);
sub visit {
my ($x, $y) = @_;
$visited{$x, $y} = 1;
my $rand = int rand 4;
for my $n ( $rand .. 3, 0 .. $rand-1 ) {
my ($xx, $yy) = ($x + $dx[$n], $y + $dy[$n]);
next if $visited{ $xx, $yy };
next if $xx < 0 or $xx >= $width;
next if $yy < 0 or $yy >= $height;
my $row = $y * 2 + 1 + $dy[$n];
my $col = $x * 3 + 1 + $dx[$n];
substr( $output[$row], $col, 2, ' ' );
no warnings 'recursion';
visit( $xx, $yy );
}
}
visit( int rand $width, int rand $height );
print "Here is the maze:\n";
print @output;
%visited = ();
my @d = ('>>', '<<', 'vv', '^^');
sub solve {
my ($x, $y) = @_;
return 1 if $x == 0 and $y == 0;
$visited{ $x, $y } = 1;
my $rand = int rand 4;
for my $n ( $rand .. 3, 0 .. $rand-1 ) {
my ($xx, $yy) = ($x + $dx[$n], $y + $dy[$n]);
next if $visited{ $xx, $yy };
next if $xx < 0 or $xx >= $width;
next if $yy < 0 or $yy >= $height;
my $row = $y * 2 + 1 + $dy[$n];
my $col = $x * 3 + 1 + $dx[$n];
my $b = substr( $output[$row], $col, 2 );
next if " " ne $b;
no warnings 'recursion';
next if not solve( $xx, $yy );
substr( $output[$row], $col, 2, $d[$n] );
substr( $output[$row-$dy[$n]], $col-$dx[$n], 2, $d[$n] );
return 1;
}
0;
}
if( solve( $width-1, $height-1 ) ) {
print "Here is the solution:\n";
substr( $output[1], 1, 2, '**' );
print @output;
} else {
print "Could not solve!\n";
}
|
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.
| #JavaScript | JavaScript |
var arr = [
[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]
];
while (arr.length !== 1) {
var len = arr.length;
var row = [];
var current = arr[len-2];
var currentLen = current.length - 1;
var end = arr[len-1];
for ( var i = 0; i <= currentLen; i++ ) {
row.push(Math.max(current[i] + end[i] || 0, current[i] + end[i+1] || 0) )
}
arr.pop();
arr.pop();
arr.push(row);
}
console.log(arr);
|
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
| #Rust | Rust | // MD4, based on RFC 1186 and RFC 1320.
//
// https://www.ietf.org/rfc/rfc1186.txt
// https://tools.ietf.org/html/rfc1320
//
use std::fmt::Write;
use std::mem;
// Let not(X) denote the bit-wise complement of X.
// Let X v Y denote the bit-wise OR of X and Y.
// Let X xor Y denote the bit-wise XOR of X and Y.
// Let XY denote the bit-wise AND of X and Y.
// f(X,Y,Z) = XY v not(X)Z
fn f(x: u32, y: u32, z: u32) -> u32 {
(x & y) | (!x & z)
}
// g(X,Y,Z) = XY v XZ v YZ
fn g(x: u32, y: u32, z: u32) -> u32 {
(x & y) | (x & z) | (y & z)
}
// h(X,Y,Z) = X xor Y xor Z
fn h(x: u32, y: u32, z: u32) -> u32 {
x ^ y ^ z
}
// Round 1 macro
// Let [A B C D i s] denote the operation
// A = (A + f(B,C,D) + X[i]) <<< s
macro_rules! md4round1 {
( $a:expr, $b:expr, $c:expr, $d:expr, $i:expr, $s:expr, $x:expr) => {
{
// Rust defaults to non-overflowing arithmetic, so we need to specify wrapping add.
$a = ($a.wrapping_add( f($b, $c, $d) ).wrapping_add( $x[$i] ) ).rotate_left($s);
}
};
}
// Round 2 macro
// Let [A B C D i s] denote the operation
// A = (A + g(B,C,D) + X[i] + 5A827999) <<< s .
macro_rules! md4round2 {
( $a:expr, $b:expr, $c:expr, $d:expr, $i:expr, $s:expr, $x:expr) => {
{
$a = ($a.wrapping_add( g($b, $c, $d)).wrapping_add($x[$i]).wrapping_add(0x5a827999_u32)).rotate_left($s);
}
};
}
// Round 3 macro
// Let [A B C D i s] denote the operation
// A = (A + h(B,C,D) + X[i] + 6ED9EBA1) <<< s .
macro_rules! md4round3 {
( $a:expr, $b:expr, $c:expr, $d:expr, $i:expr, $s:expr, $x:expr) => {
{
$a = ($a.wrapping_add(h($b, $c, $d)).wrapping_add($x[$i]).wrapping_add(0x6ed9eba1_u32)).rotate_left($s);
}
};
}
fn convert_byte_vec_to_u32(mut bytes: Vec<u8>) -> Vec<u32> {
bytes.shrink_to_fit();
let num_bytes = bytes.len();
let num_words = num_bytes / 4;
unsafe {
let words = Vec::from_raw_parts(bytes.as_mut_ptr() as *mut u32, num_words, num_words);
mem::forget(bytes);
words
}
}
// Returns a 128-bit MD4 hash as an array of four 32-bit words.
// Based on RFC 1186 from https://www.ietf.org/rfc/rfc1186.txt
fn md4<T: Into<Vec<u8>>>(input: T) -> [u32; 4] {
let mut bytes = input.into().to_vec();
let initial_bit_len = (bytes.len() << 3) as u64;
// Step 1. Append padding bits
// Append one '1' bit, then append 0 ≤ k < 512 bits '0', such that the resulting message
// length in bis is congruent to 448 (mod 512).
// Since our message is in bytes, we use one byte with a set high-order bit (0x80) plus
// a variable number of zero bytes.
// Append zeros
// Number of padding bytes needed is 448 bits (56 bytes) modulo 512 bits (64 bytes)
bytes.push(0x80_u8);
while (bytes.len() % 64) != 56 {
bytes.push(0_u8);
}
// Everything after this operates on 32-bit words, so reinterpret the buffer.
let mut w = convert_byte_vec_to_u32(bytes);
// Step 2. Append length
// A 64-bit representation of b (the length of the message before the padding bits were added)
// is appended to the result of the previous step, low-order bytes first.
w.push(initial_bit_len as u32); // Push low-order bytes first
w.push((initial_bit_len >> 32) as u32);
// Step 3. Initialize MD buffer
let mut a = 0x67452301_u32;
let mut b = 0xefcdab89_u32;
let mut c = 0x98badcfe_u32;
let mut d = 0x10325476_u32;
// Step 4. Process message in 16-word blocks
let n = w.len();
for i in 0..n / 16 {
// Select the next 512-bit (16-word) block to process.
let x = &w[i * 16..i * 16 + 16];
let aa = a;
let bb = b;
let cc = c;
let dd = d;
// [Round 1]
md4round1!(a, b, c, d, 0, 3, x); // [A B C D 0 3]
md4round1!(d, a, b, c, 1, 7, x); // [D A B C 1 7]
md4round1!(c, d, a, b, 2, 11, x); // [C D A B 2 11]
md4round1!(b, c, d, a, 3, 19, x); // [B C D A 3 19]
md4round1!(a, b, c, d, 4, 3, x); // [A B C D 4 3]
md4round1!(d, a, b, c, 5, 7, x); // [D A B C 5 7]
md4round1!(c, d, a, b, 6, 11, x); // [C D A B 6 11]
md4round1!(b, c, d, a, 7, 19, x); // [B C D A 7 19]
md4round1!(a, b, c, d, 8, 3, x); // [A B C D 8 3]
md4round1!(d, a, b, c, 9, 7, x); // [D A B C 9 7]
md4round1!(c, d, a, b, 10, 11, x);// [C D A B 10 11]
md4round1!(b, c, d, a, 11, 19, x);// [B C D A 11 19]
md4round1!(a, b, c, d, 12, 3, x); // [A B C D 12 3]
md4round1!(d, a, b, c, 13, 7, x); // [D A B C 13 7]
md4round1!(c, d, a, b, 14, 11, x);// [C D A B 14 11]
md4round1!(b, c, d, a, 15, 19, x);// [B C D A 15 19]
// [Round 2]
md4round2!(a, b, c, d, 0, 3, x); //[A B C D 0 3]
md4round2!(d, a, b, c, 4, 5, x); //[D A B C 4 5]
md4round2!(c, d, a, b, 8, 9, x); //[C D A B 8 9]
md4round2!(b, c, d, a, 12, 13, x);//[B C D A 12 13]
md4round2!(a, b, c, d, 1, 3, x); //[A B C D 1 3]
md4round2!(d, a, b, c, 5, 5, x); //[D A B C 5 5]
md4round2!(c, d, a, b, 9, 9, x); //[C D A B 9 9]
md4round2!(b, c, d, a, 13, 13, x);//[B C D A 13 13]
md4round2!(a, b, c, d, 2, 3, x); //[A B C D 2 3]
md4round2!(d, a, b, c, 6, 5, x); //[D A B C 6 5]
md4round2!(c, d, a, b, 10, 9, x); //[C D A B 10 9]
md4round2!(b, c, d, a, 14, 13, x);//[B C D A 14 13]
md4round2!(a, b, c, d, 3, 3, x); //[A B C D 3 3]
md4round2!(d, a, b, c, 7, 5, x); //[D A B C 7 5]
md4round2!(c, d, a, b, 11, 9, x); //[C D A B 11 9]
md4round2!(b, c, d, a, 15, 13, x);//[B C D A 15 13]
// [Round 3]
md4round3!(a, b, c, d, 0, 3, x); //[A B C D 0 3]
md4round3!(d, a, b, c, 8, 9, x); //[D A B C 8 9]
md4round3!(c, d, a, b, 4, 11, x); //[C D A B 4 11]
md4round3!(b, c, d, a, 12, 15, x);//[B C D A 12 15]
md4round3!(a, b, c, d, 2, 3, x); //[A B C D 2 3]
md4round3!(d, a, b, c, 10, 9, x); //[D A B C 10 9]
md4round3!(c, d, a, b, 6, 11, x); //[C D A B 6 11]
md4round3!(b, c, d, a, 14, 15, x);//[B C D A 14 15]
md4round3!(a, b, c, d, 1, 3, x); //[A B C D 1 3]
md4round3!(d, a, b, c, 9, 9, x); //[D A B C 9 9]
md4round3!(c, d, a, b, 5, 11, x); //[C D A B 5 11]
md4round3!(b, c, d, a, 13, 15, x);//[B C D A 13 15]
md4round3!(a, b, c, d, 3, 3, x); //[A B C D 3 3]
md4round3!(d, a, b, c, 11, 9, x); //[D A B C 11 9]
md4round3!(c, d, a, b, 7, 11, x); //[C D A B 7 11]
md4round3!(b, c, d, a, 15, 15, x);//[B C D A 15 15]
a = a.wrapping_add(aa);
b = b.wrapping_add(bb);
c = c.wrapping_add(cc);
d = d.wrapping_add(dd);
}
// Step 5. Output
// The message digest produced as output is A, B, C, D. That is, we begin with the low-order
// byte of A, and end with the high-order byte of D.
[u32::from_be(a), u32::from_be(b), u32::from_be(c), u32::from_be(d)]
}
fn digest_to_str(digest: &[u32]) -> String {
let mut s = String::new();
for &word in digest {
write!(&mut s, "{:08x}", word).unwrap();
}
s
}
fn main() {
let val = "Rosetta Code";
println!("md4(\"{}\") = {}", val, digest_to_str(&md4(val)));
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #zkl | zkl | fcn middle(ns){
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
if(nl<3 or nl.isEven) return(False);
n[(nl-3)/2,3] : "%03d".fmt(_)
})
}
middle(T(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)).println()
middle(T(1, 2, -1, -10, 2002, -2002, 0)).println(); |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Forth | Forth | include ffl/md5.fs
\ Create a MD5 variable md1 in the dictionary
md5-create md1
\ Update the variable with data
s" The quick brown fox jumps over the lazy dog" md1 md5-update
\ Finish the MD5 calculation resulting in four unsigned 32 bit words
\ on the stack representing the hash value
md1 md5-finish
\ Convert the hash value to a hex string and print it
md5+to-string type cr |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
Task
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number n which cannot be expressed with 6x + 9y + 20z = n
where x, y and z are natural numbers).
| #REXX | REXX | /*REXX pgm solves the McNuggets problem: the largest McNugget number for given meals. */
parse arg y /*obtain optional arguments from the CL*/
if y='' | y="," then y= 6 9 20 /*Not specified? Then use the defaults*/
say 'The number of McNuggets in the serving sizes of: ' space(y)
$=
#= 0 /*the Y list must be in ascending order*/
z=.
do j=1 for words(y); _= word(y, j) /*examine Y list for dups, neg, zeros*/
if _==1 then signal done /*Value ≡ 1? Then all values possible.*/
if _<1 then iterate /*ignore zero and negative # of nuggets*/
if wordpos(_, $)\==0 then iterate /*search for duplicate values. */
do k=1 for # /* " " multiple " */
if _//word($,k)==0 then iterate j /*a multiple of a previous value, skip.*/
end /*k*/
$= $ _; #= # + 1; $.#= _ /*add─►list; bump counter; assign value*/
end /*j*/
if #<2 then signal done /*not possible, go and tell bad news. */
_= gcd($) if _\==1 then signal done /* " " " " " " " */
if #==2 then z= $.1 * $.2 - $.1 - $.2 /*special case, construct the result. */
if z\==. then signal done
h= 0 /*construct a theoretical high limit H.*/
do j=2 for #-1; _= j-1; _= $._; h= max(h, _ * $.j - _ - $.j)
end /*j*/
@.=0
do j=1 for #; _= $.j /*populate the Jth + Kth summand. */
do a=_ by _ to h; @.a= 1 /*populate every multiple as possible. */
end /*s*/
do k=1 for h; if \@.k then iterate
s= k + _; @.s= 1 /*add two #s; mark as being possible.*/
end /*k*/
end /*j*/
do z=h by -1 for h until \@.z /*find largest integer not summed. */
end /*z*/
say
done: if z==. then say 'The largest McNuggets number not possible.'
else say 'The largest McNuggets number is: ' z
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gcd: procedure; $=; do j=1 for arg(); $=$ arg(j); end; $= space($)
parse var $ x $; x= abs(x);
do while $\==''; parse var $ y $; y= abs(y); if y==0 then iterate
do until y==0; parse value x//y y with y x; end
end; return x |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most significant
digit at the left). This task will be using a left─to─right (horizontal) format, mostly for familiarity and
readability, and to conserve screen space (when showing the output) on this task page.
Mayan numerals
Mayan numerals (a base─20 "digit" or glyph) are written in two orientations, this
task will be using the "vertical" format (as displayed below). Using the vertical format makes
it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.)
and hyphen (-); (however, round bullets (•) and long dashes (─)
make a better presentation on Rosetta Code).
Furthermore, each Mayan numeral (for this task) is to be displayed as a
cartouche (enclosed in a box) to make it easier to parse (read); the box may be
drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers.
Mayan numerals added to Unicode
Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018 (this corresponds with
version 11.0). But since most web browsers don't support them at this time, this Rosetta Code
task will be constructing the glyphs with "simple" characters and/or ASCII art.
The "zero" glyph
The Mayan numbering system has the concept of zero, and should be shown by a glyph that represents
an upside─down (sea) shell, or an egg. The Greek letter theta (Θ) can be
used (which more─or─less, looks like an
egg). A commercial at symbol (@) could make a poor substitute.
Mayan glyphs (constructed)
The Mayan numbering system is
a [vigesimal (base 20)] positional numeral system.
The Mayan numerals (and some random numbers) shown in the vertical format would be shown as
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙ ║ ║ ║ ║
1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║
║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙∙ ║ ║ ║ ║
2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║
║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙ ║ ║ ║ ║
3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║
║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙∙║ ║ ║ ║
4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║
║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
5──► ║ ║ 15──► ║────║ 90──► ║ ║────║
║────║ ║────║ ║∙∙∙∙║────║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║∙∙∙ ║ ║ ║ ║
║ ║ ║────║ 300──► ║────║ ║
8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╦════╗
║ ║ ║∙∙∙∙║ ║ ║ ║ ║
║ ║ ║────║ 400──► ║ ║ ║ ║
9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║
║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╩════╝
╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║
║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║
╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝
Note that the Mayan numeral 13 in horizontal format would be shown as:
╔════╗
║ ││║
║ ∙││║
13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task.
║ ∙││║
╚════╝
Other forms of cartouches (boxes) can be used for this task.
Task requirements
convert the following decimal numbers to Mayan numbers:
4,005
8,017
326,205
886,205
show a unique interesting/pretty/unusual/intriguing/odd/amusing/weird Mayan number
show all output here
Related tasks
Roman numerals/Encode ─── convert numeric values into Roman numerals
Roman numerals/Decode ─── convert Roman numerals into Arabic numbers
See also
The Wikipedia entry: [Mayan numerals]
| #Rust | Rust | const ONE: &str = "●";
const FIVE: &str = "——";
const ZERO: &str = "Θ";
fn main() {
println!("{}", mayan(4005));
println!("{}", mayan(8017));
println!("{}", mayan(326_205));
println!("{}", mayan(886_205));
println!("{}", mayan(69));
println!("{}", mayan(420));
println!("{}", mayan(1_063_715_456));
}
fn mayan(dec: i64) -> String {
let mut digits = vec![];
let mut num = dec;
while num > 0 {
digits.push(num % 20);
num /= 20;
}
digits = digits.into_iter().rev().collect();
let mut boxes = vec!["".to_string(); 6];
let n = digits.len();
for (i, digit) in digits.iter().enumerate() {
if i == 0 {
boxes[0] = "┏━━━━".to_string();
if i == n - 1 {
boxes[0] += "┓";
}
} else if i == n - 1 {
boxes[0] += "┳━━━━┓";
} else {
boxes[0] += "┳━━━━";
}
for j in 1..5 {
boxes[j] += "┃";
let elem = 0.max(digit - (4 - j as i64) * 5);
if elem >= 5 {
boxes[j] += &format!("{: ^4}", FIVE);
} else if elem > 0 {
boxes[j] += &format!("{: ^4}", ONE.repeat(elem as usize % 15));
} else if j == 4 {
boxes[j] += &format!("{: ^4}", ZERO);
} else {
boxes[j] += &" ";
}
if i == n - 1 {
boxes[j] += "┃";
}
}
if i == 0 {
boxes[5] = "┗━━━━".to_string();
if i == n - 1 {
boxes[5] += "┛";
}
} else if i == n - 1 {
boxes[5] += "┻━━━━┛";
} else {
boxes[5] += "┻━━━━";
}
}
let mut mayan = format!("Mayan {}:\n", dec);
for b in boxes {
mayan += &(b + "\n");
}
mayan
} |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most significant
digit at the left). This task will be using a left─to─right (horizontal) format, mostly for familiarity and
readability, and to conserve screen space (when showing the output) on this task page.
Mayan numerals
Mayan numerals (a base─20 "digit" or glyph) are written in two orientations, this
task will be using the "vertical" format (as displayed below). Using the vertical format makes
it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.)
and hyphen (-); (however, round bullets (•) and long dashes (─)
make a better presentation on Rosetta Code).
Furthermore, each Mayan numeral (for this task) is to be displayed as a
cartouche (enclosed in a box) to make it easier to parse (read); the box may be
drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers.
Mayan numerals added to Unicode
Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018 (this corresponds with
version 11.0). But since most web browsers don't support them at this time, this Rosetta Code
task will be constructing the glyphs with "simple" characters and/or ASCII art.
The "zero" glyph
The Mayan numbering system has the concept of zero, and should be shown by a glyph that represents
an upside─down (sea) shell, or an egg. The Greek letter theta (Θ) can be
used (which more─or─less, looks like an
egg). A commercial at symbol (@) could make a poor substitute.
Mayan glyphs (constructed)
The Mayan numbering system is
a [vigesimal (base 20)] positional numeral system.
The Mayan numerals (and some random numbers) shown in the vertical format would be shown as
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙ ║ ║ ║ ║
1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║
║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║ ∙∙ ║ ║ ║ ║
2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║
║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙ ║ ║ ║ ║
3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║
║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║∙∙∙∙║ ║ ║ ║
4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║
║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
5──► ║ ║ 15──► ║────║ 90──► ║ ║────║
║────║ ║────║ ║∙∙∙∙║────║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║ ∙∙ ║ ║ ║ ║
║ ║ ║────║ ║ ║ ║
7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╗
║ ║ ║∙∙∙ ║ ║ ║ ║
║ ║ ║────║ 300──► ║────║ ║
8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║
║────║ ║────║ ║────║ Θ ║
╚════╝ ╚════╝ ╚════╩════╝
╔════╗ ╔════╗ ╔════╦════╦════╗
║ ║ ║∙∙∙∙║ ║ ║ ║ ║
║ ║ ║────║ 400──► ║ ║ ║ ║
9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║
║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║
╚════╝ ╚════╝ ╚════╩════╩════╝
╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║
║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║
╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝
Note that the Mayan numeral 13 in horizontal format would be shown as:
╔════╗
║ ││║
║ ∙││║
13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task.
║ ∙││║
╚════╝
Other forms of cartouches (boxes) can be used for this task.
Task requirements
convert the following decimal numbers to Mayan numbers:
4,005
8,017
326,205
886,205
show a unique interesting/pretty/unusual/intriguing/odd/amusing/weird Mayan number
show all output here
Related tasks
Roman numerals/Encode ─── convert numeric values into Roman numerals
Roman numerals/Decode ─── convert Roman numerals into Arabic numbers
See also
The Wikipedia entry: [Mayan numerals]
| #Wren | Wren | import "/fmt" for Conv
var ul = "╔"
var uc = "╦"
var ur = "╗"
var ll = "╚"
var lc = "╩"
var lr = "╝"
var hb = "═"
var vb = "║"
var mayan= [
" ",
" ∙ ",
" ∙∙ ",
"∙∙∙ ",
"∙∙∙∙"
]
var m0 = " Θ "
var m5 = "────"
var dec2vig = Fn.new { |n| Conv.itoa(n, 20).map { |c| Conv.atoi(c, 20) }.toList }
var vig2quin = Fn.new { |n|
if (n >= 20) Fiber.abort("Cant't convert a number >= 20.")
var res = [mayan[0], mayan[0], mayan[0], mayan[0]]
if (n == 0) {
res[3] = m0
return res
}
var fives = (n/5).floor
var rem = n % 5
res[3-fives] = mayan[rem]
for (i in 3...3-fives) res[i] = m5
return res
}
var draw = Fn.new { |mayans|
var lm = mayans.count
System.write(ul)
for (i in 0...lm) {
for (j in 0..3) System.write(hb)
if (i < lm - 1) {
System.write(uc)
} else {
System.print(ur)
}
}
for (i in 1..4) {
System.write(vb)
for (j in 0...lm) {
System.write(mayans[j][i-1])
System.write(vb)
}
System.print()
}
System.write(ll)
for (i in 0...lm) {
for (j in 0..3) System.write(hb)
if (i < lm - 1) {
System.write(lc)
} else {
System.print(lr)
}
}
}
var numbers = [4005, 8017, 326205, 886205, 1081439556]
for (n in numbers) {
System.print("Converting %(n) to Mayan:")
var vigs = dec2vig.call(n)
var mayans = vigs.map { |vig| vig2quin.call(vig) }.toList
draw.call(mayans)
System.print()
} |
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)
| #11l | 11l | -V LOG_10 = 2.302585092994
F build_oms(=s)
I s % 2 == 0
s++
V q = [[0] * s] * s
V p = 1
V i = s I/ 2
V j = 0
L p <= (s * s)
q[i][j] = p
V ti = i + 1
I ti >= s
ti = 0
V tj = j - 1
I tj < 0
tj = s - 1
I q[ti][tj] != 0
ti = i
tj = j + 1
i = ti
j = tj
p++
R (q, s)
F build_sems(=s)
I s % 2 == 1
s++
L s % 4 == 0
s += 2
V q = [[0] * s] * s
V z = s I/ 2
V b = z * z
V c = 2 * b
V d = 3 * b
V o = build_oms(z)
L(j) 0 .< z
L(i) 0 .< z
V a = o[0][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
V lc = z I/ 2
V rc = lc
L(j) 0 .< z
L(i) 0 .< s
I i < lc
| i > s - rc
| (i == lc & j == lc)
I !(i == 0 & j == lc)
swap(&q[i][j], &q[i][j + z])
R (q, s)
F display(q)
V s = q[1]
print(" - #. x #.\n".format(s, s))
V k = 1 + Int(floor(log(s * s) / :LOG_10))
L(j) 0 .< s
L(i) 0 .< s
print(String(q[0][i][j]).zfill(k), end' ‘ ’)
print()
print(‘Magic sum: #.’.format(s * ((s * s) + 1) I/ 2))
print(‘Singly Even Magic Square’, end' ‘’)
display(build_sems(6)) |
http://rosettacode.org/wiki/Magic_constant | Magic constant | A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant.
EG
A 3 x 3 magic square always sums to 15.
┌───┬───┬───┐
│ 2 │ 7 │ 6 │
├───┼───┼───┤
│ 9 │ 5 │ 1 │
├───┼───┼───┤
│ 4 │ 3 │ 8 │
└───┴───┴───┘
A 4 x 4 magic square always sums to 34.
Traditionally, the sequence leaves off terms for n = 0 and n = 1 as the magic squares of order 0 and 1 are trivial; and a term for n = 2 because it is impossible to form a magic square of order 2.
Task
Starting at order 3, show the first 20 magic constants.
Show the 1000th magic constant. (Order 1003)
Find and show the order of the smallest N x N magic square whose constant is greater than 10¹ through 10¹⁰.
Stretch
Find and show the order of the smallest N x N magic square whose constant is greater than 10¹¹ through 10²⁰.
See also
Wikipedia: Magic constant
OEIS: A006003 (Similar sequence, though it includes terms for 0, 1 & 2.)
| #ALGOL_68 | ALGOL 68 | BEGIN # find some magic constants - the row, column and diagonal sums of a magin square #
# translation of the Free Basic sample with the Julia/Wren inverse function #
# returns the magic constant of a magic square of order n + 2 #
PROC a = ( INT n )LONG LONG INT:
BEGIN
LONG LONG INT n2 = n + 2;
( n2 * ( ( n2 * n2 ) + 1 ) ) OVER 2
END # a # ;
# returns the order of the magic square whose magic constant is at least x #
PROC inv a = ( LONG LONG INT x )LONG LONG INT:
ENTIER long long exp( long long ln( x * 2 ) / 3 ) + 1;
print( ( "The first 20 magic constants are " ) );
FOR n TO 20 DO
print( ( whole( a( n ), 0 ), " " ) )
OD;
print( ( newline ) );
print( ( "The 1,000th magic constant is ", whole( a( 1000 ), 0 ), newline ) );
LONG LONG INT e := 1;
FOR n TO 20 DO
e *:= 10;
print( ( "10^", whole( n, -2 ), ": ", whole( inv a( e ), -9 ), newline ) )
OD
END |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #APL | APL | x ← +.×
A ← ↑A*¨⊂A←⍳4 ⍝ Same A as in other examples (1 1 1 1⍪ 2 4 8 16⍪ 3 9 27 81,[0.5] 4 16 64 256)
B ← ⌹A ⍝ Matrix inverse of A
'F6.2' ⎕FMT A x B
1.00 0.00 0.00 0.00
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00 |
http://rosettacode.org/wiki/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.
| #Elixir | Elixir | File.mkdir_p("./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.
| #ERRE | ERRE | OS_MKDIR("C:\EXAMPLES\03192015") |
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.
| #F.23 | F# | > System.IO.Directory.CreateDirectory (System.IO.Directory.GetCurrentDirectory())
;;
val it : System.IO.DirectoryInfo =
Temp {Attributes = Directory;
CreationTime = 2016-06-01 04:12:25;
CreationTimeUtc = 2016-06-01 02:12:25;
Exists = true;
Extension = "";
FullName = "C:\Users\Kai\AppData\Local\Temp";
LastAccessTime = 2016-08-18 20:42:21;
LastAccessTimeUtc = 2016-08-18 18:42:21;
LastWriteTime = 2016-08-18 20:42:21;
LastWriteTimeUtc = 2016-08-18 18:42:21;
Name = "Temp";
Parent = Local;
Root = C:\;}
> |
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.
| #Factor | Factor | USE: io.directories
"path/to/dir" make-directories |
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.
| #FreeBASIC | FreeBASIC | #ifdef __FB_WIN32__
Dim pathname As String = "Ring\docs"
#else
Dim pathname As String = "Ring/docs"
#endif
Dim As String mkpathname = "mkdir " & pathname
Dim result As Long = Shell (mkpathname)
If result = 0 Then
Print "Created the directory..."
Chdir(pathname)
Print Curdir
Else
Print "error: unable to create folder " & pathname & " in the current path."
End If
Sleep |
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
| #ALGOL_W | ALGOL W | begin
real procedure A (integer value k; real procedure x1, x2, x3, x4, x5);
begin
real procedure B;
begin k:= k - 1;
A (k, B, x1, x2, x3, x4)
end;
if k <= 0 then x4 + x5 else B
end;
write (r_format := "A", r_w := 8, r_d := 2, A (10, 1, -1, -1, 1, 0))
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
| #AppleScript | AppleScript | on a(k, x1, x2, x3, x4, x5)
script b
set k to k - 1
return a(k, b, x1, x2, x3, x4)
end script
if k ≤ 0 then
return (run x4) + (run x5)
else
return (run b)
end if
end a
on int(x)
script s
return x
end script
return s
end int
a(10, int(1), int(-1), int(-1), int(1), int(0))
|
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.
| #FreeBASIC | FreeBASIC | Dim Shared As Ubyte k87(255), k65(255), k43(255), k21(255)
Sub kboxinit()
Dim As Ubyte k8(15) = {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}
Dim As Ubyte k7(15) = {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}
Dim As Ubyte k6(15) = {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}
Dim As Ubyte k5(15) = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}
Dim As Ubyte k4(15) = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}
Dim As Ubyte k3(15) = {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}
Dim As Ubyte k2(15) = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}
Dim As Ubyte k1(15) = {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}
For i As Uinteger = 0 To 255
k87(i) = k8(i Shr 4) Shl 4 Or k7(i And 15)
k65(i) = k6(i Shr 4) Shl 4 Or k5(i And 15)
k43(i) = k4(i Shr 4) Shl 4 Or k3(i And 15)
k21(i) = k2(i Shr 4) Shl 4 Or k1(i And 15)
Next i
End Sub
Function f(x As Integer) As Integer
x = k87(x Shr 24 And 255) Shl 24 Or k65(x Shr 16 And 255) Shl 16 Or _
k43(x Shr 8 And 255) Shl 8 Or k21(x And 255)
Return x Shl 11 Or x Shr (32-11)
End Function |
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.
| #C.23 | C# | using System; using static System.Console;
class Program {
static bool[] np; // not-prime array
static void ms(long lmt) { // populates array, a not-prime is true
np = new bool[lmt]; np[0] = np[1] = true;
for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])
for (long k = n * n; k < lmt; k += n) np[k] = true; }
static bool is_Mag(long n) { long res, rem;
for (long p = 10; n >= p; p *= 10) {
res = Math.DivRem (n, p, out rem);
if (np[res + rem]) return false; } return true; }
static void Main(string[] args) { ms(100_009); string mn;
WriteLine("First 45{0}", mn = " magnanimous numbers:");
for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {
if (c++ < 45 || (c > 240 && c <= 250) || c > 390)
Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l);
if (c < 45 && c % 15 == 0) WriteLine();
if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn);
if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } }
} |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #ALGOL_68 | ALGOL 68 | main:(
[,]REAL m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625));
OP ZIP = ([,]REAL in)[,]REAL:(
[2 LWB in:2 UPB in,1 LWB in:1UPB in]REAL out;
FOR i FROM LWB in TO UPB in DO
out[,i]:=in[i,]
OD;
out
);
PROC pprint = ([,]REAL m)VOID:(
FORMAT real fmt = $g(-6,2)$; # width of 6, with no '+' sign, 2 decimals #
FORMAT vec fmt = $"("n(2 UPB m-1)(f(real fmt)",")f(real fmt)")"$;
FORMAT matrix fmt = $x"("n(UPB m-1)(f(vec fmt)","lxx)f(vec fmt)");"$;
# finally print the result #
printf((matrix fmt,m))
);
printf(($x"Transpose:"l$));
pprint((ZIP m))
) |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int BMP_SIZE = 512, CELL_SIZE = 8;
//--------------------------------------------------------------------------------------------------
enum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 };
//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear()
{
ZeroMemory( pBits, width * height * sizeof( DWORD ) );
}
void setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
void *pBits;
int width, height;
};
//--------------------------------------------------------------------------------------------------
class mazeGenerator
{
public:
mazeGenerator()
{
_world = 0;
_bmp.create( BMP_SIZE, BMP_SIZE );
_bmp.setPenColor( RGB( 0, 255, 0 ) );
}
~mazeGenerator() { killArray(); }
void create( int side )
{
_s = side;
generate();
display();
}
private:
void generate()
{
killArray();
_world = new BYTE[_s * _s];
ZeroMemory( _world, _s * _s );
_ptX = rand() % _s; _ptY = rand() % _s;
carve();
}
void carve()
{
while( true )
{
int d = getDirection();
if( d < NOR ) return;
switch( d )
{
case NOR:
_world[_ptX + _s * _ptY] |= NOR; _ptY--;
_world[_ptX + _s * _ptY] = SOU | SOU << 4;
break;
case EAS:
_world[_ptX + _s * _ptY] |= EAS; _ptX++;
_world[_ptX + _s * _ptY] = WES | WES << 4;
break;
case SOU:
_world[_ptX + _s * _ptY] |= SOU; _ptY++;
_world[_ptX + _s * _ptY] = NOR | NOR << 4;
break;
case WES:
_world[_ptX + _s * _ptY] |= WES; _ptX--;
_world[_ptX + _s * _ptY] = EAS | EAS << 4;
}
}
}
void display()
{
_bmp.clear();
HDC dc = _bmp.getDC();
for( int y = 0; y < _s; y++ )
{
int yy = y * _s;
for( int x = 0; x < _s; x++ )
{
BYTE b = _world[x + yy];
int nx = x * CELL_SIZE,
ny = y * CELL_SIZE;
if( !( b & NOR ) )
{
MoveToEx( dc, nx, ny, NULL );
LineTo( dc, nx + CELL_SIZE + 1, ny );
}
if( !( b & EAS ) )
{
MoveToEx( dc, nx + CELL_SIZE, ny, NULL );
LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 );
}
if( !( b & SOU ) )
{
MoveToEx( dc, nx, ny + CELL_SIZE, NULL );
LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE );
}
if( !( b & WES ) )
{
MoveToEx( dc, nx, ny, NULL );
LineTo( dc, nx, ny + CELL_SIZE + 1 );
}
}
}
//_bmp.saveBitmap( "f:\\rc\\maze.bmp" );
BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY );
}
int getDirection()
{
int d = 1 << rand() % 4;
while( true )
{
for( int x = 0; x < 4; x++ )
{
if( testDir( d ) ) return d;
d <<= 1;
if( d > 8 ) d = 1;
}
d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4;
if( !d ) return -1;
switch( d )
{
case NOR: _ptY--; break;
case EAS: _ptX++; break;
case SOU: _ptY++; break;
case WES: _ptX--; break;
}
d = 1 << rand() % 4;
}
}
bool testDir( int d )
{
switch( d )
{
case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] );
case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] );
case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] );
case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] );
}
return false;
}
void killArray() { if( _world ) delete [] _world; }
BYTE* _world;
int _s, _ptX, _ptY;
myBitmap _bmp;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
srand( GetTickCount() );
mazeGenerator mg;
int s;
while( true )
{
cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s;
if( !s ) return 0;
if( !( s & 1 ) ) s++;
if( s >= 3 ) mg.create( s );
cout << endl;
system( "pause" );
system( "cls" );
}
return 0;
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #J | J | mp=: +/ .* NB. Matrix multiplication
pow=: pow0=: 4 : 'mp&x^:y =i.#x' |
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.
| #JavaScript | JavaScript | // IdentityMatrix is a "subclass" of Matrix
function IdentityMatrix(n) {
this.height = n;
this.width = n;
this.mtx = [];
for (var i = 0; i < n; i++) {
this.mtx[i] = [];
for (var j = 0; j < n; j++) {
this.mtx[i][j] = (i == j ? 1 : 0);
}
}
}
IdentityMatrix.prototype = Matrix.prototype;
// the Matrix exponentiation function
// returns a new matrix
Matrix.prototype.exp = function(n) {
var result = new IdentityMatrix(this.height);
for (var i = 1; i <= n; i++) {
result = result.mult(this);
}
return result;
}
var m = new Matrix([[3, 2], [2, 1]]);
[0,1,2,3,4,10].forEach(function(e){print(m.exp(e)); print()}) |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\displaystyle t}
in range
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
where:
t
=
b
1
+
(
s
−
a
1
)
(
b
2
−
b
1
)
(
a
2
−
a
1
)
{\displaystyle t=b_{1}+{(s-a_{1})(b_{2}-b_{1}) \over (a_{2}-a_{1})}}
Task
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
Extra credit
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| #BASIC | BASIC | function MapRange(s, a1, a2, b1, b2)
return b1+(s-a1)*(b2-b1)/(a2-a1)
end function
for i = 0 to 10
print i; " maps to "; MapRange(i,0,10,-1,0)
next i
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.
| #bc | bc | /* map s from [a, b] to [c, d] */
define m(a, b, c, d, s) {
return (c + (s - a) * (d - c) / (b - a))
}
scale = 6 /* division to 6 decimal places */
"[0, 10] => [-1, 0]
"
for (i = 0; i <= 10; i += 2) {
/*
* If your bc(1) has a print statement, you can try
* print i, " => ", m(0, 10, -1, 0, i), "\n"
*/
i; " => "; m(0, 10, -1, 0, i)
}
quit |
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.
| #Perl | Perl | #!/user/bin/perl
use strict;
use warnings;
use Tk;
my $delay = 50; # milliseconds
my $fade = 8; # number of characters to "fade"
my $base_color = '#004000'; # dark green
my $fontname = 'Times'; # Whatever
my $fontsize = 12; # point size
my $font = "{$fontname} $fontsize bold";
my @objects;
my ( $xv, $yv ) = ( 0, 0 );
my $top = MainWindow->new();
$top->geometry('800x600');
my $run = 1;
$top->protocol( 'WM_DELETE_WINDOW' => sub { $run = 0; } );
my @letters = ( 'A' .. 'Z', 'a' .. 'z', '0' .. '9' );
my $canvas = $top->Canvas(
-background => 'black'
)->pack(
-fill => 'both',
-expand => 'y'
);
my $testch = $canvas->createText(
100, 100,
-text => 'o',
-fill => 'black',
-font => $font
);
$top->update;
my @coords = $canvas->bbox($testch);
$canvas->delete($testch);
my $lwidth = $coords[2] - $coords[0];
my $lheight = ( $coords[3] - $coords[1] ) * .8;
my $cols = int $canvas->width / $lwidth;
my $rows = int $canvas->height / $lheight;
for my $y ( 0 .. $rows ) {
for my $x ( 0 .. $cols ) {
$objects[$x][$y] = $canvas->createText(
$x * $lwidth, $y * $lheight,
-text => $letters[ int rand @letters ],
-fill => $base_color,
-font => $font
);
}
}
my $neo_image = $top->Photo( -data => neo() );
my $neo = $canvas->createImage(
$canvas->width / 2,
$canvas->height / 2,
-image => $neo_image
);
while ($run) {
drop('Nothing Like The Matrix');
}
exit;
MainLoop;
sub drop {
my @phrase = split //, reverse shift;
my $x = int rand $cols;
my @orig;
for my $y ( 0 .. $rows ) {
$orig[$y] = $canvas->itemcget( $objects[$x][$y], '-text' );
}
for my $y ( 0 .. $rows + @phrase + $fade ) {
for my $letter ( 0 .. @phrase ) {
last if ( $y - $letter < 0 );
$canvas->itemconfigure(
$objects[$x][ $y - $letter ],
-text => $phrase[$letter],
-fill => "#00FF00"
);
}
if ( $y > @phrase ) {
$canvas->itemconfigure(
$objects[$x][ $y - @phrase ],
-text => $orig[ $y - @phrase ],
-fill => "#009000"
);
}
if ( $y > @phrase + 2 ) {
$canvas->itemconfigure( $objects[$x][ $y - @phrase - int ($fade / 2) ],
-fill => "#006000" );
$canvas->itemconfigure( $objects[$x][ $y - @phrase - $fade + 1 ],
-fill => $base_color );
}
last unless $run;
$top->after($delay);
neo_move();
$top->update;
}
}
sub neo_move {
$xv += ( ( rand 2 ) - 1 > 0 ) ? 1 : -1;
$yv += ( ( rand 2 ) - 1 > 0 ) ? 1 : -1;
my ( $x, $y ) = $canvas->coords($neo);
$xv = -$xv if ( ( $x < 0 ) or ( $x > $canvas->width ) );
$yv = -$yv if ( ( $y < 0 ) or ( $y > $canvas->height ) );
$canvas->move( $neo, $xv, $yv );
}
sub neo {
return '
R0lGODlhjAC1APcAAAQDBISCZEJDM8nDq6eihGJjSyQjFOzj0oSEhGRlZCktLKKkpEhNTMHFxBES
BFBSNDMyJJSSbOru7HFyVGt0aqm1q5OVhMnTy2RELLmzmy0UEUQiDMa1pZSEbCo4MrSVhIh0Z9jO
tLSljNPV1IhkSPjy3D9EPCYDBB4VHJGVlCIjHGxKTOrl3GFkVLnCuUU5LQsLCXmDesq9tk9XTBEa
FOXVxSEqImRUQvv37HF1dJOahZmkmOzq3Km6tMe8qEJLQJhyVIZ9Z9bFtJeEeLamlG5sVFEzIUAp
LKSUfGBeXN/FxBIUFHN7XF9FPiwcDD0kITc9PF5ZTk1LNFlbQ3p9ZYqMdXhqZOna1C4lHREOFOXb
xLesl/z6/JeNdj47JJqafLy7pZ+Vhjs+MKurlYl8dBUEBa2chNrQvBUNC9e8qkAsHIqLbGtrTH10
W8O6m1Q+PPXs301EMpyMhMGtpFhURNzbykU+MVBMPS8dHPTq1B4UDD0zI4qTfDo4LU5FPJKclvTm
3G1dTYFjVHhcXIOMhlprZKqrpFxMNJWLbEw+JF1NPqSbfGBQTKyri8XMxEQsFNbb1CYMBB8dHGRa
PHR9dD8xLNvNxH1tWbCelOXQvG5lVUgcEIhcTM/KrDAqFPny7bTKvLq+t3RuZC8yLk1STZRqTPz6
5FFeUfz+86B6XNbKt+ve1dTDrG1lTC4jFPTl1Hh1Zru2pNzUxMS0nEAWENW1qaiCaJh2aMzFtFw6
NImFdte9tCEcEzEsIaCchqmmlLa4tZZ7aayGdFQiHMWtnKaNfJ+blo6OiWlsZm9OQ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qioTg5UXtAGA9eTUKCAwx4FBu9OB0fvbmkoz2EpC1+FOtBGqmCBMdmKD79l+PCFL6CGL6gCWCgA
AehOEoqGJdCGJWBxPfkDWJgBrx08i+gD4H7wNQiD+IOUUlIFLLtw/x5IBzuJIsA8g04orlLqhAHI
AAJ4wHbGhgIQg6WyQm3QlSlPljGgglPwgjozAC1/1imYABb6Anh42lKa0TOog2t8hw8UzA5PQ5aK
0+Ls678ugh+AAF5IvmiAgSzIGz5PFguIhRj4ARvwNSyAgO/cBjZYOF9oqFJ7u5AELMI0kyAXmxl9
DDBoBGpYgzWgginYXJUJi7yRclKvmxhgCM+cUNKkg26oAiP3hccsNTCrKVxwBpdjLixzD3Uagy8Q
dhMXA87VBj3PGxogB2XHID4QAF4Y9ELF0CkQ1Qes9sho1YomJb/qdfZrhC/ABiYoACkouIhQEw5S
d3bHIGfQBeOzM//pvYMC6G8wllb4E4ExaIRGeD1thQymXaAc1YE1KIJt6AMDMHhdSXflU3gMqgAK
gADsrLPqLU2J5+93XhQ+KHJfaGHHdEzF4PlHroIgWHIVoAE9PzQOWnnF2gFzGAUVsOMCNoE7mIIC
KIDVLIJ2iJlugIV4nngv/oIid2cqUJ9eoIFD0xsAS/oSGwNzoF4x8AATgOaZBG5p3gYiIzLYZoMi
EGYmIGySJngVuEJdATCkT/sS44MBFgBo9mQC7kWx5s4CJuDSvAMToPw+sAEV15WjPzIYKPwSAwMd
aIcfSHwC7rU6OsLkA0Z4V4EBX4mIADDBN9bOl7UdAH0CJtTOVBmcSVi+JYDyc3d9BxD86jNWzpd9
WeODHJ7eXiAHLNDHldD95fMLv4DyhzD7wT+y4sc79eFtQmx+lYmGibDCJXgI6yd87PdB22f+XJ2R
I2R9vtCDKDf78jf/lCRvGFv9CrRClL/++ffTLM9V/geIfgIHEixo8CDChAoXMmzo8CHEiBInUqxo
8SLGjBo3cuzo8SPIkCJHkixp8iTKiQEBADs=
';
}
|
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
| #Nim | Nim | import random, sequtils, strformat, strutils
proc encode(correct, guess: string): string =
result.setlen(correct.len)
for i in 0..correct.high:
result[i] = if correct[i] == guess[i]: 'X' else: (if guess[i] in correct: 'O' else: '-')
result.join(" ")
proc safeIntInput(prompt: string; minVal, maxVal: Positive): int =
while true:
stdout.write prompt
let userInput = stdin.readLine()
result = try: parseInt(userInput)
except ValueError: continue
if result in minVal..maxVal:
return
proc playGame() =
echo "You will need to guess a random code."
echo "For each guess, you will receive a hint."
echo "In this hint, X denotes a correct letter, " &
"and O a letter in the original string but in a different position."
echo ""
let numLetters = safeIntInput("Select a number of possible letters for the code (2-20): ", 2, 20)
let codeLength = safeIntInput("Select a length for the code (4-10): ", 4, 10)
let letters = "ABCDEFGHIJKLMNOPQRST"[0..<numLetters]
let code = newSeqWith(codeLength, letters.sample()).join()
var guesses: seq[string]
while true:
echo ""
stdout.write &"Enter a guess of length {codeLength} ({letters}): "
let guess = stdin.readLine().toUpperAscii().strip()
if guess.len != codeLength or guess.anyIt(it notin letters):
continue
elif guess == code:
echo &"\nYour guess {guess} was correct!"
break
else:
guesses.add &"{guesses.len + 1}: {guess.join(\" \")} => {encode(code, guess)}"
for guess in guesses:
echo "------------------------------------"
echo guess
echo "------------------------------------"
randomize()
playGame() |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #Python | Python | def parens(n):
def aux(n, k):
if n == 1:
yield k
elif n == 2:
yield [k, k + 1]
else:
a = []
for i in range(1, n):
for u in aux(i, k):
for v in aux(n - i, k + i):
yield [u, v]
yield from aux(n, 0) |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.
For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.
Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):
AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15. The total cost is 105.
BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30. The total cost is 48.
In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.
Task
Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and not [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.
Try this function on the following two lists:
[1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
[1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.
See also Matrix chain multiplication on Wikipedia.
| #R | R | aux <- function(i, j, u) {
k <- u[[i, j]]
if (k < 0) {
i
} else {
paste0("(", Recall(i, k, u), "*", Recall(i + k, j - k, u), ")")
}
}
chain.mul <- function(a) {
n <- length(a) - 1
u <- matrix(0, n, n)
v <- matrix(0, n, n)
u[, 1] <- -1
for (j in seq(2, n)) {
for (i in seq(n - j + 1)) {
v[[i, j]] <- Inf
for (k in seq(j - 1)) {
s <- v[[i, k]] + v[[i + k, j - k]] + a[[i]] * a[[i + k]] * a[[i + j]]
if (s < v[[i, j]]) {
u[[i, j]] <- k
v[[i, j]] <- s
}
}
}
}
list(cost = v[[1, n]], solution = aux(1, n, u))
}
chain.mul(c(5, 6, 3, 1))
# $cost
# [1] 48
# $solution
# [1] "(1*(2*3))"
chain.mul(c(1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2))
# $cost
# [1] 38120
# $solution
# [1] "((((((((1*2)*3)*4)*5)*6)*7)*(8*(9*10)))*(11*12))"
chain.mul(c(1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10))
# $cost
# [1] 1773740
# $solution
# [1] "(1*((((((2*3)*4)*(((5*6)*7)*8))*9)*10)*11))" |
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.
| #Phix | Phix | --
-- demo\rosetta\Maze_solving.exw
-- =============================
--
with javascript_semantics
constant w = 11, h = 8
sequence wall = join(repeat("+",w+1),"---")&"\n",
cell = join(repeat("|",w+1)," ? ")&"\n",
grid = split(join(repeat(wall,h+1),cell),'\n')
procedure amaze(integer x, y)
grid[y][x] = ' ' -- mark cell visited
sequence p = shuffle({{x-4,y},{x,y+2},{x+4,y},{x,y-2}})
for i=1 to length(p) do
integer {nx,ny} = p[i]
if nx>1 and nx<w*4 and ny>1 and ny<=2*h and grid[ny][nx]='?' then
integer mx = (x+nx)/2
grid[(y+ny)/2][mx-1..mx+1] = ' ' -- knock down wall
amaze(nx,ny)
end if
end for
end procedure
integer dx, dy -- door location (in a wall!)
function solve_maze(integer x, y)
sequence p = {{x-4,y},{x,y+2},{x+4,y},{x,y-2}}
for d=1 to length(p) do
integer {nx,ny} = p[d]
integer {wx,wy} = {(x+nx)/2,(y+ny)/2}
if grid[wy][wx]=' ' then
grid[wy][wx] = "-:-:"[d] -- mark path
if {wx,wy}={dx,dy} then return true end if
if grid[ny][nx]=' ' then
grid[ny][nx] = 'o' -- mark cell
if solve_maze(nx,ny) then return true end if
grid[ny][nx] = ' ' -- unmark cell
end if
grid[wy][wx] = ' ' -- unmark path
end if
end for
return false
end function
function heads()
return rand(2)=1 -- toin coss 50:50 true(1)/false(0)
end function
integer {x,y} = {(rand(w)*4)-1,rand(h)*2}
amaze(x,y)
-- mark start pos
grid[y][x] = '*'
-- add a random door (heads=rhs/lhs, tails=top/btm)
if heads() then
{dy,dx} = {rand(h)*2,heads()*w*4+1}
grid[dy][dx] = ' '
else
{dy,dx} = {heads()*h*2+1,rand(w)*4-1}
grid[dy][dx-1..dx+1] = ' '
end if
{} = solve_maze(x,y)
puts(1,join(grid,'\n'))
|
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.
| #jq | jq | # Usage: TRIANGLE | solve
def solve:
# update(next) updates the input row of maxima:
def update(next):
. as $maxima
| [ range(0; next|length)
| next[.] + ([$maxima[.], $maxima[. + 1]] | max) ];
. as $in
| reduce range(length -2; -1; -1) as $i
($in[-1]; update( $in[$i] ) ) ; |
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.