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/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #K | K |
/ Rosetta code - Middle three digits
/ mid3.k
mid3: {qs:$x;:[qs[0]="-";qs: 1 _ qs];:[(#qs)<3;:"small";(1+#qs)!2;:"even"];p:(-3+#qs)%2;:(|p _|p _ qs)}
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Prolog | Prolog | :- module(primality, [is_prime/2]).
% is_prime/2 returns false if N is composite, true if N probably prime
% implements a Miller-Rabin primality test and is deterministic for N < 3.415e+14,
% and is probabilistic for larger N. Adapted from the Erlang version.
is_prime(1, Ret) :- Ret = false, !. % 1 is non-prime
is_prime(2, Ret) :- Ret = true, !. % 2 is prime
is_prime(3, Ret) :- Ret = true, !. % 3 is prime
is_prime(N, Ret) :-
N > 3, (N mod 2 =:= 0), Ret = false, !. % even number > 3 is composite
is_prime(N, Ret) :-
N > 3, (N mod 2 =:= 1), % odd number > 3
N < 341550071728321,
deterministic_witnesses(N, L),
is_mr_prime(N, L, Ret), !. % deterministic test
is_prime(N, Ret) :-
random_witnesses(N, 100, [], Out),
is_mr_prime(N, Out, Ret), !. % probabilistic test
% returns list of deterministic witnesses
deterministic_witnesses(N, L) :- N < 1373653,
L = [2, 3].
deterministic_witnesses(N, L) :- N < 9080191,
L = [31, 73].
deterministic_witnesses(N, L) :- N < 25326001,
L = [2, 3, 5].
deterministic_witnesses(N, L) :- N < 3215031751,
L = [2, 3, 5, 7].
deterministic_witnesses(N, L) :- N < 4759123141,
L = [2, 7, 61].
deterministic_witnesses(N, L) :- N < 1122004669633,
L = [2, 13, 23, 1662803].
deterministic_witnesses(N, L) :- N < 2152302898747,
L = [2, 3, 5, 7, 11].
deterministic_witnesses(N, L) :- N < 3474749660383,
L = [2, 3, 5, 7, 11, 13].
deterministic_witnesses(N, L) :- N < 341550071728321,
L = [2, 3, 5, 7, 11, 13, 17].
% random_witnesses/4 returns a list of K witnesses selected at random with range 2 -> N-2
random_witnesses(_, 0, T, T).
random_witnesses(N, K, T, Out) :-
G is N - 2,
H is 1 + random(G),
I is K - 1,
random_witnesses(N, I, [H | T], Out), !.
% find_ds/2 receives odd integer N and returns [D, S] s.t. N-1 = 2^S * D
find_ds(N, L) :-
A is N - 1,
find_ds(A, 0, L), !.
find_ds(D, S, L) :-
D mod 2 =:= 0,
P is D // 2,
Q is S + 1,
find_ds(P, Q, L), !.
find_ds(D, S, L) :-
L = [D, S].
is_mr_prime(N, As, Ret) :-
find_ds(N, L),
L = [D | T],
T = [S | _],
outer_loop(N, As, D, S, Ret), !.
outer_loop(N, As, D, S, Ret) :-
As = [A | At],
Base is powm(A, D, N),
inner_loop(Base, N, 0, S, Result),
( Result == false -> Ret = false
; Result == true, At == [] -> Ret = true
; outer_loop(N, At, D, S, Ret)
).
inner_loop(Base, N, Loop, S, Result) :-
Next_Base is (Base * Base) mod N,
Next_Loop is Loop + 1,
( Loop =:= 0, Base =:= 1 -> Result = true
; Base =:= N-1 -> Result = true
; Next_Loop =:= S -> Result = false
; inner_loop(Next_Base, N, Next_Loop, S, Result)
). |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Kotlin | Kotlin | // version 1.1.2
fun menu(list: List<String>): String {
if (list.isEmpty()) return ""
val n = list.size
while (true) {
println("\n M E N U\n")
for (i in 0 until n) println("${i + 1}: ${list[i]}")
print("\nEnter your choice 1 - $n : ")
val index = readLine()!!.toIntOrNull()
if (index == null || index !in 1..n) continue
return list[index - 1]
}
}
fun main(args: Array<String>) {
val list = listOf(
"fee fie",
"huff and puff",
"mirror mirror",
"tick tock"
)
val choice = menu(list)
println("\nYou chose : $choice")
} |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Python | Python | import math
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]
init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \
16*[lambda b, c, d: (d & b) | (~d & c)] + \
16*[lambda b, c, d: b ^ c ^ d] + \
16*[lambda b, c, d: c ^ (b | ~d)]
index_functions = 16*[lambda i: i] + \
16*[lambda i: (5*i + 1)%16] + \
16*[lambda i: (3*i + 5)%16] + \
16*[lambda i: (7*i)%16]
def left_rotate(x, amount):
x &= 0xFFFFFFFF
return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF
def md5(message):
message = bytearray(message) #copy our input into a mutable buffer
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message)%64 != 56:
message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')
hash_pieces = init_values[:]
for chunk_ofst in range(0, len(message), 64):
a, b, c, d = hash_pieces
chunk = message[chunk_ofst:chunk_ofst+64]
for i in range(64):
f = functions[i](b, c, d)
g = index_functions[i](i)
to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
a, b, c, d = d, new_b, b, c
for i, val in enumerate([a, b, c, d]):
hash_pieces[i] += val
hash_pieces[i] &= 0xFFFFFFFF
return sum(x<<(32*i) for i, x in enumerate(hash_pieces))
def md5_to_hex(digest):
raw = digest.to_bytes(16, byteorder='little')
return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))
if __name__=='__main__':
demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz",
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"]
for message in demo:
print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 )
len [
get ( dup " : " ) lprint
abs tostr len >ps
tps 3 < ( ["too short" ?]
[ tps 2 mod ( [tps 2 / 3 slice ?] ["is even" ?] ) if]
) if
ps> drop drop
] for
" " input
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #PureBasic | PureBasic | Enumeration
#Composite
#Probably_prime
EndEnumeration
Procedure Miller_Rabin(n, k)
Protected d=n-1, s, x, r
If n=2
ProcedureReturn #Probably_prime
ElseIf n%2=0 Or n<2
ProcedureReturn #Composite
EndIf
While d%2=0
d/2
s+1
Wend
While k>0
k-1
x=Int(Pow(2+Random(n-4),d))%n
If x=1 Or x=n-1: Continue: EndIf
For r=1 To s-1
x=(x*x)%n
If x=1: ProcedureReturn #Composite: EndIf
If x=n-1: Break: EndIf
Next
If x<>n-1: ProcedureReturn #Composite: EndIf
Wend
ProcedureReturn #Probably_prime
EndProcedure |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #langur | langur | val .select = f(.entries) {
if not isArray(.entries): throw "invalid args"
if len(.entries) == 0: return ZLS
# print the menu
writeln join "\n", map(f $"\.i:2;: \.e;", .entries, 1..len .entries)
val .idx = toNumber read(
"Select entry #: ",
f(.x) {
if not matching(RE/^[0-9]+$/, .x): return false
val .y = toNumber .x
.y > 0 and .y <= len(.entries)
},
"invalid selection\n", -1,
)
.entries[.idx]
}
writeln .select(["fee fie", "eat pi", "huff and puff", "tick tock"]) |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Racket | Racket |
#lang racket
(require file/md5)
(md5 #"Rosetta Code")
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Klong | Klong | items::[123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0]
mid3::{[d k];:[3>k::#$#x;"small":|0=k!2;"even";(-d)_(d::_(k%2)-1)_$#x]}
.p(mid3'items) |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Python | Python |
import random
def is_Prime(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if n!=int(n):
return False
n=int(n)
#Miller-Rabin test for prime
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):#number of trials
a = random.randrange(2, n)
if trial_composite(a):
return False
return True |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Logo | Logo | to select :prompt [:options]
foreach :options [(print # ?)]
forever [
type :prompt type "| |
make "n readword
if (and [number? :n] [:n >= 1] [:n <= count :options]) [output item :n :options]
print sentence [Must enter a number between 1 and] count :options
]
end
print equal? [huff and puff] (select
[Which is from the three pigs?]
[fee fie] [huff and puff] [mirror mirror] [tick tock])
|
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Raku | Raku | sub infix:<⊞>(uint32 $a, uint32 $b --> uint32) { ($a + $b) +& 0xffffffff }
sub infix:«<<<»(uint32 $a, UInt $n --> uint32) { ($a +< $n) +& 0xffffffff +| ($a +> (32-$n)) }
constant FGHI = { ($^a +& $^b) +| (+^$a +& $^c) },
{ ($^a +& $^c) +| ($^b +& +^$c) },
{ $^a +^ $^b +^ $^c },
{ $^b +^ ($^a +| +^$^c) };
constant _S = flat (7, 12, 17, 22) xx 4,
(5, 9, 14, 20) xx 4,
(4, 11, 16, 23) xx 4,
(6, 10, 15, 21) xx 4;
constant T = (floor(abs(sin($_ + 1)) * 2**32) for ^64);
constant k = flat ( $_ for ^16),
((5*$_ + 1) % 16 for ^16),
((3*$_ + 5) % 16 for ^16),
((7*$_ ) % 16 for ^16);
sub little-endian($w, $n, *@v) {
my \step1 = $w X* ^$n;
my \step2 = @v X+> step1;
step2 X% 2**$w;
}
sub md5-pad(Blob $msg)
{
my $bits = 8 * $msg.elems;
my @padded = flat $msg.list, 0x80, 0x00 xx -($bits div 8 + 1 + 8) % 64;
flat @padded.map({ :256[$^d,$^c,$^b,$^a] }), little-endian(32, 2, $bits);
}
sub md5-block(@H, @X)
{
my uint32 ($A, $B, $C, $D) = @H;
($A, $B, $C, $D) = ($D, $B ⊞ (($A ⊞ FGHI[$_ div 16]($B, $C, $D) ⊞ T[$_] ⊞ @X[k[$_]]) <<< _S[$_]), $B, $C) for ^64;
@H «⊞=» ($A, $B, $C, $D);
}
sub md5(Blob $msg --> Blob)
{
my uint32 @M = md5-pad($msg);
my uint32 @H = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476;
md5-block(@H, @M[$_ .. $_+15]) for 0, 16 ...^ +@M;
Blob.new: little-endian(8, 4, @H);
}
use Test;
plan 7;
for 'd41d8cd98f00b204e9800998ecf8427e', '',
'0cc175b9c0f1b6a831c399e269772661', 'a',
'900150983cd24fb0d6963f7d28e17f72', 'abc',
'f96b697d7cb7938d525a2f31aaf161d0', 'message digest',
'c3fcd3d76192e4007dfb496cca67e13b', 'abcdefghijklmnopqrstuvwxyz',
'd174ab98d277d9f5a5611c2c9f419d9f', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
-> $expected, $msg {
my $digest = md5($msg.encode('ascii')).list».fmt('%02x').join;
is($digest, $expected, "$digest is MD5 digest of '$msg'");
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Kotlin | Kotlin | fun middleThree(x: Int): Int? {
val s = Math.abs(x).toString()
return when {
s.length < 3 -> null // throw Exception("too short!")
s.length % 2 == 0 -> null // throw Exception("even number of digits")
else -> ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt()
}
}
fun main(args: Array<String>) {
println(middleThree(12345)) // 234
println(middleThree(1234)) // null
println(middleThree(1234567)) // 345
println(middleThree(123))// 123
println(middleThree(123555)) //null
} |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Racket | Racket | #lang racket
(define (miller-rabin-expmod base exp m)
(define (squaremod-with-check x)
(define (check-nontrivial-sqrt1 x square)
(if (and (= square 1)
(not (= x 1))
(not (= x (- m 1))))
0
square))
(check-nontrivial-sqrt1 x (remainder (expt x 2) m)))
(cond ((= exp 0) 1)
((even? exp) (squaremod-with-check
(miller-rabin-expmod base (/ exp 2) m)))
(else
(remainder (* base (miller-rabin-expmod base (- exp 1) m))
m))))
(define (miller-rabin-test n)
(define (try-it a)
(define (check-it x)
(and (not (= x 0)) (= x 1)))
(check-it (miller-rabin-expmod a (- n 1) n)))
(try-it (+ 1 (random (remainder (- n 1) 4294967087)))))
(define (fast-prime? n times)
(for/and ((i (in-range times)))
(miller-rabin-test n)))
(define (prime? n(times 100))
(fast-prime? n times))
(prime? 4547337172376300111955330758342147474062293202868155909489) ;-> outputs true
|
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Lua | Lua | function select (list)
if not list or #list == 0 then
return ""
end
local last, sel = #list
repeat
for i,option in ipairs(list) do
io.write(i, ". ", option, "\n")
end
io.write("Choose an item (1-", tostring(last), "): ")
sel = tonumber(string.match(io.read("*l"), "^%d+$"))
until type(sel) == "number" and sel >= 1 and sel <= last
return list[math.floor(sel)]
end
print("Nothing:", select {})
print()
print("You chose:", select {"fee fie", "huff and puff", "mirror mirror", "tick tock"}) |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #REXX | REXX | /*REXX program tests the MD5 procedure (below) as per a test suite from IETF RFC (1321).*/
@.1 = /*─────MD5 test suite [from above doc].*/
@.2 = 'a'
@.3 = 'abc'
@.4 = 'message digest'
@.5 = 'abcdefghijklmnopqrstuvwxyz'
@.6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
@.7 = 12345678901234567890123456789012345678901234567890123456789012345678901234567890
@.0 = 7 /* [↑] last value doesn't need quotes.*/
do m=1 for @.0; say /*process each of the seven messages. */
say ' in =' @.m /*display the in message. */
say 'out =' MD5(@.m) /* " " out " */
end /*m*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
MD5: procedure; parse arg !; numeric digits 20 /*insure there's enough decimal digits.*/
a= '67452301'x; b= "efcdab89"x; c= '98badcfe'x; d= "10325476"x
#= length(!) /*length in bytes of the input message.*/
L= #*8//512; if L<448 then plus= 448 - L /*is the length less than 448 ? */
if L>448 then plus= 960 - L /* " " " greater " " */
if L=448 then plus= 512 /* " " " equal to " */
/* [↓] a little of this, ··· */
$=! || "80"x || copies('0'x,plus%8-1)reverse(right(d2c(8*#), 4, '0'x)) || '00000000'x
/* [↑] ··· and a little of that.*/
do j=0 for length($) % 64 /*process the message (lots of steps).*/
a_= a; b_= b; c_= c; d_= d /*save the original values for later.*/
chunk= j * 64 /*calculate the size of the chunks. */
do k=1 for 16 /*process the message in chunks. */
!.k= reverse( substr($, chunk + 1 + 4*(k-1), 4) ) /*magic stuff.*/
end /*k*/ /*────step────*/
a = .p1( a, b, c, d, 0, 7, 3614090360) /*■■■■ 1 ■■■■*/
d = .p1( d, a, b, c, 1, 12, 3905402710) /*■■■■ 2 ■■■■*/
c = .p1( c, d, a, b, 2, 17, 606105819) /*■■■■ 3 ■■■■*/
b = .p1( b, c, d, a, 3, 22, 3250441966) /*■■■■ 4 ■■■■*/
a = .p1( a, b, c, d, 4, 7, 4118548399) /*■■■■ 5 ■■■■*/
d = .p1( d, a, b, c, 5, 12, 1200080426) /*■■■■ 6 ■■■■*/
c = .p1( c, d, a, b, 6, 17, 2821735955) /*■■■■ 7 ■■■■*/
b = .p1( b, c, d, a, 7, 22, 4249261313) /*■■■■ 8 ■■■■*/
a = .p1( a, b, c, d, 8, 7, 1770035416) /*■■■■ 9 ■■■■*/
d = .p1( d, a, b, c, 9, 12, 2336552879) /*■■■■ 10 ■■■■*/
c = .p1( c, d, a, b, 10, 17, 4294925233) /*■■■■ 11 ■■■■*/
b = .p1( b, c, d, a, 11, 22, 2304563134) /*■■■■ 12 ■■■■*/
a = .p1( a, b, c, d, 12, 7, 1804603682) /*■■■■ 13 ■■■■*/
d = .p1( d, a, b, c, 13, 12, 4254626195) /*■■■■ 14 ■■■■*/
c = .p1( c, d, a, b, 14, 17, 2792965006) /*■■■■ 15 ■■■■*/
b = .p1( b, c, d, a, 15, 22, 1236535329) /*■■■■ 16 ■■■■*/
a = .p2( a, b, c, d, 1, 5, 4129170786) /*■■■■ 17 ■■■■*/
d = .p2( d, a, b, c, 6, 9, 3225465664) /*■■■■ 18 ■■■■*/
c = .p2( c, d, a, b, 11, 14, 643717713) /*■■■■ 19 ■■■■*/
b = .p2( b, c, d, a, 0, 20, 3921069994) /*■■■■ 20 ■■■■*/
a = .p2( a, b, c, d, 5, 5, 3593408605) /*■■■■ 21 ■■■■*/
d = .p2( d, a, b, c, 10, 9, 38016083) /*■■■■ 22 ■■■■*/
c = .p2( c, d, a, b, 15, 14, 3634488961) /*■■■■ 23 ■■■■*/
b = .p2( b, c, d, a, 4, 20, 3889429448) /*■■■■ 24 ■■■■*/
a = .p2( a, b, c, d, 9, 5, 568446438) /*■■■■ 25 ■■■■*/
d = .p2( d, a, b, c, 14, 9, 3275163606) /*■■■■ 26 ■■■■*/
c = .p2( c, d, a, b, 3, 14, 4107603335) /*■■■■ 27 ■■■■*/
b = .p2( b, c, d, a, 8, 20, 1163531501) /*■■■■ 28 ■■■■*/
a = .p2( a, b, c, d, 13, 5, 2850285829) /*■■■■ 29 ■■■■*/
d = .p2( d, a, b, c, 2, 9, 4243563512) /*■■■■ 30 ■■■■*/
c = .p2( c, d, a, b, 7, 14, 1735328473) /*■■■■ 31 ■■■■*/
b = .p2( b, c, d, a, 12, 20, 2368359562) /*■■■■ 32 ■■■■*/
a = .p3( a, b, c, d, 5, 4, 4294588738) /*■■■■ 33 ■■■■*/
d = .p3( d, a, b, c, 8, 11, 2272392833) /*■■■■ 34 ■■■■*/
c = .p3( c, d, a, b, 11, 16, 1839030562) /*■■■■ 35 ■■■■*/
b = .p3( b, c, d, a, 14, 23, 4259657740) /*■■■■ 36 ■■■■*/
a = .p3( a, b, c, d, 1, 4, 2763975236) /*■■■■ 37 ■■■■*/
d = .p3( d, a, b, c, 4, 11, 1272893353) /*■■■■ 38 ■■■■*/
c = .p3( c, d, a, b, 7, 16, 4139469664) /*■■■■ 39 ■■■■*/
b = .p3( b, c, d, a, 10, 23, 3200236656) /*■■■■ 40 ■■■■*/
a = .p3( a, b, c, d, 13, 4, 681279174) /*■■■■ 41 ■■■■*/
d = .p3( d, a, b, c, 0, 11, 3936430074) /*■■■■ 42 ■■■■*/
c = .p3( c, d, a, b, 3, 16, 3572445317) /*■■■■ 43 ■■■■*/
b = .p3( b, c, d, a, 6, 23, 76029189) /*■■■■ 44 ■■■■*/
a = .p3( a, b, c, d, 9, 4, 3654602809) /*■■■■ 45 ■■■■*/
d = .p3( d, a, b, c, 12, 11, 3873151461) /*■■■■ 46 ■■■■*/
c = .p3( c, d, a, b, 15, 16, 530742520) /*■■■■ 47 ■■■■*/
b = .p3( b, c, d, a, 2, 23, 3299628645) /*■■■■ 48 ■■■■*/
a = .p4( a, b, c, d, 0, 6, 4096336452) /*■■■■ 49 ■■■■*/
d = .p4( d, a, b, c, 7, 10, 1126891415) /*■■■■ 50 ■■■■*/
c = .p4( c, d, a, b, 14, 15, 2878612391) /*■■■■ 51 ■■■■*/
b = .p4( b, c, d, a, 5, 21, 4237533241) /*■■■■ 52 ■■■■*/
a = .p4( a, b, c, d, 12, 6, 1700485571) /*■■■■ 53 ■■■■*/
d = .p4( d, a, b, c, 3, 10, 2399980690) /*■■■■ 54 ■■■■*/
c = .p4( c, d, a, b, 10, 15, 4293915773) /*■■■■ 55 ■■■■*/
b = .p4( b, c, d, a, 1, 21, 2240044497) /*■■■■ 56 ■■■■*/
a = .p4( a, b, c, d, 8, 6, 1873313359) /*■■■■ 57 ■■■■*/
d = .p4( d, a, b, c, 15, 10, 4264355552) /*■■■■ 58 ■■■■*/
c = .p4( c, d, a, b, 6, 15, 2734768916) /*■■■■ 59 ■■■■*/
b = .p4( b, c, d, a, 13, 21, 1309151649) /*■■■■ 60 ■■■■*/
a = .p4( a, b, c, d, 4, 6, 4149444226) /*■■■■ 61 ■■■■*/
d = .p4( d, a, b, c, 11, 10, 3174756917) /*■■■■ 62 ■■■■*/
c = .p4( c, d, a, b, 2, 15, 718787259) /*■■■■ 63 ■■■■*/
b = .p4( b, c, d, a, 9, 21, 3951481745) /*■■■■ 64 ■■■■*/
a = .a(a_, a); b=.a(b_, b); c=.a(c_, c); d=.a(d_, d)
end /*j*/
return .rx(a).rx(b).rx(c).rx(d) /*same as: .rx(a) || .rx(b) || ··· */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.a: return right( d2c( c2d( arg(1) ) + c2d( arg(2) ) ), 4, '0'x)
.h: return bitxor( bitxor( arg(1), arg(2) ), arg(3) )
.i: return bitxor( arg(2), bitor(arg(1), bitxor(arg(3), 'ffffffff'x) ) )
.f: return bitor( bitand(arg(1), arg(2)), bitand(bitxor(arg(1), 'ffffffff'x), arg(3) ) )
.g: return bitor( bitand(arg(1), arg(3)), bitand(arg(2), bitxor(arg(3), 'ffffffff'x) ) )
.rx: return c2x( reverse( arg(1) ) )
.Lr: procedure; parse arg _,#; if #==0 then return _ /*left bit rotate.*/
?=x2b(c2x(_)); return x2c( b2x( right(? || left(?, #), length(?) ) ) )
.p1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(_+c2d(w) + c2d(.f(x,y,z)) + c2d(!.n)),4,'0'x),m),x)
.p2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(_+c2d(w) + c2d(.g(x,y,z)) + c2d(!.n)),4,'0'x),m),x)
.p3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(_+c2d(w) + c2d(.h(x,y,z)) + c2d(!.n)),4,'0'x),m),x)
.p4: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n + 1
return .a(.Lr(right(d2c(c2d(w) + c2d(.i(x,y,z)) + c2d(!.n)+_),4,'0'x),m),x) |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Lambdatalk | Lambdatalk |
{def S 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0}
-> S
{def middle3digits
{lambda {:w}
{let { {:w {abs :w}}
{:l {W.length {abs :w}}}
} {if {= {% :l 2} 0}
then has an even number of digits
else {if {< :l 3}
then has not enough digits
else {W.get {- {/ :l 2} 1} :w}
{W.get {/ :l 2} :w}
{W.get {+ {/ :l 2} 1} :w} }}}}}
-> middle3digits
{table
{S.map {lambda {:i}
{tr {td {@ style="text-align:right;"}:i:}
{td {middle3digits :i}}}}
{S}} }
->
123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: has not enough digits
2: has not enough digits
-1: has not enough digits
-10: has an even number of digits
2002: has an even number of digits
-2002: has an even number of digits
0: has not enough digits
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Raku | Raku | # the expmod-function from: http://rosettacode.org/wiki/Modular_exponentiation
sub expmod(Int $a is copy, Int $b is copy, $n) {
my $c = 1;
repeat while $b div= 2 {
($c *= $a) %= $n if $b % 2;
($a *= $a) %= $n;
}
$c;
}
subset PrimeCandidate of Int where { $_ > 2 and $_ % 2 };
my Bool multi sub is_prime(Int $n, Int $k) { return False; }
my Bool multi sub is_prime(2, Int $k) { return True; }
my Bool multi sub is_prime(PrimeCandidate $n, Int $k) {
my Int $d = $n - 1;
my Int $s = 0;
while $d %% 2 {
$d div= 2;
$s++;
}
for (2 ..^ $n).pick($k) -> $a {
my $x = expmod($a, $d, $n);
# one could just write "next if $x == 1 | $n - 1"
# but this takes much more time in current rakudo/nom
next if $x == 1 or $x == $n - 1;
for 1 ..^ $s {
$x = $x ** 2 mod $n;
return False if $x == 1;
last if $x == $n - 1;
}
return False if $x !== $n - 1;
}
return True;
}
say (1..1000).grep({ is_prime($_, 10) }).join(", "); |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | textMenu[data_List] := Module[{choice},
If[Length@data == 0, Return@""];
While[!(IntegerQ@choice && Length@data >= choice > 0),
MapIndexed[Print[#2[[1]], ") ", #1]&, data];
choice = Input["Enter selection..."]
];
data[[choice]]
] |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #RPG | RPG | **FREE
Ctl-opt MAIN(Main);
Ctl-opt DFTACTGRP(*NO) ACTGRP(*NEW);
dcl-pr QDCXLATE EXTPGM('QDCXLATE');
dataLen packed(5 : 0) CONST;
data char(32767) options(*VARSIZE);
conversionTable char(10) CONST;
end-pr;
dcl-c MASK32 CONST(4294967295);
dcl-s SHIFT_AMTS int(3) dim(16) CTDATA PERRCD(16);
dcl-s MD5_TABLE_T int(20) dim(64) CTDATA PERRCD(4);
dcl-proc Main;
dcl-s inputData char(45);
dcl-s inputDataLen int(10) INZ(0);
dcl-s outputHash char(16);
dcl-s outputHashHex char(32);
DSPLY 'Input: ' '' inputData;
inputData = %trim(inputData);
inputDataLen = %len(%trim(inputData));
DSPLY ('Input=' + inputData);
DSPLY ('InputLen=' + %char(inputDataLen));
// Convert from EBCDIC to ASCII
if inputDataLen > 0;
QDCXLATE(inputDataLen : inputData : 'QTCPASC');
endif;
CalculateMD5(inputData : inputDataLen : outputHash);
// Convert to hex
ConvertToHex(outputHash : 16 : outputHashHex);
DSPLY ('MD5: ' + outputHashHex);
return;
end-proc;
dcl-proc CalculateMD5;
dcl-pi *N;
message char(65535) options(*VARSIZE) CONST;
messageLen int(10) value;
outputHash char(16);
end-pi;
dcl-s numBlocks int(10);
dcl-s padding char(72);
dcl-s a int(20) INZ(1732584193);
dcl-s b int(20) INZ(4023233417);
dcl-s c int(20) INZ(2562383102);
dcl-s d int(20) INZ(271733878);
dcl-s buffer int(20) dim(16) INZ(0);
dcl-s i int(10);
dcl-s j int(10);
dcl-s k int(10);
dcl-s multiplier int(20);
dcl-s index int(10);
dcl-s originalA int(20);
dcl-s originalB int(20);
dcl-s originalC int(20);
dcl-s originalD int(20);
dcl-s div16 int(10);
dcl-s f int(20);
dcl-s tempInt int(20);
dcl-s bufferIndex int(10);
dcl-ds byteToInt QUALIFIED;
n int(5) INZ(0);
c char(1) OVERLAY(n : 2);
end-ds;
numBlocks = (messageLen + 8) / 64 + 1;
MD5_FillPadding(messageLen : numBlocks : padding);
for i = 0 to numBlocks - 1;
index = i * 64;
// Read message as little-endian 32-bit words
for j = 1 to 16;
multiplier = 1;
for k = 1 to 4;
index += 1;
if index <= messageLen;
byteToInt.c = %subst(message : index : 1);
else;
byteToInt.c = %subst(padding : index - messageLen : 1);
endif;
buffer(j) += multiplier * byteToInt.n;
multiplier *= 256;
endfor;
endfor;
originalA = a;
originalB = b;
originalC = c;
originalD = d;
for j = 0 to 63;
div16 = j / 16;
select;
when div16 = 0;
f = %bitor(%bitand(b : c) : %bitand(%bitnot(b) : d));
bufferIndex = j;
when div16 = 1;
f = %bitor(%bitand(b : d) : %bitand(c : %bitnot(d)));
bufferIndex = %bitand(j * 5 + 1 : 15);
when div16 = 2;
f = %bitxor(b : %bitxor(c : d));
bufferIndex = %bitand(j * 3 + 5 : 15);
when div16 = 3;
f = %bitxor(c : %bitor(b : Mask32Bit(%bitnot(d))));
bufferIndex = %bitand(j * 7 : 15);
endsl;
tempInt = Mask32Bit(b + RotateLeft32Bit(a + f + buffer(bufferIndex + 1) + MD5_TABLE_T(j + 1) :
SHIFT_AMTS(div16 * 4 + %bitand(j : 3) + 1)));
a = d;
d = c;
c = b;
b = tempInt;
endfor;
a = Mask32Bit(a + originalA);
b = Mask32Bit(b + originalB);
c = Mask32Bit(c + originalC);
d = Mask32Bit(d + originalD);
endfor;
for i = 0 to 3;
if i = 0;
tempInt = a;
elseif i = 1;
tempInt = b;
elseif i = 2;
tempInt = c;
else;
tempInt = d;
endif;
for j = 0 to 3;
byteToInt.n = %bitand(tempInt : 255);
%subst(outputHash : i * 4 + j + 1 : 1) = byteToInt.c;
tempInt /= 256;
endfor;
endfor;
return;
end-proc;
dcl-proc MD5_FillPadding;
dcl-pi *N;
messageLen int(10);
numBlocks int(10);
padding char(72);
end-pi;
dcl-s totalLen int(10);
dcl-s paddingSize int(10);
dcl-ds *N;
messageLenBits int(20);
mlb_bytes char(8) OVERLAY(messageLenBits);
end-ds;
dcl-s i int(10);
%subst(padding : 1 : 1) = X'80';
totalLen = numBlocks * 64;
paddingSize = totalLen - messageLen; // 9 to 72
messageLenBits = messageLen;
messageLenBits *= 8;
for i = 1 to 8;
%subst(padding : paddingSize - i + 1 : 1) = %subst(mlb_bytes : i : 1);
endfor;
for i = 2 to paddingSize - 8;
%subst(padding : i : 1) = X'00';
endfor;
return;
end-proc;
dcl-proc RotateLeft32Bit;
dcl-pi *N int(20);
n int(20) value;
amount int(3) value;
end-pi;
dcl-s i int(3);
n = Mask32Bit(n);
for i = 1 to amount;
n *= 2;
if n >= 4294967296;
n -= MASK32;
endif;
endfor;
return n;
end-proc;
dcl-proc Mask32Bit;
dcl-pi *N int(20);
n int(20) value;
end-pi;
return %bitand(n : MASK32);
end-proc;
dcl-proc ConvertToHex;
dcl-pi *N;
inputData char(32767) options(*VARSIZE) CONST;
inputDataLen int(10) value;
outputData char(65534) options(*VARSIZE);
end-pi;
dcl-c HEX_CHARS CONST('0123456789ABCDEF');
dcl-s i int(10);
dcl-s outputOffset int(10) INZ(1);
dcl-ds dataStruct QUALIFIED;
numField int(5) INZ(0);
// IBM i is big-endian
charField char(1) OVERLAY(numField : 2);
end-ds;
for i = 1 to inputDataLen;
dataStruct.charField = %BitAnd(%subst(inputData : i : 1) : X'F0');
dataStruct.numField /= 16;
%subst(outputData : outputOffset : 1) = %subst(HEX_CHARS : dataStruct.numField + 1 : 1);
outputOffset += 1;
dataStruct.charField = %BitAnd(%subst(inputData : i : 1) : X'0F');
%subst(outputData : outputOffset : 1) = %subst(HEX_CHARS : dataStruct.numField + 1 : 1);
outputOffset += 1;
endfor;
return;
end-proc;
**CTDATA SHIFT_AMTS
7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21
**CTDATA MD5_TABLE_T
3614090360 3905402710 606105819 3250441966
4118548399 1200080426 2821735955 4249261313
1770035416 2336552879 4294925233 2304563134
1804603682 4254626195 2792965006 1236535329
4129170786 3225465664 643717713 3921069994
3593408605 38016083 3634488961 3889429448
568446438 3275163606 4107603335 1163531501
2850285829 4243563512 1735328473 2368359562
4294588738 2272392833 1839030562 4259657740
2763975236 1272893353 4139469664 3200236656
681279174 3936430074 3572445317 76029189
3654602809 3873151461 530742520 3299628645
4096336452 1126891415 2878612391 4237533241
1700485571 2399980690 4293915773 2240044497
1873313359 4264355552 2734768916 1309151649
4149444226 3174756917 718787259 3951481745 |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Lasso | Lasso | define middlethree(value::integer) => {
local(
pos_value = math_abs(#value),
stringvalue = #pos_value -> asstring,
intlength = #stringvalue -> size,
middle = integer((#intlength + 1) / 2),
prefix = string(#value) -> padleading(15)& + ': '
)
#intlength < 3 ? return #prefix + 'Error: too few digits'
not(#intlength % 2) ? return #prefix + 'Error: even number of digits'
return #prefix + #stringvalue -> sub(#middle -1, 3)
}
'<pre>'
with number in array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) do {^
middlethree(#number)
'<br />'
^}
'</pre>' |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #REXX | REXX | /*REXX program puts the Miller─Rabin primality test through its paces. */
parse arg limit times seed . /*obtain optional arguments from the CL*/
if limit=='' | limit=="," then limit= 1000 /*Not specified? Then use the default.*/
if times=='' | times=="," then times= 10 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*If seed specified, use it for RANDOM.*/
numeric digits max(200, 2*limit) /*we're dealing with some ginormous #s.*/
tell= times<0 /*display primes only if times is neg.*/
times= abs(times); w= length(times) /*use absolute value of TIMES; get len.*/
call genP limit /*suspenders now, use a belt later ··· */
@MR= 'Miller─Rabin primality test' /*define a character literal for SAY. */
say "There are" # 'primes ≤' limit /*might as well display some stuff. */
say /* [↓] (skipping unity); show sep line*/
do a=2 to times; say copies('─', 89) /*(skipping unity) do range of TIMEs.*/
p= 0 /*the counter of primes for this pass. */
do z=1 for limit /*now, let's get busy and crank primes.*/
if \M_Rt(z, a) then iterate /*Not prime? Then try another number.*/
p= p + 1 /*well, we found another one, by gum! */
if tell then say z 'is prime according to' @MR "with K="a
if !.z then iterate
say '[K='a"] " z "isn't prime !" /*oopsy─doopsy and/or whoopsy─daisy !*/
end /*z*/
say ' for 1──►'limit", K="right(a,w)',' @MR "found" p 'primes {out of' #"}."
end /*a*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: parse arg high; @.=0; @.1=2; @.2=3; !.=@.; !.2=1; !.3=1; #=2
do j=@.#+2 by 2 to high /*just examine odd integers from here. */
do k=2 while k*k<=j; if j//@.k==0 then iterate j; end /*k*/
#= # + 1; @.#= j; !.j= 1 /*bump prime counter; add prime to the */
end /*j*/; return /*@. array; define a prime in !. array.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
M_Rt: procedure; parse arg n,k; d= n-1; nL=d /*Miller─Rabin: A.K.A. Rabin─Miller.*/
if n==2 then return 1 /*special case of (the) even prime. */
if n<2 | n//2==0 then return 0 /*check for too low, or an even number.*/
do s=-1 while d//2==0; d= d % 2 /*keep halving until a zero remainder.*/
end /*while*/
do k; ?= random(2, nL) /* [↓] perform the DO loop K times.*/
x= ?**d // n /*X can get real gihugeic really fast.*/
if x==1 | x==nL then iterate /*First or penultimate? Try another pow*/
do s; x= x**2 // n /*compute new X ≡ X² modulus N. */
if x==1 then return 0 /*if unity, it's definitely not prime.*/
if x==nL then leave /*if N-1, then it could be prime. */
end /*r*/ /* [↑] // is REXX's division remainder*/
if x\==nL then return 0 /*nope, it ain't prime nohows, noway. */
end /*k*/ /*maybe it's prime, maybe it ain't ··· */
return 1 /*coulda/woulda/shoulda be prime; yup.*/ |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #MATLAB | MATLAB | function sucess = menu(list)
if numel(list) == 0
sucess = '';
return
end
while(true)
disp('Please select one of these options:');
for i = (1:numel(list))
disp([num2str(i) ') ' list{i}]);
end
disp([num2str(numel(list)+1) ') exit']);
try
key = input(':: ');
if key == numel(list)+1
break
elseif (key > numel(list)) || (key < 0)
continue
else
disp(['-> ' list{key}]);
end
catch
continue
end
end
sucess = true;
end
|
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Rust | Rust |
#![allow(non_snake_case)] // RFC 1321 uses many capitalized variables
use std::mem;
fn md5(mut msg: Vec<u8>) -> (u32, u32, u32, u32) {
let bitcount = msg.len().saturating_mul(8) as u64;
// Step 1: Append Padding Bits
msg.push(0b10000000);
while (msg.len() * 8) % 512 != 448 {
msg.push(0u8);
}
// Step 2. Append Length (64 bit integer)
msg.extend(&[
bitcount as u8,
(bitcount >> 8) as u8,
(bitcount >> 16) as u8,
(bitcount >> 24) as u8,
(bitcount >> 32) as u8,
(bitcount >> 40) as u8,
(bitcount >> 48) as u8,
(bitcount >> 56) as u8,
]);
// Step 3. Initialize MD Buffer
/*A four-word buffer (A,B,C,D) is used to compute the message digest.
Here each of A, B, C, D is a 32-bit register.*/
let mut A = 0x67452301u32;
let mut B = 0xefcdab89u32;
let mut C = 0x98badcfeu32;
let mut D = 0x10325476u32;
// Step 4. Process Message in 16-Word Blocks
/* We first define four auxiliary functions */
let F = |X: u32, Y: u32, Z: u32| -> u32 { X & Y | !X & Z };
let G = |X: u32, Y: u32, Z: u32| -> u32 { X & Z | Y & !Z };
let H = |X: u32, Y: u32, Z: u32| -> u32 { X ^ Y ^ Z };
let I = |X: u32, Y: u32, Z: u32| -> u32 { Y ^ (X | !Z) };
/* This step uses a 64-element table T[1 ... 64] constructed from the sine function. */
let T = [
0x00000000, // enable use as a 1-indexed table
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
0xeb86d391,
];
/* Process each 16-word block. (since 1 word is 4 bytes, then 16 words is 64 bytes) */
for mut block in msg.chunks_exact_mut(64) {
/* Copy block into X. */
#![allow(unused_mut)]
let mut X = unsafe { mem::transmute::<&mut [u8], &mut [u32]>(&mut block) };
#[cfg(target_endian = "big")]
for j in 0..16 {
X[j] = X[j].swap_bytes();
}
/* Save Registers A,B,C,D */
let AA = A;
let BB = B;
let CC = C;
let DD = D;
/* Round 1. Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op1 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(F($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
/* Do the following 16 operations. */
op1!(A, B, C, D, 0, 7, 1);
op1!(D, A, B, C, 1, 12, 2);
op1!(C, D, A, B, 2, 17, 3);
op1!(B, C, D, A, 3, 22, 4);
op1!(A, B, C, D, 4, 7, 5);
op1!(D, A, B, C, 5, 12, 6);
op1!(C, D, A, B, 6, 17, 7);
op1!(B, C, D, A, 7, 22, 8);
op1!(A, B, C, D, 8, 7, 9);
op1!(D, A, B, C, 9, 12, 10);
op1!(C, D, A, B, 10, 17, 11);
op1!(B, C, D, A, 11, 22, 12);
op1!(A, B, C, D, 12, 7, 13);
op1!(D, A, B, C, 13, 12, 14);
op1!(C, D, A, B, 14, 17, 15);
op1!(B, C, D, A, 15, 22, 16);
/* Round 2. Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op2 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(G($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
/* Do the following 16 operations. */
op2!(A, B, C, D, 1, 5, 17);
op2!(D, A, B, C, 6, 9, 18);
op2!(C, D, A, B, 11, 14, 19);
op2!(B, C, D, A, 0, 20, 20);
op2!(A, B, C, D, 5, 5, 21);
op2!(D, A, B, C, 10, 9, 22);
op2!(C, D, A, B, 15, 14, 23);
op2!(B, C, D, A, 4, 20, 24);
op2!(A, B, C, D, 9, 5, 25);
op2!(D, A, B, C, 14, 9, 26);
op2!(C, D, A, B, 3, 14, 27);
op2!(B, C, D, A, 8, 20, 28);
op2!(A, B, C, D, 13, 5, 29);
op2!(D, A, B, C, 2, 9, 30);
op2!(C, D, A, B, 7, 14, 31);
op2!(B, C, D, A, 12, 20, 32);
/* Round 3. Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op3 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(H($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
/* Do the following 16 operations. */
op3!(A, B, C, D, 5, 4, 33);
op3!(D, A, B, C, 8, 11, 34);
op3!(C, D, A, B, 11, 16, 35);
op3!(B, C, D, A, 14, 23, 36);
op3!(A, B, C, D, 1, 4, 37);
op3!(D, A, B, C, 4, 11, 38);
op3!(C, D, A, B, 7, 16, 39);
op3!(B, C, D, A, 10, 23, 40);
op3!(A, B, C, D, 13, 4, 41);
op3!(D, A, B, C, 0, 11, 42);
op3!(C, D, A, B, 3, 16, 43);
op3!(B, C, D, A, 6, 23, 44);
op3!(A, B, C, D, 9, 4, 45);
op3!(D, A, B, C, 12, 11, 46);
op3!(C, D, A, B, 15, 16, 47);
op3!(B, C, D, A, 2, 23, 48);
/* Round 4. Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
macro_rules! op4 {
($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {
$a = $b.wrapping_add(
($a.wrapping_add(I($b, $c, $d))
.wrapping_add(X[$k])
.wrapping_add(T[$i]))
.rotate_left($s),
)
};
}
/* Do the following 16 operations. */
op4!(A, B, C, D, 0, 6, 49);
op4!(D, A, B, C, 7, 10, 50);
op4!(C, D, A, B, 14, 15, 51);
op4!(B, C, D, A, 5, 21, 52);
op4!(A, B, C, D, 12, 6, 53);
op4!(D, A, B, C, 3, 10, 54);
op4!(C, D, A, B, 10, 15, 55);
op4!(B, C, D, A, 1, 21, 56);
op4!(A, B, C, D, 8, 6, 57);
op4!(D, A, B, C, 15, 10, 58);
op4!(C, D, A, B, 6, 15, 59);
op4!(B, C, D, A, 13, 21, 60);
op4!(A, B, C, D, 4, 6, 61);
op4!(D, A, B, C, 11, 10, 62);
op4!(C, D, A, B, 2, 15, 63);
op4!(B, C, D, A, 9, 21, 64);
/* . . . increment each of the four registers by the value
it had before this block was started.) */
A = A.wrapping_add(AA);
B = B.wrapping_add(BB);
C = C.wrapping_add(CC);
D = D.wrapping_add(DD);
}
(
A.swap_bytes(),
B.swap_bytes(),
C.swap_bytes(),
D.swap_bytes(),
)
}
fn md5_utf8(smsg: &str) -> String {
let mut msg = vec![0u8; 0];
msg.extend(smsg.as_bytes());
let (A, B, C, D) = md5(msg);
format!("{:08x}{:08x}{:08x}{:08x}", A, B, C, D)
}
fn main() {
assert!(md5_utf8("") == "d41d8cd98f00b204e9800998ecf8427e");
assert!(md5_utf8("a") == "0cc175b9c0f1b6a831c399e269772661");
assert!(md5_utf8("abc") == "900150983cd24fb0d6963f7d28e17f72");
assert!(md5_utf8("message digest") == "f96b697d7cb7938d525a2f31aaf161d0");
assert!(md5_utf8("abcdefghijklmnopqrstuvwxyz") == "c3fcd3d76192e4007dfb496cca67e13b");
assert!(md5_utf8("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") == "d174ab98d277d9f5a5611c2c9f419d9f");
assert!(md5_utf8("12345678901234567890123456789012345678901234567890123456789012345678901234567890") == "57edf4a22be3c955ac49da2e2107b67a");
}
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Logo | Logo | to middle3digits :n
if [less? :n 0] [make "n minus :n]
local "len make "len count :n
if [less? :len 3] [(throw "error [Number must have at least 3 digits])]
if [equal? 0 modulo :len 2] [(throw "error [Number must have odd number of digits])]
while [greater? count :n 3] [
make "n butlast butfirst :n
]
output :n
end
foreach [123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0] [
type sentence (word ? ": char 9) runresult [if [less? count ? 7] [char 9]]
make "mid runresult [catch "error [middle3digits ?]]
print ifelse [empty? :mid] [item 2 error] [:mid]
]
bye |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Ring | Ring |
# Project : Miller–Rabin primality test
see "Input a number: " give n
see "Input test: " give k
test = millerrabin(n,k)
if test = 0
see "Probably Prime" + nl
else
see "Composite" + nl
ok
func millerrabin(n, k)
if n = 2
millerRabin = 0
return millerRabin
ok
if n % 2 = 0 or n < 2
millerRabin = 1
return millerRabin
ok
d = n - 1
s = 0
while d % 2 = 0
d = d / 2
s = s + 1
end
while k > 0
k = k - 1
base = 2 + floor((random(10)/10)*(n-3))
x = pow(base, d) % n
if x != 1 and x != n-1
for r=1 to s-1
x = (x * x) % n
if x = 1
millerRabin = 1
return millerRabin
ok
if x = n-1
exit
ok
next
if x != n-1
millerRabin = 1
return millerRabin
ok
ok
end
|
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #min | min | (
:prompt =list
(list bool)
(list (' dup append) map prompt choose)
("") if
) :menu
("fee fie" "huff and puff" "mirror mirror" "tick tock")
"Enter an option" menu
"You chose: " print! puts! |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Modula-2 | Modula-2 | MODULE Menu;
FROM InOut IMPORT WriteString, WriteCard, WriteLn, ReadCard;
CONST StringLength = 100;
MenuSize = 4;
TYPE String = ARRAY[0..StringLength-1] OF CHAR;
VAR menu : ARRAY[0..MenuSize] OF String;
selection, index : CARDINAL;
BEGIN
menu[1] := "fee fie";
menu[2] := "huff and puff";
menu[3] := "mirror mirror";
menu[4] := "tick tock";
FOR index := 1 TO HIGH(menu) DO
WriteString("[");
WriteCard( index,1);
WriteString( "] ");
WriteString( menu[index]);
WriteLn;
END;(*of FOR*)
WriteString("Choose what you want : ");
ReadCard(selection);
IF (selection <= HIGH(menu)) AND (selection > 0) THEN
WriteString("You have chosen: ");
WriteString( menu[selection]);
WriteLn;
ELSE
WriteString("Selection is out of range!");
WriteLn;
END (*of IF*)
END Menu. |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Scala | Scala | object MD5 extends App {
def hash(s: String) = {
def b = s.getBytes("UTF-8")
def m = java.security.MessageDigest.getInstance("MD5").digest(b)
BigInt(1, m).toString(16).reverse.padTo(32, "0").reverse.mkString
}
assert("d41d8cd98f00b204e9800998ecf8427e" == hash(""))
assert("0000045c5e2b3911eb937d9d8c574f09" == hash("iwrupvqb346386"))
assert("0cc175b9c0f1b6a831c399e269772661" == hash("a"))
assert("900150983cd24fb0d6963f7d28e17f72" == hash("abc"))
assert("f96b697d7cb7938d525a2f31aaf161d0" == hash("message digest"))
assert("c3fcd3d76192e4007dfb496cca67e13b" == hash("abcdefghijklmnopqrstuvwxyz"))
assert("d174ab98d277d9f5a5611c2c9f419d9f" == hash("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
assert("57edf4a22be3c955ac49da2e2107b67a" == hash("12345678901234567890123456789012345678901234567890123456789012345678901234567890"))
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Lua | Lua | function middle_three(n)
if n < 0 then
n = -n
end
n = tostring(n)
if #n % 2 == 0 then
return "Error: the number of digits is even."
elseif #n < 3 then
return "Error: the number has less than 3 digits."
end
local l = math.floor(#n/2)
return n:sub(l, l+2)
end
-- test
do
local t = {123, 12345, 1234567, 987654321,
10001, -10001, -123, -100, 100, -12345, 1,
2, -1, -10, 2002, -2002, 0}
for _,n in pairs(t) do
print(n, middle_three(n))
end
end |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Ruby | Ruby | def miller_rabin_prime?(n, g)
d = n - 1
s = 0
while d % 2 == 0
d /= 2
s += 1
end
g.times do
a = 2 + rand(n - 4)
x = a.pow(d, n) # x = (a**d) % n
next if x == 1 || x == n - 1
for r in (1..s - 1)
x = x.pow(2, n) # x = (x**2) % n
return false if x == 1
break if x == n - 1
end
return false if x != n - 1
end
true # probably
end
p primes = (3..1000).step(2).find_all {|i| miller_rabin_prime?(i,10)} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #MUMPS | MUMPS | MENU(STRINGS,SEP)
;http://rosettacode.org/wiki/Menu
NEW I,A,MAX
;I is a loop variable
;A is the string read in from the user
;MAX is the number of substrings in the STRINGS list
;SET STRINGS="fee fie^huff and puff^mirror mirror^tick tock"
SET MAX=$LENGTH(STRINGS,SEP)
QUIT:MAX=0 ""
WRITEMENU
FOR I=1:1:MAX WRITE I,": ",$PIECE(STRINGS,SEP,I),!
READ:30 !,"Choose a string by its index: ",A,!
IF (A<1)!(A>MAX)!(A\1'=A) GOTO WRITEMENU
KILL I,MAX
QUIT $PIECE(STRINGS,SEP,A) |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Nanoquery | Nanoquery | def _menu($items)
for ($i = 0) ($i < len($items)) ($i = $i + 1)
println " " + $i + ") " + $items[$i]
end
end
def _ok($reply, $itemcount)
try
$n = int($reply)
return (($n >= 0) && ($n < $itemcount))
catch
return $false
end
end
def selector($items, $pmt)
// Prompt to select an item from the items
if (len($items) = 0)
return ""
end
$reply = -1
$itemcount = len($items)
while !_ok($reply, $itemcount)
_menu($items)
println $pmt
$reply = int(input())
end
return $items[$reply]
end
$items = list()
append $items "fee fie" "huff and puff" "mirror mirror" "tick tock"
$item = selector($items, "Which is from the three pigs: ")
println "You chose: " + $item |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bytedata.s7i";
include "bin32.s7i";
include "float.s7i";
include "math.s7i";
# Use binary integer part of the sines of integers (Radians) as constants:
const func array integer: createMd5Table is func
result
var array integer: k is 64 times 0;
local
var integer: index is 0;
begin
for index range 1 to 64 do
k[index] := trunc(abs(sin(flt(index))) * 2.0 ** 32);
end for;
end func;
const func string: md5 (in var string: message) is func
result
var string: digest is "";
local
# Specify the per-round shift amounts
const array integer: shiftAmount is [] (
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21);
const array integer: k is createMd5Table;
var integer: length is 0;
var integer: chunkIndex is 0;
var integer: index is 0;
var array bin32: m is 16 times bin32.value;
var integer: a0 is 16#67452301; # a
var integer: b0 is 16#efcdab89; # b
var integer: c0 is 16#98badcfe; # c
var integer: d0 is 16#10325476; # d
var bin32: a is bin32(0);
var bin32: b is bin32(0);
var bin32: c is bin32(0);
var bin32: d is bin32(0);
var bin32: f is bin32(0);
var integer: g is 0;
var bin32: temp is bin32(0);
begin
length := length(message);
# Append the bit '1' to the message.
message &:= '\16#80;';
# Append '0' bits, so that the resulting bit length is congruent to 448 (mod 512).
message &:= "\0;" mult 63 - (length + 8) mod 64;
# Append length of message (before pre-processing), in bits, as 64-bit little-endian integer.
message &:= int64AsEightBytesLe(8 * length);
# Process the message in successive 512-bit chunks:
for chunkIndex range 1 to length(message) step 64 do
# Break chunk into sixteen 32-bit little-endian words.
for index range 1 to 16 do
m[index] := bin32(bytes2Int(message[chunkIndex + 4 * pred(index) len 4], UNSIGNED, LE));
end for;
a := bin32(a0 mod 16#100000000);
b := bin32(b0 mod 16#100000000);
c := bin32(c0 mod 16#100000000);
d := bin32(d0 mod 16#100000000);
for index range 1 to 64 do
if index <= 16 then
f := d >< (b & (c >< d));
g := index;
elsif index <= 32 then
f := c >< (d & (b >< c));
g := (5 * index - 4) mod 16 + 1;
elsif index <= 48 then
f := b >< c >< d;
g := (3 * index + 2) mod 16 + 1;
else
f := c >< (b | (bin32(16#ffffffff) >< d));
g := (7 * pred(index)) mod 16 + 1;
end if;
temp := d;
d := c;
c := b;
b := bin32((ord(b) +
ord(rotLeft(bin32((ord(a) + ord(f) + k[index] + ord(m[g])) mod 16#100000000),
shiftAmount[index]))) mod 16#100000000);
a := temp;
end for;
# Add this chunk's hash to result so far:
a0 +:= ord(a);
b0 +:= ord(b);
c0 +:= ord(c);
d0 +:= ord(d);
end for;
# Produce the final hash value:
digest := int32AsFourBytesLe(a0) &
int32AsFourBytesLe(b0) &
int32AsFourBytesLe(c0) &
int32AsFourBytesLe(d0);
end func;
const func boolean: checkMd5 (in string: message, in string: hexMd5) is
return hex(md5(message)) = hexMd5;
const proc: main is func
begin
if checkMd5("", "d41d8cd98f00b204e9800998ecf8427e") and
checkMd5("a", "0cc175b9c0f1b6a831c399e269772661") and
checkMd5("abc", "900150983cd24fb0d6963f7d28e17f72") and
checkMd5("message digest", "f96b697d7cb7938d525a2f31aaf161d0") and
checkMd5("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b") and
checkMd5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f") and
checkMd5("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a") then
writeln("md5 is computed correct");
else
writeln("There is an error in the md5 function");
end if;
end func; |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Maple | Maple | middleDigits := proc(n)
local nList, start;
nList := [seq(parse(i), i in convert (abs(n), string))];
if numelems(nList) < 3 then
printf ("%9a: Error: Not enough digits.", n);
elif numelems(nList) mod 2 = 0 then
printf ("%9a: Error: Even number of digits.", n);
else
start := (numelems(nList)-1)/2;
printf("%9a: %a%a%a", n, op(nList[start..start+2]));
end if;
end proc:
a := [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]:
for i in a do
middleDigits(i);
printf("\n");
end do; |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Run_BASIC | Run BASIC | input "Input a number:";n
input "Input test:";k
test = millerRabin(n,k)
if test = 0 then
print "Probably Prime"
else
print "Composite"
end if
wait
' ----------------------------------------
' Returns
' Composite = 1
' Probably Prime = 0
' ----------------------------------------
FUNCTION millerRabin(n, k)
if n = 2 then
millerRabin = 0 'probablyPrime
goto [funEnd]
end if
if n mod 2 = 0 or n < 2 then
millerRabin = 1 'composite
goto [funEnd]
end if
d = n - 1
while d mod 2 = 0
d = d / 2
s = s + 1
wend
while k > 0
k = k - 1
base = 2 + int(rnd(1)*(n-3))
x = (base^d) mod n
if x <> 1 and x <> n-1 then
for r=1 To s-1
x =(x * x) mod n
if x=1 then
millerRabin = 1 ' composite
goto [funEnd]
end if
if x = n-1 then exit for
next r
if x<>n-1 then
millerRabin = 1 ' composite
goto [funEnd]
end if
end if
wend
[funEnd]
END FUNCTION |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Nim | Nim | import strutils, rdstdin
proc menu(xs: openArray[string]) =
for i, x in xs: echo " ", i, ") ", x
proc ok(reply: string; count: Positive): bool =
try:
let n = parseInt(reply)
return 0 <= n and n < count
except: return false
proc selector(xs: openArray[string]; prompt: string): string =
if xs.len == 0: return ""
var reply = "-1"
while not ok(reply, xs.len):
menu(xs)
reply = readLineFromStdin(prompt).strip()
return xs[parseInt(reply)]
const xs = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
let item = selector(xs, "Which is from the three pigs: ")
echo "You chose: ", item |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Sidef | Sidef | class MD5(String msg) {
method init {
msg = msg.bytes
}
const FGHI = [
{|a,b,c| (a & b) | (~a & c) },
{|a,b,c| (a & c) | (b & ~c) },
{|a,b,c| (a ^ b ^ c) },
{|a,b,c| (b ^ (a | ~c)) },
]
const S = [
[7, 12, 17, 22] * 4,
[5, 9, 14, 20] * 4,
[4, 11, 16, 23] * 4,
[6, 10, 15, 21] * 4,
].flat
const T = 64.of {|i| floor(abs(sin(i+1)) * 1<<32) }
const K = [
^16 -> map {|n| n },
^16 -> map {|n| (5*n + 1) % 16 },
^16 -> map {|n| (3*n + 5) % 16 },
^16 -> map {|n| (7*n ) % 16 },
].flat
func radix(Number b, Array a) {
^a -> sum {|i| b**i * a[i] }
}
func little_endian(Number w, Number n, Array v) {
var step1 = (^n »*» w)
var step2 = (v ~X>> step1)
step2 »%» (1 << w)
}
func block(Number a, Number b) { (a + b) & 0xffffffff }
func srble(Number a, Number n) { (a << n) & 0xffffffff | (a >> (32-n)) }
func md5_pad(msg) {
var bits = 8*msg.len
var padded = [msg..., 128, [0] * (-(floor(bits / 8) + 1 + 8) % 64)].flat
gather {
padded.each_slice(4, {|*a|
take(radix(256, a))
})
take(little_endian(32, 2, [bits]))
}.flat
}
func md5_block(Array H, Array X) {
var (A, B, C, D) = H...
for i in ^64 {
(A, B, C, D) = (D,
block(B, srble(
block(
block(
block(A, FGHI[floor(i / 16)](B, C, D)), T[i]
), X[K[i]]
), S[i])
), B, C)
}
for k,v in ([A, B, C, D].kv) {
H[k] = block(H[k], v)
}
return H
}
method md5_hex {
self.md5.map {|n| '%02x' % n }.join
}
method md5 {
var M = md5_pad(msg)
var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
for i in (range(0, M.end, 16)) {
md5_block(H, M.ft(i, i+15))
}
little_endian(8, 4, H)
}
}
var tests = [
['d41d8cd98f00b204e9800998ecf8427e', ''],
['0cc175b9c0f1b6a831c399e269772661', 'a'],
['900150983cd24fb0d6963f7d28e17f72', 'abc'],
['f96b697d7cb7938d525a2f31aaf161d0', 'message digest'],
['c3fcd3d76192e4007dfb496cca67e13b', 'abcdefghijklmnopqrstuvwxyz'],
['d174ab98d277d9f5a5611c2c9f419d9f', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'],
['57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'],
]
for md5,msg in tests {
var hash = MD5(msg).md5_hex
say "#{hash} : #{msg}"
if (hash != md5) {
say "\tHowever, that is incorrect (expected: #{md5})"
}
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | middleThree[n_Integer] :=
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
If[len < 3 || EvenQ[len], "number digits odd or less than 3",
len = Ceiling[len/2];
StringJoin @@ (ToString /@ digits[[len - 1 ;; len + 1]])]]
testData = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
Column[middleThree /@ testData] |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Rust | Rust | /* Add these lines to the [dependencies] section of your Cargo.toml file:
num = "0.2.0"
rand = "0.6.5"
*/
use num::bigint::BigInt;
use num::bigint::ToBigInt;
// The modular_exponentiation() function takes three identical types
// (which get cast to BigInt), and returns a BigInt:
fn modular_exponentiation<T: ToBigInt>(n: &T, e: &T, m: &T) -> BigInt {
// Convert n, e, and m to BigInt:
let n = n.to_bigint().unwrap();
let e = e.to_bigint().unwrap();
let m = m.to_bigint().unwrap();
// Sanity check: Verify that the exponent is not negative:
assert!(e >= Zero::zero());
use num::traits::{Zero, One};
// As most modular exponentiations do, return 1 if the exponent is 0:
if e == Zero::zero() {
return One::one()
}
// Now do the modular exponentiation algorithm:
let mut result: BigInt = One::one();
let mut base = n % &m;
let mut exp = e;
loop { // Loop until we can return our result.
if &exp % 2 == One::one() {
result *= &base;
result %= &m;
}
if exp == One::one() {
return result
}
exp /= 2;
base *= base.clone();
base %= &m;
}
}
// is_prime() checks the passed-in number against many known small primes.
// If that doesn't determine if the number is prime or not, then the number
// will be passed to the is_rabin_miller_prime() function:
fn is_prime<T: ToBigInt>(n: &T) -> bool {
let n = n.to_bigint().unwrap();
if n.clone() < 2.to_bigint().unwrap() {
return false
}
let small_primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
991, 997, 1009, 1013];
use num::traits::Zero; // for Zero::zero()
// Check to see if our number is a small prime (which means it's prime),
// or a multiple of a small prime (which means it's not prime):
for sp in small_primes {
let sp = sp.to_bigint().unwrap();
if n.clone() == sp {
return true
} else if n.clone() % sp == Zero::zero() {
return false
}
}
is_rabin_miller_prime(&n, None)
}
// Note: "use bigint::RandBigInt;" (which is needed for gen_bigint_range())
// fails to work in the Rust playground ( https://play.rust-lang.org ).
// Therefore, I'll create my own here:
fn get_random_bigint(low: &BigInt, high: &BigInt) -> BigInt {
if low == high { // base case
return low.clone()
}
let middle = (low.clone() + high) / 2.to_bigint().unwrap();
let go_low: bool = rand::random();
if go_low {
return get_random_bigint(low, &middle)
} else {
return get_random_bigint(&middle, high)
}
}
// k is the number of times for testing (pass in None to use 5 (the default)).
fn is_rabin_miller_prime<T: ToBigInt>(n: &T, k: Option<usize>) -> bool {
let n = n.to_bigint().unwrap();
let k = k.unwrap_or(10); // number of times for testing (defaults to 10)
use num::traits::{Zero, One}; // for Zero::zero() and One::one()
let zero: BigInt = Zero::zero();
let one: BigInt = One::one();
let two: BigInt = 2.to_bigint().unwrap();
// The call to is_prime() should have already checked this,
// but check for two, less than two, and multiples of two:
if n <= one {
return false
} else if n == two {
return true // 2 is prime
} else if n.clone() % &two == Zero::zero() {
return false // even number (that's not 2) is not prime
}
let mut t: BigInt = zero.clone();
let n_minus_one: BigInt = n.clone() - &one;
let mut s = n_minus_one.clone();
while &s % &two == one {
s /= &two;
t += &one;
}
// Try k times to test if our number is non-prime:
'outer: for _ in 0..k {
let a = get_random_bigint(&two, &n_minus_one);
let mut v = modular_exponentiation(&a, &s, &n);
if v == one {
continue 'outer;
}
let mut i: BigInt = zero.clone();
'inner: while &i < &t {
v = (v.clone() * &v) % &n;
if &v == &n_minus_one {
continue 'outer;
}
i += &one;
}
return false;
}
// If we get here, then we have a degree of certainty
// that n really is a prime number, so return true:
true
} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #OCaml | OCaml |
let select ?(prompt="Choice? ") = function
| [] -> ""
| choices ->
let rec menu () =
List.iteri (Printf.printf "%d: %s\n") choices;
print_string prompt;
try List.nth choices (read_int ())
with _ -> menu ()
in menu ()
|
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Swift | Swift |
import Foundation
public class MD5 {
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let K: [UInt32] = (0 ..< 64).map { UInt32(0x100000000 * abs(sin(Double($0 + 1)))) }
let a0: UInt32 = 0x67452301
let b0: UInt32 = 0xefcdab89
let c0: UInt32 = 0x98badcfe
let d0: UInt32 = 0x10325476
private var message: NSData
//MARK: Public
public init(_ message: NSData) {
self.message = message
}
public func calculate() -> NSData? {
var tmpMessage: NSMutableData = NSMutableData(data: message)
let wordSize = sizeof(UInt32)
var aa = a0
var bb = b0
var cc = c0
var dd = d0
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (Byte with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
while tmpMessage.length % 64 != 56 {
tmpMessage.appendBytes([0x00])
}
// Step 2. Append Length a 64-bit representation of lengthInBits
var lengthInBits = (message.length * 8)
var lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage.appendBytes(reverse(lengthBytes));
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8
var leftMessageBytes = tmpMessage.length
for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
// println("wordSize \(wordSize)");
var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
for x in 0..<M.count {
var range = NSRange(location:x * wordSize, length: wordSize)
chunk.getBytes(&M[x], range:range);
}
// Initialize hash value for this chunk:
var A:UInt32 = a0
var B:UInt32 = b0
var C:UInt32 = c0
var D:UInt32 = d0
var dTemp:UInt32 = 0
// Main loop
for j in 0...63 {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ K[j] &+ M[g]), s[j])
A = dTemp
}
aa = aa &+ A
bb = bb &+ B
cc = cc &+ C
dd = dd &+ D
}
var buf: NSMutableData = NSMutableData();
buf.appendBytes(&aa, length: wordSize)
buf.appendBytes(&bb, length: wordSize)
buf.appendBytes(&cc, length: wordSize)
buf.appendBytes(&dd, length: wordSize)
return buf.copy() as? NSData;
}
//MARK: Class
class func calculate(message: NSData) -> NSData?
{
return MD5(message).calculate();
}
//MARK: Private
private func rotateLeft(x:UInt32, _ n:UInt32) -> UInt32 {
return (x &<< n) | (x &>> (32 - n))
}
}
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #MATLAB_.2F_Octave | MATLAB / Octave | function s=middle_three_digits(a)
% http://rosettacode.org/wiki/Middle_three_digits
s=num2str(abs(a));
if ~mod(length(s),2)
s='*** error: number of digits must be odd ***';
return;
end;
if length(s)<3,
s='*** error: number of digits must not be smaller than 3 ***';
return;
end;
s = s((length(s)+1)/2+[-1:1]); |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Scala | Scala | import scala.math.BigInt
object MillerRabinPrimalityTest extends App {
val (n, certainty )= (BigInt(args(0)), args(1).toInt)
println(s"$n is ${if (n.isProbablePrime(certainty)) "probably prime" else "composite"}")
} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION bashMenu RETURNS CHAR(
i_c AS CHAR
):
DEF VAR ii AS INT.
DEF VAR hfr AS HANDLE.
DEF VAR hmenu AS HANDLE EXTENT.
DEF VAR ikey AS INT.
DEF VAR ireturn AS INT INITIAL ?.
EXTENT( hmenu ) = NUM-ENTRIES( i_c ).
CREATE FRAME hfr ASSIGN
WIDTH = 80
HEIGHT = NUM-ENTRIES( i_c )
PARENT = CURRENT-WINDOW
VISIBLE = TRUE
.
DO ii = 1 TO NUM-ENTRIES( i_c ):
CREATE TEXT hmenu ASSIGN
FRAME = hfr
FORMAT = "x(79)"
SCREEN-VALUE = SUBSTITUTE( "&1. &2", ii, ENTRY( ii, i_c ) )
ROW = ii
VISIBLE = TRUE
.
END.
IF i_c = "" THEN
ireturn = 1.
DO WHILE ireturn = ?:
READKEY.
ikey = INTEGER( CHR( LASTKEY ) ) NO-ERROR.
IF ikey >= 1 AND ikey <= NUM-ENTRIES( i_c ) THEN
ireturn = ikey.
END.
RETURN ENTRY( ireturn, i_c ).
END FUNCTION.
MESSAGE
bashMenu( "fee fie,huff and puff,mirror mirror,tick tock" )
VIEW-AS ALERT-BOX. |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Tcl | Tcl | # We just define the body of md5::md5 here; later we regsub to inline a few
# function calls for speed
variable ::md5::md5body {
### Step 1. Append Padding Bits
set msgLen [string length $msg]
set padLen [expr {56 - $msgLen%64}]
if {$msgLen % 64 > 56} {
incr padLen 64
}
# pad even if no padding required
if {$padLen == 0} {
incr padLen 64
}
# append single 1b followed by 0b's
append msg [binary format "a$padLen" \200]
### Step 2. Append Length
# RFC doesn't say whether to use little- or big-endian; code demonstrates
# little-endian.
# This step limits our input to size 2^32b or 2^24B
append msg [binary format "i1i1" [expr {8*$msgLen}] 0]
### Step 3. Initialize MD Buffer
set A [expr 0x67452301]
set B [expr 0xefcdab89]
set C [expr 0x98badcfe]
set D [expr 0x10325476]
### Step 4. Process Message in 16-Word Blocks
# process each 16-word block
# RFC doesn't say whether to use little- or big-endian; code says
# little-endian.
binary scan $msg i* blocks
# loop over the message taking 16 blocks at a time
foreach {X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15} $blocks {
# Save A as AA, B as BB, C as CC, and D as DD.
set AA $A
set BB $B
set CC $C
set DD $D
# Round 1.
# Let [abcd k s i] denote the operation
# a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s).
# [ABCD 0 7 1] [DABC 1 12 2] [CDAB 2 17 3] [BCDA 3 22 4]
set A [expr {$B + [<<< [expr {$A + [F $B $C $D] + $X0 + $T01}] 7]}]
set D [expr {$A + [<<< [expr {$D + [F $A $B $C] + $X1 + $T02}] 12]}]
set C [expr {$D + [<<< [expr {$C + [F $D $A $B] + $X2 + $T03}] 17]}]
set B [expr {$C + [<<< [expr {$B + [F $C $D $A] + $X3 + $T04}] 22]}]
# [ABCD 4 7 5] [DABC 5 12 6] [CDAB 6 17 7] [BCDA 7 22 8]
set A [expr {$B + [<<< [expr {$A + [F $B $C $D] + $X4 + $T05}] 7]}]
set D [expr {$A + [<<< [expr {$D + [F $A $B $C] + $X5 + $T06}] 12]}]
set C [expr {$D + [<<< [expr {$C + [F $D $A $B] + $X6 + $T07}] 17]}]
set B [expr {$C + [<<< [expr {$B + [F $C $D $A] + $X7 + $T08}] 22]}]
# [ABCD 8 7 9] [DABC 9 12 10] [CDAB 10 17 11] [BCDA 11 22 12]
set A [expr {$B + [<<< [expr {$A + [F $B $C $D] + $X8 + $T09}] 7]}]
set D [expr {$A + [<<< [expr {$D + [F $A $B $C] + $X9 + $T10}] 12]}]
set C [expr {$D + [<<< [expr {$C + [F $D $A $B] + $X10 + $T11}] 17]}]
set B [expr {$C + [<<< [expr {$B + [F $C $D $A] + $X11 + $T12}] 22]}]
# [ABCD 12 7 13] [DABC 13 12 14] [CDAB 14 17 15] [BCDA 15 22 16]
set A [expr {$B + [<<< [expr {$A + [F $B $C $D] + $X12 + $T13}] 7]}]
set D [expr {$A + [<<< [expr {$D + [F $A $B $C] + $X13 + $T14}] 12]}]
set C [expr {$D + [<<< [expr {$C + [F $D $A $B] + $X14 + $T15}] 17]}]
set B [expr {$C + [<<< [expr {$B + [F $C $D $A] + $X15 + $T16}] 22]}]
# Round 2.
# Let [abcd k s i] denote the operation
# a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s).
# Do the following 16 operations.
# [ABCD 1 5 17] [DABC 6 9 18] [CDAB 11 14 19] [BCDA 0 20 20]
set A [expr {$B + [<<< [expr {$A + [G $B $C $D] + $X1 + $T17}] 5]}]
set D [expr {$A + [<<< [expr {$D + [G $A $B $C] + $X6 + $T18}] 9]}]
set C [expr {$D + [<<< [expr {$C + [G $D $A $B] + $X11 + $T19}] 14]}]
set B [expr {$C + [<<< [expr {$B + [G $C $D $A] + $X0 + $T20}] 20]}]
# [ABCD 5 5 21] [DABC 10 9 22] [CDAB 15 14 23] [BCDA 4 20 24]
set A [expr {$B + [<<< [expr {$A + [G $B $C $D] + $X5 + $T21}] 5]}]
set D [expr {$A + [<<< [expr {$D + [G $A $B $C] + $X10 + $T22}] 9]}]
set C [expr {$D + [<<< [expr {$C + [G $D $A $B] + $X15 + $T23}] 14]}]
set B [expr {$C + [<<< [expr {$B + [G $C $D $A] + $X4 + $T24}] 20]}]
# [ABCD 9 5 25] [DABC 14 9 26] [CDAB 3 14 27] [BCDA 8 20 28]
set A [expr {$B + [<<< [expr {$A + [G $B $C $D] + $X9 + $T25}] 5]}]
set D [expr {$A + [<<< [expr {$D + [G $A $B $C] + $X14 + $T26}] 9]}]
set C [expr {$D + [<<< [expr {$C + [G $D $A $B] + $X3 + $T27}] 14]}]
set B [expr {$C + [<<< [expr {$B + [G $C $D $A] + $X8 + $T28}] 20]}]
# [ABCD 13 5 29] [DABC 2 9 30] [CDAB 7 14 31] [BCDA 12 20 32]
set A [expr {$B + [<<< [expr {$A + [G $B $C $D] + $X13 + $T29}] 5]}]
set D [expr {$A + [<<< [expr {$D + [G $A $B $C] + $X2 + $T30}] 9]}]
set C [expr {$D + [<<< [expr {$C + [G $D $A $B] + $X7 + $T31}] 14]}]
set B [expr {$C + [<<< [expr {$B + [G $C $D $A] + $X12 + $T32}] 20]}]
# Round 3.
# Let [abcd k s t] [sic] denote the operation
# a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s).
# Do the following 16 operations.
# [ABCD 5 4 33] [DABC 8 11 34] [CDAB 11 16 35] [BCDA 14 23 36]
set A [expr {$B + [<<< [expr {$A + [H $B $C $D] + $X5 + $T33}] 4]}]
set D [expr {$A + [<<< [expr {$D + [H $A $B $C] + $X8 + $T34}] 11]}]
set C [expr {$D + [<<< [expr {$C + [H $D $A $B] + $X11 + $T35}] 16]}]
set B [expr {$C + [<<< [expr {$B + [H $C $D $A] + $X14 + $T36}] 23]}]
# [ABCD 1 4 37] [DABC 4 11 38] [CDAB 7 16 39] [BCDA 10 23 40]
set A [expr {$B + [<<< [expr {$A + [H $B $C $D] + $X1 + $T37}] 4]}]
set D [expr {$A + [<<< [expr {$D + [H $A $B $C] + $X4 + $T38}] 11]}]
set C [expr {$D + [<<< [expr {$C + [H $D $A $B] + $X7 + $T39}] 16]}]
set B [expr {$C + [<<< [expr {$B + [H $C $D $A] + $X10 + $T40}] 23]}]
# [ABCD 13 4 41] [DABC 0 11 42] [CDAB 3 16 43] [BCDA 6 23 44]
set A [expr {$B + [<<< [expr {$A + [H $B $C $D] + $X13 + $T41}] 4]}]
set D [expr {$A + [<<< [expr {$D + [H $A $B $C] + $X0 + $T42}] 11]}]
set C [expr {$D + [<<< [expr {$C + [H $D $A $B] + $X3 + $T43}] 16]}]
set B [expr {$C + [<<< [expr {$B + [H $C $D $A] + $X6 + $T44}] 23]}]
# [ABCD 9 4 45] [DABC 12 11 46] [CDAB 15 16 47] [BCDA 2 23 48]
set A [expr {$B + [<<< [expr {$A + [H $B $C $D] + $X9 + $T45}] 4]}]
set D [expr {$A + [<<< [expr {$D + [H $A $B $C] + $X12 + $T46}] 11]}]
set C [expr {$D + [<<< [expr {$C + [H $D $A $B] + $X15 + $T47}] 16]}]
set B [expr {$C + [<<< [expr {$B + [H $C $D $A] + $X2 + $T48}] 23]}]
# Round 4.
# Let [abcd k s t] [sic] denote the operation
# a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s).
# Do the following 16 operations.
# [ABCD 0 6 49] [DABC 7 10 50] [CDAB 14 15 51] [BCDA 5 21 52]
set A [expr {$B + [<<< [expr {$A + [I $B $C $D] + $X0 + $T49}] 6]}]
set D [expr {$A + [<<< [expr {$D + [I $A $B $C] + $X7 + $T50}] 10]}]
set C [expr {$D + [<<< [expr {$C + [I $D $A $B] + $X14 + $T51}] 15]}]
set B [expr {$C + [<<< [expr {$B + [I $C $D $A] + $X5 + $T52}] 21]}]
# [ABCD 12 6 53] [DABC 3 10 54] [CDAB 10 15 55] [BCDA 1 21 56]
set A [expr {$B + [<<< [expr {$A + [I $B $C $D] + $X12 + $T53}] 6]}]
set D [expr {$A + [<<< [expr {$D + [I $A $B $C] + $X3 + $T54}] 10]}]
set C [expr {$D + [<<< [expr {$C + [I $D $A $B] + $X10 + $T55}] 15]}]
set B [expr {$C + [<<< [expr {$B + [I $C $D $A] + $X1 + $T56}] 21]}]
# [ABCD 8 6 57] [DABC 15 10 58] [CDAB 6 15 59] [BCDA 13 21 60]
set A [expr {$B + [<<< [expr {$A + [I $B $C $D] + $X8 + $T57}] 6]}]
set D [expr {$A + [<<< [expr {$D + [I $A $B $C] + $X15 + $T58}] 10]}]
set C [expr {$D + [<<< [expr {$C + [I $D $A $B] + $X6 + $T59}] 15]}]
set B [expr {$C + [<<< [expr {$B + [I $C $D $A] + $X13 + $T60}] 21]}]
# [ABCD 4 6 61] [DABC 11 10 62] [CDAB 2 15 63] [BCDA 9 21 64]
set A [expr {$B + [<<< [expr {$A + [I $B $C $D] + $X4 + $T61}] 6]}]
set D [expr {$A + [<<< [expr {$D + [I $A $B $C] + $X11 + $T62}] 10]}]
set C [expr {$D + [<<< [expr {$C + [I $D $A $B] + $X2 + $T63}] 15]}]
set B [expr {$C + [<<< [expr {$B + [I $C $D $A] + $X9 + $T64}] 21]}]
# Then perform the following additions. (That is increment each of the
# four registers by the value it had before this block was started.)
incr A $AA
incr B $BB
incr C $CC
incr D $DD
}
### Step 5. Output
# ... begin with the low-order byte of A, and end with the high-order byte
# of D.
return [bytes $A][bytes $B][bytes $C][bytes $D]
}
### Here we inline/regsub the functions F, G, H, I and <<<
namespace eval ::md5 {
#proc md5pure::F {x y z} {expr {(($x & $y) | ((~$x) & $z))}}
regsub -all -- {\[ *F +(\$.) +(\$.) +(\$.) *\]} $md5body {((\1 \& \2) | ((~\1) \& \3))} md5body
#proc md5pure::G {x y z} {expr {(($x & $z) | ($y & (~$z)))}}
regsub -all -- {\[ *G +(\$.) +(\$.) +(\$.) *\]} $md5body {((\1 \& \3) | (\2 \& (~\3)))} md5body
#proc md5pure::H {x y z} {expr {$x ^ $y ^ $z}}
regsub -all -- {\[ *H +(\$.) +(\$.) +(\$.) *\]} $md5body {(\1 ^ \2 ^ \3)} md5body
#proc md5pure::I {x y z} {expr {$y ^ ($x | (~$z))}}
regsub -all -- {\[ *I +(\$.) +(\$.) +(\$.) *\]} $md5body {(\2 ^ (\1 | (~\3)))} md5body
# inline <<< (bitwise left-rotate)
regsub -all -- {\[ *<<< +\[ *expr +({[^\}]*})\] +([0-9]+) *\]} $md5body {(([set x [expr \1]] << \2) | (($x >> R\2) \& S\2))} md5body
# now replace the R and S
variable map {}
variable i
foreach i {
7 12 17 22
5 9 14 20
4 11 16 23
6 10 15 21
} {
lappend map R$i [expr {32 - $i}] S$i [expr {0x7fffffff >> (31-$i)}]
}
# inline the values of T
variable tName
variable tVal
foreach tName {
T01 T02 T03 T04 T05 T06 T07 T08 T09 T10
T11 T12 T13 T14 T15 T16 T17 T18 T19 T20
T21 T22 T23 T24 T25 T26 T27 T28 T29 T30
T31 T32 T33 T34 T35 T36 T37 T38 T39 T40
T41 T42 T43 T44 T45 T46 T47 T48 T49 T50
T51 T52 T53 T54 T55 T56 T57 T58 T59 T60
T61 T62 T63 T64
} tVal {
0xd76aa478 0xe8c7b756 0x242070db 0xc1bdceee
0xf57c0faf 0x4787c62a 0xa8304613 0xfd469501
0x698098d8 0x8b44f7af 0xffff5bb1 0x895cd7be
0x6b901122 0xfd987193 0xa679438e 0x49b40821
0xf61e2562 0xc040b340 0x265e5a51 0xe9b6c7aa
0xd62f105d 0x2441453 0xd8a1e681 0xe7d3fbc8
0x21e1cde6 0xc33707d6 0xf4d50d87 0x455a14ed
0xa9e3e905 0xfcefa3f8 0x676f02d9 0x8d2a4c8a
0xfffa3942 0x8771f681 0x6d9d6122 0xfde5380c
0xa4beea44 0x4bdecfa9 0xf6bb4b60 0xbebfbc70
0x289b7ec6 0xeaa127fa 0xd4ef3085 0x4881d05
0xd9d4d039 0xe6db99e5 0x1fa27cf8 0xc4ac5665
0xf4292244 0x432aff97 0xab9423a7 0xfc93a039
0x655b59c3 0x8f0ccc92 0xffeff47d 0x85845dd1
0x6fa87e4f 0xfe2ce6e0 0xa3014314 0x4e0811a1
0xf7537e82 0xbd3af235 0x2ad7d2bb 0xeb86d391
} {
lappend map \$$tName $tVal
}
set md5body [string map $map $md5body]
# Finally, define the proc
proc md5 {msg} $md5body
# unset auxiliary variables
unset md5body tName tVal map
proc byte0 {i} {expr {0xff & $i}}
proc byte1 {i} {expr {(0xff00 & $i) >> 8}}
proc byte2 {i} {expr {(0xff0000 & $i) >> 16}}
proc byte3 {i} {expr {((0xff000000 & $i) >> 24) & 0xff}}
proc bytes {i} {
format %0.2x%0.2x%0.2x%0.2x [byte0 $i] [byte1 $i] [byte2 $i] [byte3 $i]
}
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #MiniScript | MiniScript | middle3 = function(num)
if num < 0 then num = -num
s = str(num)
if s.len < 3 then return "Input too short"
if s.len % 2 == 0 then return "Input length not odd"
mid = (s.len + 1) / 2 - 1
return s[mid-1:mid+2]
end function
for test in [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
print test + " --> " + middle3(test)
end for |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Scheme | Scheme | #!r6rs
(import (rnrs base (6))
(srfi :27 random-bits))
;; Fast modular exponentiation.
(define (modexpt b e M)
(cond
((zero? e) 1)
((even? e) (modexpt (mod (* b b) M) (div e 2) M))
((odd? e) (mod (* b (modexpt b (- e 1) M)) M))))
;; Return s, d such that d is odd and 2^s * d = n.
(define (split n)
(let recur ((s 0) (d n))
(if (odd? d)
(values s d)
(recur (+ s 1) (div d 2)))))
;; Test whether the number a proves that n is composite.
(define (composite-witness? n a)
(let*-values (((s d) (split (- n 1)))
((x) (modexpt a d n)))
(and (not (= x 1))
(not (= x (- n 1)))
(let try ((r (- s 1)))
(set! x (modexpt x 2 n))
(or (zero? r)
(= x 1)
(and (not (= x (- n 1)))
(try (- r 1))))))))
;; Test whether n > 2 is a Miller-Rabin pseudoprime, k trials.
(define (pseudoprime? n k)
(or (zero? k)
(let ((a (+ 2 (random-integer (- n 2)))))
(and (not (composite-witness? n a))
(pseudoprime? n (- k 1))))))
;; Test whether any integer is prime.
(define (prime? n)
(and (> n 1)
(or (= n 2)
(pseudoprime? n 50)))) |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Oz | Oz | declare
fun {Select Prompt Items}
case Items of nil then ""
else
for
Item in Items
Index in 1..{Length Items}
do
{System.showInfo Index#") "#Item}
end
{System.printInfo Prompt}
try
{Nth Items {ReadInt}}
catch _ then
{Select Prompt Items}
end
end
end
fun {ReadInt}
class TextFile from Open.file Open.text end
StdIo = {New TextFile init(name:stdin)}
in
{String.toInt {StdIo getS($)}}
end
Item = {Select "Which is from the three pigs: "
["fee fie" "huff and puff" "mirror mirror" "tick tock"]}
in
{System.showInfo "You chose: "#Item} |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #Wren | Wren | import "/fmt" for Fmt
var k = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee ,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 ,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be ,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa ,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 ,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed ,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c ,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 ,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 ,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 ,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 ,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 ,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
]
var r = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
]
var leftRotate = Fn.new { |x, c| (x << c) | (x >> (32 - c)) }
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 md5 = Fn.new { |initMsg|
var h0 = 0x67452301
var h1 = 0xefcdab89
var h2 = 0x98badcfe
var h3 = 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 w = List.filled(16, 0)
while (offset < newLen) {
for (i in 0...16) w[i] = toInt.call(msg[offset+i*4...offset + i*4 + 4])
var a = h0
var b = h1
var c = h2
var d = h3
var f
var g
for (i in 0...64) {
if (i < 16) {
f = (b & c) | ((~b) & d)
g = i
} else if (i < 32) {
f = (d & b) | ((~d) & c)
g = (5*i + 1) % 16
} else if (i < 48) {
f = b ^ c ^ d
g = (3*i + 5) % 16
} else {
f = c ^ (b | (~d))
g = (7*i) % 16
}
var temp = d
d = c
c = b
b = b + leftRotate.call((a + f + k[i] + w[g]), r[i])
a = temp
}
h0 = h0 + a
h1 = h1 + b
h2 = h2 + c
h3 = h3 + d
offset = offset + 64
}
var digest = List.filled(16, 0)
var dBytes = toBytes.call(h0)
for (i in 0...4) digest[i] = dBytes[i]
dBytes = toBytes.call(h1)
for (i in 0...4) digest[i+4] = dBytes[i]
dBytes = toBytes.call(h2)
for (i in 0...4) digest[i+8] = dBytes[i]
dBytes = toBytes.call(h3)
for (i in 0...4) digest[i+12] = dBytes[i]
return digest
}
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
]
for (s in strings) {
var digest = md5.call(s)
Fmt.print("0x$s <== '$0s'", Fmt.v("xz", 2, digest, 0, "", ""), s)
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 lg [x] 3 - x>=0 23 ИП0 1 0
/ [x] ^ lg [x] 10^x П1 / {x} ИП1
* БП 00 1 + x=0 29 ИП0 С/П 0
/ |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const func boolean: millerRabin (in bigInteger: n, in integer: k) is func
result
var boolean: probablyPrime is TRUE;
local
var bigInteger: d is 0_;
var integer: r is 0;
var integer: s is 0;
var bigInteger: a is 0_;
var bigInteger: x is 0_;
var integer: tests is 0;
begin
if n < 2_ or (n > 2_ and not odd(n)) then
probablyPrime := FALSE;
elsif n > 3_ then
d := pred(n);
s := lowestSetBit(d);
d >>:= s;
while tests < k and probablyPrime do
a := rand(2_, pred(n));
x := modPow(a, d, n);
if x <> 1_ and x <> pred(n) then
r := 1;
while r < s and x <> 1_ and x <> pred(n) do
x := modPow(x, 2_, n);
incr(r);
end while;
probablyPrime := x = pred(n);
end if;
incr(tests);
end while;
end if;
end func;
const proc: main is func
local
var bigInteger: number is 0_;
begin
for number range 2_ to 1000_ do
if millerRabin(number, 10) then
writeln(number);
end if;
end for;
end func; |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #PARI.2FGP | PARI/GP | choose(v)=my(n);for(i=1,#v,print(i". "v[i]));while(type(n=input())!="t_INT"|n>#v|n<1,);v[n]
choose(["fee fie","huff and puff","mirror mirror","tick tock"]) |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #x86_Assembly | x86 Assembly | section .text
org 0x100
mov di, md5_for_display
mov si, test_input_1
mov cx, test_input_1_len
call compute_md5
call display_md5
mov si, test_input_2
mov cx, test_input_2_len
call compute_md5
call display_md5
mov si, test_input_3
mov cx, test_input_3_len
call compute_md5
call display_md5
mov si, test_input_4
mov cx, test_input_4_len
call compute_md5
call display_md5
mov si, test_input_5
mov cx, test_input_5_len
call compute_md5
call display_md5
mov si, test_input_6
mov cx, test_input_6_len
call compute_md5
call display_md5
mov si, test_input_7
mov cx, test_input_7_len
call compute_md5
call display_md5
mov ax, 0x4c00
int 21h
md5_for_display times 16 db 0
HEX_CHARS db '0123456789ABCDEF'
display_md5:
mov ah, 9
mov dx, display_str_1
int 0x21
push cx
push si
mov cx, 16
mov si, di
xor bx, bx
.loop:
lodsb
mov bl, al
and bl, 0x0F
push bx
mov bl, al
shr bx, 4
mov ah, 2
mov dl, [HEX_CHARS + bx]
int 0x21
pop bx
mov dl, [HEX_CHARS + bx]
int 0x21
dec cx
jnz .loop
mov ah, 9
mov dx, display_str_2
int 0x21
pop si
pop cx
test cx, cx
jz do_newline
mov ah, 2
display_string:
lodsb
mov dl, al
int 0x21
dec cx
jnz display_string
do_newline:
mov ah, 9
mov dx, display_str_3
int 0x21
ret;
compute_md5:
; si --> input bytes, cx = input len, di --> 16-byte output buffer
; assumes all in the same segment
cld
pusha
push di
push si
mov [message_len], cx
mov bx, cx
shr bx, 6
mov [ending_bytes_block_num], bx
mov [num_blocks], bx
inc word [num_blocks]
shl bx, 6
add si, bx
and cx, 0x3f
push cx
mov di, ending_bytes
rep movsb
mov al, 0x80
stosb
pop cx
sub cx, 55
neg cx
jge add_padding
add cx, 64
inc word [num_blocks]
add_padding:
mov al, 0
rep stosb
xor eax, eax
mov ax, [message_len]
shl eax, 3
mov cx, 8
store_message_len:
stosb
shr eax, 8
dec cx
jnz store_message_len
pop si
mov [md5_a], dword INIT_A
mov [md5_b], dword INIT_B
mov [md5_c], dword INIT_C
mov [md5_d], dword INIT_D
block_loop:
push cx
cmp cx, [ending_bytes_block_num]
jne backup_abcd
; switch buffers if towards the end where padding needed
mov si, ending_bytes
backup_abcd:
push dword [md5_d]
push dword [md5_c]
push dword [md5_b]
push dword [md5_a]
xor cx, cx
xor eax, eax
main_loop:
push cx
mov ax, cx
shr ax, 4
test al, al
jz pass0
cmp al, 1
je pass1
cmp al, 2
je pass2
; pass3
mov eax, [md5_c]
mov ebx, [md5_d]
not ebx
or ebx, [md5_b]
xor eax, ebx
jmp do_rotate
pass0:
mov eax, [md5_b]
mov ebx, eax
and eax, [md5_c]
not ebx
and ebx, [md5_d]
or eax, ebx
jmp do_rotate
pass1:
mov eax, [md5_d]
mov edx, eax
and eax, [md5_b]
not edx
and edx, [md5_c]
or eax, edx
jmp do_rotate
pass2:
mov eax, [md5_b]
xor eax, [md5_c]
xor eax, [md5_d]
do_rotate:
add eax, [md5_a]
mov bx, cx
shl bx, 1
mov bx, [BUFFER_INDEX_TABLE + bx]
add eax, [si + bx]
mov bx, cx
shl bx, 2
add eax, dword [TABLE_T + bx]
mov bx, cx
ror bx, 2
shr bl, 2
rol bx, 2
mov cl, [SHIFT_AMTS + bx]
rol eax, cl
add eax, [md5_b]
push eax
push dword [md5_b]
push dword [md5_c]
push dword [md5_d]
pop dword [md5_a]
pop dword [md5_d]
pop dword [md5_c]
pop dword [md5_b]
pop cx
inc cx
cmp cx, 64
jb main_loop
; add to original values
pop eax
add [md5_a], eax
pop eax
add [md5_b], eax
pop eax
add [md5_c], eax
pop eax
add [md5_d], eax
; advance pointers
add si, 64
pop cx
inc cx
cmp cx, [num_blocks]
jne block_loop
mov cx, 4
mov si, md5_a
pop di
rep movsd
popa
ret
section .data
INIT_A equ 0x67452301
INIT_B equ 0xEFCDAB89
INIT_C equ 0x98BADCFE
INIT_D equ 0x10325476
SHIFT_AMTS db 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21
TABLE_T dd 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501, 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE, 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA, 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED, 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C, 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70, 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665, 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1, 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391
BUFFER_INDEX_TABLE dw 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 4, 24, 44, 0, 20, 40, 60, 16, 36, 56, 12, 32, 52, 8, 28, 48, 20, 32, 44, 56, 4, 16, 28, 40, 52, 0, 12, 24, 36, 48, 60, 8, 0, 28, 56, 20, 48, 12, 40, 4, 32, 60, 24, 52, 16, 44, 8, 36
ending_bytes_block_num dw 0
ending_bytes times 128 db 0
message_len dw 0
num_blocks dw 0
md5_a dd 0
md5_b dd 0
md5_c dd 0
md5_d dd 0
display_str_1 db '0x$'
display_str_2 db ' <== "$'
display_str_3 db '"', 13, 10, '$'
test_input_1:
test_input_1_len equ $ - test_input_1
test_input_2 db 'a'
test_input_2_len equ $ - test_input_2
test_input_3 db 'abc'
test_input_3_len equ $ - test_input_3
test_input_4 db 'message digest'
test_input_4_len equ $ - test_input_4
test_input_5 db 'abcdefghijklmnopqrstuvwxyz'
test_input_5_len equ $ - test_input_5
test_input_6 db 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
test_input_6_len equ $ - test_input_6
test_input_7 db '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
test_input_7_len equ $ - test_input_7 |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #ML | ML |
val test_array = ["123","12345","1234567","987654321","10001","~10001","~123","~100","100","~12345","1","2","~1","~10","2002","~2002","0"];
fun even (x rem 2 = 0) = true | _ = false;
fun middleThreeDigits
(h :: t, s, 1 ) = s @ " --> too small"
| (h :: t, s, 2 ) = s @ " --> has even digits"
| (h :: t, s, 3 ) where (len (h :: t) = 3) = s @ " --> " @ (implode (h :: t))
| (h :: t, s, 3 ) = (middleThreeDigits ( sub (t, 0, (len t)-1), s, 3))
| (h :: t, s, m) = if len (h :: t) < 3 then
middleThreeDigits (h :: t, s, 1)
else
if even ` len (h :: t) then
middleThreeDigits (h :: t, s, 2)
else
middleThreeDigits (h :: t, s, 3)
| s = if sub (s, 0, 1) = "~" then
middleThreeDigits (sub (explode s, 1, len s), s, 0)
else
middleThreeDigits (explode s, s, 0)
;
map (println o middleThreeDigits) test_array; |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Sidef | Sidef | func miller_rabin(n, k=10) {
return false if (n <= 1)
return true if (n == 2)
return false if (n.is_even)
var t = n-1
var s = t.valuation(2)
var d = t>>s
k.times {
var a = irand(2, t)
var x = powmod(a, d, n)
next if (x ~~ [1, t])
(s-1).times {
x.powmod!(2, n)
return false if (x == 1)
break if (x == t)
}
return false if (x != t)
}
return true
}
say miller_rabin.grep(^1000).join(', ') |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Pascal | Pascal | program Menu;
{$ASSERTIONS ON}
uses
objects;
var
MenuItems :PUnSortedStrCollection;
selected :string;
Function SelectMenuItem(MenuItems :PUnSortedStrCollection):string;
var
i, idx :integer;
code :word;
choice :string;
begin
// Return empty string if the collection is empty.
if MenuItems^.Count = 0 then
begin
SelectMenuItem := '';
Exit;
end;
repeat
for i:=0 to MenuItems^.Count-1 do
begin
writeln(i+1:2, ') ', PString(MenuItems^.At(i))^);
end;
write('Make your choice: ');
readln(choice);
// Try to convert choice to an integer.
// Code contains 0 if this was successful.
val(choice, idx, code)
until (code=0) and (idx>0) and (idx<=MenuItems^.Count);
// Return the selected element.
SelectMenuItem := PString(MenuItems^.At(idx-1))^;
end;
begin
// Create an unsorted string collection for the menu items.
MenuItems := new(PUnSortedStrCollection, Init(10, 10));
// Add some menu items to the collection.
MenuItems^.Insert(NewStr('fee fie'));
MenuItems^.Insert(NewStr('huff and puff'));
MenuItems^.Insert(NewStr('mirror mirror'));
MenuItems^.Insert(NewStr('tick tock'));
// Display the menu and get user input.
selected := SelectMenuItem(MenuItems);
writeln('You chose: ', selected);
dispose(MenuItems, Done);
// Test function with an empty collection.
MenuItems := new(PUnSortedStrCollection, Init(10, 10));
selected := SelectMenuItem(MenuItems);
// Assert that the function returns an empty string.
assert(selected = '', 'Assertion failed: the function did not return an empty string.');
dispose(MenuItems, Done);
end. |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #MUMPS | MUMPS | /* MUMPS */
MID3(N) ;
N LEN,N2
S N2=$S(N<0:-N,1:N)
I N2<100 Q "NUMBER TOO SMALL"
S LEN=$L(N2)
I LEN#2=0 Q "EVEN NUMBER OF DIGITS"
Q $E(N2,LEN\2,LEN\2+2)
F I=123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0 W !,$J(I,10),": ",$$MID3^MID3(I)
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Smalltalk | Smalltalk | Integer extend [
millerRabinTest: kl [ |k| k := kl.
self <= 3
ifTrue: [ ^true ]
ifFalse: [
(self even)
ifTrue: [ ^false ]
ifFalse: [ |d s|
d := self - 1.
s := 0.
[ (d rem: 2) == 0 ]
whileTrue: [
d := d / 2.
s := s + 1.
].
[ k:=k-1. k >= 0 ]
whileTrue: [ |a x r|
a := Random between: 2 and: (self - 2).
x := (a raisedTo: d) rem: self.
( x = 1 )
ifFalse: [ |r|
r := -1.
[ r := r + 1. (r < s) & (x ~= (self - 1)) ]
whileTrue: [
x := (x raisedTo: 2) rem: self
].
( x ~= (self - 1) ) ifTrue: [ ^false ]
]
].
^true
]
]
]
]. |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Perl | Perl | sub menu
{
my ($prompt,@array) = @_;
return '' unless @array;
print " $_: $array[$_]\n" for(0..$#array);
print $prompt;
$n = <>;
return $array[$n] if $n =~ /^\d+$/ and defined $array[$n];
return &menu($prompt,@array);
}
@a = ('fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
$prompt = 'Which is from the three pigs: ';
$a = &menu($prompt,@a);
print "You chose: $a\n"; |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
Task
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number n which cannot be expressed with 6x + 9y + 20z = n
where x, y and z are natural numbers).
| #11l | 11l | V nuggets = Set(0..100)
L(s, n, t) cart_product(0 .. 100 I/ 6,
0 .. 100 I/ 9,
0 .. 100 I/ 20)
nuggets.discard(6*s + 9*n + 20*t)
print(max(nuggets)) |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Fortran | Fortran |
PROGRAM MAYA_DRIVER
IMPLICIT NONE
!
! Local variables
!
CHARACTER(80) :: haab_carry
CHARACTER(80) :: long_carry
CHARACTER(80) :: nightlord
CHARACTER(80) :: tzolkin_carry
INTEGER,DIMENSION(8) :: DAY, MONTH, YEAR
INTEGER :: INDEX
DATA YEAR /2071,2004,2012,2012,2019,2019,2020,2020/
DATA MONTH /5,6,12,12,1,3,2,3/
DATA DAY /16,19,18,21,19,27,29,01/
! 2071-05-16
! 2004-06-19
! 2012-12-18
! 2012-12-21
! 2019-01-19
! 2019-03-27
! 2020-02-29
! 2020-03-01
DO INDEX = 1,8
!
CALL MAYA_TIME(day(INDEX) , month(INDEX) , year(INDEX) , long_carry , haab_carry , tzolkin_carry , &
& nightlord)
WRITE(6,20)day(INDEX),month(INDEX),year(INDEX),TRIM(tzolkin_carry),TRIM(haab_carry),TRIM(long_carry),TRIM(nightlord)
20 FORMAT(1X,I0,'-',I0,'-',I0,T12,A,T24,A,T38,A,T58,A)
END DO
STOP
END PROGRAM MAYA_DRIVER
!
! SUBROUTINE MAYA_TIME
subroutine maya_time(day,month,year, long_carry,haab_carry, tzolkin_carry,nightlord)
implicit none
integer(kind=4), parameter :: startdate = 584283 ! Start of the Mayan Calendar in Julian days
integer(kind=4), parameter :: kin = 1
integer(kind=4), parameter :: winal = 20*kin
integer(kind=4), parameter :: tun = winal*18
integer(kind=4), parameter :: katun = tun*20
integer(kind=4), parameter :: baktun = katun*20
integer(kind=4), parameter :: piktun = baktun*20
integer(kind=4), parameter :: longcount = baktun*20
!
character(len=8), dimension(20) ,parameter :: tzolkin = &
["Imix' ", "Ik´ ", "Ak´bal ", "K´an ", "Chikchan", "Kimi ", &
"Manik´ ", "Lamat ", "Muluk ", "Ok ", "Chuwen ", "Eb ", &
"Ben ", "Hix ", "Men ", "K´ib´ ", "Kaban ", "Etz´nab´", &
"Kawak ", "Ajaw "]
character(len=8), dimension(19) ,parameter :: haab = &
["Pop ", "Wo´ ", "Sip ", "Sotz´ ", "Sek ", "Xul ", &
"Yaxk´in ", "Mol ", "Ch´en ", "Yax ", "Sak´ ", "Keh ", &
"Mak ", "K´ank´in", "Muwan ", "Pax ", "K´ayab ", "Kumk´u ", &
"Wayeb´ "]
character(len=20), dimension(9) ,parameter :: night_lords = &
["(G1) Xiuhtecuhtli ", & ! ("Turquoise/Year/Fire Lord")
"(G2) Tezcatlipoca ", & ! ("Smoking Mirror")
"(G3) Piltzintecuhtli", & ! ("Prince Lord")
"(G4) Centeotl ", & ! ("Maize God")
"(G5) Mictlantecuhtli", & ! ("Underworld Lord")
"(G6) Chalchiuhtlicue", & ! ("Jade Is Her Skirt")
"(G7) Tlazolteotl ", & ! ("Filth God[dess]")
"(G8) Tepeyollotl ", & ! ("Mountain Heart")
"(G9) Tlaloc " ] ! (Rain God)
integer(kind=4) :: day,month,year
intent(in) :: day,month,year
!
integer(kind=4) :: j,l, numdays, keptdays
integer(kind=4) :: kin_no, winal_no, tun_no, katun_no, baktun_no, longcount_no
character(*) :: haab_carry, nightlord, tzolkin_carry, long_carry
intent(inout) :: haab_carry, nightlord, tzolkin_carry, long_carry
integer :: mo,da
!
keptdays = julday(day,month,year) ! Get the Julian date for selected date
numdays = keptdays ! Keep for calcs later
! Adjust from the beginning
numdays = numdays-startdate ! Adjust the number of days from start of Mayan Calendar
if (numdays .ge. longcount)then ! We check if we have passed a longcount and need to adjust for a new start
longcount_no = numdays/longcount
print*, ' We have more than one longcount ',longcount_no
endif
!
! Calculate the longdate
baktun_no = numdays/baktun
numdays = numdays - (baktun_no*baktun) ! Decrement days down by the number of baktuns
katun_no = numdays/katun ! Get number of katuns
numdays = numdays - (katun_no*katun)
tun_no = numdays/tun
numdays = numdays-(tun_no*tun)
winal_no = numdays/winal
numdays = numdays-(winal_no*winal)
kin_no = numdays ! What is left is simply the days
long_carry = ' ' ! blank it out
write(long_carry,'(4(i2.2,"."),I2.2)') baktun_no,katun_no,tun_no,winal_no,kin_no
!
! OK. Now the longcount is done, let's calculate Tzolk´in, Haab´ & Nightlord (the calendar round)
!
haab_carry = " "
L = mod((keptdays+65),365)
mo = (L/20)+1
da = mod(l,20)
if(da.ne.0)then
write(haab_carry,'(i2,1x,a)') da,haab(mo)
else
write(haab_carry,'(a,1x,a)') 'Chum',haab(mo)
endif
!
! Ok, Now let's calculate the Tzolk´in
! The calendar starts on the 4 Ahu
tzolkin_carry = " " ! Total blank the carrier
mo = mod((keptdays+16),20) + 1
da = mod((keptdays+5),13) + 1
write(tzolkin_carry,'(i2,1x,a)') da,tzolkin(mo)
!
! Now let's have a look at the lords of the night
! There are 9 lords of the night, let's assume that they start on the first day of the year
!
numdays = keptdays -startdate ! Elapsed Julian days since start of calendar
J = mod(numdays,9) ! Number of days into this cycle
if (j.eq.0) j = 9
nightlord = night_lords(j)
RETURN
contains
!
FUNCTION JULDAY( Id , Mm, Iyyy)
IMPLICIT NONE
!
! PARAMETER definitions
!
INTEGER , PARAMETER :: IGREG = 15 + 31*(10 + 12*1582)
!
! Dummy arguments
!
INTEGER :: Id , Iyyy , Mm
INTEGER :: JULDAY
INTENT (IN) Id , Iyyy , Mm
!
! Local variables
!
INTEGER :: ja , jm , jy
!
jy = Iyyy
IF(jy == 0)STOP 'julday: there is no year zero'
IF(jy < 0)jy = jy + 1
IF(Mm > 2)THEN
jm = Mm + 1
ELSE
jy = jy - 1
jm = Mm + 13
END IF
JULDAY = 365*jy + INT(0.25D0*jy + 2000.D0) + INT(30.6001D0*jm) + Id + 1718995
IF(Id + 31*(Mm + 12*Iyyy) >= IGREG)THEN
ja = INT(0.01D0*jy)
JULDAY = JULDAY + 2 - ja + INT(0.25D0*ja)
END IF
RETURN
END FUNCTION JULDAY
END SUBROUTINE maya_time
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
sl = '123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345' -
'1 2 -1 -10 2002 -2002 0' -
'abc 1e3 -17e-3 4004.5 12345678 9876543210' -- extras
parse arg digsL digsR .
if \digsL.datatype('w') then digsL = 3
if \digsR.datatype('w') then digsR = digsL
if digsL > digsR then digsR = digsL
loop dc = digsL to digsR
say 'Middle' dc 'characters'
loop nn = 1 to sl.words()
val = sl.word(nn)
say middleDigits(dc, val)
end nn
say
end dc
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method middle3Digits(val) constant
return middleDigits(3, val)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method middleDigits(digitCt, val) constant
text = val.right(15)':'
even = digitCt // 2 == 0 -- odd or even?
select
when digitCt <= 0 then text = 'digit selection size must be >= 1'
when \val.datatype('w') then text = text 'is not a whole number'
when val.abs().length < digitCt then text = text 'has less than' digitCt 'digits'
when \even & val.abs().length // 2 == 0 then text = text 'does not have an odd number of digits'
when even & val.abs().length // 2 \= 0 then text = text 'does not have an even number of digits'
otherwise do
val = val.abs()
valL = val.length
cutP = (valL - digitCt) % 2
text = text val.substr(cutP + 1, digitCt)
end
catch NumberFormatException
text = val 'is not numeric'
end
return text
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Standard_ML | Standard ML | open LargeInt;
val mr_iterations = Int.toLarge 20;
val rng = Random.rand (557216670, 13504100); (* arbitrary pair to seed RNG *)
fun expmod base 0 m = 1
| expmod base exp m =
if exp mod 2 = 0
then let val rt = expmod base (exp div 2) m;
val sq = (rt*rt) mod m
in if sq = 1
andalso rt <> 1 (* ignore the two *)
andalso rt <> (m-1) (* 'trivial' roots *)
then 0
else sq
end
else (base*(expmod base (exp-1) m)) mod m;
(* arbitrary precision random number [0,n) *)
fun rand n =
let val base = Int.toLarge(valOf Int.maxInt)+1;
fun step r lim =
if lim < n then step (Int.toLarge(Random.randNat rng) + r*base) (lim*base)
else r mod n
in step 0 1 end;
fun miller_rabin n =
let fun trial n 0 = true
| trial n t = let val a = 1+rand(n-1)
in (expmod a (n-1) n) = 1
andalso trial n (t-1)
end
in trial n mr_iterations end;
fun trylist label lst = (label, ListPair.zip (lst, map miller_rabin lst));
trylist "test the first six Carmichael numbers"
[561, 1105, 1729, 2465, 2821, 6601];
trylist "test some known primes"
[7369, 7393, 7411, 27367, 27397, 27407];
(* find ten random 30 digit primes (according to Miller-Rabin) *)
let fun findPrime trials = let val t = trials+1;
val n = 2*rand(500000000000000000000000000000)+1
in if miller_rabin n
then (n,t)
else findPrime t end
in List.tabulate (10, fn e => findPrime 0) end; |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Phix | Phix | function menu_select(sequence items, object prompt)
sequence res = ""
items = remove_all("",items)
if length(items)!=0 then
while 1 do
for i=1 to length(items) do
printf(1,"%d) %s\n",{i,items[i]})
end for
puts(1,iff(atom(prompt)?"Choice?":prompt))
res = scanf(trim(gets(0)),"%d")
puts(1,"\n")
if length(res)=1 then
integer nres = res[1][1]
if nres>0 and nres<=length(items) then
res = items[nres]
exit
end if
end if
end while
end if
return res
end function
constant items = {"fee fie", "huff and puff", "mirror mirror", "tick tock"}
constant prompt = "Which is from the three pigs? "
string res = menu_select(items,prompt)
printf(1,"You chose %s.\n",{res}) |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #PHP | PHP | <?php
$stdin = fopen("php://stdin", "r");
$allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
for(;;) {
foreach ($allowed as $id => $name) {
echo " $id: $name\n";
}
echo "Which is from the four pigs: ";
$stdin_string = fgets($stdin, 4096);
if (isset($allowed[(int) $stdin_string])) {
echo "You chose: {$allowed[(int) $stdin_string]}\n";
break;
}
} |
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).
| #Action.21 | Action! | PROC Main()
BYTE x,y,z,n
BYTE ARRAY nuggets(101)
FOR n=0 TO 100
DO
nuggets(n)=0
OD
FOR x=0 TO 100 STEP 6
DO
FOR y=0 TO 100 STEP 9
DO
FOR z=0 TO 100 STEP 20
DO
n=x+y+z
IF n<=100 THEN
nuggets(n)=1
FI
OD
OD
OD
n=100
DO
IF nuggets(n)=0 THEN
PrintF("The largest non McNugget number is %B%E",n)
EXIT
ELSEIF n=0 THEN
PrintE("There is no result")
EXIT
ELSE
n==-1
FI
OD
RETURN |
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).
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure McNugget is
Limit : constant := 100;
List : array (0 .. Limit) of Boolean := (others => False);
N : Integer;
begin
for A in 0 .. Limit / 6 loop
for B in 0 .. Limit / 9 loop
for C in 0 .. Limit / 20 loop
N := A * 6 + B * 9 + C * 20;
if N <= 100 then
List (N) := True;
end if;
end loop;
end loop;
end loop;
for N in reverse 1 .. Limit loop
if not List (N) then
Put_Line ("The largest non McNugget number is:" & Integer'Image (N));
exit;
end if;
end loop;
end McNugget; |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Go | Go | package main
import (
"fmt"
"strconv"
"strings"
"time"
)
var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw")
var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’")
var (
date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC)
date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC)
)
func tzolkin(date time.Time) (int, string) {
diff := int(date.Sub(date1).Hours()) / 24
rem := diff % 13
if rem < 0 {
rem = 13 + rem
}
var num int
if rem <= 9 {
num = rem + 4
} else {
num = rem - 9
}
rem = diff % 20
if rem <= 0 {
rem = 20 + rem
}
return num, sacred[rem-1]
}
func haab(date time.Time) (string, string) {
diff := int(date.Sub(date2).Hours()) / 24
rem := diff % 365
if rem < 0 {
rem = 365 + rem
}
month := civil[(rem+1)/20]
last := 20
if month == "Wayeb’" {
last = 5
}
d := rem%20 + 1
if d < last {
return strconv.Itoa(d), month
}
return "Chum", month
}
func longCount(date time.Time) string {
diff := int(date.Sub(date1).Hours()) / 24
diff += 13 * 400 * 360
baktun := diff / (400 * 360)
diff %= 400 * 360
katun := diff / (20 * 360)
diff %= 20 * 360
tun := diff / 360
diff %= 360
winal := diff / 20
kin := diff % 20
return fmt.Sprintf("%d.%d.%d.%d.%d", baktun, katun, tun, winal, kin)
}
func lord(date time.Time) string {
diff := int(date.Sub(date1).Hours()) / 24
rem := diff % 9
if rem <= 0 {
rem = 9 + rem
}
return fmt.Sprintf("G%d", rem)
}
func main() {
const shortForm = "2006-01-02"
dates := []string{
"2004-06-19",
"2012-12-18",
"2012-12-21",
"2019-01-19",
"2019-03-27",
"2020-02-29",
"2020-03-01",
"2071-05-16",
}
fmt.Println(" Gregorian Tzolk’in Haab’ Long Lord of")
fmt.Println(" Date # Name Day Month Count the Night")
fmt.Println("---------- -------- ------------- -------------- ---------")
for _, dt := range dates {
date, _ := time.Parse(shortForm, dt)
n, s := tzolkin(date)
d, m := haab(date)
lc := longCount(date)
l := lord(date)
fmt.Printf("%s %2d %-8s %4s %-9s %-14s %s\n", dt, n, s, d, m, lc, l)
}
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #NewLISP | NewLISP |
(define (middle3 x)
(if (even? (length x))
(println "You entered " x ". I need an odd number of digits, not " (length x) ".")
(if (< (length x) 3)
(println "You entered " x ". Sorry, but I need 3 or more digits.")
(println "The middle 3 digits of " x " are " ((- (/ (- (length x) 1) 2) 1) 3 (string (abs x))) ".")
)
)
)
(map middle3 lst)
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Swift | Swift | import BigInt
private let numTrails = 5
func isPrime(_ n: BigInt) -> Bool {
guard n >= 2 else { fatalError() }
guard n != 2 else { return true }
guard n % 2 != 0 else { return false }
var s = 0
var d = n - 1
while true {
let (quo, rem) = (d / 2, d % 2)
guard rem != 1 else { break }
s += 1
d = quo
}
func tryComposite(_ a: BigInt) -> Bool {
guard a.power(d, modulus: n) != 1 else { return false }
for i in 0..<s where a.power((2 as BigInt).power(i) * d, modulus: n) == n - 1 {
return false
}
return true
}
for _ in 0..<numTrails where tryComposite(BigInt(BigUInt.randomInteger(lessThan: BigUInt(n)))) {
return false
}
return true
} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #PicoLisp | PicoLisp | (de choose (Prompt Items)
(use N
(loop
(for (I . Item) Items
(prinl I ": " Item) )
(prin Prompt " ")
(flush)
(NIL (setq N (in NIL (read))))
(T (>= (length Items) N 1) (prinl (get Items N))) ) ) )
(choose "Which is from the three pigs?"
'("fee fie" "huff and puff" "mirror mirror" "tick tock") ) |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #PL.2FI | PL/I |
test: proc options (main);
declare menu(4) character(100) varying static initial (
'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');
declare (i, k) fixed binary;
do i = lbound(menu,1) to hbound(menu,1);
put skip edit (trim(i), ': ', menu(i) ) (a);
end;
put skip list ('please choose an item number');
get list (k);
if k >= lbound(menu,1) & k <= hbound(menu,1) then
put skip edit ('you chose ', menu(k)) (a);
else
put skip list ('Could not find your phrase');
end test;
|
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).
| #ALGOL_68 | ALGOL 68 | BEGIN
# Solve the McNuggets problem: find the largest n <= 100 for which there #
# are no non-negative integers x, y, z such that 6x + 9y + 20z = n #
INT max nuggets = 100;
[ 0 : max nuggets ]BOOL sum;
FOR i FROM LWB sum TO UPB sum DO sum[ i ] := FALSE OD;
FOR x FROM 0 BY 6 TO max nuggets DO
FOR y FROM x BY 9 TO max nuggets DO
FOR z FROM y BY 20 TO max nuggets DO
sum[ z ] := TRUE
OD # z #
OD # y #
OD # x # ;
# show the highest number that cannot be formed #
INT largest := -1;
FOR i FROM UPB sum BY -1 TO LWB sum WHILE sum[ largest := i ] DO SKIP OD;
print( ( "The largest non McNugget number is: "
, whole( largest, 0 )
, newline
)
)
END |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #J | J | require 'types/datetime'
NB. 1794214= (0 20 18 20 20#.13 0 0 0 0)-todayno 2012 12 21
longcount=: {{ rplc&' .'":0 20 18 20 20#:y+1794214 }}
tsolkin=: (cut {{)n
Imix’ Ik’ Ak’bal K’an Chikchan
Kimi Manik’ Lamat Muluk Ok
Chuwen Eb Ben Hix Men
K’ib’ Kaban Etz’nab’ Kawak Ajaw
}}-.LF){{ (":1+13|y-4),' ',(20|y-7){::m }}
haab=:(cut {{)n
Pop Wo’ Sip Sotz’ Sek Xul
Yaxk’in Mol Ch’en Yax Sak’ Keh
Mak K’ank’in Muwan Pax K’ayab Kumk’u
Wayeb’
}}-.LF){{
'M D'=.0 20#:365|y-143
({{ if.*y do.":y else.'Chum'end. }} D),' ',(M-0=D){::m
}}
round=: [:;:inv tsolkin;haab;'G',&":1+9|]
gmt=: >@(fmtDate;round;longcount)@todayno |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Julia | Julia | using Dates
const Tzolk´in = [
"Imix´", "Ik´", "Ak´bal", "K´an", "Chikchan", "Kimi", "Manik´", "Lamat", "Muluk", "Ok",
"Chuwen", "Eb", "Ben", "Hix", "Men", "K´ib´", "Kaban", "Etz´nab´", "Kawak", "Ajaw"
]
const Haab´ = [
"Pop", "Wo´", "Sip", "Sotz´", "Sek", "Xul", "Yaxk´in", "Mol", "Ch´en", "Yax",
"Sak´", "Keh", "Mak", "K´ank´in", "Muwan", "Pax", "K´ayab", "Kumk´u", "Wayeb´"
]
const creationTzolk´in = Date(2012, 12, 21)
const zeroHaab´ = Date(2019, 4, 2)
daysperMayanmonth(month) = (month == "Wayeb´" ? 5 : 20)
function tzolkin(gregorian::Date)
deltadays = (gregorian - creationTzolk´in).value
rem = mod1(deltadays, 13)
return string(rem <= 9 ? rem + 4 : rem - 9) * " " * Tzolk´in[mod1(deltadays, 20)]
end
function haab(gregorian::Date)
rem = mod1((gregorian - zeroHaab´).value, 365)
month = Haab´[(rem + 21) ÷ 20]
dayofmonth = rem % 20 + 1
return dayofmonth < daysperMayanmonth(month) ? "$dayofmonth $month" : "Chum $month"
end
function tolongdate(gregorian::Date)
delta = (gregorian - creationTzolk´in).value + 13 * 360 * 400
baktun = delta ÷ (360 * 400)
delta %= (400 * 360)
katun = delta ÷ (20 * 360)
delta %= (20 * 360)
tun = delta ÷ 360
delta %= 360
winal, kin = divrem(delta, 20)
return mapreduce(x -> lpad(x, 3), *, [baktun, katun, tun, winal, kin])
end
nightlord(gregorian::Date) = "G$(mod1((gregorian - creationTzolk´in).value, 9))"
testdates = [
Date(1963, 11, 21), Date(2004, 06, 19), Date(2012, 12, 18), Date(2012, 12, 21),
Date(2019, 01, 19), Date(2019, 03, 27), Date(2020, 02, 29), Date(2020, 03, 01),
Date(2071, 5, 16), Date(2020, 2, 2)
]
println("Gregorian Long Count Tzolk´in Haab´ Nightlord")
println("-----------------------------------------------------------------")
for date in testdates
println(rpad(date,14), rpad(tolongdate(date), 18), rpad(tzolkin(date), 10),
rpad(haab(date), 15), nightlord(date))
end
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Nim | Nim | proc middleThreeDigits(i: int): string =
var s = $abs(i)
if s.len < 3 or s.len mod 2 == 0:
raise newException(ValueError, "Need odd and >= 3 digits")
let mid = s.len div 2
return s[mid-1..mid+1]
const passing = @[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
const failing = @[1, 2, -1, -10, 2002, -2002, 0]
for i in passing & failing:
var answer = try: middleThreeDigits(i)
except ValueError: getCurrentExceptionMsg()
echo "middleThreeDigits(", i, ") returned: ", answer |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Tcl | Tcl | package require Tcl 8.5
proc miller_rabin {n k} {
if {$n <= 3} {return true}
if {$n % 2 == 0} {return false}
# write n - 1 as 2^s·d with d odd by factoring powers of 2 from n − 1
set d [expr {$n - 1}]
set s 0
while {$d % 2 == 0} {
set d [expr {$d / 2}]
incr s
}
while {$k > 0} {
incr k -1
set a [expr {2 + int(rand()*($n - 4))}]
set x [expr {($a ** $d) % $n}]
if {$x == 1 || $x == $n - 1} continue
for {set r 1} {$r < $s} {incr r} {
set x [expr {($x ** 2) % $n}]
if {$x == 1} {return false}
if {$x == $n - 1} break
}
if {$x != $n-1} {return false}
}
return true
}
for {set i 1} {$i < 1000} {incr i} {
if {[miller_rabin $i 10]} {
puts $i
}
} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #PowerShell | PowerShell |
function Select-TextItem
{
<#
.SYNOPSIS
Prints a textual menu formatted as an index value followed by its corresponding string for each object in the list.
.DESCRIPTION
Prints a textual menu formatted as an index value followed by its corresponding string for each object in the list;
Prompts the user to enter a number;
Returns an object corresponding to the selected index number.
.PARAMETER InputObject
An array of objects.
.PARAMETER Prompt
The menu prompt string.
.EXAMPLE
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem
.EXAMPLE
“huff and puff”, “fee fie”, “tick tock”, “mirror mirror” | Sort-Object | Select-TextItem -Prompt "Select a string"
.EXAMPLE
Select-TextItem -InputObject (Get-Process)
.EXAMPLE
(Get-Process | Where-Object {$_.Name -match "notepad"}) | Select-TextItem -Prompt "Select a Process" | Stop-Process -ErrorAction SilentlyContinue
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true)]
$InputObject,
[Parameter(Mandatory=$false)]
[string]
$Prompt = "Enter Selection"
)
Begin
{
$menuOptions = @()
}
Process
{
$menuOptions += $InputObject
}
End
{
if(!$inputObject){
return ""
}
do
{
[int]$optionNumber = 1
foreach ($option in $menuOptions)
{
Write-Host ("{0,3}: {1}" -f $optionNumber,$option)
$optionNumber++
}
Write-Host ("{0,3}: {1}" -f 0,"To cancel")
$choice = Read-Host $Prompt
$selectedValue = ""
if ($choice -gt 0 -and $choice -le $menuOptions.Count)
{
$selectedValue = $menuOptions[$choice - 1]
}
}
until ($choice -match "^[0-9]+$" -and ($choice -eq 0 -or $choice -le $menuOptions.Count))
return $selectedValue
}
}
“fee fie”, “huff and puff”, “mirror mirror”, “tick tock” | Select-TextItem -Prompt "Select a string"
|
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).
| #APL | APL | 100 (⌈/(⍳⊣)~(⊂⊢)(+/×)¨(,⎕IO-⍨(⍳∘⌊÷))) 6 9 20 |
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).
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
on run
set setNuggets to mcNuggetSet(100, 6, 9, 20)
script isMcNugget
on |λ|(x)
setMember(x, setNuggets)
end |λ|
end script
set xs to dropWhile(isMcNugget, enumFromThenTo(100, 99, 1))
set setNuggets to missing value -- Clear ObjC pointer value
if 0 < length of xs then
item 1 of xs
else
"No unreachable quantities in this range"
end if
end run
-- mcNuggetSet :: Int -> Int -> Int -> Int -> ObjC Set
on mcNuggetSet(n, mcx, mcy, mcz)
set upTo to enumFromTo(0)
script fx
on |λ|(x)
script fy
on |λ|(y)
script fz
on |λ|(z)
set v to sum({mcx * x, mcy * y, mcz * z})
if 101 > v then
{v}
else
{}
end if
end |λ|
end script
concatMap(fz, upTo's |λ|(n div mcz))
end |λ|
end script
concatMap(fy, upTo's |λ|(n div mcy))
end |λ|
end script
setFromList(concatMap(fx, upTo's |λ|(n div mcx)))
end mcNuggetSet
-- GENERIC FUNCTIONS ----------------------------------------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & |λ|(item i of xs, i, xs)
end repeat
end tell
return acc
end concatMap
-- drop :: Int -> [a] -> [a]
-- drop :: Int -> String -> String
on drop(n, xs)
set c to class of xs
if c is not script then
if c is not string then
if n < length of xs then
items (1 + n) thru -1 of xs
else
{}
end if
else
if n < length of xs then
text (1 + n) thru -1 of xs
else
""
end if
end if
else
take(n, xs) -- consumed
return xs
end if
end drop
-- dropWhile :: (a -> Bool) -> [a] -> [a]
-- dropWhile :: (Char -> Bool) -> String -> String
on dropWhile(p, xs)
set lng to length of xs
set i to 1
tell mReturn(p)
repeat while i ≤ lng and |λ|(item i of xs)
set i to i + 1
end repeat
end tell
drop(i - 1, xs)
end dropWhile
-- enumFromThenTo :: Int -> Int -> Int -> [Int]
on enumFromThenTo(x1, x2, y)
set xs to {}
repeat with i from x1 to y by (x2 - x1)
set end of xs to i
end repeat
return xs
end enumFromThenTo
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m)
script
on |λ|(n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end |λ|
end script
end enumFromTo
-- 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
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
-- NB All names of NSMutableSets should be set to *missing value*
-- before the script exits.
-- ( scpt files can not be saved if they contain ObjC pointer values )
-- setFromList :: Ord a => [a] -> Set a
on setFromList(xs)
set ca to current application
ca's NSMutableSet's ¬
setWithArray:(ca's NSArray's arrayWithArray:(xs))
end setFromList
-- setMember :: Ord a => a -> Set a -> Bool
on setMember(x, objcSet)
missing value is not (objcSet's member:(x))
end setMember |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | sacred = {"Imix\[CloseCurlyQuote]", "Ik\[CloseCurlyQuote]",
"Ak\[CloseCurlyQuote]bal", "K\[CloseCurlyQuote]an", "Chikchan",
"Kimi", "Manik\[CloseCurlyQuote]", "Lamat", "Muluk", "Ok",
"Chuwen", "Eb", "Ben", "Hix", "Men",
"K\[CloseCurlyQuote]ib\[CloseCurlyQuote]", "Kaban",
"Etz\[CloseCurlyQuote]nab\[CloseCurlyQuote]", "Kawak", "Ajaw"};
civil = {"Pop", "Wo\[CloseCurlyQuote]", "Sip",
"Sotz\[CloseCurlyQuote]", "Sek", "Xul", "Yaxk\[CloseCurlyQuote]in",
"Mol", "Ch\[CloseCurlyQuote]en", "Yax", "Sak\[CloseCurlyQuote]",
"Keh", "Mak", "K\[CloseCurlyQuote]ank\[CloseCurlyQuote]in",
"Muwan\[CloseCurlyQuote]", "Pax", "K\[CloseCurlyQuote]ayab",
"Kumk\[CloseCurlyQuote]u", "Wayeb\[CloseCurlyQuote]"};
date1 = {2012, 12, 21, 0, 0, 0};
date2 = {2019, 4, 2, 0, 0, 0};
ClearAll[Tzolkin]
Tzolkin[date_] := Module[{diff, rem, num},
diff = QuantityMagnitude[DateDifference[date1, date], "Days"];
rem = Mod[diff, 13];
If[rem <= 9,
num = rem + 4
,
num = rem - 9
];
rem = Mod[diff, 20, 1];
ToString[num] <> " " <> sacred[[rem]]
]
ClearAll[Haab]
Haab[date_] := Module[{diff, rem, month, last, d},
diff = QuantityMagnitude[DateDifference[date2, date], "Days"];
rem = Mod[diff, 365];
month = civil[[Floor[(rem + 1)/20] + 1]];
last = 20;
If[month == Last[civil],
last = 5
];
d = Mod[rem, 20] + 1;
If[d < last,
ToString[d] <> " " <> month
,
"Chum " <> month
]
]
ClearAll[LongCount]
LongCount[date_] := Module[{diff, baktun, katun, tun, winal, kin},
diff = QuantityMagnitude[DateDifference[date1, date], "Days"];
diff += 13 400 360;
{baktun, diff} = QuotientRemainder[diff, 400 360];
{katun, diff} = QuotientRemainder[diff, 20 360];
{tun, diff} = QuotientRemainder[diff, 360];
{winal, kin} = QuotientRemainder[diff, 20];
StringRiffle[ToString /@ {baktun, katun, tun, winal, kin}, "."]
]
ClearAll[LordOfTheNight]
LordOfTheNight[date_] := Module[{diff, rem},
diff = QuantityMagnitude[DateDifference[date1, date], "Days"];
rem = Mod[diff, 9, 1];
"G" <> ToString[rem]
]
data = {{2004, 06, 19}, {2012, 12, 18}, {2012, 12, 21}, {2019, 01,
19}, {2019, 03, 27}, {2020, 02, 29}, {2020, 03, 01}, {2071, 05,
16}};
tzolkindata = Tzolkin /@ data;
haabdata = Haab /@ data;
longcountdata = LongCount /@ data;
lotndata = LordOfTheNight /@ data;
{DateObject /@ data, tzolkindata, haabdata, longcountdata, lotndata} // Transpose // Grid |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Nim | Nim | import math, strformat, times
const
Tzolk´in = ["Imix´", "Ik´", "Ak´bal", "K´an", "Chikchan", "Kimi", "Manik´", "Lamat", "Muluk", "Ok",
"Chuwen", "Eb", "Ben", "Hix", "Men", "K´ib´", "Kaban", "Etz´nab´", "Kawak", "Ajaw"]
Haab´ = ["Pop", "Wo´", "Sip", "Sotz´", "Sek", "Xul", "Yaxk´in", "Mol", "Ch´en", "Yax",
"Sak´", "Keh", "Mak", "K´ank´in", "Muwan", "Pax", "K´ayab", "Kumk´u", "Wayeb´"]
let
creationTzolk´in = initDateTime(21, mDec, 2012, 0, 0, 0, utc())
zeroHaab´ = initDateTime(2, mApr, 2019, 0, 0, 0, utc())
func daysPerMayanMonth(month: string): int =
if month == "Wayeb´": 5 else: 20
proc tzolkin(gregorian: DateTime): string =
let deltaDays = (gregorian - creationTzolk´in).inDays
let rem = floorMod(deltaDays, 13)
result = $(if rem <= 9: rem + 4 else: rem - 9) & ' ' & Tzolk´in[floorMod(deltaDays - 1, 20)]
proc haab(gregorian: DateTime): string =
let rem = floorMod((gregorian - zeroHaab´).inDays, 365)
let month = Haab´[(rem + 1) div 20]
let dayOfMonth = rem mod 20 + 1
result = if dayOfMonth < daysPerMayanMonth(month): &"{dayOfMonth} {month}" else: &"Chum {month}"
proc toLongDate(gregorian: DateTime): string =
var delta = (gregorian - creationTzolk´in).inDays + 13 * 360 * 400
var baktun = delta div (360 * 400)
delta = delta mod (400 * 360)
let katun = delta div (20 * 360)
delta = delta mod (20 * 360)
let tun = delta div 360
delta = delta mod 360
let winal = delta div 20
let kin = delta mod 20
result = &"{baktun:2} {katun:2} {tun:2} {winal:2} {kin:2}"
proc nightLord(gregorian: DateTime): string =
var rem = (gregorian - creationTzolk´in).inDays mod 9
if rem <= 0: rem += 9
result = 'G' & $rem
when isMainModule:
let testDates = [initDateTime(21, mNov, 1963, 0, 0, 0, utc()),
initDateTime(19, mJun, 2004, 0, 0, 0, utc()),
initDateTime(18, mDec, 2012, 0, 0, 0, utc()),
initDateTime(21, mDec, 2012, 0, 0, 0, utc()),
initDateTime(19, mJan, 2019, 0, 0, 0, utc()),
initDateTime(27, mMar, 2019, 0, 0, 0, utc()),
initDateTime(29, mFeb, 2020, 0, 0, 0, utc()),
initDateTime(01, mMar, 2020, 0, 0, 0, utc()),
initDateTime(16, mMay, 2071, 0, 0, 0, utc()),
initDateTime(02, mfeb, 2020, 0, 0, 0, utc())]
echo "Gregorian Long Count Tzolk´in Haab´ Nightlord"
echo "———————————————————————————————————————————————————————————————"
for date in testDates:
let dateStr = date.format("YYYY-MM-dd")
echo &"{dateStr:14} {date.toLongDate:16} {tzolkin(date):9} {haab(date):14} {nightLord(date)}" |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Perl | Perl | use strict;
use warnings;
use utf8;
binmode STDOUT, ":utf8";
use Math::BaseArith;
use Date::Calc 'Delta_Days';
my @sacred = qw<Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok
Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw>;
my @civil = qw<Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh
Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’>;
my %correlation = (
'gregorian' => '2012-12-21',
'round' => [3,19,263,8],
'long' => 1872000,
);
sub mayan_calendar_round {
my $date = shift;
tzolkin($date), haab($date);
}
sub offset {
my $date = shift;
Delta_Days( split('-', $correlation{'gregorian'}), split('-', $date) );
}
sub haab {
my $date = shift;
my $index = ($correlation{'round'}[2] + offset $date) % 365;
my ($day, $month);
if ($index > 360) {
$day = $index - 360;
$month = $civil[18];
if ($day == 5) {
$day = 'Chum';
$month = $civil[0];
}
} else {
$day = $index % 20;
$month = $civil[int $index / 20];
if ($day == 0) {
$day = 'Chum';
$month = $civil[int (1 + $index) / 20];
}
}
$day, $month
}
sub tzolkin {
my $date = shift;
my $offset = offset $date;
1 + ($offset + $correlation{'round'}[0]) % 13,
$sacred[($offset + $correlation{'round'}[1]) % 20]
}
sub lord {
my $date = shift;
1 + ($correlation{'round'}[3] + offset $date) % 9
}
sub mayan_long_count {
my $date = shift;
my $days = $correlation{'long'} + offset $date;
encode($days, [20,20,20,18,20]);
}
print <<'EOH';
Gregorian Tzolk’in Haab’ Long Lord of
Date # Name Day Month Count the Night
-----------------------------------------------------------------------
EOH
for my $date (<1961-10-06 2004-06-19 2012-12-18 2012-12-21 2019-01-19 2019-03-27 2020-02-29 2020-03-01 2071-05-16>) {
printf "%10s %2s %-9s %4s %-10s %-14s G%d\n",
$date, mayan_calendar_round($date), join('.',mayan_long_count($date)), lord($date);
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Objeck | Objeck |
class Test {
function : Main(args : String[]) ~ Nil {
text := "123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0";
ins := text->Split(",");
each(i : ins) {
in := ins[i]->Trim();
IO.Console->Print(in)->Print(": ");
in := (in->Size() > 0 & in->Get(0) = '-') ? in->SubString(1, in->Size() - 1) : in;
IO.Console->PrintLine((in->Size() < 2 | in->Size() % 2 = 0) ? "Error" : in->SubString((in->Size() - 3) / 2, 3));
};
}
} |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Wren | Wren | import "/big" for BigInt
var iters = 10
// find all primes < 100
System.print("The following numbers less than 100 are prime:")
System.write("2 ")
for (i in 3..99) {
if (BigInt.new(i).isProbablePrime(iters)) System.write("%(i) ")
}
System.print("\n")
var bia = [
BigInt.new("4547337172376300111955330758342147474062293202868155909489"),
BigInt.new("4547337172376300111955330758342147474062293202868155909393")
]
for (bi in bia) {
System.print("%(bi) is %(bi.isProbablePrime(iters) ? "probably prime" : "composite")")
} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #ProDOS | ProDOS |
:a
printline ==========MENU==========
printline 1. Fee Fie
printline 2. Huff Puff
printline 3. Mirror, Mirror
printline 4. Tick, Tock
editvar /newvar /value=a /userinput=1 /title=What page do you want to go to?
if -a- /hasvalue 1 printline You chose a line from the book Jack and the Beanstalk. & exitcurrentprogram 1
if -a- /hasvalue 2 printline You chose a line from the book The Three Little Pigs. & exitcurrentprogram 1
if -a- /hasvalue 3 printline You chose a line from the book Snow White. & exitcurrentprogram 1
if -a- /hasvalue 4 printline You chose a line from the book Beauty and the Beast. & exitcurrentprogram 1
printline You either chose an invalid choice or didn't chose.
editvar /newvar /value=goback /userinput=1 /title=Do you want to chose something else?
if -goback- /hasvalue y goto :a else exitcurrentprogram 1 |
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).
| #Arturo | Arturo | nonMcNuggets: function [lim][
result: new 0..lim
loop range.step:6 1 lim 'x [
loop range.step:9 1 lim 'y [
loop range.step:20 1 lim 'z
-> 'result -- sum @[x y z]
]
]
return result
]
print max nonMcNuggets 100 |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Phix | Phix | with javascript_semantics
include timedate.e
sequence sacred = split("Imix' Ik' Ak'bal K'an Chikchan Kimi Manik' Lamat Muluk Ok Chuwen Eb Ben Hix Men K'ib' Kaban Etz'nab' Kawak Ajaw"),
civil = split("Pop Wo' Sip Sotz' Sek Xul Yaxk'in Mol Ch'en Yax Sak' Keh Mak K'ank'in Muwan' Pax K'ayab Kumk'u Wayeb'"),
date1 = parse_date_string("21/12/2012",{"DD/MM/YYYY"}),
date2 = parse_date_string("2/4/2019",{"DD/MM/YYYY"})
function tzolkin(integer diff)
integer rem = mod(diff,13)
if rem<0 then rem += 13 end if
integer num = iff(rem<=9?rem+4:rem-9)
rem = mod(diff,20)
if rem<=0 then rem += 20 end if
return {num, sacred[rem]}
end function
function haab(integer diff)
integer rem = mod(diff,365)
if rem<0 then rem += 365 end if
string month = civil[floor((rem+1)/20)+1]
integer last = iff(month="Wayeb'"?5:20),
d = mod(rem,20) + 1
return {iff(d<last?sprintf("%d",d):"Chum"), month}
end function
function longCount(integer diff)
diff += 13 * 400 * 360
integer baktun := floor(diff/(400*360))
diff = mod(diff,400*360)
integer katun := floor(diff/(20*360))
diff = mod(diff,20*360)
integer tun = floor(diff/360)
diff = mod(diff,360)
integer winal = floor(diff/20),
kin = mod(diff,20)
return sprintf("%d.%d.%d.%d.%d", {baktun, katun, tun, winal, kin})
end function
function lord(integer diff)
integer rem = mod(diff,9)
if rem<=0 then rem += 9 end if
return sprintf("G%d", rem)
end function
constant dates = {"1961-10-06",
"1963-11-21",
"2004-06-19",
"2012-12-18",
"2012-12-21",
"2019-01-19",
"2019-03-27",
"2020-02-29",
"2020-03-01",
"2071-05-16",
},
headers = """
Gregorian Tzolk'in Haab' Long Lord of
Date # Name Day Month Count the Night
---------- -------- ------------- -------------- ---------
"""
procedure main()
printf(1,headers)
for i=1 to length(dates) do
string dt = dates[i]
timedate td = parse_date_string(dt,{"YYYY-MM-DD"})
integer diff1 = floor(timedate_diff(date1,td,DT_DAY) / (24*60*60)),
diff2 = floor(timedate_diff(date2,td,DT_DAY) / (24*60*60))
{integer n, string s} = tzolkin(diff1)
string {d, m} = haab(diff2),
lc := longCount(diff1),
l := lord(diff1)
printf(1,"%s %2d %-8s %4s %-9s %-14s %s\n", {dt, n, s, d, m, lc, l})
end for
end procedure
main()
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #OCaml | OCaml | let even x = (x land 1) <> 1
let middle_three_digits x =
let s = string_of_int (abs x) in
let n = String.length s in
if n < 3 then failwith "need >= 3 digits" else
if even n then failwith "need odd number of digits" else
String.sub s (n / 2 - 1) 3
let passing = [123; 12345; 1234567; 987654321; 10001; -10001; -123; -100; 100; -12345]
let failing = [1; 2; -1; -10; 2002; -2002; 0]
let print x =
let res =
try (middle_three_digits x)
with Failure e -> "failure: " ^ e
in
Printf.printf "%d: %s\n" x res
let () =
print_endline "Should pass:";
List.iter print passing;
print_endline "Should fail:";
List.iter print failing;
;; |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #zkl | zkl | zkl: var BN=Import("zklBigNum");
zkl: BN("4547337172376300111955330758342147474062293202868155909489").probablyPrime()
True
zkl: BN("4547337172376300111955330758342147474062293202868155909393").probablyPrime()
False |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Prolog | Prolog |
rosetta_menu([], "") :- !. %% Incase of an empty list.
rosetta_menu(Items, SelectedItem) :-
repeat, %% Repeat until everything that follows is true.
display_menu(Items), %% IO
get_choice(Choice), %% IO
number(Choice), %% True if Choice is a number.
nth1(Choice, Items, SelectedItem), %% True if SelectedItem is the 1-based nth member of Items, (fails if Choice is out of range)
!.
display_menu(Items) :-
nl,
foreach( nth1(Index, Items, Item),
format('~w) ~s~n', [Index, Item]) ).
get_choice(Choice) :-
prompt1('Select a menu item by number:'),
read(Choice).
|
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).
| #AWK | AWK |
# syntax: GAWK -f MCNUGGETS_PROBLEM.AWK
# converted from Go
BEGIN {
limit = 100
for (a=0; a<=limit; a+=6) {
for (b=a; b<=limit; b+=9) {
for (c=b; c<=limit; c+=20) {
arr[c] = 1
}
}
}
for (i=limit; i>=0; i--) {
if (!arr[i]+0) {
printf("%d\n",i)
break
}
}
exit(0)
}
|
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Python | Python |
import datetime
def g2m(date, gtm_correlation=True):
"""
Translates Gregorian date into Mayan date, see
https://rosettacode.org/wiki/Mayan_calendar
Input arguments:
date: string date in ISO-8601 format: YYYY-MM-DD
gtm_correlation: GTM correlation to apply if True, Astronomical correlation otherwise (optional, True by default)
Output arguments:
long_date: Mayan date in Long Count system as string
round_date: Mayan date in Calendar Round system as string
"""
# define some parameters and names
correlation = 584283 if gtm_correlation else 584285
long_count_days = [144000, 7200, 360, 20, 1]
tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen',
'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw'] # tzolk'in
haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak',
'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’'] # haab'
gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal()
julian_days = gregorian_days + 1721425
# 1. calculate long count date
long_date = list()
remainder = julian_days - correlation
for days in long_count_days:
result, remainder = divmod(remainder, days)
long_date.append(int(result))
long_date = '.'.join(['{:02d}'.format(d) for d in long_date])
# 2. calculate round calendar date
tzolkin_month = (julian_days + 16) % 20
tzolkin_day = ((julian_days + 5) % 13) + 1
haab_month = int(((julian_days + 65) % 365) / 20)
haab_day = ((julian_days + 65) % 365) % 20
haab_day = haab_day if haab_day else 'Chum'
lord_number = (julian_days - correlation) % 9
lord_number = lord_number if lord_number else 9
round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}'
return long_date, round_date
if __name__ == '__main__':
dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01']
for date in dates:
long, round = g2m(date)
print(date, long, round)
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Oforth | Oforth | : middle3
| s sz |
abs asString dup ->s size ->sz
sz 3 < ifTrue: [ "Too short" println return ]
sz isEven ifTrue: [ "Not odd number of digits" println return ]
sz 3 - 2 / 1+ dup 2 + s extract ; |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #PureBasic | PureBasic | If OpenConsole()
Define i, txt$, choice
Dim txts.s(4)
EnableGraphicalConsole(1) ;- Enable graphical mode in the console
Repeat
ClearConsole()
Restore TheStrings ; Set reads address
For i=1 To 4
Read.s txt$
txts(i)=txt$
ConsoleLocate(3,i): Print(Str(i)+": "+txt$)
Next
ConsoleLocate(3,6): Print("Your choice? ")
choice=Val(Input())
Until choice>=1 And choice<=4
ClearConsole()
ConsoleLocate(3,2): Print("You chose: "+txts(choice))
;
;-Now, wait for the user before ending to allow a nice presentation
ConsoleLocate(3,5): Print("Press ENTER to quit"): Input()
EndIf
End
DataSection
TheStrings:
Data.s "fee fie", "huff And puff", "mirror mirror", "tick tock"
EndDataSection |
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).
| #BASIC | BASIC | 10 DEFINT A-Z: DIM F(100)
20 FOR A=0 TO 100 STEP 6
30 FOR B=A TO 100 STEP 9
40 FOR C=B TO 100 STEP 20
50 F(C)=-1
60 NEXT C,B,A
70 FOR A=100 TO 0 STEP -1
80 IF NOT F(A) THEN PRINT A: END
90 NEXT A |
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).
| #BCPL | BCPL | get "libhdr"
manifest $( limit = 100 $)
let start() be
$( let flags = vec limit
for i = 0 to limit do flags!i := false
for a = 0 to limit by 6
for b = a to limit by 9
for c = b to limit by 20
do flags!c := true
for i = limit to 0 by -1
unless flags!i
$( writef("Maximum non-McNuggets number: %N.*N", i)
finish
$)
$) |
http://rosettacode.org/wiki/Mayan_calendar | Mayan calendar | The ancient Maya people had two somewhat distinct calendar systems.
In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round,
that meshes several sacred and civil cycles; the other is an offset calendar
known as The Long Count, similar in many ways to the Gregorian calendar.
The Calendar Round
The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.
The Tzolk’in
The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names:
Imix’
Ik’
Ak’bal
K’an
Chikchan
Kimi
Manik’
Lamat
Muluk
Ok
Chuwen
Eb
Ben
Hix
Men
K’ib’
Kaban
Etz’nab’
Kawak
Ajaw
Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.
For example:
1 Imix’
2 Ik’
3 Ak’bal
...
11 Chuwen
12 Eb
13 Ben
1 Hix
2 Men
3 K’ib’
... and so on.
The Haab’
The Mayan civil calendar is called the Haab’. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of Wayeb’ (the last month), are usually considered to be
a time of bad luck.
Each month in the Haab’ has a name. The Mayan names for the civil months are:
Pop
Wo’
Sip
Sotz’
Sek
Xul
Yaxk’in
Mol
Ch’en
Yax
Sak’
Keh
Mak
K’ank’in
Muwan
Pax
K’ayab
Kumk’u
Wayeb’ (Short, "unlucky" month)
The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.
Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January
is the first day of our year. In 2019, 1 Pop falls on April 2nd. But,
because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023.
The only really unusual aspect of the Haab’ calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was chum, So you might
have:
...
18 Pop (18th day of the first month)
19 Pop (19th day of the first month)
Chum Wo’ (20th day of the first month)
1 Wo’ (1st day of the second month)
... and so on.
Dates for any particular day are a combination of the Tzolk’in sacred date,
and Haab’ civil date. When put together we get the “Calendar Round.”
Calendar Round dates always have two numbers and two names, and they are
always written in the same order:
(1) the day number in the Tzolk’in
(2) the day name in the Tzolk’in
(3) the day of the month in the Haab’
(4) the month name in the Haab’
A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)
Lords of the Night
A third cycle of nine days honored the nine Lords of the Night; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as G1 through G9. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate G(x) at the end.
The Long Count
Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called “The Long Count.” Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.
The basic unit is a k’in - one day.
A 20 day month is a winal.
18 winal (360 days) is a tun - sometimes referred to as a short year.
20 short years (tun) is a k’atun
20 k’atun is a bak’tun
There are longer units too:
Piktun == 20 Bak’tun (8,000 short years)
Kalabtun == 20 Piktun (160,000 short years)
Kinchiltun == 20 Kalabtun (3,200,000 short years)
For the most part, the Maya only used the blocks of time up to the bak’tun. One
bak’tun is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.
Mayan Date correlations
There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets every 13 bak’tun. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.
The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.
Excerpts taken from, and recommended reading:
From the website of the Foundation for the Advancement of Meso-America Studies, Inc.
Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf
wikipedia: Maya calendar
wikipedia: Mesoamerican Long Count calendar
The Task:
Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations.
Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:
Dec 21, 2012 (Gregorian)
4 Ajaw 3 K’ank’in G9 (Calendar round)
13.0.0.0.0 (Long count)
Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.)
Show the output here, on this page, for at least the following dates:
(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
| #Raku | Raku | my @sacred = <Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok
Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw>;
my @civil = <Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh
Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’>;
my %correlation = :GMT({
:gregorian(Date.new('2012-12-21')),
:round([3,19,263,8]),
:long(1872000)
});
sub mayan-calendar-round ($date) { .&tzolkin, .&haab given $date }
sub offset ($date, $factor = 'GMT') { Date.new($date) - %correlation{$factor}<gregorian> }
sub haab ($date, $factor = 'GMT') {
my $index = (%correlation{$factor}<round>[2] + offset $date) % 365;
my ($day, $month);
if $index > 360 {
$day = $index - 360;
$month = @civil[18];
if $day == 5 {
$day = 'Chum';
$month = @civil[0];
}
} else {
$day = $index % 20;
$month = @civil[$index div 20];
if $day == 0 {
$day = 'Chum';
$month = @civil[(1 + $index) div 20];
}
}
$day, $month
}
sub tzolkin ($date, $factor = 'GMT') {
my $offset = offset $date;
1 + ($offset + %correlation{$factor}<round>[0]) % 13,
@sacred[($offset + %correlation{$factor}<round>[1]) % 20]
}
sub lord ($date, $factor = 'GMT') {
'G' ~ 1 + (%correlation{$factor}<round>[3] + offset $date) % 9
}
sub mayan-long-count ($date, $factor = 'GMT') {
my $days = %correlation{$factor}<long> + offset $date;
reverse $days.polymod(20,18,20,20);
}
# HEADER
say ' Gregorian Tzolk’in Haab’ Long Lord of ';
say ' Date # Name Day Month Count the Night';
say '-----------------------------------------------------------------------';
# DATES
<
1963-11-21
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
2071-05-16
>.map: -> $date {
printf "%10s %2s %-9s %4s %-10s %-14s %6s\n", Date.new($date),
flat mayan-calendar-round($date), mayan-long-count($date).join('.'), lord($date);
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #PARI.2FGP | PARI/GP | middle(n)=my(v=digits(n));if(#v>2&&#v%2,100*v[#v\2]+10*v[#v\2+1]+v[#v\2+2],"no middle 3 digits");
apply(middle,[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]) |
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.