task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Matrix_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.
| #AWK | AWK | # Usage: GAWK -f MATRIX_MULTIPLICATION.AWK filename
# Separate matrices a and b by a blank line
BEGIN {
ranka1 = 0; ranka2 = 0
rankb1 = 0; rankb2 = 0
matrix = 1 # Indicate first (1) or second (2) matrix
i = 0
}
NF == 0 {
if (++matrix > 2) {
printf("Warning: Ignoring data below line %d.\n", NR)
}
i = 0
next
}
{
# Store first matrix in a, second matrix in b
if (matrix == 1) {
ranka1 = ++i
ranka2 = max(ranka2, NF)
for (j = 1; j <= NF; j++)
a[i,j] = $j
}
if (matrix == 2) {
rankb1 = ++i
rankb2 = max(rankb2, NF)
for (j = 1; j <= NF; j++)
b[i,j] = $j
}
}
END {
# Check ranks of a and b
if ((ranka1 < 1) || (ranka2 < 1) || (rankb1 < 1) || (rankb2 < 1) ||
(ranka2 != rankb1)) {
printf("Error: Incompatible ranks (%dx%d)*(%dx%d).\n", ranka1, ranka2, rankb1, rankb2)
exit
}
# Multiplication c = a * b
for (i = 1; i <= ranka1; i++) {
for (j = 1; j <= rankb2; j++) {
c[i,j] = 0
for (k = 1; k <= ranka2; k++)
c[i,j] += a[i,k] * b[k,j]
}
}
# Print matrix c
for (i = 1; i <= ranka1; i++) {
for (j = 1; j <= rankb2; j++)
printf("%g%s", c[i,j], j < rankb2 ? " " : "\n")
}
}
function max(m, n) {
return m > n ? m : n
} |
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.
| #NewLISP | NewLISP | (define (mkdir-p mypath)
(if (= "/" (mypath 0)) ;; Abs or relative path?
(setf /? "/")
(setf /? "")
)
(setf path-components (clean empty? (parse mypath "/"))) ;; Split path and remove empty elements
(for (x 0 (length path-components))
(setf walking-path (string /? (join (slice path-components 0 (+ 1 x)) "/")))
(make-dir walking-path)
)
)
;; Using user-made function...
(mkdir-p "/tmp/rosetta/test1")
;; ... or calling OS command directly.
(! "mkdir -p /tmp/rosetta/test2")
(exit) |
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.
| #Nim | Nim | import os
try:
createDir("./path/to/dir")
echo "Directory now exists."
except OSError:
echo "Failed to create the directory." |
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.
| #Objeck | Objeck | class Program {
function : Main(args : String[]) ~ Nil {
System.IO.File.Directory->CreatePath("your/path/name")->PrintLine();
}
} |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #AppleScript | AppleScript | -- MAGIC SQUARE OF DOUBLY EVEN ORDER -----------------------------------------
-- magicSquare :: Int -> [[Int]]
on magicSquare(n)
if n mod 4 > 0 then
{}
else
set sqr to n * n
set maybePowerOfTwo to asPowerOfTwo(sqr)
if maybePowerOfTwo is not missing value then
-- For powers of 2, the (append not) 'magic' series directly
-- yields the truth table that we need
set truthSeries to magicSeries(maybePowerOfTwo)
else
-- where n is not a power of 2, we can replicate a
-- minimum truth table, horizontally and vertically
script scale
on |λ|(x)
replicate(n / 4, x)
end |λ|
end script
set truthSeries to ¬
flatten(scale's |λ|(map(scale, splitEvery(4, magicSeries(4)))))
end if
set limit to sqr + 1
script inOrderOrReversed
on |λ|(x, i)
cond(x, i, limit - i)
end |λ|
end script
-- Taken directly from an integer series [1..sqr] where True
-- and from the reverse of that series where False
splitEvery(n, map(inOrderOrReversed, truthSeries))
end if
end magicSquare
-- magicSeries :: Int -> [Bool]
on magicSeries(n)
script boolToggle
on |λ|(x)
not x
end |λ|
end script
if n ≤ 0 then
{true}
else
set xs to magicSeries(n - 1)
xs & map(boolToggle, xs)
end if
end magicSeries
-- TEST ----------------------------------------------------------------------
on run
formattedTable(magicSquare(8))
end run
-- formattedTable :: [[Int]] -> String
on formattedTable(lstTable)
set n to length of lstTable
set w to 2.5 * n
"magic(" & n & ")" & linefeed & wikiTable(lstTable, ¬
false, "text-align:center;width:" & ¬
w & "em;height:" & w & "em;table-layout:fixed;")
end formattedTable
-- wikiTable :: [Text] -> Bool -> Text -> Text
on wikiTable(lstRows, blnHdr, strStyle)
script fWikiRows
on |λ|(lstRow, iRow)
set strDelim to cond(blnHdr and (iRow = 0), "!", "|")
set strDbl to strDelim & strDelim
linefeed & "|-" & linefeed & strDelim & space & ¬
intercalate(space & strDbl & space, lstRow)
end |λ|
end script
linefeed & "{| class=\"wikitable\" " & ¬
cond(strStyle ≠ "", "style=\"" & strStyle & "\"", "") & ¬
intercalate("", ¬
map(fWikiRows, lstRows)) & linefeed & "|}" & linefeed
end wikiTable
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- asPowerOfTwo :: Int -> maybe Int
on asPowerOfTwo(n)
if not isPowerOf(2, n) then
missing value
else
set strCMD to ("echo 'l(" & n as string) & ")/l(2)' | bc -l"
(do shell script strCMD) as integer
end if
end asPowerOfTwo
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
script append
on |λ|(a, b)
a & b
end |λ|
end script
foldl(append, {}, map(f, xs))
end concatMap
-- cond :: Bool -> a -> a -> a
on cond(bool, f, g)
if bool then
f
else
g
end if
end cond
-- flatten :: Tree a -> [a]
on flatten(t)
if class of t is list then
concatMap(my flatten, t)
else
t
end if
end flatten
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- isPowerOf :: Int -> Int -> Bool
on isPowerOf(k, n)
set v to k
script remLeft
on |λ|(x)
x mod v is not 0
end |λ|
end script
script integerDiv
on |λ|(x)
x div v
end |λ|
end script
|until|(remLeft, integerDiv, n) = 1
end isPowerOf
-- 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
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- 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
-- splitAt :: Int -> [a] -> ([a],[a])
on splitAt(n, xs)
if n > 0 and n < length of xs then
if class of xs is text then
{items 1 thru n of xs as text, items (n + 1) thru -1 of xs as text}
else
{items 1 thru n of xs, items (n + 1) thru -1 of xs}
end if
else
if n < 1 then
{{}, xs}
else
{xs, {}}
end if
end if
end splitAt
-- splitEvery :: Int -> [a] -> [[a]]
on splitEvery(n, xs)
if length of xs ≤ n then
{xs}
else
set {gp, t} to splitAt(n, xs)
{gp} & splitEvery(n, t)
end if
end splitEvery
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
set v to x
tell mReturn(f)
repeat until mp's |λ|(v)
set v to |λ|(v)
end repeat
end tell
return v
end |until| |
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
| #Clipper | Clipper | Procedure Main()
Local k
For k := 0 to 20
? "A(", k, ", 1, -1, -1, 1, 0) =", A(k, 1, -1, -1, 1, 0)
Next
Return
Static Function A(k, x1, x2, x3, x4, x5)
Local ARetVal
Local B := {|| --k, ARetVal := A(k, B, x1, x2, x3, x4) }
If k <= 0
ARetVal := Evaluate(x4) + Evaluate(x5)
Else
B:Eval()
Endif
Return ARetVal
Static Function Evaluate(x)
Local xVal
If ValType(x) == "B"
xVal := x:Eval()
Else
xVal := x
Endif
Return xVal |
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
| #Clojure | Clojure | (declare a)
(defn man-or-boy
"Man or boy test for Clojure"
[k]
(let [k (atom k)]
(a k
(fn [] 1)
(fn [] -1)
(fn [] -1)
(fn [] 1)
(fn [] 0))))
(defn a
[k x1 x2 x3 x4 x5]
(let [k (atom @k)]
(letfn [(b []
(swap! k dec)
(a k b x1 x2 x3 x4))]
(if (<= @k 0)
(+ (x4) (x5))
(b)))))
(man-or-boy 10)
|
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #Julia | Julia |
const k8 = [ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3]
const k7 = [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9]
const k6 = [ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11]
const k5 = [ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3]
const k4 = [ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2]
const k3 = [ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14]
const k2 = [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12]
const k1 = [ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]
const k87 = zeros(UInt32,256)
const k65 = zeros(UInt32,256)
const k43 = zeros(UInt32,256)
const k21 = zeros(UInt32,256)
for i in 1:256
j = (i-1) >> 4 + 1
k = (i-1) & 15 + 1
k87[i] = (k1[j] << 4) | k2[k]
k65[i] = (k3[j] << 4) | k4[k]
k43[i] = (k5[j] << 4) | k6[k]
k21[i] = (k7[j] << 4) | k8[k]
end
function f(x)
y = (k87[(x>>24) & 0xff + 1] << 24) | (k65[(x>>16) & 0xff + 1] << 16) |
(k43[(x>> 8) & 0xff + 1] << 8) | k21[x & 0xff + 1]
(y << 11) | (y >> (32-11))
end
bytes2int(arr) = arr[1] + (UInt32(arr[2]) << 8) + (UInt32(arr[3]) << 16) + (UInt32(arr[4])) << 24
int2bytes(x) = [UInt8(x&0xff), UInt8((x&0xff00)>>8), UInt8((x&0xff0000)>>16), UInt8(x>>24)]
function mainstep(inputbytes, keybytes)
intkey = bytes2int(keybytes)
lowint = bytes2int(inputbytes[1:4])
topint = bytes2int(inputbytes[5:8])
xorbytes = f(UInt32(intkey) + UInt32(lowint)) ⊻ topint
vcat(int2bytes(xorbytes), inputbytes[1:4])
end
const input = [0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04]
const key = [0xF9, 0x04, 0xC1, 0xE2]
println("The encoded bytes are $(mainstep(input, key))")
|
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.
| #Kotlin | Kotlin | // version 1.1.4-3
fun Byte.toUInt() = java.lang.Byte.toUnsignedInt(this)
fun Byte.toULong() = java.lang.Byte.toUnsignedLong(this)
fun Int.toULong() = java.lang.Integer.toUnsignedLong(this)
val s = arrayOf(
byteArrayOf( 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3),
byteArrayOf(14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9),
byteArrayOf( 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11),
byteArrayOf( 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3),
byteArrayOf( 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2),
byteArrayOf( 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14),
byteArrayOf(13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12),
byteArrayOf( 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12)
)
class Gost(val sBox: Array<ByteArray>) {
val k87 = ByteArray(256)
val k65 = ByteArray(256)
val k43 = ByteArray(256)
val k21 = ByteArray(256)
val enc = ByteArray(8)
init {
for (i in 0 until 256) {
val j = i ushr 4
val k = i and 15
k87[i] = ((sBox[7][j].toUInt() shl 4) or sBox[6][k].toUInt()).toByte()
k65[i] = ((sBox[5][j].toUInt() shl 4) or sBox[4][k].toUInt()).toByte()
k43[i] = ((sBox[3][j].toUInt() shl 4) or sBox[2][k].toUInt()).toByte()
k21[i] = ((sBox[1][j].toUInt() shl 4) or sBox[0][k].toUInt()).toByte()
}
}
fun f(x: Int): Int {
val y = (k87[(x ushr 24) and 255].toULong() shl 24) or
(k65[(x ushr 16) and 255].toULong() shl 16) or
(k43[(x ushr 8) and 255].toULong() shl 8) or
(k21[ x and 255].toULong())
return ((y shl 11) or (y ushr 21)).toInt()
}
fun u32(ba: ByteArray): Int =
(ba[0].toULong() or
(ba[1].toULong() shl 8) or
(ba[2].toULong() shl 16) or
(ba[3].toULong() shl 24)).toInt()
fun b4(u: Int) {
enc[0] = u.toByte()
enc[1] = (u ushr 8).toByte()
enc[2] = (u ushr 16).toByte()
enc[3] = (u ushr 24).toByte()
}
fun mainStep(input: ByteArray, key: ByteArray) {
val key32 = u32(key)
val input1 = u32(input.sliceArray(0..3))
val input2 = u32(input.sliceArray(4..7))
val temp = (key32.toULong() + input1.toULong()).toInt()
b4(f(temp) xor input2)
for (i in 0..3) enc[4 + i] = input[i]
}
}
fun main(args: Array<String>) {
val input = byteArrayOf(0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04)
val key = byteArrayOf(0xF9.toByte(), 0x04, 0xC1.toByte(), 0xE2.toByte())
val g = Gost(s)
g.mainStep(input, key)
for (b in g.enc) print("[%02X]".format(b))
println()
} |
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.
| #Haskell | Haskell | import Data.List.Split ( chunksOf )
import Data.List ( (!!) )
isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ fromIntegral n
isMagnanimous :: Int -> Bool
isMagnanimous n = all isPrime $ map (\p -> fst p + snd p ) numberPairs
where
str:: String
str = show n
splitStrings :: [(String , String)]
splitStrings = map (\i -> splitAt i str) [1 .. length str - 1]
numberPairs :: [(Int , Int)]
numberPairs = map (\p -> ( read $ fst p , read $ snd p )) splitStrings
printInWidth :: Int -> Int -> String
printInWidth number width = replicate ( width - l ) ' ' ++ str
where
str :: String
str = show number
l :: Int
l = length str
solution :: [Int]
solution = take 400 $ filter isMagnanimous [0 , 1 ..]
main :: IO ( )
main = do
let numbers = solution
numberlines = chunksOf 10 $ take 45 numbers
putStrLn "First 45 magnanimous numbers:"
mapM_ (\li -> putStrLn (foldl1 ( ++ ) $ map (\n -> printInWidth n 6 )
li )) numberlines
putStrLn "241'st to 250th magnanimous numbers:"
putStr $ show ( numbers !! 240 )
putStrLn ( foldl1 ( ++ ) $ map(\n -> printInWidth n 8 ) $ take 9 $
drop 241 numbers )
putStrLn "391'st to 400th magnanimous numbers:"
putStr $ show ( numbers !! 390 )
putStrLn ( foldl1 ( ++ ) $ map(\n -> printInWidth n 8 ) $ drop 391 numbers) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Arturo | Arturo | transpose: function [a][
X: size a
Y: size first a
result: array.of: @[Y X] 0
loop 0..X-1 'i [
loop 0..Y-1 'j [
result\[j]\[i]: a\[i]\[j]
]
]
return result
]
arr: [
[ 0 1 2 3 4 ]
[ 5 6 7 8 9 ]
[ 1 0 0 0 42 ]
]
loop arr 'row -> print row
print "-------------"
loop transpose arr 'row -> print row |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #D | D | void main() @safe {
import std.stdio, std.algorithm, std.range, std.random;
enum uint w = 14, h = 10;
auto vis = new bool[][](h, w),
hor = iota(h + 1).map!(_ => ["+---"].replicate(w)).array,
ver = h.iota.map!(_ => ["| "].replicate(w) ~ "|").array;
void walk(in uint x, in uint y) /*nothrow*/ @safe /*@nogc*/ {
vis[y][x] = true;
//foreach (immutable p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) {
foreach (const p; [[x-1, y], [x, y+1], [x+1, y], [x, y-1]].randomCover) {
if (p[0] >= w || p[1] >= h || vis[p[1]][p[0]]) continue;
if (p[0] == x) hor[max(y, p[1])][x] = "+ ";
if (p[1] == y) ver[y][max(x, p[0])] = " ";
walk(p[0], p[1]);
}
}
walk(uniform(0, w), uniform(0, h));
foreach (const a, const b; hor.zip(ver ~ []))
join(a ~ "+\n" ~ b).writeln;
} |
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.
| #Lambdatalk | Lambdatalk |
{require lib_matrix}
{def M.exp
{lambda {:m :n}
{if {= :n 0}
then {M.new [ [1,0],[0,1] ]}
else {S.reduce M.multiply {S.map {{lambda {:m _} :m} :m} {S.serie 1 :n}}}}}}
-> M.exp
'{def M
{M.new [[3,2],
[2,1]]}}
-> M
{S.map {lambda {:i} {br}M{sup :i} = {M.exp {M} :i}}
0 1 2 3 4 10}
->
M^0 = [[1,0],[0,1]]
M^1 = [[3,2],[2,1]]
M^2 = [[13,8],[8,5]]
M^3 = [[55,34],[34,21]]
M^4 = [[233,144],[144,89]]
M^10 = [[1346269,832040],[832040,514229]]
|
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. demo-map-range.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 i USAGE FLOAT-LONG.
01 mapped-num USAGE FLOAT-LONG.
01 a-begin USAGE FLOAT-LONG VALUE 0.
01 a-end USAGE FLOAT-LONG VALUE 10.
01 b-begin USAGE FLOAT-LONG VALUE -1.
01 b-end USAGE FLOAT-LONG VALUE 0.
01 i-display PIC --9.9.
01 mapped-display PIC --9.9.
PROCEDURE DIVISION.
PERFORM VARYING i FROM 0 BY 1 UNTIL i > 10
CALL "map-range" USING CONTENT a-begin, a-end, b-begin,
b-end, i, REFERENCE mapped-num
COMPUTE i-display ROUNDED = i
COMPUTE mapped-display ROUNDED = mapped-num
DISPLAY FUNCTION TRIM(i-display) " maps to "
FUNCTION TRIM(mapped-display)
END-PERFORM
.
END PROGRAM demo-map-range.
IDENTIFICATION DIVISION.
PROGRAM-ID. map-range.
DATA DIVISION.
LINKAGE SECTION.
01 a-begin USAGE FLOAT-LONG.
01 a-end USAGE FLOAT-LONG.
01 b-begin USAGE FLOAT-LONG.
01 b-end USAGE FLOAT-LONG.
01 val-to-map USAGE FLOAT-LONG.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION USING a-begin, a-end, b-begin, b-end,
val-to-map, ret.
COMPUTE ret =
b-begin + ((val-to-map - a-begin) * (b-end - b-begin)
/ (a-end - a-begin))
.
END PROGRAM map-range. |
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.
| #Raku | Raku | # clean up on exit, reset ANSI codes, scroll, re-show the cursor & clear screen
signal(SIGINT).tap: { print "\e[0m", "\n" xx 50, "\e[H\e[J\e[?25h"; exit(0) }
# a list of glyphs to use
my @codes = flat 'Α' .. 'Π', 'Ѐ' .. 'ѵ', 'Ҋ' .. 'ԯ', 'Ϣ' .. 'ϯ', 'ヲ'.. 'ン',
'Ⲁ' .. '⳩', '∀' .. '∗', '℀' .. '℺', '⨀' .. '⫿';
# palette of gradient ANSI foreground colors
my @palette = flat "\e[38;2;255;255;255m", (255,245 … 30).map({"\e[38;2;0;$_;0m"}),
"\e[38;2;0;25;0m" xx 75;
my @screen; # buffer to hold glyphs
my @rotate; # palette rotation position buffer
my ($rows, $cols) = qx/stty size/.words; # get the terminal size
init($rows, $cols); # set up the screen buffer and palette offsets
my $size-check;
print "\e[?25l\e[48;5;232m"; # hide the cursor, set the background color
loop {
if ++$size-check %% 20 { # periodically check for
my ($r, $c) = qx/stty size/.words; # resized terminal and
init($r, $c) if $r != $rows or $c != $cols; # re-initialize screen buffer
$size-check = 0
}
print "\e[1;1H"; # set cursor to top left
print join '', (^@screen).map: {
@rotate[$_] = (@rotate[$_] + 1) % +@palette; # rotate the palettes
flat @palette[@rotate[$_]], @screen[$_] # and print foreground, glyph
}
@screen[(^@screen).pick] = @codes.roll for ^30; # replace some random glyphs
}
sub init ($r, $c) {
@screen = @codes.roll($r * $c);
($rows, $cols) = $r, $c;
my @offset = (^@palette).pick xx $cols;
for ^$rows -> $row {
@rotate[$row * $cols ..^ $row * $cols + $cols] = @offset;
# for no "lightning" effect, add '1 + ' ↓ here: (1 + $_ % 3)
@offset = (^@offset).map: {(@offset[$_] - ($_ % 3)) % +@palette};
}
} |
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
| #Raku | Raku | sub MAIN (
Int :$colors where 1 < * < 21 = 6, Int :$length where 3 < * < 11 = 4,
Int :$guesses where 7 < * < 21 = 10, Bool :$repeat = False
) {
my @valid = ('A' .. 'T')[^$colors];
my $puzzle = $repeat ?? @valid.roll($length) !! @valid.pick($length);
my @guesses;
my $black = '●';
my $white = '○';
loop {
clearscr();
say header();
printf " %{$length * 2}s :: %s\n", @guesses[$_][0], @guesses[$_][1] for ^@guesses;
say '';
lose() if @guesses == $guesses;
my $guess = get-guess();
next unless $guess.&is-valid;
my $score = score($puzzle, $guess);
win() if $score eq ($black xx $length).join: ' ';
@guesses.push: [$guess, $score];
}
sub header {
my $num = $guesses - @guesses;
qq:to/END/;
Valid letter, but wrong position: ○ - Correct letter and position: ●
Guess the {$length} element sequence containing the letters {@valid}
Repeats are {$repeat ?? '' !! 'not '}allowed. You have $num guess{ $num == 1 ?? '' !! 'es'} remaining.
END
}
sub score ($puzzle, $guess) {
my @score;
for ^$length {
if $puzzle[$_] eq $guess[$_] {
@score.push: $black;
}
elsif $puzzle[$_] eq any(@$guess) {
@score.push: $white;
}
else {
@score.push('-');
}
}
@score.sort.reverse.join: ' ';
}
sub clearscr { $*KERNEL ~~ /'win32'/ ?? run('cls') !! run('clear') }
sub get-guess { (uc prompt 'Your guess?: ').comb(/@valid/) }
sub is-valid (@guess) { so $length == @guess }
sub win { say 'You Win! The correct answer is: ', $puzzle; exit }
sub lose { say 'Too bad, you ran out of guesses. The solution was: ', $puzzle; exit }
} |
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.
| #zkl | zkl | fcn optim3(a){ // list --> (int,list)
aux:=fcn(n,k,a){ // (int,int,list) --> (int,int,int,list)
if(n==1){
p,q := a[k,2];
return(0,p,q,k);
}
if(n==2){
p,q,r := a[k,3];
return(p*q*r, p, r, T(k,k+1));
}
m,p,q,u := Void, a[k], a[k + n], Void;
foreach i in ([1..n-1]){
#if 0 // 0.70 sec for both tests
s1,p1,q1,u1 := self.fcn(i,k,a);
s2,p2,q2,u2 := self.fcn(n - i, k + i, a);
#else // 0.33 sec for both tests
s1,p1,q1,u1 := memoize(self.fcn, i,k,a);
s2,p2,q2,u2 := memoize(self.fcn, n - i, k + i, a);
#endif
_assert_(q1==p2);
s:=s1 + s2 + p1*q1*q2;
if((Void==m) or (s<m)) m,u = s,T(u1,u2);
}
return(m,p,q,u);
};
h=Dictionary(); // reset memoize
s,_,_,u := aux(a.len() - 1, 0,a);
return(s,u);
}
var h; // a Dictionary, set/reset in optim3()
fcn memoize(f,n,k,a){
key:="%d,%d".fmt(n,k); // Lists make crappy keys
if(r:=h.find(key)) return(r);
r:=f(n,k,a);
h[key]=r;
return(r);
} |
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.
| #PureBasic | PureBasic | ;code from the maze generation task is place here in its entirety before the rest of the code
Procedure displayMazePath(Array maze(2), List Path.POINT())
Protected x, y, vWall.s, hWall.s
Protected mazeWidth = ArraySize(maze(), 1), mazeHeight = ArraySize(maze(), 2)
Protected Dim mazeOutput.mazeOutput(mazeHeight)
Protected Dim mazeRow.mazeOutput(0)
Static pathChars.s = "@^>v<"
For y = 0 To mazeHeight
makeDisplayMazeRow(mazeRow(), maze(), y): mazeOutput(y) = mazeRow(0)
Next
If ListSize(path())
FirstElement(path())
Protected prevPath.POINT = path()
While NextElement(path())
x = path()\x - prevPath\x
y = path()\y - prevPath\y
Select x
Case -1: dirTaken = #dir_W
Case 1: dirTaken = #dir_E
Default
If y < 0
dirTaken = #dir_N
Else
dirTaken = #dir_S
EndIf
EndSelect
hWall = mazeOutput(prevPath\y)\hWall
mazeOutput(prevPath\y)\hWall = Left(hWall, prevPath\x * #cellDWidth + 2) + Mid(pathChars, dirTaken + 1, 1) + Right(hWall, Len(hWall) - (prevPath\x * #cellDWidth + 3))
prevPath = path()
Wend
hWall = mazeOutput(prevPath\y)\hWall
mazeOutput(prevPath\y)\hWall = Left(hWall, prevPath\x * #cellDWidth + 2) + Mid(pathChars, #dir_ID + 1, 1) + Right(hWall, Len(hWall) - (prevPath\x * #cellDWidth + 3))
For y = 0 To mazeHeight
PrintN(mazeOutput(y)\vWall): PrintN(mazeOutput(y)\hWall)
Next
EndIf
EndProcedure
Procedure solveMaze(Array maze(2), *start.POINT, *finish.POINT, List Path.POINT())
Protected mazeWidth = ArraySize(maze(), 1), mazeHeight = ArraySize(maze(), 2)
Dim visited(mazeWidth + 1, mazeHeight + 1) ;includes padding for easy border detection
Protected i
;mark outside border as already visited (off limits)
For i = 1 To mazeWidth
visited(i, 0) = #True: visited(i, mazeHeight + 1) = #True
Next
For i = 1 To mazeHeight
visited(0, i) = #True: visited(mazeWidth + 1, i) = #True
Next
Protected x = *start\x, y = *start\y, nextCellDir
visited(x + offset(#visited, #dir_ID)\x, y + offset(#visited, #dir_ID)\y) = #True
ClearList(path())
Repeat
If x = *finish\x And y = *finish\y
AddElement(path())
path()\x = x: path()\y = y
Break ;success
EndIf
nextCellDir = #firstDir - 1
For i = #firstDir To #numDirs
If Not visited(x + offset(#visited, i)\x, y + offset(#visited, i)\y)
If maze(x + offset(#wall, i)\x, y + offset(#wall, i)\y) & wallvalue(i) <> #Null
nextCellDir = i: Break ;exit for/next search
EndIf
EndIf
Next
If nextCellDir >= #firstDir
visited(x + offset(#visited, nextCellDir)\x, y + offset(#visited, nextCellDir)\y) = #True
AddElement(path())
path()\x = x: path()\y = y
x + offset(#maze, nextCellDir)\x: y + offset(#maze, nextCellDir)\y
ElseIf ListSize(path()) > 0
x = path()\x: y = path()\y
DeleteElement(path())
Else
Break
EndIf
ForEver
EndProcedure
;demonstration
If OpenConsole()
Define.POINT start, finish
start\x = Random(mazeWidth - 1): start\y = Random(mazeHeight - 1)
finish\x = Random(mazeWidth - 1): finish\y = Random(mazeHeight - 1)
NewList Path.POINT()
solveMaze(maze(), start, finish, path())
If ListSize(path()) > 0
PrintN("Solution found for path between (" + Str(start\x) + ", " + Str(start\y) + ") and (" + Str(finish\x) + ", " + Str(finish\y) + ")")
displayMazePath(maze(), path())
Else
PrintN("No solution found for path between (" + Str(start\x) + ", " + Str(start\y) + ") and (" + Str(finish\x) + ", " + Str(finish\y) + ")")
EndIf
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | nums={{55},{94,48},{95,30,96},{77,71,26,67},{97,13,76,38,45},{7,36,79,16,37,68},{48,7,9,18,70,26,6},{18,72,79,46,59,79,29,90},{20,76,87,11,32,7,7,49,18},{27,83,58,35,71,11,25,57,29,85},{14,64,36,96,27,11,58,56,92,18,55},{2,90,3,60,48,49,41,46,33,36,47,23},{92,50,48,2,36,59,42,79,72,20,82,77,42},{56,78,38,80,39,75,2,71,66,66,1,3,55,72},{44,25,67,84,71,67,11,61,40,57,58,89,40,56,36},{85,32,25,85,57,48,84,35,47,62,17,1,1,99,89,52},{6,71,28,75,94,48,37,10,23,51,6,48,53,18,74,98,15},{27,2,92,23,8,71,76,84,15,52,92,63,81,10,44,10,69,93}};
ClearAll[DoStep,MaximumTrianglePathSum]
DoStep[lst1_List,lst2_List]:=lst2+Join[{First[lst1]},Max/@Partition[lst1,2,1],{Last[lst1]}]
MaximumTrianglePathSum[triangle_List]:=Max[Fold[DoStep,First[triangle],Rest[triangle]]] |
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.
| #Wren | Wren | import "/fmt" for Fmt
var toBytes = Fn.new { |val|
var bytes = List.filled(4, 0)
bytes[0] = val & 255
bytes[1] = (val >> 8) & 255
bytes[2] = (val >> 16) & 255
bytes[3] = (val >> 24) & 255
return bytes
}
var toInt = Fn.new { |bytes| bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24 }
var md4 = Fn.new { |initMsg|
var f = Fn.new { |x, y, z| (x & y) | (~x & z) }
var g = Fn.new { |x, y, z| (x & y) | (x & z) | (y & z) }
var h = Fn.new { |x, y, z| x ^ y ^ z }
var r = Fn.new { |v, s| (v << s) | (v >> (32 - s)) }
var a = 0x67452301
var b = 0xefcdab89
var c = 0x98badcfe
var d = 0x10325476
var initBytes = initMsg.bytes
var initLen = initBytes.count
var newLen = initLen + 1
while (newLen % 64 != 56) newLen = newLen + 1
var msg = List.filled(newLen + 8, 0)
for (i in 0...initLen) msg[i] = initBytes[i]
msg[initLen] = 0x80 // remaining bytes already 0
var lenBits = toBytes.call(initLen * 8)
for (i in newLen...newLen+4) msg[i] = lenBits[i-newLen]
var extraBits = toBytes.call(initLen >> 29)
for (i in newLen+4...newLen+8) msg[i] = extraBits[i-newLen-4]
var offset = 0
var x = List.filled(16, 0)
while (offset < newLen) {
for (i in 0...16) x[i] = toInt.call(msg[offset+i*4...offset + i*4 + 4])
var a2 = a
var b2 = b
var c2 = c
var d2 = d
for (i in [0, 4, 8, 12]) {
a = r.call(a + f.call(b, c, d) + x[i+0], 3)
d = r.call(d + f.call(a, b, c) + x[i+1], 7)
c = r.call(c + f.call(d, a, b) + x[i+2], 11)
b = r.call(b + f.call(c, d, a) + x[i+3], 19)
}
for (i in 0..3) {
a = r.call(a + g.call(b, c, d) + x[i+0] + 0x5a827999, 3)
d = r.call(d + g.call(a, b, c) + x[i+4] + 0x5a827999, 5)
c = r.call(c + g.call(d, a, b) + x[i+8] + 0x5a827999, 9)
b = r.call(b + g.call(c, d, a) + x[i+12] + 0x5a827999, 13)
}
for (i in [0, 2, 1, 3]) {
a = r.call(a + h.call(b, c, d) + x[i+0] + 0x6ed9eba1, 3)
d = r.call(d + h.call(a, b, c) + x[i+8] + 0x6ed9eba1, 9)
c = r.call(c + h.call(d, a, b) + x[i+4] + 0x6ed9eba1, 11)
b = r.call(b + h.call(c, d, a) + x[i+12] + 0x6ed9eba1, 15)
}
a = a + a2
b = b + b2
c = c + c2
d = d + d2
offset = offset + 64
}
var digest = List.filled(16, 0)
var dBytes = toBytes.call(a)
for (i in 0...4) digest[i] = dBytes[i]
dBytes = toBytes.call(b)
for (i in 0...4) digest[i+4] = dBytes[i]
dBytes = toBytes.call(c)
for (i in 0...4) digest[i+8] = dBytes[i]
dBytes = toBytes.call(d)
for (i in 0...4) digest[i+12] = dBytes[i]
return digest
}
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"Rosetta Code"
]
for (s in strings) {
var digest = md4.call(s)
Fmt.print("$s <== '$0s'", Fmt.v("xz", 2, digest, 0, "", ""), s)
} |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Go | Go | package main
import (
"crypto/md5"
"fmt"
)
func main() {
for _, p := range [][2]string{
// RFC 1321 test cases
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
{"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
{"d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"},
// test case popular with other RC solutions
{"e38ca1d920c4b8b8d3946b2c72f01680",
"The quick brown fox jumped over the lazy dog's back"},
} {
validate(p[0], p[1])
}
}
var h = md5.New()
func validate(check, s string) {
h.Reset()
h.Write([]byte(s))
sum := fmt.Sprintf("%x", h.Sum(nil))
if sum != check {
fmt.Println("MD5 fail")
fmt.Println(" for string,", s)
fmt.Println(" expected: ", check)
fmt.Println(" got: ", sum)
}
} |
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).
| #Vlang | Vlang | fn mcnugget(limit int) {
mut sv := []bool{len: limit+1} // all false by default
for s := 0; s <= limit; s += 6 {
for n := s; n <= limit; n += 9 {
for t := n; t <= limit; t += 20 {
sv[t] = true
}
}
}
for i := limit; i >= 0; i-- {
if !sv[i] {
println("Maximum non-McNuggets number is $i")
return
}
}
}
fn main() {
mcnugget(100)
} |
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).
| #VTL-2 | VTL-2 | 10 N=0
20 :N+1)=0
30 N=N+1
40 #=100>N*20
50 A=0
60 B=A
70 C=B
80 :C+1)=160
90 C=C+20
100 #=100>C*80
110 B=B+9
120 #=100>B*70
130 A=A+6
140 #=100>A*60
150 N=101
160 N=N-1
170 #=:N+1)
180 ?="Largest non-McNuggets number: ";
190 ?=N |
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)
| #Elixir | Elixir | defmodule Magic_square do
@lux %{ L: [4, 1, 2, 3], U: [1, 4, 2, 3], X: [1, 4, 3, 2] }
def singly_even(n) when rem(n-2,4)!=0, do: raise ArgumentError, "must be even, but not divisible by 4."
def singly_even(2), do: raise ArgumentError, "2x2 magic square not possible."
def singly_even(n) do
n2 = div(n, 2)
oms = odd_magic_square(n2)
mat = make_lux_matrix(n2)
square = synthesis(n2, oms, mat)
IO.puts to_string(n, square)
square
end
defp odd_magic_square(m) do # zero beginning, it is 4 multiples.
for i <- 0..m-1, j <- 0..m-1, into: %{},
do: {{i,j}, (m*(rem(i+j+1+div(m,2),m)) + rem(i+2*j-5+2*m, m)) * 4}
end
defp make_lux_matrix(m) do
center = div(m, 2)
lux = List.duplicate(:L, center+1) ++ [:U] ++ List.duplicate(:X, m-center-2)
(for {x,i} <- Enum.with_index(lux), j <- 0..m-1, into: %{}, do: {{i,j}, x})
|> Map.put({center, center}, :U)
|> Map.put({center+1, center}, :L)
end
defp synthesis(m, oms, mat) do
range = 0..m-1
Enum.reduce(range, [], fn i,acc ->
{row0, row1} = Enum.reduce(range, {[],[]}, fn j,{r0,r1} ->
x = oms[{i,j}]
[lux0, lux1, lux2, lux3] = @lux[mat[{i,j}]]
{[x+lux0, x+lux1 | r0], [x+lux2, x+lux3 | r1]}
end)
[row0, row1 | acc]
end)
end
defp to_string(n, square) do
format = String.duplicate("~#{length(to_char_list(n*n))}w ", n) <> "\n"
Enum.map_join(square, fn row ->
:io_lib.format(format, row)
end)
end
end
Magic_square.singly_even(6) |
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)
| #FreeBASIC | FreeBASIC | ' version 18-03-2016
' compile with: fbc -s console
' singly even magic square 6, 10, 14, 18...
Sub Err_msg(msg As String)
Print msg
Beep : Sleep 5000, 1 : Exit Sub
End Sub
Sub se_magicsq(n As UInteger, filename As String = "")
' filename <> "" then save square in a file
' filename can contain directory name
' if filename exist it will be overwriten, no error checking
If n < 6 Then
Err_msg( "Error: n is to small")
Exit Sub
End If
If ((n -2) Mod 4) <> 0 Then
Err_msg "Error: not possible to make singly" + _
" even magic square size " + Str(n)
Exit Sub
End If
Dim As UInteger sq(1 To n, 1 To n)
Dim As UInteger magic_sum = n * (n ^ 2 +1) \ 2
Dim As UInteger sq_d_2 = n \ 2, q2 = sq_d_2 ^ 2
Dim As UInteger l = (n -2) \ 4
Dim As UInteger x = sq_d_2 \ 2 + 1, y = 1, nr = 1
Dim As String frmt = String(Len(Str(n * n)) +1, "#")
' fill pattern A C
' D B
' main loop for creating magic square in section A
' the value for B,C and D is derived from A
' uses the FreeBASIC odd order magic square routine
Do
If sq(x, y) = 0 Then
sq(x , y ) = nr ' A
sq(x + sq_d_2, y + sq_d_2) = nr + q2 ' B
sq(x + sq_d_2, y ) = nr + q2 * 2 ' C
sq(x , y + sq_d_2) = nr + q2 * 3 ' D
If nr Mod sq_d_2 = 0 Then
y += 1
Else
x += 1 : y -= 1
End If
nr += 1
End If
If x > sq_d_2 Then
x = 1
Do While sq(x,y) <> 0
x += 1
Loop
End If
If y < 1 Then
y = sq_d_2
Do While sq(x,y) <> 0
y -= 1
Loop
End If
Loop Until nr > q2
' swap left side
For y = 1 To sq_d_2
For x = 1 To l
Swap sq(x, y), sq(x,y + sq_d_2)
Next
Next
' make indent
y = (sq_d_2 \ 2) +1
Swap sq(1, y), sq(1, y + sq_d_2) ' was swapped, restore to orignal value
Swap sq(l +1, y), sq(l +1, y + sq_d_2)
' swap right side
For y = 1 To sq_d_2
For x = n - l +2 To n
Swap sq(x, y), sq(x,y + sq_d_2)
Next
Next
' check columms and rows
For y = 1 To n
nr = 0 : l = 0
For x = 1 To n
nr += sq(x,y)
l += sq(y,x)
Next
If nr <> magic_sum Or l <> magic_sum Then
Err_msg "Error: value <> magic_sum"
Exit Sub
End If
Next
' check diagonals
nr = 0 : l = 0
For x = 1 To n
nr += sq(x, x)
l += sq(n - x +1, n - x +1)
Next
If nr <> magic_sum Or l <> magic_sum Then
Err_msg "Error: value <> magic_sum"
Exit Sub
End If
' printing square's on screen bigger when
' n > 19 results in a wrapping of the line
Print "Single even magic square size: "; n; "*"; n
Print "The magic sum = "; magic_sum
Print
For y = 1 To n
For x = 1 To n
Print Using frmt; sq(x, y);
Next
Print
Next
' output magic square to a file with the name provided
If filename <> "" Then
nr = FreeFile
Open filename For Output As #nr
Print #nr, "Single even magic square size: "; n; "*"; n
Print #nr, "The magic sum = "; magic_sum
Print #nr,
For y = 1 To n
For x = 1 To n
Print #nr, Using frmt; sq(x,y);
Next
Print #nr,
Next
Close #nr
End If
End Sub
' ------=< MAIN >=------
se_magicsq(6, "magicse6.txt") : Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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.)
| #Python | Python | #!/usr/bin/python
def a(n):
n += 2
return n*(n**2 + 1)/2
def inv_a(x):
k = 0
while k*(k**2+1)/2+2 < x:
k+=1
return k
if __name__ == '__main__':
print("The first 20 magic constants are:");
for n in range(1, 20):
print(int(a(n)), end = " ");
print("\nThe 1,000th magic constant is:",int(a(1000)));
for e in range(1, 20):
print(f'10^{e}: {inv_a(10**e)}'); |
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.)
| #Quackery | Quackery | [ 3 + dup 3 ** + 2 / ] is magicconstant ( n --> n )
20 times [ i^ magicconstant echo sp ] cr cr
1000 magicconstant echo cr cr
0 1
[ over magicconstant over > if
[ over 3 + echo cr
10 * ]
dip 1+
[ 10 21 ** ] constant
over = until ]
2drop |
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.)
| #Raku | Raku | use Lingua::EN::Numbers:ver<2.8+>;
my @magic-constants = lazy (3..∞).hyper.map: { (1 + .²) * $_ / 2 };
put "First 20 magic constants: ", @magic-constants[^20]».,
say "1000th magic constant: ", @magic-constants[999].,
say "\nSmallest order magic square with a constant greater than:";
(1..20).map: -> $p {printf "10%-2s: %s\n", $p.&super, comma 3 + @magic-constants.first( * > exp($p, 10), :k ) } |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Ada | Ada | with Lumen.Binary;
package body Mandelbrot is
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor is
use type Lumen.Binary.Byte;
Result : Lumen.Image.Descriptor;
X0, Y0 : Float;
X, Y, Xtemp : Float;
Iteration : Float;
Max_Iteration : constant Float := 1000.0;
Color : Lumen.Binary.Byte;
begin
Result.Width := Width;
Result.Height := Height;
Result.Complete := True;
Result.Values := new Lumen.Image.Pixel_Matrix (1 .. Width, 1 .. Height);
for Screen_X in 1 .. Width loop
for Screen_Y in 1 .. Height loop
X0 := -2.5 + (3.5 / Float (Width) * Float (Screen_X));
Y0 := -1.0 + (2.0 / Float (Height) * Float (Screen_Y));
X := 0.0;
Y := 0.0;
Iteration := 0.0;
while X * X + Y * Y <= 4.0 and then Iteration < Max_Iteration loop
Xtemp := X * X - Y * Y + X0;
Y := 2.0 * X * Y + Y0;
X := Xtemp;
Iteration := Iteration + 1.0;
end loop;
if Iteration = Max_Iteration then
Color := 255;
else
Color := 0;
end if;
Result.Values (Screen_X, Screen_Y) := (R => Color, G => Color, B => Color, A => 0);
end loop;
end loop;
return Result;
end Create_Image;
end Mandelbrot; |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #ALGOL_68 | ALGOL 68 | # construct a magic square of odd order #
PROC magic square = ( INT order ) [,]INT:
IF NOT ODD order OR order < 1
THEN
# can't make a magic square of the specified order #
LOC [ 1 : 0, 1 : 0 ]INT
ELSE
# order is OK - construct the square using de la Loubère's #
# algorithm as in the wikipedia page #
[ 1 : order, 1 : order ]INT square;
FOR i TO order DO FOR j TO order DO square[ i, j ] := 0 OD OD;
# as square [ 1, 1 ] if the top-left, moving "up" reduces the row #
# operator to advance "up" the square #
OP PREV = ( INT pos )INT: IF pos = 1 THEN order ELSE pos - 1 FI;
# operator to advance "across right" or "down" the square #
OP NEXT = ( INT pos )INT: ( pos MOD order ) + 1;
# fill in the square, starting from the middle of the top row #
INT col := ( order + 1 ) OVER 2;
INT row := 1;
FOR i TO order * order DO
square[ row, col ] := i;
IF square[ PREV row, NEXT col ] /= 0
THEN
# the up/right position is already taken, move down #
row := NEXT row
ELSE
# can move up and right #
row := PREV row;
col := NEXT col
FI
OD;
square
FI # magic square # ;
# prints the magic square #
PROC print square = ( [,]INT square )VOID:
BEGIN
INT order = 1 UPB square;
# calculate print width: negative so a leading "+" is not printed #
INT width := -1;
INT mag := order * order;
WHILE mag >= 10 DO mag OVERAB 10; width MINUSAB 1 OD;
# calculate the "magic sum" #
INT sum := 0;
FOR i TO order DO sum +:= square[ 1, i ] OD;
# print the square #
print( ( "maqic square of order ", whole( order, 0 ), ": sum: ", whole( sum, 0 ), newline ) );
FOR i TO order DO
FOR j TO order DO write( ( " ", whole( square[ i, j ], width ) ) ) OD;
write( ( newline ) )
OD
END # print square # ;
# test the magic square generation #
FOR order BY 2 TO 7 DO print square( magic square( order ) ) OD |
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.
| #BASIC | BASIC | Assume the matrices TO be multiplied are a AND b
IF (LEN(a,2) = LEN(b)) 'if valid dims
n = LEN(a,2)
m = LEN(a)
p = LEN(b,2)
DIM ans(0 TO m - 1, 0 TO p - 1)
FOR i = 0 TO m - 1
FOR j = 0 TO p - 1
FOR k = 0 TO n - 1
ans(i, j) = ans(i, j) + (a(i, k) * b(k, j))
NEXT k, j, i
'print answer
FOR i = 0 TO m - 1
FOR j = 0 TO p - 1
PRINT ans(i, j);
NEXT j
PRINT
NEXT i
ELSE
PRINT "invalid dimensions"
END IF |
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.
| #OCaml | OCaml | #load "unix.cma"
let mkdir_p ~path ~perms =
let ps = String.split_on_char '/' path in
let rec aux acc = function [] -> ()
| p::ps ->
let this = String.concat Filename.dir_sep (List.rev (p::acc)) in
Unix.mkdir this perms;
aux (p::acc) ps
in
aux [] ps
let () =
mkdir_p "path/to/dir" 0o700 |
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.
| #Perl | Perl | use File::Path qw(make_path);
make_path('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.
| #Phix | Phix | without js -- (file i/o)
if not create_directory("myapp/interface/letters") then
crash("Filesystem problem - could not create the new folder")
end if
|
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #AWK | AWK | # Usage: GAWK -f MAGIC_SQUARES_OF_DOUBLY_EVEN_ORDER.AWK
BEGIN {
n = 8
msquare[0, 0] = 0
if (magicsquaredoublyeven(msquare, n)) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%2d ", msquare[i, j])
}
printf("\n")
}
printf("\nMagic constant: %d\n", (n * n + 1) * n / 2)
exit 1
} else {
exit 0
}
}
function magicsquaredoublyeven(msquare, n, size, mult, r, c, i) {
if (n < 4 || n % 4 != 0) {
printf("Base must be a positive multiple of 4.\n")
return 0
}
size = n * n
mult = n / 4 # how many multiples of 4
i = 0
for (r = 0; r < n; r++) {
for (c = 0; c < n; c++) {
msquare[r, c] = countup(r, c, mult) ? i + 1 : size - i
i++
}
}
return 1
}
function countup(r, c, mult, pattern, bitpos) {
# Returns 1, if we are in a count-up zone (0 otherwise)
pattern = "1001011001101001"
bitpos = int(c / mult) + int(r / mult) * 4 + 1
return substr(pattern, bitpos, 1) + 0
} |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #Common_Lisp | Common Lisp | (defun man-or-boy (x)
(a x (lambda () 1)
(lambda () -1)
(lambda () -1)
(lambda () 1)
(lambda () 0)))
(defun a (k x1 x2 x3 x4 x5)
(labels ((b ()
(decf k)
(a k #'b x1 x2 x3 x4)))
(if (<= k 0)
(+ (funcall x4) (funcall x5))
(b))))
(man-or-boy 10) |
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89 | Main step of GOST 28147-89 | GOST 28147-89 is a standard symmetric encryption based on a Feistel network.
The structure of the algorithm consists of three levels:
encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.
Task
Implement the main step of this encryption algorithm.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ИП6 С/П + П6 ИП7 С/П + П7 ИПE -
x>=0 14 П7 КИП6 ИП6 ИПE - x>=0 20 П6
8 П2 П3 2 П1 4 П0 0 П8 1
П9 КИП2 ИПB / [x] ПA Вх {x} ИПB *
С/П ИП9 * ИП8 + П8 ИП9 ИПB * П9
ИПA L0 32 ИП8 КП3 L1 25 8 П0 ИП7
ПП 93 П1 ИП6 ПП 93 ИП5 + П6 ИП1
ИП4 + П7 ИП4 ИП6 С/П П4 ИП5 ИП7 С/П
П5 ИП4 ИП6 П4 <-> П6 ИП5 ИП7 П5 <->
П7 БП 00 ИПC / [x] КП0 Вx {x} ИПC
* ИПD * В/О |
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.
| #Nim | Nim | import sequtils, strutils
const
K1 = [byte 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3]
K2 = [byte 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9]
K3 = [byte 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11]
K4 = [byte 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3]
K5 = [byte 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2]
K6 = [byte 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14]
K7 = [byte 13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12]
K8 = [byte 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]
proc kboxInit: tuple[k87, k65, k43, k21: array[256, byte]] {.compileTime.} =
for i in 0 .. 255:
result.k87[i] = K8[i shr 4] shl 4 or K7[i and 15]
result.k65[i] = K6[i shr 4] shl 4 or K5[i and 15]
result.k43[i] = K4[i shr 4] shl 4 or K3[i and 15]
result.k21[i] = K2[i shr 4] shl 4 or K1[i and 15]
const (K87, K65, K43, K21) = kboxInit()
template rol(x: uint32; n: typed): uint32 =
x shl n or x shr (32 - n)
proc f(x: uint32): uint32 =
let x = K87[x shr 24 and 255].uint32 shl 24 or K65[x shr 16 and 255].uint32 shl 16 or
K43[x shr 8 and 255].uint32 shl 8 or K21[x and 255].uint32
result = x.rol(11)
proc mainStep(input: array[8, byte]; key: array[4, byte]): array[8, byte] =
let input32 = cast[array[2, uint32]](input)
let key = cast[uint32](key)
let val = f(key + input32[0]) xor input32[1]
result[0..3] = cast[array[4, byte]](val)
result[4..7] = input[0..3]
when isMainModule:
const
Input = [byte 0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04]
Key = [byte 0xF9, 0x04, 0xC1, 0xE2]
let output = mainStep(Input, Key)
echo mapIt(output, it.toHex).join(" ") |
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.
| #Perl | Perl | use strict;
use warnings;
use ntheory 'fromdigits';
# sboxes from http://en.wikipedia.org/wiki/GOST_(block_cipher)
my @sbox = (
[4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
[14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
[5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
[7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
[6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
[4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
[13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
[1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]
);
sub rol32 {
my($y, $n) = @_;
($y << $n) % 2**32 | ($y >> (32 - $n))
}
sub GOST_round {
my($R, $K) = @_;
my $a = ($R + $K) % 2**32;
my $b = fromdigits([map { $sbox[$_][($a >> (4*$_))%16] } reverse 0..7],16);
rol32($b,11);
}
sub feistel_step {
my($F, $L, $R, $K) = @_;
$R, $L ^ &$F($R, $K)
}
my @input = (0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04);
my @key = (0xF9, 0x04, 0xC1, 0xE2);
my $R = fromdigits([reverse @input[0..3]], 256); # 1st half
my $L = fromdigits([reverse @input[4..7]], 256); # 2nd half
my $K = fromdigits([reverse @key ], 256);
($L,$R) = feistel_step(\&GOST_round, $L, $R, $K);
printf '%02X ', (($L << 32) + $R >> (8*$_))%256 for 0..7;
print "\n"; |
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.
| #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class MagnanimousNumbers {
public static void main(String[] args) {
runTask("Find and display the first 45 magnanimous numbers.", 1, 45);
runTask("241st through 250th magnanimous numbers.", 241, 250);
runTask("391st through 400th magnanimous numbers.", 391, 400);
}
private static void runTask(String message, int startN, int endN) {
int count = 0;
List<Integer> nums = new ArrayList<>();
for ( int n = 0 ; count < endN ; n++ ) {
if ( isMagnanimous(n) ) {
nums.add(n);
count++;
}
}
System.out.printf("%s%n", message);
System.out.printf("%s%n%n", nums.subList(startN-1, endN));
}
private static boolean isMagnanimous(long n) {
if ( n >= 0 && n <= 9 ) {
return true;
}
long q = 11;
for ( long div = 10 ; q >= 10 ; div *= 10 ) {
q = n / div;
long r = n % div;
if ( ! isPrime(q+r) ) {
return false;
}
}
return true;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
private static final void sieve() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
// See http://primes.utm.edu/glossary/page.php?sort=StrongPRP
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
// Try 5 "random" primes
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
//throw new RuntimeException("ERROR isPrime: Value too large = "+testValue);
return true;
}
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
//System.out.println("a = "+a+", s = "+s+", d = "+d+", n = "+n+", modpow = "+modPow);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
// Result is a*b % mod, without overflow.
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
}
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #AutoHotkey | AutoHotkey | a = a
m = 10
n = 10
Loop, 10
{
i := A_Index - 1
Loop, 10
{
j := A_Index - 1
%a%%i%%j% := i - j
}
}
before := matrix_print("a", m, n)
transpose("a", m, n)
after := matrix_print("a", m, n)
MsgBox % before . "`ntransposed:`n" . after
Return
transpose(a, m, n)
{
Local i, j, row, matrix
Loop, % m
{
i := A_Index - 1
Loop, % n
{
j := A_Index - 1
temp%i%%j% := %a%%j%%i%
}
}
Loop, % m
{
i := A_Index - 1
Loop, % n
{
j := A_Index - 1
%a%%i%%j% := temp%i%%j%
}
}
}
matrix_print(a, m, n)
{
Local i, j, row, matrix
Loop, % m
{
i := A_Index - 1
row := ""
Loop, % n
{
j := A_Index - 1
row .= %a%%i%%j% . ","
}
StringTrimRight, row, row, 1
matrix .= row . "`n"
}
Return matrix
}
|
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.
| #Delphi | Delphi | program MazeGen_Rosetta;
{$APPTYPE CONSOLE}
uses System.SysUtils, System.Types, System.Generics.Collections, System.IOUtils;
type
TMCell = record
Visited : Boolean;
PassTop : Boolean;
PassLeft : Boolean;
end;
TMaze = array of array of TMCell;
TRoute = TStack<TPoint>;
const
mwidth = 24;
mheight = 14;
procedure ClearVisited(var AMaze: TMaze);
var
x, y: Integer;
begin
for y := 0 to mheight - 1 do
for x := 0 to mwidth - 1 do
AMaze[x, y].Visited := False;
end;
procedure PrepareMaze(var AMaze: TMaze);
var
Route : TRoute;
Position : TPoint;
d : Integer;
Pool : array of TPoint; // Pool of directions to pick randomly from
begin
SetLength(AMaze, mwidth, mheight);
ClearVisited(AMaze);
Position := Point(Random(mwidth), Random(mheight));
Route := TStack<TPoint>.Create;
try
with Position do
while True do
begin
repeat
SetLength(Pool, 0);
if (y > 0) and not AMaze[x, y-1].Visited then Pool := Pool + [Point(0, -1)];
if (x < mwidth-1) and not AMaze[x+1, y].Visited then Pool := Pool + [Point(1, 0)];
if (y < mheight-1) and not AMaze[x, y+1].Visited then Pool := Pool + [Point(0, 1)];
if (x > 0) and not AMaze[x-1, y].Visited then Pool := Pool + [Point(-1, 0)];
if Length(Pool) = 0 then // no direction to draw from
begin
if Route.Count = 0 then Exit; // and we are back at start so this is the end
Position := Route.Pop;
end;
until Length(Pool) > 0;
d := Random(Length(Pool));
Offset(Pool[d]);
AMaze[x, y].Visited := True;
if Pool[d].y = -1 then AMaze[x, y+1].PassTop := True; // comes from down to up ( ^ )
if Pool[d].x = 1 then AMaze[x, y].PassLeft := True; // comes from left to right ( --> )
if Pool[d].y = 1 then AMaze[x, y].PassTop := True; // comes from left to right ( v )
if Pool[d].x = -1 then AMaze[x+1, y].PassLeft := True; // comes from right to left ( <-- )
Route.Push(Position);
end;
finally
Route.Free;
end;
end;
function MazeToString(const AMaze: TMaze; const S, E: TPoint): String; overload;
var
x, y: Integer;
v : Char;
begin
Result := '';
for y := 0 to mheight - 1 do
begin
for x := 0 to mwidth - 1 do
if AMaze[x, y].PassTop then Result := Result + '+'#32#32#32 else Result := Result + '+---';
Result := Result + '+' + sLineBreak;
for x := 0 to mwidth - 1 do
begin
if S = Point(x, y) then v := 'S' else
if E = Point(x, y) then v := 'E' else
v := #32'*'[Ord(AMaze[x, y].Visited) + 1];
Result := Result + '|'#32[Ord(AMaze[x, y].PassLeft) + 1] + #32 + v + #32;
end;
Result := Result + '|' + sLineBreak;
end;
for x := 0 to mwidth - 1 do Result := Result + '+---';
Result := Result + '+' + sLineBreak;
end;
procedure Main;
var
Maze: TMaze;
begin
Randomize;
PrepareMaze(Maze);
ClearVisited(Maze); // show no route
Write(MazeToString(Maze, Point(-1, -1), Point(-1, -1)));
ReadLn;
end;
begin
Main;
end. |
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.
| #Liberty_BASIC | Liberty BASIC |
MatrixD$ ="3, 3, 0.86603, 0.50000, 0.00000, -0.50000, 0.86603, 0.00000, 0.00000, 0.00000, 1.00000"
print "Exponentiation of a matrix"
call DisplayMatrix MatrixD$
print " Raised to power 5 ="
MatrixE$ =MatrixToPower$( MatrixD$, 5)
call DisplayMatrix MatrixE$
print " Raised to power 9 ="
MatrixE$ =MatrixToPower$( MatrixD$, 9)
call DisplayMatrix MatrixE$
|
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.
| #CoffeeScript | CoffeeScript |
mapRange = (a1,a2,b1,b2,s) ->
t = b1 + ((s-a1)*(b2 - b1)/(a2-a1))
for s in [0..10]
console.log("#{s} maps to #{mapRange(0,10,-1,0,s)}")
|
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.
| #Common_Lisp | Common Lisp | (defun map-range (a1 a2 b1 b2 s)
(+ b1
(/ (* (- s a1)
(- b2 b1))
(- a2 a1))))
(loop
for i from 0 to 10
do (format t "~F maps to ~F~C" i
(map-range 0 10 -1 0 i)
#\Newline)) |
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.
| #REXX | REXX | /*REXX program creates/displays Matrix (the movie) digital rain; favors non-Latin chars.*/
signal on halt /*allow the user to halt/stop this pgm.*/
parse arg pc seed . /*obtain optional arguments from the CL*/
if pc=='' | pc=="," then pc= 20 /*Not specified? Then use the default.*/
if datatype(seed, 'W') then call random ,,seed /*Numeric? Use seed for repeatability.*/
parse value scrsize() with sd sw . /*obtain the dimensions of the screen. */
if sd==0 then sd= 54; sd= sd - 2 + 1 /*Not defined? Then use default; adjust*/
if sw==0 then sw= 80; sw= sw - 1 /* " " " " " " */
lowC= c2d(' ') + 1 /*don't use any characters ≤ a blank.*/
@.= ' ' /*PC is the % new Matric rain streams.*/
cloud= copies(@., sw) /*the cloud, where matrix rain is born.*/
cls= 'CLS' /*DOS command used to clear the screen.*/
do forever; call nimbus /*define bottom of cloud (the drops). */
call rain /*generate rain, display the raindrops.*/
end /*j*/
halt: exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
rain: do a=sd by -1 for sd-1; _= a-1; @.a= @._; end; call fogger; return
show: cls; @.1= cloud; do r=1 for sd; say strip(@.r, 'T'); end /*r*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
nimbus: if random(, 100)<pc then call mist /*should this be a new rain stream ? */
else call unmist /*should any of the rain streams cease?*/
return /*note: this subroutine may pass──►MIST*/
if random(, 100)<pc then return /*should this be a new rain stream ? */
?= random(1, sw) /*pick a random rain cloud position. */
if substr(cloud,?,1)\==' ' then return /*Is cloud position not a blank? Return*/
/*───── ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ────────────────────────────────────────────────────*/
mist: ?= random(1, sw) /*obtain a random column in cloud. */
if substr(cloud,?,1)\==' ' then return /*if this stream is active, return. */
if random(, 100)<pc then return /*should this be a new rain stream ? */
cloud= overlay(drop(), cloud, ?) /*seed cloud with new matrix rain drop.*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
unmist: ?= random(1, sw) /*obtain a random column in cloud. */
if substr(cloud,?,1) ==' ' then return /*if this stream is dry, return. */
if random(, 100)>pc then return /*should this be a new dry stream ? */
cloud= overlay(' ', cloud, ?); return /*seed cloud with new matrix rain drop.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
drop: Lat= random(1, 4) /*Now, chose a matrix rain stream char.*/
tChr= 254; if Lat==1 then tChr= 127 /*choose the type of rain stream char.*/
return d2c( random(lowC, tChr) ) /*Lat = 1? This favors Latin letters.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
fogger: do f=1 for sw /*display a screen full of rain streams*/
if substr(cloud, f, 1) \== ' ' then cloud= overlay( drop(), cloud, f)
end /*f*/; call show; return /* [↑] if raindrop, then change drop. */ |
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
| #REXX | REXX | /*REXX pgm scores mastermind game with a human or CBLFs (Carbon Based Life Forms). */
parse arg let wid mxG oRep seed _ /*obtain optional arguments from the CL*/
arg . . . rep . /*get uppercase 4th argument " " " */
if let=='' | let=="," then let= 20 /*Not specified? Then use the default.*/
if wid=='' | wid=="," then wid= 4 /* " " " " " " */
if mxG=='' | mxG=="," then mxG= 20 /* " " " " " " */
if rep=='' | rep=="," then rep= 0 /* " " " " " " */
if datatype(seed,'W') then call random ,,seed /*use a seed for random repeatability. */
if abbrev( 'REPEATSALLOWED',rep,3) then rep=1 /*allow an abbreviated option for REP. */
if abbrev('NOREPEATSALLOWED',rep,3) then rep=0 /* " " " " " " */
call vet arg(), 'args' /*Vet the number of arguments entered. */ /*◄■■■■■■ optional vetting.*/
call vet let, 'letters', 2, 20 /* " " " " letters in the code*/ /*◄■■■■■■ optional vetting.*/
call vet wid, 'width', 4, 10 /* " " " " the width of code. */ /*◄■■■■■■ optional vetting.*/
call vet mxG, 'maxGuess', 7, 20 /* " " " " maximum guesses. */ /*◄■■■■■■ optional vetting.*/
call vet rep, 'REP', 0, 1e8 /* " " value if repeats are allowed*/ /*◄■■■■■■ optional vetting.*/
call gen; yourG= 'Your guess must be exactly '
youve= "You've already tried that guess "
do prompt=0 by 0 until xx==wid; say /*play until guessed or QUIT is entered*/
say id 'Please enter a guess with ' wid ' letters [or Quit]:'
pull g; g=space(g,0); L=length(g); if abbrev('QUIT',g,1) then exit 0
if L\==wid then do; say id '***error***' yourG wid " letters."; iterate; end
call dups /*look through the history log for dups*/
q=?; XX=0; OO=0; try=try+1 /*initialize some REXX vars; bump TRY.*/
do j=1 for L; if substr(g,j,1) \== substr(q,j,1) then iterate /*hit? */
xx=xx+1; q=overlay('▒', q, j) /*bump the XX correct count. */
end /*j*/ /* [↑] XX correct count; scrub guess.*/
do k=1 for L; _=substr(g, k, 1) /*process the count for "spots". */
if pos(_, q)==0 then iterate /*is this (spot) letter in the code? */
oo=oo+1; q=translate(q, , _) /*bump the OO spot count. */
end /*k*/ /* [↑] OO spot count; & scrub guess.*/
say
@.try=id right('guess' try, 11) ' ('mxG "is the max):" g '──►' ,
copies('X', xx)copies("O", oo)copies('-', wid-xx-oo)
call hist
if try==mxG then do; say; say id "you've used the maximum guesses:" mxG
say; say id "The code was: " ?; say; exit 1
end
end /*prompt*/
say; say " ┌─────────────────────────────────────────┐"
say " │ │"
say " │ Congratulations, you've guessed it !! │"
say " │ │"
say " └─────────────────────────────────────────┘"
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
dups: do h=1 for try; if g\=word(@.h, 8) then iterate /*any duplicated guesses? */
say; say id youve " (guess number" h').'; iterate prompt; end /*h*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: if rep==0 then reps= 'no' /*create a literal for the prompt msg. */
else reps=
@abc= 'QWERTYUIOPASDFGHJKLZXCVBNM' /*capital letters used for random code.*/
id='────────'; try=0; L@abc=length(@abc) /*identifier in front of msg from here.*/
?=
do until length(?)==wid /*gen random codes 'til there's enough.*/
r=substr(@abc, random(1, L@abc), 1) /*generate a random letter, 1 at a time*/
if \rep & pos(r, ?)\==0 then iterate /*maybe don't allow a repeated digit.*/
?=? || r; if ?=='QUIT'&let==4 then ?= /*append random letter; ··· except this*/
end /*until*/ /* [↑] builds a unique N-letter code.*/
say
say id 'A random code of ' wid "letters (out of a possible " let ' letters) '
say id 'has been generated (with' reps "repeats)."
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
hist: do hist=1 for try; say @.hist; end; return /*show "guess" history.*/
s: if arg(1)==1 then return ''; return "s" /*a simpler pluraizer. */
ser: say; say; say '***error***' arg(1); say; say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/ /*◄■■■■■■ optional vetting.*/
vet: parse arg val,?,mn,mx /*vet (validate) a specified argument. */ /*◄■■■■■■ optional vetting.*/
if ?=="args" & (val>1 | _\='') then call ser "Too many arguments specified. " _ /*◄■■■■■■ optional vetting.*/
if ?=="args" then return /*◄■■■■■■ optional vetting.*/
if \datatype(val, 'N') then call ser ? "isn't numeric: " val /*◄■■■■■■ optional vetting.*/
if \datatype(val, 'W') then call ser ? "isn't an integer: " val /*◄■■■■■■ optional vetting.*/
if val < mn then call ser ? "has a value less than " mn /*◄■■■■■■ optional vetting.*/
if val > mx then call ser ? "has a value greater than " mx /*◄■■■■■■ optional vetting.*/
if ?=='REP' & \datatype(val,W) then call ser "Value for REPEATS isn't valid: " oRep /*◄■■■■■■ optional vetting.*/
return 1 |
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.
| #Python | Python |
# python 3
def Dijkstra(Graph, source):
'''
+ +---+---+
| 0 1 2 |
+---+ + +
| 3 4 | 5
+---+---+---+
>>> graph = ( # or ones on the diagonal
... (0,1,0,0,0,0,),
... (1,0,1,0,1,0,),
... (0,1,0,0,0,1,),
... (0,0,0,0,1,0,),
... (0,1,0,1,0,0,),
... (0,0,1,0,0,0,),
... )
...
>>> Dijkstra(graph, 0)
([0, 1, 2, 3, 2, 3], [1e+140, 0, 1, 4, 1, 2])
>>> display_solution([1e+140, 0, 1, 4, 1, 2])
5<2<1<0
'''
# Graph[u][v] is the weight from u to v (however 0 means infinity)
infinity = float('infinity')
n = len(graph)
dist = [infinity]*n # Unknown distance function from source to v
previous = [infinity]*n # Previous node in optimal path from source
dist[source] = 0 # Distance from source to source
Q = list(range(n)) # All nodes in the graph are unoptimized - thus are in Q
while Q: # The main loop
u = min(Q, key=lambda n:dist[n]) # vertex in Q with smallest dist[]
Q.remove(u)
if dist[u] == infinity:
break # all remaining vertices are inaccessible from source
for v in range(n): # each neighbor v of u
if Graph[u][v] and (v in Q): # where v has not yet been visited
alt = dist[u] + Graph[u][v]
if alt < dist[v]: # Relax (u,v,a)
dist[v] = alt
previous[v] = u
return dist,previous
def display_solution(predecessor):
cell = len(predecessor)-1
while cell:
print(cell,end='<')
cell = predecessor[cell]
print(0)
|
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.
| #Nim | Nim | import sequtils, strutils, sugar
proc solve(tri: seq[seq[int]]): int =
var tri = tri
while tri.len > 1:
let t0 = tri.pop
for i, t in tri[tri.high]: tri[tri.high][i] = max(t0[i], t0[i+1]) + t
tri[0][0]
const data = """
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"""
echo solve data.splitLines.map((x: string) => x.strip.split.map parseInt)
|
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.
| #Groovy | Groovy | import java.security.MessageDigest
String.metaClass.md5Checksum = {
MessageDigest.getInstance('md5').digest(delegate.bytes).collect { String.format("%02x", it) }.join('')
} |
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).
| #Wren | Wren | var mcnugget = Fn.new { |limit|
var sv = List.filled(limit+1, false)
var s = 0
while (s <= limit) {
var n = s
while (n <= limit) {
var t = n
while (t <= limit) {
sv[t] = true
t = t + 20
}
n = n + 9
}
s = s + 6
}
for (i in limit..0) {
if (!sv[i]) {
System.print("Maximum non-McNuggets number is %(i)")
return
}
}
}
mcnugget.call(100) |
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)
| #Go | Go | package main
import (
"fmt"
"log"
)
func magicSquareOdd(n int) ([][]int, error) {
if n < 3 || n%2 == 0 {
return nil, fmt.Errorf("base must be odd and > 2")
}
value := 1
gridSize := n * n
c, r := n/2, 0
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for value <= gridSize {
result[r][c] = value
if r == 0 {
if c == n-1 {
r++
} else {
r = n - 1
c++
}
} else if c == n-1 {
r--
c = 0
} else if result[r-1][c+1] == 0 {
r--
c++
} else {
r++
}
value++
}
return result, nil
}
func magicSquareSinglyEven(n int) ([][]int, error) {
if n < 6 || (n-2)%4 != 0 {
return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2")
}
size := n * n
halfN := n / 2
subSquareSize := size / 4
subSquare, err := magicSquareOdd(halfN)
if err != nil {
return nil, err
}
quadrantFactors := [4]int{0, 2, 3, 1}
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
quadrant := r/halfN*2 + c/halfN
result[r][c] = subSquare[r%halfN][c%halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
}
nColsLeft := halfN / 2
nColsRight := nColsLeft - 1
for r := 0; r < halfN; r++ {
for c := 0; c < n; c++ {
if c < nColsLeft || c >= n-nColsRight ||
(c == nColsLeft && r == nColsLeft) {
if c == 0 && r == nColsLeft {
continue
}
tmp := result[r][c]
result[r][c] = result[r+halfN][c]
result[r+halfN][c] = tmp
}
}
}
return result, nil
}
func main() {
const n = 6
msse, err := magicSquareSinglyEven(n)
if err != nil {
log.Fatal(err)
}
for _, row := range msse {
for _, x := range row {
fmt.Printf("%2d ", x)
}
fmt.Println()
}
fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2)
} |
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.)
| #Sidef | Sidef | func f(n) {
(n+2) * ((n+2)**2 + 1) / 2
}
func order(n) {
iroot(2*n, 3) + 1
}
say ("First 20 terms: ", f.map(1..20).join(' '))
say ("1000th term: ", f(1000), " with order ", order(f(1000)))
for n in (1 .. 20) {
printf("order(10^%-2s) = %s\n", n, order(10**n))
} |
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.)
| #Wren | Wren | import "./seq" for Lst
import "./fmt" for Fmt
var magicConstant = Fn.new { |n| (n*n + 1) * n / 2 }
var ss = ["\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074",
"\u2075", "\u2076", "\u2077", "\u2078", "\u2079"]
var superscript = Fn.new { |n| (n < 10) ? ss[n] : (n < 20) ? ss[1] + ss[n - 10] : ss[2] + ss[0] }
System.print("First 20 magic constants:")
var mc20 = (3..22).map { |n| magicConstant.call(n) }.toList
for (chunk in Lst.chunks(mc20, 10)) Fmt.print("$5d", chunk)
Fmt.print("\n1,000th magic constant: $,d", magicConstant.call(1002))
System.print("\nSmallest order magic square with a constant greater than:")
for (i in 1..20) {
var goal = 10.pow(i)
var order = (goal * 2).cbrt.floor + 1
Fmt.print("10$-2s : $,9d", superscript.call(i), order)
} |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #ALGOL_68 | ALGOL 68 |
INT pix = 300, max iter = 256, REAL zoom = 0.33 / pix;
[-pix : pix, -pix : pix] INT plane;
COMPL ctr = 0.05 I 0.75 # center of set #;
# Compute the length of an orbit. #
PROC iterate = (COMPL z0) INT:
BEGIN COMPL z := 0, INT iter := 1;
WHILE (iter +:= 1) < max iter # not converged # AND ABS z < 2 # not diverged #
DO z := z * z + z0
OD;
iter
END;
# Compute set and find maximum orbit length. #
INT max col := 0;
FOR x FROM -pix TO pix
DO FOR y FROM -pix TO pix
DO COMPL z0 = ctr + (x * zoom) I (y * zoom);
IF (plane [x, y] := iterate (z0)) < max iter
THEN (plane [x, y] > max col | max col := plane [x, y])
FI
OD
OD;
# Make a plot. #
FILE plot;
INT num pix = 2 * pix + 1;
make device (plot, "gif", whole (num pix, 0) + "x" + whole (num pix, 0));
open (plot, "mandelbrot.gif", stand draw channel);
FOR x FROM -pix TO pix
DO FOR y FROM -pix TO pix
DO INT col = (plane [x, y] > max col | max col | plane [x, y]);
REAL c = sqrt (1- col / max col); # sqrt to enhance contrast #
draw colour (plot, c, c, c);
draw point (plot, (x + pix) / (num pix - 1), (y + pix) / (num pix - 1))
OD
OD;
close (plot)
|
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #ALGOL_W | ALGOL W | begin
% construct a magic square of odd order - as a procedure can't return an %
% array, the caller must supply one that is big enough %
logical procedure magicSquare( integer array square ( *, * )
; integer value order
) ;
if not odd( order ) or order < 1 then begin
% can't make a magic square of the specified order %
false
end
else begin
% order is OK - construct the square using de la Loubère's %
% algorithm as in the wikipedia page %
% ensure a row/col position is on the square %
integer procedure inSquare( integer value pos ) ;
if pos < 1 then order else if pos > order then 1 else pos;
% move "up" a row in the square %
integer procedure up ( integer value row ) ; inSquare( row - 1 );
% move "accross right" in the square %
integer procedure right( integer value col ) ; inSquare( col + 1 );
integer row, col;
% initialise square %
for i := 1 until order do for j := 1 until order do square( i, j ) := 0;
% initial position is the middle of the top row %
col := ( order + 1 ) div 2;
row := 1;
% construct square %
for i := 1 until ( order * order ) do begin
square( row, col ) := i;
if square( up( row ), right( col ) ) not = 0 then begin
% the up/right position is already taken, move down %
row := row + 1;
end
else begin
% can move up/right %
row := up( row );
col := right( col );
end
end for_i;
% sucessful result %
true
end magicSquare ;
% prints the magic square %
procedure printSquare( integer array square ( *, * )
; integer value order
) ;
begin
integer sum, w;
% set integer width to accomodate the largest number in the square %
w := ( order * order ) div 10;
i_w := s_w := 1;
while w > 0 do begin i_w := i_w + 1; w := w div 10 end;
for i := 1 until order do sum := sum + square( 1, i );
write( "maqic square of order ", order, ": sum: ", sum );
for i := 1 until order do begin
write( square( i, 1 ) );
for j := 2 until order do writeon( square( i, j ) )
end for_i
end printSquare ;
% test the magic square generation %
integer array sq ( 1 :: 11, 1 :: 11 );
for i := 1, 3, 5, 7 do begin
if magicSquare( sq, i ) then printSquare( sq, i )
else write( "can't generate square" );
end for_i
end. |
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #APL | APL | magic←{⍵{+/1,(1 ⍺⍺)×⍺(⍺⍺|1+⊢+2×⊣)⍵,⍺⍺-⍵+1}/¨⎕IO-⍨⍳⍵ ⍵} |
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.
| #BBC_BASIC | BBC BASIC | DIM matrix1(3,1), matrix2(1,2), product(3,2)
matrix1() = 1, 2, \
\ 3, 4, \
\ 5, 6, \
\ 7, 8
matrix2() = 1, 2, 3, \
\ 4, 5, 6
product() = matrix1() . matrix2()
FOR row% = 0 TO DIM(product(),1)
FOR col% = 0 TO DIM(product(),2)
PRINT product(row%,col%),;
NEXT
PRINT
NEXT
|
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.
| #PicoLisp | PicoLisp | (call "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.
| #PowerShell | PowerShell |
New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue
|
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.
| #Python | Python |
from errno import EEXIST
from os import mkdir, curdir
from os.path import split, exists
def mkdirp(path, mode=0777):
head, tail = split(path)
if not tail:
head, tail = split(head)
if head and tail and not exists(head):
try:
mkdirp(head, mode)
except OSError as e:
# be happy if someone already created the path
if e.errno != EEXIST:
raise
if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
return
try:
mkdir(path, mode)
except OSError as e:
# be happy if someone already created the path
if e.errno != EEXIST:
raise
|
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.
| #Racket | Racket | #lang racket
(define path-str "/tmp/woo/yay")
(define path/..-str "/tmp/woo")
;; clean up from a previous run
(when (directory-exists? path-str)
(delete-directory path-str)
(delete-directory path/..-str))
;; delete-directory/files could also be used -- but that requires goggles and rubber
;; gloves to handle safely!
(define (report-path-exists)
(printf "~s exists (as a directory?):~a~%~s exists (as a directory?):~a~%~%"
path/..-str (directory-exists? path/..-str)
path-str (directory-exists? path-str)))
(report-path-exists)
;; Really ... this is the only bit that matters!
(make-directory* path-str)
(report-path-exists) |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #Befunge | Befunge | 8>>>v>10p00g:*1-*\110g2*-*+1+.:00g%!9+,:#v_@
p00:<^:!!-!%3//4g00%g00\!!%3/*:g00*4:::-1<*: |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #C | C |
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
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
| #Crystal | Crystal | def a(k, x1, x2, x3, x4, x5)
b = uninitialized -> typeof(k)
b = ->() { k -= 1; a(k, b, x1, x2, x3, x4) }
k <= 0 ? x4.call + x5.call : b.call
end
puts a(10, -> {1}, -> {-1}, -> {-1}, -> {1}, -> {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.
| #Phix | Phix | with javascript_semantics
constant 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}}
function generate(integer k)
sequence res = repeat(0,256)
for i=1 to length(res) do
integer hdx = floor((i-1)/16)+1,
ldx = and_bits(i-1,#F)+1
res[i] = or_bits(cbrf[k][hdx]*#10,cbrf[k-1][ldx])
end for
return res
end function
constant k87 = generate(8),
k65 = generate(6),
k43 = generate(4),
k21 = generate(2)
function r32(atom a)
if a<0 then a+=#100000000 end if
return remainder(a,#100000000)
end function
function mainstep(sequence input, atom key)
atom s = r32(input[1]+key)
s = r32(or_all({k87[and_bits(floor(s/#1000000),#FF)+1]*#1000000,
k65[and_bits(floor(s/#0010000),#FF)+1]*#0010000,
k43[and_bits(floor(s/#0000100),#FF)+1]*#0000100,
k21[and_bits(floor(s/#0000001),#FF)+1]*#0000001}))
s = r32(s*power(2,11))+floor(s/power(2,32-11))
s = xor_bits(s,input[2])
return {s,input[1]}
end function
sequence res = mainstep({#043B0421, #04320430}, #E2C104F9)
printf(1,"%08x %08x\n",res)
--or, for other-endian:
sequence s = sprintf("%08x",res[1]),
t = sprintf("%08x",res[2])
s = reverse(split(join_by(s,1,2,""," ")))
t = reverse(split(join_by(t,1,2,""," ")))
?{s,t}
|
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.
| #J | J | write_sum_expressions=: ([: }: ]\) ,"1 '+' ,"1 ([: }. ]\.) NB. combine prefixes with suffixes
interstitial_sums=: ".@write_sum_expressions@":
primeQ=: 1&p:
magnanimousQ=: 1:`([: *./ [: primeQ interstitial_sums)@.(>&9)
A=: (#~ magnanimousQ&>) i.1000000 NB. filter 1000000 integers
#A
434
strange=: ({. + [: i. -~/)@:(_1 0&+) NB. produce index ranges for output
I=: _2 <@strange\ 1 45 241 250 391 400
I (":@:{~ >)~"0 _ A
0 1 2 3 4 5 6 7 8 9 11 12 14 16 20 21 23 25 29 30 32 34 38 41 43 47 49 50 52 56 58 61 65 67 70 74 76 83 85 89 92 94 98 101 110
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081
|
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.
| #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
def divrem($x; $y):
[$x/$y|floor, $x % $y];
|
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.
| #Julia | Julia | using Primes
function ismagnanimous(n)
n < 10 && return true
for i in 1:ndigits(n)-1
q, r = divrem(n, 10^i)
!isprime(q + r) && return false
end
return true
end
function magnanimous(N)
mvec, i = Int[], 0
while length(mvec) < N
if ismagnanimous(i)
push!(mvec, i)
end
i += 1
end
return mvec
end
const mag400 = magnanimous(400)
println("First 45 magnanimous numbers:\n", mag400[1:24], "\n", mag400[25:45])
println("\n241st through 250th magnanimous numbers:\n", mag400[241:250])
println("\n391st through 400th magnanimous numbers:\n", mag400[391:400])
|
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #AWK | AWK |
# syntax: GAWK -f MATRIX_TRANSPOSITION.AWK filename
{ if (NF > nf) {
nf = NF
}
for (i=1; i<=nf; i++) {
row[i] = row[i] $i " "
}
}
END {
for (i=1; i<=nf; i++) {
printf("%s\n",row[i])
}
exit(0)
}
|
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth-first search algorithm.
Start at a random cell.
Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
Related tasks
Maze solving.
| #EasyLang | EasyLang | size = 20
n = 2 * size + 1
endpos = n * n - 2
startpos = n + 1
#
f = 100 / (n - 0.5)
len m[] n * n
#
background 000
func show_maze . .
clear
for i range len m[]
if m[i] = 0
x = i mod n
y = i div n
color 777
move x * f - f / 2 y * f - f / 2
rect f * 1.5 f * 1.5
.
.
sleep 0.001
.
offs[] = [ 1 n -1 (-n) ]
brdc[] = [ n - 2 -1 1 -1 ]
brdr[] = [ -1 n - 2 -1 1 ]
#
func m_maze pos . .
m[pos] = 0
call show_maze
d[] = [ 0 1 2 3 ]
for i = 3 downto 0
d = random (i + 1)
dir = d[d]
d[d] = d[i]
r = pos div n
c = pos mod n
posn = pos + 2 * offs[dir]
if c <> brdc[dir] and r <> brdr[dir] and m[posn] <> 0
posn = pos + 2 * offs[dir]
m[(pos + posn) div 2] = 0
call m_maze posn
.
.
.
func make_maze . .
for i range len m[]
m[i] = 1
.
call m_maze startpos
m[endpos] = 0
.
call make_maze
call show_maze |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Lua | Lua | Matrix = {}
function Matrix.new( dim_y, dim_x )
assert( dim_y and dim_x )
local matrix = {}
local metatab = {}
setmetatable( matrix, metatab )
metatab.__add = Matrix.Add
metatab.__mul = Matrix.Mul
metatab.__pow = Matrix.Pow
matrix.dim_y = dim_y
matrix.dim_x = dim_x
matrix.data = {}
for i = 1, dim_y do
matrix.data[i] = {}
end
return matrix
end
function Matrix.Show( m )
for i = 1, m.dim_y do
for j = 1, m.dim_x do
io.write( tostring( m.data[i][j] ), " " )
end
io.write( "\n" )
end
end
function Matrix.Add( m, n )
assert( m.dim_x == n.dim_x and m.dim_y == n.dim_y )
local r = Matrix.new( m.dim_y, m.dim_x )
for i = 1, m.dim_y do
for j = 1, m.dim_x do
r.data[i][j] = m.data[i][j] + n.data[i][j]
end
end
return r
end
function Matrix.Mul( m, n )
assert( m.dim_x == n.dim_y )
local r = Matrix.new( m.dim_y, n.dim_x )
for i = 1, m.dim_y do
for j = 1, n.dim_x do
r.data[i][j] = 0
for k = 1, m.dim_x do
r.data[i][j] = r.data[i][j] + m.data[i][k] * n.data[k][j]
end
end
end
return r
end
function Matrix.Pow( m, p )
assert( m.dim_x == m.dim_y )
local r = Matrix.new( m.dim_y, m.dim_x )
if p == 0 then
for i = 1, m.dim_y do
for j = 1, m.dim_x do
if i == j then
r.data[i][j] = 1
else
r.data[i][j] = 0
end
end
end
elseif p == 1 then
for i = 1, m.dim_y do
for j = 1, m.dim_x do
r.data[i][j] = m.data[i][j]
end
end
else
r = m
for i = 2, p do
r = r * m
end
end
return r
end
m = Matrix.new( 2, 2 )
m.data = { { 1, 2 }, { 3, 4 } }
n = m^4;
Matrix.Show( 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.
| #D | D | double mapRange(in double[] a, in double[] b, in double s)
pure nothrow @nogc {
return b[0] + ((s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]));
}
void main() {
import std.stdio;
immutable r1 = [0.0, 10.0];
immutable r2 = [-1.0, 0.0];
foreach (immutable s; 0 .. 11)
writefln("%2d maps to %5.2f", s, mapRange(r1, r2, s));
} |
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.
| #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color, Font
import "random" for Random
var Rand = Random.new()
class MatrixDigitalRain {
construct new(width, height) {
Window.resize(width, height)
Canvas.resize(width, height)
Window.title = "Matrix digital rain"
Font.load("Mem12", "memory.ttf", 24)
Canvas.font = "Mem12"
}
letter(x, y, r, g, b) {
if (y < 0 || y >= _my) return
var col = Color.rgb(r, g, b)
var c = String.fromByte(_scr[x][y])
Canvas.print(c, x * 12.8 , y * 12.8 , col)
}
init() {
_mx = 50
_my = 42
_scr = List.filled(_mx, null)
for (x in 0..._mx) {
_scr[x] = List.filled(_my, 0)
for (y in 0..._my) _scr[x][y] = Rand.int(33, 128)
}
_ms = 50
_sx = List.filled(_ms, 0)
_sy = List.filled(_ms, 0)
}
update() {
for (a in 0..._ms) {
_sx[a] = Rand.int(_mx)
_sy[a] = Rand.int(_my)
}
}
draw(alpha) {
for (s in 0..._ms) {
var x = _sx[s]
var y = _sy[s]
letter(x, y, 0, 255, 0)
y = y - 1
letter(x, y, 0, 200, 0)
y = y - 1
letter(x, y, 0, 150, 0)
y = y - 1
if (y*12.8 + 3 < 0) y = 0
var c = Color.rgb(0, 0, 0)
Canvas.rectfill(x*12.8, y*12.8 + 3, 13, 14, c)
letter(x, y, 0, 70, 0)
y = y - 24
if (y*12.8 + 3 < 0) y = 0
Canvas.rectfill(x*12.8, y*12.8 + 3, 13, 14, c)
}
for (s in 0..._ms) {
if (Rand.int(1, 6) == 1) _sy[s] = _sy[s] + 1
if (_sy[s] > _my + 25) {
_sy[s] = 0
_sx[s] = Rand.int(_mx)
}
}
}
}
var Game = MatrixDigitalRain.new(640, 550) |
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
| #Ring | Ring |
# Project : Mastermind
colors = ["A", "B", "C", "D"]
places = list(2)
mind = list(len(colors))
rands = list(len(colors))
master = list(len(colors))
test = list(len(colors))
guesses = 7
repeat = false
nr = 0
if repeat
for n = 1 to len(colors)
while true
rnd = random(len(colors)-1) + 1
if rands[rnd] != 1
mind[n] = rnd
rands[rnd] = 1
exit
ok
end
next
else
for n = 1 to len(colors)
rnd = random(len(colors)-1) + 1
mind[n] = rnd
next
ok
for n = 1 to len(colors)
master[n] = char(64+mind[n])
next
while true
for p = 1 to len(places)
places[p] = 0
next
nr = nr + 1
see "Your guess (ABCD)? "
give testbegin
for d = 1 to len(test)
test[d] = testbegin[d]
next
flag = 1
for n = 1 to len(test)
if upper(test[n]) != master[n]
flag = 0
ok
next
if flag = 1
exit
else
for x = 1 to len(master)
if upper(test[x]) = master[x]
places[1] = places[1] + 1
ok
next
mastertemp = master
for p = 1 to len(test)
pos = find(mastertemp, upper(test[p]))
if pos > 0
del(mastertemp, pos)
places[2] = places[2] + 1
ok
next
ok
place1 = places[1]
place2 = places[2] - place1
place3 = len(master) - (place1 + place2)
showresult(test, place1, place2, place3)
if nr = guesses
exit
ok
end
see "Well done!" + nl
see "End of game" + nl
func showresult(test, place1, place2, place3)
see "" + nr + " : "
for r = 1 to len(test)
see test[r]
next
see " : "
for n1 = 1 to place1
see "X" + " "
next
for n2 = 1 to place2
see "O" + " "
next
for n3 = 1 to place3
see "-" + " "
next
see nl
|
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
| #Rust | Rust | extern crate rand;
use rand::prelude::*;
use std::io;
fn main() {
let mut input_line = String::new();
let colors_n;
let code_len;
let guesses_max;
let colors_dup;
loop {
println!("Please enter the number of colors to be used in the game (2 - 20): ");
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
match (input_line.trim()).parse::<i32>() {
Ok(n) => {
if n >= 2 && n <= 20 {
colors_n = n;
break;
} else {
println!("Outside of range (2 - 20).");
}
}
Err(_) => println!("Invalid input."),
}
}
let colors = &"ABCDEFGHIJKLMNOPQRST"[..colors_n as usize];
println!("Playing with colors {}.\n", colors);
loop {
println!("Are duplicated colors allowed in the code? (Y/N): ");
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if ["Y", "N"].contains(&&input_line.trim().to_uppercase()[..]) {
colors_dup = input_line.trim().to_uppercase() == "Y";
break;
} else {
println!("Invalid input.");
}
}
println!(
"Duplicated colors {}allowed.\n",
if colors_dup { "" } else { "not " }
);
loop {
let min_len = if colors_dup { 4 } else { 4.min(colors_n) };
let max_len = if colors_dup { 10 } else { 10.min(colors_n) };
println!(
"Please enter the length of the code ({} - {}): ",
min_len, max_len
);
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
match (input_line.trim()).parse::<i32>() {
Ok(n) => {
if n >= min_len && n <= max_len {
code_len = n;
break;
} else {
println!("Outside of range ({} - {}).", min_len, max_len);
}
}
Err(_) => println!("Invalid input."),
}
}
println!("Code of length {}.\n", code_len);
loop {
println!("Please enter the number of guesses allowed (7 - 20): ");
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
match (input_line.trim()).parse::<i32>() {
Ok(n) => {
if n >= 7 && n <= 20 {
guesses_max = n;
break;
} else {
println!("Outside of range (7 - 20).");
}
}
Err(_) => println!("Invalid input."),
}
}
println!("{} guesses allowed.\n", guesses_max);
let mut rng = rand::thread_rng();
let mut code;
if colors_dup {
code = (0..code_len)
.map(|_| ((65 + rng.gen_range(0, colors_n) as u8) as char))
.collect::<Vec<_>>();
} else {
code = colors.chars().collect::<Vec<_>>();
code.shuffle(&mut rng);
code = code[..code_len as usize].to_vec();
}
//code = vec!['J', 'A', 'R', 'D', 'A', 'N', 'I'];
//println!("Secret code: {:?}", code);
let mut guesses: Vec<(String, String)> = vec![];
let mut i = 1;
loop {
println!("Your guess ({}/{})?: ", i, guesses_max);
input_line.clear();
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
let mut guess = input_line.trim().to_uppercase();
if guess.len() as i32 > code_len {
guess = guess[..code_len as usize].to_string();
}
let guess_v = guess.chars().collect::<Vec<char>>();
let res = evaluate(&code, &guess_v);
guesses.push((guess, res.clone()));
let width = 8 + guesses_max.to_string().len() + code_len as usize * 2;
println!("{}", "-".repeat(width));
for (i, guess) in guesses.iter().enumerate() {
let line = format!(
" {:w1$} : {:w2$} : {:w2$} ",
i + 1,
guess.0,
guess.1,
w1 = guesses_max.to_string().len(),
w2 = code_len as usize
);
println!("{}", line);
}
println!("{}", "-".repeat(width));
if res == "X".repeat(code_len as usize) {
println!("You won! Code: {}", code.into_iter().collect::<String>());
break;
}
i += 1;
if i > guesses_max {
println!("You lost. Code: {}", code.into_iter().collect::<String>());
break;
}
}
}
fn evaluate(code: &[char], guess: &[char]) -> String {
let mut res: Vec<char> = vec![];
for i in 0..guess.len() {
if guess[i] == code[i] {
res.push('X');
} else if code.contains(&guess[i]) {
res.push('O');
} else {
res.push('-');
}
}
res.sort_by(|a, b| b.cmp(a));
res.into_iter().collect()
} |
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.
| #Racket | Racket |
;; Returns a path connecting two given cells in the maze
;; find-path :: Maze Cell Cell -> (Listof Cell)
(define (find-path m p1 p2)
(match-define (maze N M tbl) m)
(define (alternatives p prev) (remove prev (connections tbl p)))
(define (dead-end? p prev) (empty? (alternatives p prev)))
(define ((next-turn route) p)
(define prev (car route))
(cond
[(equal? p p2) (cons p2 route)]
[(dead-end? p prev) '()]
[else (append-map (next-turn (cons p route))
(alternatives p prev))]))
(reverse
(append-map (next-turn (list p1))
(alternatives p1 (list p1)))))
|
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.
| #PARI.2FGP | PARI/GP | V=[[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]];
forstep(i=#V,2,-1,V[i-1]+=vector(i-1,j,max(V[i][j],V[i][j+1]))); V[1][1] |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning: MD5 has known weaknesses, including collisions and forged signatures. Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3.
If the solution on this page is a library solution, see MD5/Implementation for an implementation from scratch.
| #Haskell | Haskell | import Data.Digest.OpenSSL.MD5 (md5sum)
import Data.ByteString (pack)
import Data.Char (ord)
main = do
let message = "The quick brown fox jumped over the lazy dog's back"
digest = (md5sum . pack . map (fromIntegral . ord)) message
putStrLn digest |
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).
| #XPL0 | XPL0 | int N, A(101), X, Y, Z;
[for N:= 0 to 100 do A(N):= false;
for X:= 0 to 100/6 do
for Y:= 0 to 100/9 do
for Z:= 0 to 100/20 do
[N:= 6*X + 9*Y + 20*Z;
if N <= 100 then A(N):= true;
];
for N:= 100 downto 0 do
if A(N) = false then
[IntOut(0, N);
exit;
];
] |
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).
| #zkl | zkl | nuggets:=[0..101].pump(List()); // (0,1,2,3..101), mutable
foreach s,n,t in ([0..100/6],[0..100/9],[0..100/20])
{ nuggets[(6*s + 9*n + 20*t).min(101)]=0 }
println((0).max(nuggets)); |
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)
| #Haskell | Haskell | import qualified Data.Map.Strict as M
import Data.List (transpose, intercalate)
import Data.Maybe (fromJust, isJust)
import Control.Monad (forM_)
import Data.Monoid ((<>))
magic :: Int -> [[Int]]
magic n = mapAsTable ((4 * n) + 2) (hiResMap n)
-- Order of square -> sequence numbers keyed by cartesian coordinates
hiResMap :: Int -> M.Map (Int, Int) Int
hiResMap n =
let mapLux = luxMap n
mapSiam = siamMap n
in M.fromList $
foldMap
(\(xy, n) ->
luxNums xy (fromJust (M.lookup xy mapLux)) ((4 * (n - 1)) + 1))
(M.toList mapSiam)
-- LUX table coordinate -> L|U|X -> initial number -> 4 numbered coordinates
luxNums :: (Int, Int) -> Char -> Int -> [((Int, Int), Int)]
luxNums xy lux n =
zipWith (\x d -> (x, n + d)) (hiRes xy) $
case lux of
'L' -> [3, 0, 1, 2]
'U' -> [0, 3, 1, 2]
'X' -> [0, 3, 2, 1]
_ -> [0, 0, 0, 0]
-- Size of square -> integers keyed by coordinates -> rows of integers
mapAsTable :: Int -> M.Map (Int, Int) Int -> [[Int]]
mapAsTable nCols xyMap =
let axis = [0 .. nCols - 1]
in fmap (fromJust . flip M.lookup xyMap) <$>
(axis >>= \y -> [axis >>= \x -> [(x, y)]])
-- Dimension of LUX table -> LUX symbols keyed by coordinates
luxMap :: Int -> M.Map (Int, Int) Char
luxMap n =
(M.fromList . concat) $
zipWith
(\y xs -> (zipWith (\x c -> ((x, y), c)) [0 ..] xs))
[0 ..]
(luxPattern n)
-- LUX dimension -> square of L|U|X cells with two mixed rows
luxPattern :: Int -> [String]
luxPattern n =
let d = (2 * n) + 1
[ls, us] = replicate n <$> "LU"
[lRow, xRow] = replicate d <$> "LX"
in replicate n lRow <> [ls <> ('U' : ls)] <> [us <> ('L' : us)] <>
replicate (n - 1) xRow
-- Highest zero-based index of grid -> Siamese indices keyed by coordinates
siamMap :: Int -> M.Map (Int, Int) Int
siamMap n =
let uBound = (2 * n)
sPath uBound sMap (x, y) n =
let newMap = M.insert (x, y) n sMap
in if y == uBound && x == quot uBound 2
then newMap
else sPath uBound newMap (nextSiam uBound sMap (x, y)) (n + 1)
in sPath uBound (M.fromList []) (n, 0) 1
-- Highest index of square -> Siam xys so far -> xy -> next xy coordinate
nextSiam :: Int -> M.Map (Int, Int) Int -> (Int, Int) -> (Int, Int)
nextSiam uBound sMap (x, y) =
let alt (a, b)
| a > uBound && b < 0 = (uBound, 1) -- Top right corner ?
| a > uBound = (0, b) -- beyond right edge ?
| b < 0 = (a, uBound) -- above top edge ?
| isJust (M.lookup (a, b) sMap) = (a - 1, b + 2) -- already filled ?
| otherwise = (a, b) -- Up one, right one.
in alt (x + 1, y - 1)
-- LUX cell coordinate -> four coordinates at higher resolution
hiRes :: (Int, Int) -> [(Int, Int)]
hiRes (x, y) =
let [col, row] = (* 2) <$> [x, y]
[col1, row1] = succ <$> [col, row]
in [(col, row), (col1, row), (col, row1), (col1, row1)]
-- TESTS ----------------------------------------------------------------------
checked :: [[Int]] -> (Int, Bool)
checked square = (h, all (h ==) t)
where
diagonals = fmap (flip (zipWith (!!)) [0 ..]) . ((:) <*> (return . reverse))
h:t = sum <$> square <> transpose square <> diagonals square
table :: String -> [[String]] -> [String]
table delim rows =
let justifyRight c n s = drop (length s) (replicate n c <> s)
in intercalate delim <$>
transpose
((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows)
main :: IO ()
main =
forM_ [1, 2, 3] $
\n -> do
let test = magic n
putStrLn $ unlines (table " " (fmap show <$> test))
print $ checked test
putStrLn "" |
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.)
| #XPL0 | XPL0 | int N, X;
real M, Thresh, MC;
[Text(0, "First 20 magic constants:^M^J");
for N:= 3 to 20+3-1 do
[IntOut(0, (N*N*N+N)/2); ChOut(0, ^ )];
CrLf(0);
Text(0, "1000th magic constant: ");
N:= 1000+3-1;
IntOut(0, (N*N*N+N)/2);
CrLf(0);
Text(0, "Smallest order magic square with a constant greater than:^M^J");
Thresh:= 10.;
M:= 3.;
Format(1, 0);
for X:= 1 to 10 do
[repeat MC:= (M*M*M+M)/2.;
M:= M+1.;
until MC > Thresh;
Text(0, "10^^");
if X < 10 then ChOut(0, ^0);
IntOut(0, X);
Text(0, ": ");
RlOut(0, M-1.);
CrLf(0);
Thresh:= Thresh*10.;
];
] |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #ALGOL_W | ALGOL W | begin
% This is an integer ascii Mandelbrot generator, translated from the %
% Compiler/AST Interpreter Task's ASCII Mandelbrot Set example program %
integer leftEdge, rightEdge, topEdge, bottomEdge, xStep, yStep, maxIter;
leftEdge := -420;
rightEdge := 300;
topEdge := 300;
bottomEdge := -300;
xStep := 7;
yStep := 15;
maxIter := 200;
for y0 := topEdge step - yStep until bottomEdge do begin
for x0 := leftEdge step xStep until rightEdge do begin
integer x, y, i;
string(1) theChar;
y := 0;
x := 0;
theChar := " ";
i := 0;
while i < maxIter do begin
integer x_x, y_y;
x_x := (x * x) div 200;
y_y := (y * y) div 200;
if x_x + y_y > 800 then begin
theChar := code( decode( "0" ) + i );
if i > 9 then theChar := "@";
i := maxIter
end;
y := x * y div 100 + y0;
x := x_x - y_y + x0;
i := i + 1
end while_i_lt_maxIter ;
writeon( theChar );
end for_x0 ;
write();
end for_y0
end.
|
http://rosettacode.org/wiki/Magic_squares_of_odd_order | Magic squares of odd order | A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant).
The numbers are usually (but not always) the first N2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
8
1
6
3
5
7
4
9
2
Task
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Related tasks
Magic squares of singly even order
Magic squares of doubly even order
See also
MathWorld™ entry: Magic_square
Odd Magic Squares (1728.org)
| #AppleScript | AppleScript | ---------------- MAGIC SQUARE OF ODD ORDER ---------------
-- oddMagicSquare :: Int -> [[Int]]
on oddMagicSquare(n)
if 0 < (n mod 2) then
cycleRows(transpose(cycleRows(table(n))))
else
missing value
end if
end oddMagicSquare
--------------------------- TEST -------------------------
on run
-- Orders 3, 5, 11
-- wikiTableMagic :: Int -> String
script wikiTableMagic
on |λ|(n)
formattedTable(oddMagicSquare(n))
end |λ|
end script
intercalate(linefeed & linefeed, map(wikiTableMagic, {3, 5, 11}))
end run
-- table :: Int -> [[Int]]
on table(n)
set lstTop to enumFromTo(1, n)
script cols
on |λ|(row)
script rows
on |λ|(x)
(row * n) + x
end |λ|
end script
map(rows, lstTop)
end |λ|
end script
map(cols, enumFromTo(0, n - 1))
end table
-- cycleRows :: [[a]] -> [[a]]
on cycleRows(lst)
script rotationRow
-- rotatedList :: [a] -> Int -> [a]
on rotatedList(lst, n)
if n = 0 then return lst
set lng to length of lst
set m to (n + lng) mod lng
items -m thru -1 of lst & items 1 thru (lng - m) of lst
end rotatedList
on |λ|(row, i)
rotatedList(row, (((length of row) + 1) div 2) - (i))
end |λ|
end script
map(rotationRow, lst)
end cycleRows
-------------------- GENERIC FUNCTIONS -------------------
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- 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
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- splitOn :: Text -> Text -> [Text]
on splitOn(strDelim, strMain)
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
set xs to text items of strMain
set my text item delimiters to dlm
return xs
end splitOn
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
----------------------- WIKI DISPLAY ---------------------
-- formattedTable :: [[Int]] -> String
on formattedTable(lstTable)
set n to length of lstTable
set w to 2.5 * n
"magic(" & n & ")" & linefeed & linefeed & wikiTable(lstTable, ¬
false, "text-align:center;width:" & ¬
w & "em;height:" & w & "em;table-layout:fixed;")
end formattedTable
-- wikiTable :: [Text] -> Bool -> Text -> Text
on wikiTable(xs, blnHdr, strStyle)
script wikiRows
on |λ|(lstRow, iRow)
set strDelim to cond(blnHdr and (iRow = 0), "!", "|")
set strDbl to strDelim & strDelim
linefeed & "|-" & linefeed & strDelim & space & ¬
intercalate(space & strDbl & space, lstRow)
end |λ|
end script
linefeed & "{| class=\"wikitable\" " & ¬
cond(strStyle ≠ "", "style=\"" & strStyle & "\"", "") & ¬
intercalate("", ¬
map(wikiRows, xs)) & linefeed & "|}" & linefeed
end wikiTable
-- cond :: Bool -> a -> a -> a
on cond(bool, f, g)
if bool then
f
else
g
end if
end cond |
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.
| #BQN | BQN | Mul ← +˝∘×⎉1‿∞
(>⟨
⟨1, 2, 3⟩
⟨4, 5, 6⟩
⟨7, 8, 9⟩
⟩) Mul >⟨
⟨1, 2, 3, 4⟩
⟨5, 6, 7, 8⟩
⟨9, 10, 11, 12⟩
⟩ |
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.
| #Raku | Raku | mkdir 'path/to/dir' |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).
It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.
| #REXX | REXX | /*REXX program creates a directory (folder) and all its parent paths as necessary. */
trace off /*suppress possible warning msgs.*/
dPath = 'path\to\dir' /*define directory (folder) path.*/
'MKDIR' dPath "2>nul" /*alias could be used: MD dPath */
/*stick a fork in it, we're done.*/ |
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.
| #Ring | Ring |
System("mkdir C:\Ring\docs")
isdir("C:\Ring\docs")
see isdir("C:\Ring\docs") + nl
func isdir cDir
try
dir(cDir)
return true
catch
return false
done
|
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.
| #Ruby | Ruby | require 'fileutils'
FileUtils.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.
| #Run_BASIC | Run BASIC |
files #f, "c:\myDocs" ' check for directory
if #f hasanswer() then
if #f isDir() then ' is it a file or a directory
print "A directory exist"
else
print "A file exist"
end if
else
shell$("mkdir c:\myDocs" ' if not exist make a directory
end if |
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order | Magic squares of doubly even order | A magic square is an N×N square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
1
2
62
61
60
59
7
8
9
10
54
53
52
51
15
16
48
47
19
20
21
22
42
41
40
39
27
28
29
30
34
33
32
31
35
36
37
38
26
25
24
23
43
44
45
46
18
17
49
50
14
13
12
11
55
56
57
58
6
5
4
3
63
64
Task
Create a magic square of 8 × 8.
Related tasks
Magic squares of odd order
Magic squares of singly even order
See also
Doubly Even Magic Squares (1728.org)
| #C.23 | C# | using System;
namespace MagicSquareDoublyEven
{
class Program
{
static void Main(string[] args)
{
int n = 8;
var result = MagicSquareDoublyEven(n);
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write("{0,2} ", result[i, j]);
Console.WriteLine();
}
Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
Console.ReadLine();
}
private static int[,] MagicSquareDoublyEven(int n)
{
if (n < 4 || n % 4 != 0)
throw new ArgumentException("base must be a positive "
+ "multiple of 4");
// pattern of count-up vs count-down zones
int bits = 0b1001_0110_0110_1001;
int size = n * n;
int mult = n / 4; // how many multiples of 4
int[,] result = new int[n, n];
for (int r = 0, i = 0; r < n; r++)
{
for (int c = 0; c < n; c++, i++)
{
int bitPos = c / mult + (r / mult) * 4;
result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
}
} |
http://rosettacode.org/wiki/Man_or_boy_test | Man or boy test | Man or boy test
You are encouraged to solve this task according to the task description, using any language you may know.
Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
— Donald Knuth
Task: Imitate Knuth's example in Algol 60 in another language, as far as possible.
Details: Local variables of routines are often kept in activation records (also call frames). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.
In Knuth's example, each call to A allocates an activation record for the variable A. When B is called from A, any access to k now refers to this activation record. Now B in turn calls A, but passes itself as an argument. This argument remains bound to the activation record. This call to A also "shifts" the variables xi by one place, so eventually the argument B (still bound to its particular
activation record) will appear as x4 or x5 in a call to A. If this happens when the expression x4 + x5 is evaluated, then this will again call B, which in turn will update k in the activation record it was originally bound to. As this activation record is shared with other instances of calls to A and B, it will influence the whole computation.
So all the example does is to set up a convoluted calling structure, where updates to k can influence the behavior
in completely different parts of the call tree.
Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.
Performance and Memory: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.
The table below shows the result, call depths, and total calls for a range of k:
k
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
A
1
0
-2
0
1
0
1
-1
-10
-30
-67
-138
-291
-642
-1,446
-3,250
-7,244
-16,065
-35,601
-78,985
-175,416
-389,695
-865,609
-1,922,362
-4,268,854
-9,479,595
-21,051,458
-46,750,171
-103,821,058
-230,560,902
-512,016,658
A called
1
2
3
4
8
18
38
80
167
347
722
1,509
3,168
6,673
14,091
29,825
63,287
134,652
287,264
614,442
1,317,533
2,831,900
6,100,852
13,172,239
28,499,827
61,786,266
134,202,509
292,011,464
A depth
1
2
3
4
8
16
32
64
128
256
512
1,024
2,048
4,096
8,192
16,384
32,768
65,536
131,072
262,144
524,288
1,048,576
2,097,152
4,194,304
8,388,608
B called
0
1
2
3
7
17
37
79
166
346
721
1,508
3,167
6,672
14,090
29,824
63,286
134,651
287,263
614,441
1,317,532
2,831,899
6,100,851
13,172,238
28,499,826
B depth
0
1
2
3
7
15
31
63
127
255
511
1,023
2,047
4,095
8,191
16,383
32,767
65,535
131,071
262,143
524,287
1,048,575
2,097,151
4,194,303
8,388,607
Related tasks
Jensen's Device
| #D | D | import core.stdc.stdio: printf;
int a(int k, const lazy int x1, const lazy int x2, const lazy int x3,
const lazy int x4, const lazy int x5) pure {
int b() {
k--;
return a(k, b(), x1, x2, x3, x4);
}
return k <= 0 ? x4 + x5 : b();
}
void main() {
printf("%d\n", a(10, 1, -1, -1, 1, 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.
| #PicoLisp | PicoLisp | (setq K1 (13 2 8 4 6 15 11 1 10 9 3 14 5 0 12 7))
(setq K2 ( 4 11 2 14 15 0 8 13 3 12 9 7 5 10 6 1))
(setq K3 (12 1 10 15 9 2 6 8 0 13 3 4 14 7 5 11))
(setq K4 ( 2 12 4 1 7 10 11 6 8 5 3 15 13 0 14 9))
(setq K5 ( 7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15))
(setq K6 (10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8))
(setq K7 (15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10))
(setq K8 (14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7))
(setq K21
(mapcar
'((N)
(|
(>> -4 (get K2 (inc (>> 4 N))))
(get K1 (inc (& N 15))) ) )
(range 0 255) ) )
(setq K43
(mapcar
'((N)
(|
(>> -4 (get K4 (inc (>> 4 N))))
(get K3 (inc (& N 15))) ) )
(range 0 255) ) )
(setq K65
(mapcar
'((N)
(|
(>> -4 (get K6 (inc (>> 4 N))))
(get K5 (inc (& N 15))) ) )
(range 0 255) ) )
(setq K87
(mapcar
'((N)
(|
(>> -4 (get K8 (inc (>> 4 N))))
(get K7 (inc (& N 15))) ) )
(range 0 255) ) )
(de leftRotate (X C)
(|
(& `(hex "FFFFFFFF") (>> (- C) X))
(>> (- 32 C) X) ) )
(de f (X)
(leftRotate
(apply
|
(mapcar
'((Lst N)
(>>
N
(get
(val Lst)
(inc (& 255 (>> (abs N) X))) ) ) )
'(K87 K65 K43 K21)
(-24 -16 -8 0) ) )
11 ) )
(bye) |
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.
| #Python | Python |
k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ]
k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ]
k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ]
k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ]
k4 = [ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ]
k3 = [ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ]
k2 = [ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ]
k1 = [ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ]
k87 = [0] * 256
k65 = [0] * 256
k43 = [0] * 256
k21 = [0] * 256
def kboxinit():
for i in range(256):
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]
def f(x):
x = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |
k43[x>> 8 & 255] << 8 | k21[x & 255] )
return x<<11 | x>>(32-11) |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Clear[MagnanimousNumberQ]
MagnanimousNumberQ[Alternatives @@ Range[0, 9]] = True;
MagnanimousNumberQ[n_Integer] := AllTrue[Range[IntegerLength[n] - 1], PrimeQ[Total[FromDigits /@ TakeDrop[IntegerDigits[n], #]]] &]
sel = Select[Range[0, 1000000], MagnanimousNumberQ];
sel[[;; 45]]
sel[[241 ;; 250]]
sel[[391 ;; 400]] |
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.
| #Nim | Nim | func isPrime(n: Natural): bool =
if n < 2: return
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
return true
func isMagnanimous(n: Natural): bool =
var p = 10
while true:
let a = n div p
let b = n mod p
if a == 0: break
if not isPrime(a + b): return false
p *= 10
return true
iterator magnanimous(): (int, int) =
var n, count = 0
while true:
if n.isMagnanimous:
inc count
yield (count, n)
inc n
for (i, n) in magnanimous():
if i in 1..45:
if i == 1: stdout.write "First 45 magnanimous numbers:\n "
stdout.write n, if i == 45: '\n' else: ' '
elif i in 241..250:
if i == 241: stdout.write "\n241st through 250th magnanimous numbers:\n "
stdout.write n, if i == 250: "\n" else: " "
elif i in 391..400:
if i == 391: stdout.write "\n391st through 400th magnanimous numbers:\n "
stdout.write n, if i == 400: "\n" else: " "
elif i > 400:
break |
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.
| #Pascal | Pascal | program Magnanimous;
//Magnanimous Numbers
//algorithm find only numbers where all digits are even except the last
//or where all digits are odd except the last
//so 1,11,20,101,1001 will not be found
//starting at 100001 "1>"+x"0"+"1" is not prime because of 1001 not prime
{$IFDEF FPC}
{$MODE DELPHI}
{$Optimization ON}
{$CODEALIGN proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
{$DEFINE USE_GMP}
uses
//strUtils, // commatize Numb2USA
{$IFDEF USE_GMP}gmp,{$ENDIF}
SysUtils;
const
MaxLimit = 10*1000*1000 +10;
MAXHIGHIDX = 10;
type
tprimes = array of byte;
tBaseType = Byte;
tpBaseType = pByte;
tBase =array[0..15] of tBaseType;
tNumType = NativeUint;
tSplitNum = array[0..15] of tNumType;
tMagList = array[0..1023] of Uint64;
var
{$ALIGN 32}
MagList : tMagList;
dgtBase5, // count in Base 5
dgtORMask, //Mark of used digit (or (1 shl Digit ))
dgtEvenBase10,
dgtOddBase10: tbase;
primes : tprimes;
{$IFDEF USE_GMP} z : mpz_t;gmp_count :NativeUint;{$ENDIF}
pPrimes0 : pByte;
T0: int64;
HighIdx,num,MagIdx,count,cnt: NativeUint;
procedure InitPrimes;
const
smallprimes :array[0..5] of byte = (2,3,5,7,11,13);
var
pPrimes : pByte;
p,i,j,l : NativeUint;
begin
l := 1;
for j := 0 to High(smallprimes) do
l*= smallprimes[j];
//scale primelimit to be multiple of l
i :=((MaxLimit-1) DIV l+1)*l+1;//+1 should suffice
setlength(primes,i);
pPrimes := @primes[0];
for j := 0 to High(smallprimes) do
begin
p := smallprimes[j];
i := p;
if j <> 0 then
p +=p;
while i <= l do
begin
pPrimes[i] := 1;
inc(i,p)
end;
end;
//turn the prime wheel
for p := length(primes) div l -1 downto 1 do
move(pPrimes[1],pPrimes[p*l+1],l);
l := High(primes);
//reinsert smallprimes
for j := 0 to High(smallprimes) do
pPrimes[smallprimes[j]] := 0;
pPrimes[1]:=1;
pPrimes[0]:=1;
p := smallprimes[High(smallprimes)];
repeat
repeat
inc(p)
until pPrimes[p] = 0;
j := l div p;
while (pPrimes[j]<> 0) AND (j>=p) do
dec(j);
if j<p then
BREAK;
//delta going downwards no factor 2,3 :-2 -4 -2 -4
i := (j+1) mod 6;
if i = 0 then
i :=4;
repeat
while (pPrimes[j]<> 0) AND (j>=p) do
begin
dec(j,i);
i := 6-i;
end;
if j<p then
BREAK;
pPrimes[j*p] := 1;
dec(j,i);
i := 6-i;
until j<p;
until false;
pPrimes0 := pPrimes;
end;
procedure InsertSort(pMag:pUint64; Left, Right : NativeInt );
var
I, J: NativeInt;
Pivot : Uint64;
begin
for i:= 1 + Left to Right do
begin
Pivot:= pMag[i];
j:= i - 1;
while (j >= Left) and (pMag[j] > Pivot) do
begin
pMag[j+1]:=pMag[j];
Dec(j);
end;
pMag[j+1]:= pivot;
end;
end;
procedure OutBase5;
var
pb: tpBaseType;
i : NativeUint;
begin
write(count :10);
pb:= @dgtBase5[0];
for i := HighIdx downto 0 do
write(pb[i]:3);
write(' : ' );
pb:= @dgtORMask[0];
for i := HighIdx downto 0 do
write(pb[i]:3);
end;
function Base10toNum(var dgtBase10: tBase):NativeUint;
var
i : NativeInt;
begin
Result := 0;
for i := HighIdx downto 0 do
Result := Result * 10 + dgtBase10[i];
end;
procedure OutSol(cnt:Uint64);
begin
writeln(MagIdx:4,cnt:13,Base10toNum(dgtOddBase10):20,
(Gettickcount64-T0) / 1000: 10: 3, ' s');
end;
procedure CnvEvenBase10(lastIdx:NativeInt);
var
pdgt : tpBaseType;
idx: nativeint;
begin
pDgt := @dgtEvenBase10[0];
for idx := lastIdx downto 1 do
pDgt[idx] := 2 * dgtBase5[idx];
pDgt[0] := 2 * dgtBase5[0]+1;
end;
procedure CnvOddBase10(lastIdx:NativeInt);
var
pdgt : tpBaseType;
idx: nativeint;
begin
pDgt := @dgtOddBase10[0];
//make all odd
for idx := lastIdx downto 1 do
pDgt[idx] := 2 * dgtBase5[idx] + 1;
//but the lowest even
pDgt[0] := 2 * dgtBase5[0];
end;
function IncDgtBase5:NativeUint;
// increment n base 5 until resulting sum of split number
// can't end in 5
var
pb: tpBaseType;
n,i: nativeint;
begin
result := 0;
repeat
repeat
//increment Base5
pb:= @dgtBase5[0];
i := 0;
repeat
n := pb[i] + 1;
if n < 5 then
begin
pb[i] := n;
break;
end;
pb[i] := 0;
Inc(i);
until False;
if HighIdx < i then
begin
HighIdx := i;
pb[i] := 0;
end;
if result < i then
result := i;
n := dgtORMask[i+1];
while i >= 0 do
begin
n := n OR (1 shl pb[i]);
dgtORMask[i]:= n;
if n = 31 then
break;
dec(i);
end;
if HighIdx<4 then
break;
if (n <> 31) OR (i=0) then
break;
//Now there are all digits are used at digit i ( not in last pos)
//this will always lead to a number ending in 5-> not prime
//so going on with a number that will change the used below i to highest digit
//to create an overflow of the next number, to change the digits
dec(i);
repeat
pb[i] := 4;
dgtORMask[i]:= 31;
dec(i);
until i < 0;
until false;
if HighIdx<4 then
break;
n := dgtORMask[1];
//ending in 5. base10(base5) for odd 1+4(0,2),3+2(1,1),5+0(2,0)
i := pb[0];
if i <= 2 then
begin
i := 1 shl (2-i);
end
else
Begin
//ending in 5 7+8(3,4),9+6(4,3)
i := 1 shl (4-i);
n := n shr 3;
end;
if (i AND n) = 0 then
BREAK;
until false;
end;
procedure CheckMagn(var dgtBase10: tBase);
//split number into sum of all "partitions" of digits
//check if sum is always prime
//1234 -> 1+234,12+34 ;123+4
var
LowSplitNum : tSplitNum;
i,fac,n: NativeInt;
isMagn : boolean;
Begin
n := 0;
fac := 1;
For i := 0 to HighIdx-1 do
begin
n := fac*dgtBase10[i]+n;
fac *=10;
LowSplitNum[HighIdx-1-i] := n;
end;
n := 0;
fac := HighIdx;
isMagn := true;
For i := 0 to fac-1 do
begin
//n = HighSplitNum[i]
n := n*10+dgtBase10[fac-i];
LowSplitNum[i] += n;
if LowSplitNum[i]<=MAXLIMIT then
begin
isMagn := isMagn AND (pPrimes0[LowSplitNum[i]] = 0);
if NOT(isMagn) then
EXIT;
end;
end;
{$IFDEF USE_GMP}
For i := 0 to fac-1 do
begin
n := LowSplitNum[i];
if n >MAXLIMIT then
Begin
// IF NOT((n mod 30) in [1,7,11,13,17,19,23,29]) then EXIT;
mpz_set_ui(z,n);
gmp_count +=1;
isMagn := isMagn AND (mpz_probab_prime_p(z,1) >0);
if NOT(isMagn) then
EXIT;
end;
end;
{$ENDIF}
//insert magnanimous numbers
num := Base10toNum(dgtBase10);
MagList[MagIdx] := num;
inc(MagIdx);
end;
function Run(StartDgtCount:byte):Uint64;
var
lastIdx: NativeInt;
begin
result := 0;
HighIdx := StartDgtCount;// 7 start with 7 digits
LastIdx := HighIdx;
repeat
if dgtBase5[HighIdx] <> 0 then
Begin
CnvEvenBase10(LastIdx);
CheckMagn(dgtEvenBase10);
end;
CnvOddBase10(LastIdx);
CheckMagn(dgtOddBase10);
inc(result);
//output for still running every 16.22 Mio
IF result AND (1 shl 22-1) = 0 then
OutSol(result);
lastIdx := IncDgtBase5;
until HighIdx > MAXHIGHIDX;
end;
BEGIN
{$IFDEF USE_GMP}mpz_init_set_ui(z,0);{$ENDIF}
T0 := Gettickcount64;
InitPrimes;
T0 -= Gettickcount64;
writeln('getting primes ',-T0 / 1000: 0: 3, ' s');
T0 := Gettickcount64;
fillchar(dgtBase5,SizeOf(dgtBase5),#0);
fillchar(dgtEvenBase10,SizeOf(dgtEvenBase10),#0);
fillchar(dgtOddBase10,SizeOf(dgtOddBase10),#0);
//Magnanimous Numbers that can not be found by this algorithm
MagIdx := 0;
MagList[MagIdx] := 1;inc(MagIdx);
MagList[MagIdx] := 11;inc(MagIdx);
MagList[MagIdx] := 20;inc(MagIdx);
MagList[MagIdx] := 101;inc(MagIdx);
MagList[MagIdx] := 1001;inc(MagIdx);
//cant be checked easy for ending in 5
MagList[MagIdx] := 40001;inc(MagIdx);
{$IFDEF USE_GMP} mpz_init_set_ui(z,0);{$ENDIF}
count := Run(0);
writeln;
CnvOddBase10(highIdx);
writeln(MagIdx:5,count:12,Base10toNum(dgtOddBase10):18,
(Gettickcount64-T0) / 1000: 10: 3, ' s');
InsertSort(@MagList[0],0,MagIdx-1);
{$IFDEF USE_GMP} mpz_clear(z);writeln('Count of gmp tests ',gmp_count);{$ENDIF}
For cnt := 0 to MagIdx-1 do
writeln(cnt+1:3,' ',MagList[cnt]);
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end. |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #BASIC | BASIC | CLS
DIM m(1 TO 5, 1 TO 4) 'any dimensions you want
'set up the values in the array
FOR rows = LBOUND(m, 1) TO UBOUND(m, 1) 'LBOUND and UBOUND can take a dimension as their second argument
FOR cols = LBOUND(m, 2) TO UBOUND(m, 2)
m(rows, cols) = rows ^ cols 'any formula you want
NEXT cols
NEXT rows
'declare the new matrix
DIM trans(LBOUND(m, 2) TO UBOUND(m, 2), LBOUND(m, 1) TO UBOUND(m, 1))
'copy the values
FOR rows = LBOUND(m, 1) TO UBOUND(m, 1)
FOR cols = LBOUND(m, 2) TO UBOUND(m, 2)
trans(cols, rows) = m(rows, cols)
NEXT cols
NEXT rows
'print the new matrix
FOR rows = LBOUND(trans, 1) TO UBOUND(trans, 1)
FOR cols = LBOUND(trans, 2) TO UBOUND(trans, 2)
PRINT trans(rows, cols);
NEXT cols
PRINT
NEXT rows
|
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.
| #EGL | EGL | program MazeGen
// First and last columns/rows are "dead" cells. Makes generating
// a maze with border walls much easier. Therefore, a visible
// 20x20 maze has a maze size of 22.
mazeSize int = 22;
south boolean[][];
west boolean[][];
visited boolean[][];
function main()
initMaze();
generateMaze();
drawMaze();
end
private function initMaze()
visited = createBooleanArray(mazeSize, mazeSize, false);
// Initialize border cells as already visited
for(col int from 1 to mazeSize)
visited[col][1] = true;
visited[col][mazeSize] = true;
end
for(row int from 1 to mazeSize)
visited[1][row] = true;
visited[mazeSize][row] = true;
end
// Initialize all walls as present
south = createBooleanArray(mazeSize, mazeSize, true);
west = createBooleanArray(mazeSize, mazeSize, true);
end
private function createBooleanArray(col int in, row int in, initialState boolean in) returns(boolean[][])
newArray boolean[][] = new boolean[0][0];
for(i int from 1 to col)
innerArray boolean[] = new boolean[0];
for(j int from 1 to row)
innerArray.appendElement(initialState);
end
newArray.appendElement(innerArray);
end
return(newArray);
end
private function createIntegerArray(col int in, row int in, initialValue int in) returns(int[][])
newArray int[][] = new int[0][0];
for(i int from 1 to col)
innerArray int[] = new int[0];
for(j int from 1 to row)
innerArray.appendElement(initialValue);
end
newArray.appendElement(innerArray);
end
return(newArray);
end
private function generate(col int in, row int in)
// Mark cell as visited
visited[col][row] = true;
// Keep going as long as there is an unvisited neighbor
while(!visited[col][row + 1] || !visited[col + 1][row] ||
!visited[col][row - 1] || !visited[col - 1][row])
while(true)
r float = MathLib.random(); // Choose a random direction
case
when(r < 0.25 && !visited[col][row + 1]) // Go south
south[col][row] = false; // South wall down
generate(col, row + 1);
exit while;
when(r >= 0.25 && r < 0.50 && !visited[col + 1][row]) // Go east
west[col + 1][row] = false; // West wall of neighbor to the east down
generate(col + 1, row);
exit while;
when(r >= 0.5 && r < 0.75 && !visited[col][row - 1]) // Go north
south[col][row - 1] = false; // South wall of neighbor to the north down
generate(col, row - 1);
exit while;
when(r >= 0.75 && r < 1.00 && !visited[col - 1][row]) // Go west
west[col][row] = false; // West wall down
generate(col - 1, row);
exit while;
end
end
end
end
private function generateMaze()
// Pick random start position (within the visible maze space)
randomStartCol int = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2);
randomStartRow int = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2);
generate(randomStartCol, randomStartRow);
end
private function drawMaze()
line string;
// Iterate over wall arrays (skipping dead border cells as required).
// Construct a line at a time and output to console.
for(row int from 1 to mazeSize - 1)
if(row > 1)
line = "";
for(col int from 2 to mazeSize)
if(west[col][row])
line ::= "| ";
else
line ::= " ";
end
end
Syslib.writeStdout(line);
end
line = "";
for(col int from 2 to mazeSize - 1)
if(south[col][row])
line ::= "+---";
else
line ::= "+ ";
end
end
line ::= "+";
SysLib.writeStdout(line);
end
end
end |
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.