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/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.
| #CoffeeScript | CoffeeScript |
# Array sum helper function.
sum = (array) ->
array.reduce (x, y) -> x + y
md5 = do ->
# Per-round shift amounts.
s = [738695, 669989, 770404, 703814]
s = (s[i >> 4] >> i % 4 * 5 & 31 for i in [0..63])
# Constants cache generated by sine.
K = (Math.floor 2**32 * Math.abs Math.sin i for i in [1..64])
# Bitwise left rotate helper function.
lrot = (x, y) ->
x << y | x >>> 32 - y;
(input) ->
# Initialize values.
d0 = 0x10325476;
a0 = 0x67452301;
b0 = ~d0
c0 = ~a0;
# Convert the message to 32-bit words, little-endian.
M =
for i in [0...input.length] by 4
sum (input.charCodeAt(i + j) << j*8 for j in [0..3])
# Pre-processing: append a 1 bit, then message length % 2^64.
len = input.length * 8
M[len >> 5] |= 128 << len % 32
M[(len + 64 >>> 9 << 4) + 14] = len
# Process the message in chunks of 16 32-bit words.
for x in [0...M.length] by 16
[A, B, C, D] = [a0, b0, c0, d0]
# Main loop.
for i in [0..63]
if i < 16
F = B & C | ~B & D
g = i
else if i < 32
F = B & D | C & ~D
g = i * 5 + 1
else if i < 48
F = B ^ C ^ D
g = i * 3 + 5
else
F = C ^ (B | ~D)
g = i * 7
[A, B, C, D] =
[D, B + lrot(A + F + K[i] + (M[x + g % 16] ? 0), s[i]), B, C]
a0 += A
b0 += B
c0 += C
d0 += D
# Convert the four words back to a string.
return (
for x in [a0, b0, c0, d0]
(String.fromCharCode x >>> 8 * y & 255 for y in [0..3]).join ''
).join ''
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #J | J | require 'dll'
mema 1000
57139856 |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Java | Java | //All of these objects will be deallocated automatically once the program leaves
//their scope and there are no more pointers to the objects
Object foo = new Object(); //Allocate an Object and a reference to it
int[] fooArray = new int[size]; //Allocate all spaces in an array and a reference to it
int x = 0; //Allocate an integer and set its value to 0 |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #PureBasic | PureBasic | Structure Person
Name$
EndStructure
Structure Visits
Datum$
Score$
EndStructure
Structure Merge
Patient.Person
List PVisit.Visits()
EndStructure
NewMap P.Merge()
NewList ID$()
If ReadFile(1,"./Data/patients.csv")=0 : End 1 : EndIf
header=1
While Not Eof(1)
buf1$=ReadString(1)
If header=1 : header=0 : Continue : EndIf
bufId$=StringField(buf1$,1,",")
P(bufId$)\Patient\Name$=StringField(buf1$,2,",")
AddElement(ID$()) : ID$()=bufId$
Wend
CloseFile(1)
If ReadFile(2,"./Data/visits.csv")=0 : End 2 : EndIf
header=1
While Not Eof(2)
buf1$=ReadString(2)
If header=1 : header=0 : Continue : EndIf
bufId$=StringField(buf1$,1,",")
AddElement(P(bufId$)\PVisit())
P(bufId$)\PVisit()\Datum$=StringField(buf1$,2,",")
P(bufId$)\PVisit()\Score$=StringField(buf1$,3,",")
Wend
CloseFile(2)
If OpenConsole()=0 : End 3 : EndIf
SortList(ID$(),#PB_Sort_Ascending)
PrintN("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |")
ForEach ID$()
Print("| "+LSet(ID$(),11))
Print("| "+LSet(P(ID$())\Patient\Name$,9)+"|")
SortStructuredList(P(ID$())\PVisit(),#PB_Sort_Ascending,OffsetOf(Visits\Datum$),TypeOf(Visits\Datum$))
ForEach P(ID$())\PVisit()
scs.f+ValF(p(ID$())\PVisit()\Score$) : c+Bool(ValF(p(ID$())\PVisit()\Score$))
Next
If LastElement(P(ID$())\PVisit())
sca.f=scs/c
Print(" "+LSet(P(ID$())\PVisit()\Datum$,10)+" |")
Print(RSet(StrF(scs,1),10)+" |")
If Not IsNAN(sca) : Print(RSet(StrF(sca,2),10)+" |") : Else : Print(Space(11)+"|") : EndIf
Else
Print(Space(12)+"|"+Space(11)+"|"+Space(11)+"|")
EndIf
PrintN("") : scs=0 : c=0
Next
Input() |
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.
| #D | D | import std.stdio, std.traits, std.conv;
string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) {
auto s = n < 0 ? n.text[1 .. $] : n.text;
auto len = s.length;
if (len < 3 || len % 2 == 0)
return "Need odd and >= 3 digits";
auto mid = len / 2;
return s[mid - 1 .. mid + 2];
}
void main() {
immutable passing = [123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, long.min, long.max];
foreach (immutable n; passing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
immutable failing = [1, 2, -1, -10, 2002, -2002, 0,int.min,int.max];
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
} |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Python | Python |
'''
Minesweeper game.
There is an n by m grid that has a random number of between 20% to 60%
of randomly hidden mines that need to be found.
Positions in the grid are modified by entering their coordinates
where the first coordinate is horizontal in the grid and the second
vertical. The top left of the grid is position 1,1; the bottom right is
at n,m.
* The total number of mines to be found is shown at the beginning of the
game.
* Each mine occupies a single grid point, and its position is initially
unknown to the player
* The grid is shown as a rectangle of characters between moves.
* You are initially shown all grids as obscured, by a single dot '.'
* You may mark what you think is the position of a mine which will show
as a '?'
* You can mark what you think is free space by entering its coordinates.
:* If the point is free space then it is cleared, as are any adjacent
points that are also free space- this is repeated recursively for
subsequent adjacent free points unless that point is marked as a mine
or is a mine.
::* Points marked as a mine show as a '?'.
::* Other free points show as an integer count of the number of adjacent
true mines in its immediate neighbourhood, or as a single space ' ' if the
free point is not adjacent to any true mines.
* Of course you loose if you try to clear space that starts on a mine.
* You win when you have correctly identified all mines.
When prompted you may:
Toggle where you think a mine is at position x, y:
m <x> <y>
Clear the grid starting at position x, y (and print the result):
c <x> <y>
Print the grid so far:
p
Resign
r
Resigning will first show the grid with an 'N' for unfound true mines, a
'Y' for found true mines and a '?' for where you marked clear space as a
mine
'''
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgrid * ygrid
minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))
grid = set(product(range(xgrid), range(ygrid)))
mines = set(random.sample(grid, minecount))
show = {xy:'.' for xy in grid}
return grid, mines, show
def printgrid(show, gridsize=gridsize):
xgrid, ygrid = gridsize
grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid))
for y in range(ygrid))
print( grid )
def resign(showgrid, mines, markedmines):
for m in mines:
showgrid[m] = 'Y' if m in markedmines else 'N'
def clear(x,y, showgrid, grid, mines, markedmines):
if showgrid[(x, y)] == '.':
xychar = str(sum(1
for xx in (x-1, x, x+1)
for yy in (y-1, y, y+1)
if (xx, yy) in mines ))
if xychar == '0': xychar = '.'
showgrid[(x,y)] = xychar
for xx in (x-1, x, x+1):
for yy in (y-1, y, y+1):
xxyy = (xx, yy)
if ( xxyy != (x, y)
and xxyy in grid
and xxyy not in mines | markedmines ):
clear(xx, yy, showgrid, grid, mines, markedmines)
if __name__ == '__main__':
grid, mines, showgrid = gridandmines()
markedmines = set([])
print( __doc__ )
print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) )
printgrid(showgrid)
while markedmines != mines:
inp = raw_input('m x y/c x y/p/r: ').strip().split()
if inp:
if inp[0] == 'm':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in markedmines:
markedmines.remove((x,y))
showgrid[(x,y)] = '.'
else:
markedmines.add((x,y))
showgrid[(x,y)] = '?'
elif inp[0] == 'p':
printgrid(showgrid)
elif inp[0] == 'c':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in mines | markedmines:
print( '\nKLABOOM!! You hit a mine.\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
clear(x,y, showgrid, grid, mines, markedmines)
printgrid(showgrid)
elif inp[0] == 'r':
print( '\nResigning!\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
print( '\nYou got %i and missed %i of the %i mines'
% (len(mines.intersection(markedmines)),
len(markedmines.difference(mines)),
len(mines)) ) |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
x=y="1'2'3'4'5'6'7'8'9'10'11'12"
LOOP n,col=x,cnt=""
skip=n-1
LOOP m,row=y
IF (m==skip) THEN
td=""
ELSE
td=col*row
coleqrow=col*n
IF (td.lt.#coleqrow) td=""
ENDIF
td=CENTER (td,+3," ")
cnt=APPEND (cnt,td," ")
ENDLOOP
col=CENTER (col,+3," ")
PRINT col,cnt
ENDLOOP
|
http://rosettacode.org/wiki/Metaprogramming | Metaprogramming | Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
| #Z80_Assembly | Z80 Assembly | macro xchg,regpair1,regpair2
;swaps the contents of two registers.
push regpair1
push regpair2
pop regpair1
pop regpair2
endm |
http://rosettacode.org/wiki/Metaprogramming | Metaprogramming | Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
| #zkl | zkl | #define name [0|1]
#if [0|1|name]
#else, #endif |
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)
| #FreeBASIC | FreeBASIC | ' version 29-11-2016
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function mul_mod(a As ULongInt, b As ULongInt, modulus As ULongInt) As ULongInt
' returns a * b mod modulus
Dim As ULongInt x, y = a ' a mod modulus, but a is already smaller then modulus
While b > 0
If (b And 1) = 1 Then
x = (x + y) Mod modulus
End If
y = (y Shl 1) Mod modulus
b = b Shr 1
Wend
Return x
End Function
Function pow_mod(b As ULongInt, power As ULongInt, modulus As ULongInt) As ULongInt
' returns b ^ power mod modulus
Dim As ULongInt x = 1
While power > 0
If (power And 1) = 1 Then
' x = (x * b) Mod modulus
x = mul_mod(x, b, modulus)
End If
' b = (b * b) Mod modulus
b = mul_mod(b, b, modulus)
power = power Shr 1
Wend
Return x
End Function
Function miller_rabin_test(n As ULongInt, k As Integer) As Byte
If n > 9223372036854775808ull Then ' limit 2^63, pow_mod/mul_mod can't handle bigger numbers
Print "number is to big, program will end"
Sleep
End
End If
' 2 is a prime, if n is smaller then 2 or n is even then n = composite
If n = 2 Then Return TRUE
If (n < 2) OrElse ((n And 1) = 0) Then Return FALSE
Dim As ULongInt a, x, n_one = n - 1, d = n_one
Dim As UInteger s
While (d And 1) = 0
d = d Shr 1
s = s + 1
Wend
While k > 0
k = k - 1
a = Int(Rnd * (n -2)) +2 ' 2 <= a < n
x = pow_mod(a, d, n)
If (x = 1) Or (x = n_one) Then Continue While
For r As Integer = 1 To s -1
x = pow_mod(x, 2, n)
If x = 1 Then Return FALSE
If x = n_one Then Continue While
Next
If x <> n_one Then Return FALSE
Wend
Return TRUE
End Function
' ------=< MAIN >=------
Randomize Timer
Dim As Integer total
Dim As ULongInt y, limit = 2^63-1
For y = limit - 1000 To limit
If miller_rabin_test(y, 5) = TRUE Then
total = total + 1
Print y,
End If
Next
Print : Print
Print total; " primes between "; limit - 1000; " and "; y -1
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Factor | Factor | USING: formatting grouping io kernel math math.extras
math.ranges math.statistics prettyprint sequences ;
! Take the cumulative sum of the mobius sequence to avoid
! summing lower terms over and over.
: mertens-upto ( n -- seq ) [1,b] [ mobius ] map cum-sum ;
"The first 199 terms of the Mertens sequence:" print
199 mertens-upto " " prefix 20 group
[ [ "%3s" printf ] each nl ] each nl
"In the first 1,000 terms of the Mertens sequence there are:"
print 1000 mertens-upto
[ [ zero? ] count bl pprint bl "zeros." print ]
[
2 <clumps> [ first2 [ 0 = not ] [ zero? ] bi* and ] count bl
pprint bl "zero crossings." print
] bi |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Forth | Forth | : AMOUNT 1000 ;
variable mertens AMOUNT cells allot
: M 1- cells mertens + ; \ 1-indexed array
: make-mertens
1 1 M !
2 begin dup AMOUNT <= while
1 over M !
2 begin over over >= while
over over / M @
2 pick M @ swap -
2 pick M !
1+ repeat
drop
1+ repeat
drop
;
: print-row
begin dup while
swap dup M @ 3 .r 1+
swap 1-
repeat
drop
;
: print-table ." "
1 9 print-row cr
begin dup 100 < while 10 print-row cr repeat
drop
;
: find-zero-cross
0 0
1 begin dup AMOUNT <= while
dup M @ 0= if
swap 1+ swap
dup 1- M @ 0<> if rot 1+ -rot then
then
1+
repeat
drop
;
make-mertens
." The first 99 Mertens numbers are:" cr print-table
find-zero-cross
." M(N) is zero " . ." times." cr
." M(N) crosses zero " . ." times." cr
bye |
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.
| #Clojure | Clojure | (defn menu [prompt choices]
(if (empty? choices)
""
(let [menutxt (apply str (interleave
(iterate inc 1)
(map #(str \space % \newline) choices)))]
(println menutxt)
(print prompt)
(flush)
(let [index (read-string (read-line))]
; verify
(if (or (not (integer? index))
(> index (count choices))
(< index 1))
; try again
(recur prompt choices)
; ok
(nth choices (dec index)))))))
(println "You chose: "
(menu "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.
| #Common_Lisp | Common Lisp | (defpackage #:md5
(:use #:cl))
(in-package #:md5)
(require :babel)
(deftype word () '(unsigned-byte 32))
(deftype octet () '(unsigned-byte 8))
(deftype octets () '(vector octet))
(defparameter *s*
(make-array 16 :element-type 'word
:initial-contents '(7 12 17 22
5 9 14 20
4 11 16 23
6 10 15 21)))
(defun s (i)
(declare ((integer 0 63) i))
(aref *s* (+ (ash (ash i -4) 2)
(ldb (byte 2 0) i))))
(defparameter *k*
(loop with result = (make-array 64 :element-type 'word)
for i from 0 below 64
do (setf (aref result i) (floor (* (ash 1 32) (abs (sin (1+ (float i 1d0)))))))
finally (return result)))
(defun wrap (bits integer)
(declare (fixnum bits) (integer integer))
(ldb (byte bits 0) integer))
(defun integer->8octets (integer)
(declare (integer integer))
(loop for n = (wrap 64 integer) then (ash n -8)
repeat 8
collect (wrap 8 n)))
(defun pad-octets (octets)
(declare (octets octets))
(let* ((octets-length (length octets))
(zero-pad-length (- 64 (mod (+ octets-length 9) 64)))
(zero-pads (loop repeat zero-pad-length collect 0)))
(concatenate 'octets octets '(#x80) zero-pads (integer->8octets (* 8 octets-length)))))
(defun octets->words (octets)
(declare (octets octets))
(loop with result = (make-array (/ (length octets) 4) :element-type 'word)
for n from 0 below (length octets) by 4
for i from 0
do (setf (aref result i)
(dpb (aref octets (+ n 3)) (byte 8 24)
(dpb (aref octets (+ n 2)) (byte 8 16)
(dpb (aref octets (1+ n)) (byte 8 8)
(dpb (aref octets n) (byte 8 0) 0)))))
finally (return result)))
(defun words->octets (&rest words)
(loop for word of-type word in words
collect (ldb (byte 8 0) word)
collect (ldb (byte 8 8) word)
collect (ldb (byte 8 16) word)
collect (ldb (byte 8 24) word)))
(defun left-rotate (x c)
(declare (integer x) (fixnum c))
(let ((x (wrap 32 x)))
(wrap 32 (logior (ash x c)
(ash x (- c 32))))))
(defun md5 (string)
(declare (string string))
(loop with m = (octets->words (pad-octets (babel:string-to-octets string)))
with a0 of-type word = #x67452301
with b0 of-type word = #xefcdab89
with c0 of-type word = #x98badcfe
with d0 of-type word = #x10325476
for j from 0 below (length m) by 16
do (loop for a of-type word = a0 then d
and b of-type word = b0 then new-b
and c of-type word = c0 then b
and d of-type word = d0 then c
for i from 0 below 64
for new-b = (multiple-value-bind (f g)
(ecase (ash i -4)
(0 (values (wrap 32 (logior (logand b c)
(logand (lognot b) d)))
i))
(1 (values (wrap 32 (logior (logand d b)
(logand (lognot d) c)))
(wrap 4 (1+ (* 5 i)))))
(2 (values (wrap 32 (logxor b c d))
(wrap 4 (+ (* 3 i) 5))))
(3 (values (wrap 32 (logxor c
(logior b (lognot d))))
(wrap 4 (* 7 i)))))
(declare (word f g))
(wrap 32 (+ b (left-rotate (+ a f (aref *k* i) (aref m (+ j g)))
(s i)))))
finally (setf a0 (wrap 32 (+ a0 a))
b0 (wrap 32 (+ b0 b))
c0 (wrap 32 (+ c0 c))
d0 (wrap 32 (+ d0 d))))
finally (return (with-output-to-string (s)
(dolist (o (words->octets a0 b0 c0 d0))
(format s "~(~2,'0X~)" o))))))
(defun test-cases ()
(assert (string= "d41d8cd98f00b204e9800998ecf8427e"
(md5 "")))
(assert (string= "0cc175b9c0f1b6a831c399e269772661"
(md5 "a")))
(assert (string= "900150983cd24fb0d6963f7d28e17f72"
(md5 "abc")))
(assert (string= "f96b697d7cb7938d525a2f31aaf161d0"
(md5 "message digest")))
(assert (string= "c3fcd3d76192e4007dfb496cca67e13b"
(md5 "abcdefghijklmnopqrstuvwxyz")))
(assert (string= "d174ab98d277d9f5a5611c2c9f419d9f"
(md5 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")))
(assert (string= "57edf4a22be3c955ac49da2e2107b67a"
(md5 "12345678901234567890123456789012345678901234567890123456789012345678901234567890")))) |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Julia | Julia |
matrix = Array{Float64,2}(100,100)
matrix[31,42] = pi
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Kotlin | Kotlin | // version 1.1.2
class MyClass(val myInt: Int) {
// in theory this method should be called automatically prior to GC
protected fun finalize() {
println("MyClass being finalized...")
}
}
fun myFun() {
val mc: MyClass = MyClass(2) // new non-nullable MyClass object allocated on the heap
println(mc.myInt)
var mc2: MyClass? = MyClass(3) // new nullable MyClass object allocated on the heap
println(mc2?.myInt)
mc2 = null // allowed as mc2 is nullable
println(mc2?.myInt)
// 'mc' and 'mc2' both become eligible for garbage collection here as no longer used
}
fun main(args: Array<String>) {
myFun()
Thread.sleep(3000) // allow time for GC to execute
val i: Int = 4 // new non-nullable Int allocated on stack
println(i)
var j: Int? = 5 // new nullable Int allocated on heap
println(j)
j = null // allowed as 'j' is nullable
println(j)
// 'j' becomes eligible for garbage collection here as no longer used
} |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #Python | Python | # to install pandas library go to cmd prompt and type:
# cd %USERPROFILE%\AppData\Local\Programs\Python\Python38-32\Scripts\
# pip install pandas
import pandas as pd
# load data from csv files
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".")
''' # load data hard coded, create data frames
import io
str_patients = """PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
"""
df_patients = pd.read_csv(io.StringIO(str_patients), sep = ",", decimal=".")
str_visits = """PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
"""
df_visits = pd.read_csv(io.StringIO(str_visits), sep = ",", decimal=".")
'''
# typecast from string to datetime so .agg can 'max' it
df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])
# merge on PATIENT_ID
df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')
# groupby is an intermediate object
df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)
# note: you can use 'sum' instead of the lambda function but that returns NaN as 0 (zero)
df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})
print(df_result) |
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.
| #Dart | Dart |
import'dart:math';
int length(int x)
{
int i,y;
for(i=0;;i++)
{
y=pow(10,i);
if(x%y==x)
break;
}
return i;
}
int middle(int x,int l)
{
int a=(x/10)-((x%10)/10);
int b=a%(pow(10,l-2));
int l2=length(b);
if(l2==3)
{
return b;
}
if(l2!=3)
{
return middle(b,l2);
}
return 0;
}
main()
{
int x=-100,y;
if(x<0)
x=-x;
int l=length(x);
if(l.isEven||x<100)
{print('error');}
if(l==3)
{print('$x');}
if(l.isOdd&& x>100)
{
y=middle(x,l);
print('$y');
}
}
|
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Racket | Racket |
#lang racket
(require math/array)
;board uses arrays directly, but maintaining an abstraction is nice
(define (board-ref b row col) (array-ref b (vector row col)))
(define (board-rows b) (vector-ref (array-shape b) 0))
(define (board-cols b) (vector-ref (array-shape b) 1))
(define (on-board? b row col)
(and (<= 0 row (sub1 (board-rows b)))
(<= 0 col (sub1 (board-cols b)))))
(define (board->lists b) (array->list* b))
;run on adjacent board positions
(define-syntax (for-adj stx)
(syntax-case stx ()
[(_ b (r row) (c col) diag? body ...)
(with-syntax ([is (if (syntax->datum #'diag?) #''(0 0 1 1 1 -1 -1 -1) #''(0 0 1 -1))]
[js (if (syntax->datum #'diag?) #''(1 -1 0 -1 1 0 -1 1) #''(1 -1 0 0))])
#'(for ([i is] [j js])
(let ([r (+ row i)]
[c (+ col j)])
(when (on-board? b r c)
body ...))))]))
;mark is either hidden, assume-mine, or clear
;n is int equal to # adj mines or -1 for mine
(struct pos ([mark #:mutable] n) #:transparent)
(define (mine? p) (= (pos-n p) -1))
(define (mine-count b) (apply + (array->list (array-map (λ (p) (if (mine? p) 1 0)) b))))
;hidden0? is needed because only spaces with no mines in them and no mines adjacent
;to them are cleared recursively
(define (hidden0? p)
(and (symbol=? (pos-mark p) 'hidden)
(zero? (pos-n p))))
(define (show-pos p)
(match-let ([(pos m n) p])
(case m
[(hidden) "."]
[(assume-mine) "?"]
[(clear) (if (zero? n) " " (number->string n))]
[else (error "illegal mark" m)])))
;put "|" around positions
(define (show-board b)
(for ([row (board->lists b)])
(displayln (format "|~a|" (string-join (map show-pos row) "|")))))
;winning = every position is either cleared or a hidden mine
(define (win? b)
(for*/and ([r (range 0 (board-rows b))]
[c (range 0 (board-cols b))])
(let ([p (board-ref b r c)])
(or (symbol=? (pos-mark p) 'clear)
(mine? p)))))
(define (init-board rows cols)
(let ([chance (+ (/ (random) 10) 0.1)]
;empty board
[b (array->mutable-array (build-array (vector rows cols)
(λ (x) (pos 'hidden 0))))])
;loop whole board
(for* ([row (range 0 rows)]
[col (range 0 cols)])
(when (< (random) chance)
;put a mine
(array-set! b (vector row col) (pos 'hidden -1))
;increment adjacent mine counts unless that adjacent position is a mine
(for-adj b (r row) (c col) #t
(let ([p (board-ref b r c)])
(unless (mine? p)
(array-set! b (vector r c) (pos 'hidden (add1 (pos-n p)))))))))
b))
;only clear position if it's not a mine
;only continue recursing when it's a hidden0?
(define (try-clear! p)
(cond [(mine? p) #f]
[(hidden0? p) (set-pos-mark! p 'clear) #t]
[else (set-pos-mark! p 'clear) #f]))
;the following player move functions return boolean where #f = lose, #t = still going
;assuming can never directly lose ((void) == #t from the set!)
;make sure to not allow overwriting an already cleared position
(define (toggle-assume! b row col)
(let ([p (board-ref b row col)])
(set-pos-mark! p (case (pos-mark p)
[(assume-mine) 'hidden]
[(hidden) 'assume-mine]
[(clear) 'clear]
[else (error "invalid mark" (pos-mark p))]))))
;clearing loses when the chosen position is a mine
;void = #t as far as if works, so no need to return #t
(define (clear! b row col)
(let ([p (board-ref b row col)])
(and (not (mine? p))
;not a mine, so recursively check adjacents, and maintain list of visited positions
;to avoid infinite loops
(let ([seen '()])
;clear the chosen position first, only continuing if it's a 0
(when (try-clear! p)
(let clear-adj ([row row] [col col])
(for-adj b (r row) (c col) #f
;make sure its not seen
(when (and (not (member (list r c) seen))
(try-clear! (board-ref b r c)))
;it was cleared, so loop after saving this position as being seen
(set! seen (cons (list r c) seen))
(clear-adj r c)))))))))
(define assume-string "a")
(define clear-string "c")
;validates input...returns either #f for an error or the move to execute
(define (parse-and-create-move! b s)
(match (string-split s)
[(list type row col)
(let ([row (string->number row)]
[col (string->number col)])
(and (number? row)
(number? col)
(let ([row (sub1 row)]
[col (sub1 col)])
(and (on-board? b row col)
(or (and (string=? type assume-string) (λ () (toggle-assume! b row col)))
(and (string=? type clear-string) (λ () (clear! b row col))))))))]
[else #f]))
(define (run)
(displayln (string-append "--- Enter one of:\n"
(format "--- \"~a <row> <col>\" to clear at (row,col), or~n" clear-string)
(format (string-append "--- \"~a <row> <col>\" to flag a possible mine "
"(or clear a flag) at (row,col).~n")
assume-string)))
(let ([b (init-board 4 6)])
(displayln (format "There are ~a mines.~n" (mine-count b)))
(let run ()
(show-board b)
(display "enter move: ")
;parse either failed or gave the procedure to execute
(let ([proc? (parse-and-create-move! b (read-line))])
;was the parse successful?
(if proc?
;then run it
(if (proc?)
;didn't lose, so either we won or we're not done
(if (win? b) (displayln "CLEAR!") (run))
(displayln "BOOM!"))
;parse failed
(run))))))
|
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #TypeScript | TypeScript |
// Multiplication tables
function intToString(n: number, wdth: number): string {
sn = Math.floor(n).toString();
len = sn.length;
return (wdth < len ? "#".repeat(wdth) : " ".repeat(wdth - len) + sn);
}
var n = 12;
console.clear();
for (j = 1; j < n; j++)
process.stdout.write(intToString(j, 3) + " ");
console.log(intToString(n, 3));
console.log("----".repeat(n) + "+");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
process.stdout.write(j < i ? " " : intToString(i * j, 3) + " ");
console.log("| " + intToString(i, 2));
}
|
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)
| #FunL | FunL | import util.rnd
def isProbablyPrimeMillerRabin( n, k ) =
d = n - 1
s = 0
while 2|d
s++
d /= 2
repeat k
a = rnd( 2, n )
x = a^d mod n
if x == 1 or x == n - 1 then continue
repeat s - 1
x = x^2 mod n
if x == 1 then return false
if x == n - 1 then break
else
return false
true
for i <- 3..100
if isProbablyPrimeMillerRabin( i, 5 )
println( i ) |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Fortran | Fortran | program Mertens
implicit none
integer M(1000), n, k, zero, cross
C Generate Mertens numbers
M(1) = 1
do 10 n=2, 1000
M(n) = 1
do 10 k=2, n
M(n) = M(n) - M(n/k)
10 continue
C Print table
write (*,"('The first 99 Mertens numbers are:')")
write (*,"(' ')",advance='no')
k = 9
do 20 n=1, 99
write (*,'(I3)',advance='no') M(n)
k = k-1
if (k .EQ. 0) then
k=10
write (*,*)
end if
20 continue
C Calculate zeroes and crossings
zero = 0
cross = 0
do 30 n=2, 1000
if (M(n) .EQ. 0) then
zero = zero + 1
if (M(n-1) .NE. 0) cross = cross+1
end if
30 continue
40 format("M(N) is zero ",I2," times.")
write (*,40) zero
50 format("M(N) crosses zero ",I2," times.")
write (*,50) cross
end program |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Test-Prompt-Menu.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num-Options USAGE UNSIGNED-INT VALUE 4.
01 Example-Menu.
03 Example-Options-Data.
05 FILLER PIC X(30) VALUE "fee fie".
05 FILLER PIC X(30) VALUE "huff and puff".
05 FILLER PIC X(30) VALUE "mirror mirror".
05 FILLER PIC X(30) VALUE "tick tock".
03 Example-Options-Values REDEFINES Example-Options-Data.
05 Example-Options PIC X(30) OCCURS 4 TIMES.
01 Chosen-Option PIC X(30).
PROCEDURE DIVISION.
CALL "Prompt-Menu" USING BY CONTENT Num-Options
BY CONTENT Example-Menu
BY REFERENCE Chosen-Option
DISPLAY "You chose: " Chosen-Option
GOBACK
.
END PROGRAM Test-Prompt-Menu.
IDENTIFICATION DIVISION.
PROGRAM-ID. Prompt-Menu.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 User-Input USAGE UNSIGNED-INT.
01 Input-Flag PIC X.
88 Valid-Input VALUE "Y".
01 Options-Index USAGE UNSIGNED-INT.
01 Index-Display PIC Z(10).
LINKAGE SECTION.
01 Num-Options USAGE UNSIGNED-INT.
01 Menu-Options.
03 Options-Table PIC X(30) OCCURS 0 TO 10000000 TIMES
DEPENDING ON Num-Options.
01 Chosen-Option PIC X(30).
PROCEDURE DIVISION USING Num-Options Menu-Options Chosen-Option.
Main.
IF Num-Options = 0
MOVE SPACES TO Chosen-Option
GOBACK
END-IF
PERFORM UNTIL Valid-Input
PERFORM Display-Menu-Options
DISPLAY "Choose an option: " WITH NO ADVANCING
ACCEPT User-Input
PERFORM Validate-Input
END-PERFORM
MOVE Options-Table (User-Input) TO Chosen-Option
GOBACK
.
Display-Menu-Options.
PERFORM VARYING Options-Index FROM 1 BY 1
UNTIL Num-Options < Options-Index
MOVE Options-Index TO Index-Display
DISPLAY
Index-Display ". " Options-Table (Options-Index)
END-DISPLAY
END-PERFORM
.
Validate-Input.
IF User-Input = 0 OR > Num-Options
DISPLAY "Invalid input."
ELSE
SET Valid-Input TO TRUE
END-IF
.
END PROGRAM Prompt-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.
| #D | D | import std.bitmanip, core.stdc.string, std.conv, std.math, std.array,
std.string;
version (D_InlineAsm_X86) {} else {
static assert(false, "For X86 machine only.");
}
// CTFE construction of transform expressions.
uint S(in uint n) pure nothrow @safe @nogc {
static immutable aux = [7u, 12, 17, 22, 5, 9, 14, 20, 4, 11,
16, 23, 6, 10, 15, 21];
return aux[(n / 16) * 4 + (n % 4)];
}
uint K(in uint n) pure nothrow @safe @nogc {
uint r = 0;
if (n <= 15)
r = n;
else if (n <= 31)
r = 5 * n + 1;
else if (n <= 47)
r = 3 * n + 5;
else
r = 7 * n;
return r % 16;
}
uint T(in uint n) pure nothrow @nogc {
return cast(uint)(abs(sin(n + 1.0L)) * (2UL ^^ 32));
}
string[] ABCD(in int n) pure nothrow {
enum abcd = ["EAX", "EBX", "ECX", "EDX"];
return abcd[(64 - n) % 4 .. 4] ~ abcd[0 .. (64 - n) % 4];
}
string SUB(in int n, in string s) pure nothrow {
return s
.replace("ax", n.ABCD[0])
.replace("bx", n.ABCD[1])
.replace("cx", n.ABCD[2])
.replace("dx", n.ABCD[3]);
}
// FF, GG, HH & II expressions part 1 (F, G, H, I).
string fghi1(in int n) pure nothrow @nogc {
switch (n / 16) {
case 0:
// (bb & cc) | (~bb & dd)
return q{
mov ESI, bx;
mov EDI, bx;
not ESI;
and EDI, cx;
and ESI, dx;
or EDI, ESI;
add ax, EDI;
};
case 1:
// (dd & bb) | (~dd & cc)
return q{
mov ESI, dx;
mov EDI, dx;
not ESI;
and EDI, bx;
and ESI, cx;
or EDI, ESI;
add ax, EDI;
};
case 2: // (bb ^ cc ^ dd)
return q{
mov EDI, bx;
xor EDI, cx;
xor EDI, dx;
add ax, EDI;
};
case 3: // (cc ^ (bb | ~dd))
return q{
mov EDI, dx;
not EDI;
or EDI, bx;
xor EDI, cx;
add ax, EDI;
};
default:
assert(false);
}
}
// FF, GG, HH & II expressions part 2.
string fghi2(in int n) pure nothrow {
return q{
add ax, [EBP + 4 * KK];
add ax, TT;
} ~ n.fghi1;
}
// FF, GG, HH & II expressions prepended with previous parts
// & subsitute ABCD.
string FGHI(in int n) pure nothrow {
// aa = ((aa << SS)|( aa >>> (32 - SS))) + bb = ROL(aa, SS) + bb
return SUB(n, n.fghi2 ~ q{
rol ax, SS;
add ax, bx;
});
}
string genExpr(uint n) pure nothrow {
return FGHI(n)
.replace("SS", n.S.text)
.replace("KK", n.K.text)
.replace("TT", "0x" ~ to!string(n.T, 16));
}
string genTransformCode(int n) pure nothrow {
return (n < 63) ? n.genExpr ~ genTransformCode(n + 1) : n.genExpr;
}
enum string coreZMD5 = 0.genTransformCode;
struct ZMD5 {
uint[4] state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
ulong count;
ubyte[64] buffer;
ubyte[64] padding = [
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0];
private void transform(ubyte* block) pure nothrow @nogc {
uint[16] x = void;
version (BigEndian) {
foreach (immutable i; 0 .. 16)
x[i] = littleEndianToNative!uint(*cast(ubyte[4]*)&block[i * 4]);
} else {
(cast(ubyte*)x.ptr)[0 .. 64] = block[0 .. 64];
}
auto pState = state.ptr;
auto pBuffer = x.ptr;
asm pure nothrow @nogc {
mov ESI, pState[EBP];
mov EDX, [ESI + 3 * 4];
mov ECX, [ESI + 2 * 4];
mov EBX, [ESI + 1 * 4];
mov EAX, [ESI + 0 * 4];
push EBP;
push ESI;
mov EBP, pBuffer[EBP];
}
mixin("asm pure nothrow @nogc { " ~ coreZMD5 ~ "}");
asm pure nothrow @nogc {
pop ESI;
pop EBP;
add [ESI + 0 * 4], EAX;
add [ESI + 1 * 4], EBX;
add [ESI + 2 * 4], ECX;
add [ESI + 3 * 4], EDX;
}
x[] = 0;
}
void update(in void[] input) pure nothrow @nogc {
auto inputLen = input.length;
uint index = (count >> 3) & 0b11_1111U;
count += inputLen * 8;
immutable uint partLen = 64 - index;
uint i;
if (inputLen >= partLen) {
memcpy(&buffer[index], input.ptr, partLen);
transform(buffer.ptr);
for (i = partLen; i + 63 < inputLen; i += 64)
transform((cast(ubyte[])input)[i .. i + 64].ptr);
index = 0;
} else
i = 0;
if (inputLen - i)
memcpy(&buffer[index], &input[i], inputLen - i);
}
void finish(ref ubyte[16] digest) pure nothrow @nogc {
ubyte[8] bits = void;
bits[0 .. 8] = nativeToLittleEndian(count)[];
immutable uint index = (count >> 3) & 0b11_1111U;
immutable uint padLen = (index < 56) ?
(56 - index) : (120 - index);
update(padding[0 .. padLen]);
update(bits);
digest[0 .. 4] = nativeToLittleEndian(state[0])[];
digest[4 .. 8] = nativeToLittleEndian(state[1])[];
digest[8 .. 12] = nativeToLittleEndian(state[2])[];
digest[12 .. 16] = nativeToLittleEndian(state[3])[];
// Zeroize sensitive information.
memset(&this, 0, ZMD5.sizeof);
}
}
string getDigestString(in void[][] data...) pure {
ZMD5 ctx;
foreach (datum; data)
ctx.update(datum);
ubyte[16] digest;
ctx.finish(digest);
return format("%-(%02X%)", digest);
}
void main() { // Benchmark code --------------
import std.stdio, std.datetime, std.digest.md;
writefln(`md5 digest("") = %-(%02X%)`, "".md5Of);
writefln(`zmd5 digest("") = %s`, "".getDigestString);
enum megaBytes = 512;
writefln("\nTest performance / message size %dMBytes:", megaBytes);
auto data = new float[megaBytes * 0x40000 + 13];
StopWatch sw;
sw.start;
immutable d1 = data.md5Of;
sw.stop;
immutable time1 = sw.peek.msecs / 1000.0;
writefln("digest(data) = %-(%02X%)", d1);
writefln("std.md5: %8.2f M/sec ( %8.2f secs)",
megaBytes / time1, time1);
sw.reset;
sw.start;
immutable d2 = data.getDigestString;
sw.stop;
immutable time2 = sw.peek.msecs / 1000.0;
writefln("digest(data) = %s", d2);
writefln("zmd5 : %8.2f M/sec ( %8.2f secs)",
megaBytes / time2, time2);
} |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Lingo | Lingo | -- Create a ByteArray of 100 Kb (pre-filled with 0 bytes)
ba = byteArray(102400)
-- Lingo uses garbage-collection, so allocated memory is released when no more references exist.
-- For the above variable ba, this can be achieved by calling:
ba = VOID |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Buffer Clear Mem1 as Byte*12345
Print Len(Mem1)
Hex Mem1(0) ' print in Hex address of first element
Print Mem1(Len(Mem1)-1)-Mem1(0)+1=12345
Buffer Mem1 as Byte*20000 ' redim block
Print Mem1(Len(Mem1)-1)-Mem1(0)+1=20000
Try {
Print Mem1(20000) ' it is an error
}
Print Error$ ' return message: Buffer Locked, wrong use of pointer
}
Checkit
|
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #R | R | # load data from csv files
# setwd("C:\Temp\csv\")
# df_patient <- read.csv(file="patients.csv", header = TRUE, sep = ",")
# df_visits <- read.csv(file="visits.csv", header = TRUE, sep = ",", dec = ".", colClasses=c("character","character","numeric"))
# load data hard coded, create data frames
df_patient <- read.table(text = "
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
", header = TRUE, sep = ",") # character fields so no need for extra parameters colClasses etc.
df_visits <- read.table(text = "
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
", header = TRUE, dec = ".", sep = ",", colClasses=c("character","character","numeric"))
# aggregate visit date and scores
df_agg <- data.frame(
cbind(
PATIENT_ID = names(tapply(df_visits$VISIT_DATE, list(df_visits$PATIENT_ID), max, na.rm=TRUE)),
last_visit = tapply(df_visits$VISIT_DATE, list(df_visits$PATIENT_ID), max, na.rm=TRUE),
score_sum = tapply(df_visits$SCORE, list(df_visits$PATIENT_ID), sum, na.rm=TRUE),
score_avg = tapply(df_visits$SCORE, list(df_visits$PATIENT_ID), mean, na.rm=TRUE)
)
)
# merge patients and aggregate dataset
# all.x = all the non matching cases of df_patient are appended to the result as well (i.e. 'left join')
df_result <- merge(df_patient, df_agg, by = 'PATIENT_ID', all.x = TRUE)
print(df_result) |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #Raku | Raku | my @names = map { ( <PATIENT_ID LASTNAME> Z=> .list ).hash },
( 1001, 'Hopper' ),
( 4004, 'Wirth' ),
( 3003, 'Kemeny' ),
( 2002, 'Gosling' ),
( 5005, 'Kurtz' ),
;
my @visits = map { ( <PATIENT_ID VISIT_DATE SCORE> Z=> .list ).hash },
( 2002, '2020-09-10', 6.8 ),
( 1001, '2020-09-17', 5.5 ),
( 4004, '2020-09-24', 8.4 ),
( 2002, '2020-10-08', Nil ),
( 1001, Nil , 6.6 ),
( 3003, '2020-11-12', Nil ),
( 4004, '2020-11-05', 7.0 ),
( 1001, '2020-11-19', 5.3 ),
;
my %v = @visits.classify: *.<PATIENT_ID>;
my @result = gather for @names -> %n {
my @p = %v{ %n.<PATIENT_ID> }<>;
my @dates = @p».<VISIT_DATE>.grep: *.defined;
my @scores = @p».< SCORE>.grep: *.defined;
take {
%n,
LAST_VISIT => ( @dates.max if @dates ),
SCORE_AVG => ( @scores.sum/@scores if @scores ),
SCORE_SUM => ( @scores.sum if @scores ),
};
}
my @out_field_names = <PATIENT_ID LASTNAME LAST_VISIT SCORE_SUM SCORE_AVG>;
my @rows = @result.sort(*.<PATIENT_ID>).map(*.{@out_field_names});
say .map({$_ // ''}).fmt('%-10s', ' | ') for @out_field_names, |@rows; |
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.
| #DCL | DCL | $ list = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
$ i = 0
$ loop:
$ number = f$element( i, ",", list )
$ if number .eqs. "," then $ exit
$ abs_number = number - "-"
$ len = f$length( abs_number )
$ if len .lt. 3 .or. .not. len
$ then
$ write sys$output f$fao( "!9SL: ", f$integer( number )), "has no middle three"
$ else
$ write sys$output f$fao( "!9SL: ", f$integer( number )), f$extract( ( len - 3 ) / 2, 3, abs_number )
$ endif
$ i = i + 1
$ goto loop |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Raku | Raku | enum Tile-Type <Empty Mine>;
class Tile {
has Tile-Type $.type;
has $.face is rw;
method Str { with $!face { ~$!face } else { '.' } }
}
class Field {
has @.grid;
has Int $.width;
has Int $.height;
has Int $.mine-spots;
has Int $.empty-spots;
method new (Int $height, Int $width, Rat $mines-ratio=0.1) {
my $mine-spots = round $width*$height*$mines-ratio;
my $empty-spots = $width*$height - $mine-spots;
my @grid;
for ^$height X ^$width -> ($y, $x) {
@grid[$y][$x] = Tile.new(type => Empty);
}
for (^$height).pick($mine-spots) Z (^$width).pick($mine-spots) -> ($y, $x) {
@grid[$y][$x] = Tile.new( type => Mine);
}
self.bless(:$height, :$width, :@grid, :$mine-spots, :$empty-spots);
}
method open( $y, $x) {
return if @!grid[$y][$x].face.defined;
self.end-game("KaBoom") if @!grid[$y][$x].type ~~ Mine;
my @neighbors = gather do
take [$y+.[0],$x+.[1]]
if 0 <= $y + .[0] < $!height && 0 <= $x + .[1] < $!width
for [-1,-1],[+0,-1],[+1,-1],
[-1,+0], [+1,+0],
[-1,+1],[+0,+1],[+1,+1];
my $mines = +@neighbors.grep: { @!grid[.[0]][.[1]].type ~~ Mine };
$!empty-spots--;
@!grid[$y][$x].face = $mines || ' ';
if $mines == 0 {
self.open(.[0], .[1]) for @neighbors;
}
self.end-game("You won") if $!empty-spots == 0;
}
method end-game(Str $msg ) {
for ^$!height X ^$!width -> ($y, $x) {
@!grid[$y][$x].face = '*' if @!grid[$y][$x].type ~~ Mine
}
die $msg;
}
method mark ( $y, $x) {
if !@!grid[$y][$x].face.defined {
@!grid[$y][$x].face = "⚐";
$!mine-spots-- if @!grid[$y][$x].type ~~ Mine;
}
elsif !@!grid[$y][$x].face eq "⚐" {
undefine @!grid[$y][$x].face;
$!mine-spots++ if @!grid[$y][$x].type ~~ Mine;
}
self.end-game("You won") if $!mine-spots == 0;
}
constant @digs = |('a'..'z') xx *;
method Str {
[~] flat ' ', @digs[^$!width], "\n",
' ┌', '─' xx $!width, "┐\n",
join '', do for ^$!height -> $y {
$y, '│', @!grid[$y][*], "│\n"; },
' └', '─' xx $!width, '┘';
}
method valid ($y, $x) {
0 <= $y < $!height && 0 <= $x < $!width
}
}
sub a2n($a) { $a.ord > 64 ?? $a.ord % 32 - 1 !! +$a }
my $f = Field.new(6,10);
loop {
say ~$f;
my @w = prompt("[open loc|mark loc|loc]: ").words;
last unless @w;
unshift @w, 'open' if @w < 2;
my ($x,$y) = $0, $1 if @w[1] ~~ /(<alpha>)(<digit>)|$1=<digit>$0=<alpha>/;
$x = a2n($x);
given @w[0] {
when !$f.valid($y,$x) { say "invalid coordinates" }
when /^o/ { $f.open($y,$x) }
when /^m/ { $f.mark($y,$x) }
default { say "invalid cmd" }
}
CATCH {
say "$_: end of game.";
last;
}
}
say ~$f; |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #uBasic.2F4tH | uBasic/4tH | For R = 1 To 12
Print R;Tab(R * 5);
For C = R To 12
Print Using "_____";R * C;
Next
Print
Next |
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)
| #Go | Go | package main
import "log"
func main() {
// max uint32 is not prime
c := uint32(1<<32 - 1)
// a few primes near the top of the range. source: prime pages.
for _, p := range []uint32{1<<32 - 5, 1<<32 - 17, 1<<32 - 65, 1<<32 - 99} {
for ; c > p; c-- {
if prime(c) {
log.Fatalf("prime(%d) returned true", c)
}
}
if !prime(p) {
log.Fatalf("prime(%d) returned false", p)
}
c--
}
}
func prime(n uint32) bool {
// bases of 2, 7, 61 are sufficient to cover 2^32
switch n {
case 0, 1:
return false
case 2, 7, 61:
return true
}
// compute s, d where 2^s * d = n-1
nm1 := n - 1
d := nm1
s := 0
for d&1 == 0 {
d >>= 1
s++
}
n64 := uint64(n)
for _, a := range []uint32{2, 7, 61} {
// compute x := a^d % n
x := uint64(1)
p := uint64(a)
for dr := d; dr > 0; dr >>= 1 {
if dr&1 != 0 {
x = x * p % n64
}
p = p * p % n64
}
if x == 1 || uint32(x) == nm1 {
continue
}
for r := 1; ; r++ {
if r >= s {
return false
}
x = x * x % n64
if x == 1 {
return false
}
if uint32(x) == nm1 {
break
}
}
}
return true
} |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #FreeBASIC | FreeBASIC | function padto( i as ubyte, j as integer ) as string
return wspace(i-len(str(j)))+str(j)
end function
dim as integer M( 1 to 1000 ), n, col, k, psum
dim as integer num_zeroes = 0, num_cross = 0
dim as string outstr
M(1) = 1
for n = 2 to 1000
psum = 0
for k = 2 to n
psum += M(int(n/k))
next k
M(n) = 1 - psum
if M(n) = 0 then
num_zeroes += 1
if M(n-1)<>0 then
num_cross += 1
end if
end if
next n
print using "There are ### zeroes in the range 1 to 1000."; num_zeroes
print using "There are ### crossings in the range 1 to 1000."; num_cross
print "The first 100 Mertens numbers are: "
for n=1 to 100
outstr += padto(3, M(n))+" "
if n mod 10 = 0 then
print outstr
outstr = ""
end if
next n |
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.
| #Common_Lisp | Common Lisp | (defun select (prompt choices)
(if (null choices)
""
(do (n)
((and n (<= 0 n (1- (length choices))))
(nth n choices))
(format t "~&~a~%" prompt)
(loop for n from 0
for c in choices
do (format t " ~d) ~a~%" n c))
(force-output)
(setf n (parse-integer (read-line *standard-input* nil)
:junk-allowed t))))) |
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.
| #Delphi | Delphi |
program MD5Implementation;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes;
type
TTestCase = record
hashCode: string;
_: string;
end;
var
testCases: array[0..6] of TTestCase = ((
hashCode: 'D41D8CD98F00B204E9800998ECF8427E';
_: ''
), (
hashCode: '0CC175B9C0F1B6A831C399E269772661';
_: 'a'
), (
hashCode: '900150983CD24FB0D6963F7D28E17F72';
_: 'abc'
), (
hashCode: 'F96B697D7CB7938D525A2F31AAF161D0';
_: 'message digest'
), (
hashCode: 'C3FCD3D76192E4007DFB496CCA67E13B';
_: 'abcdefghijklmnopqrstuvwxyz'
), (
hashCode: 'D174AB98D277D9F5A5611C2C9F419D9F';
_: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
), (
hashCode: '57EDF4A22BE3C955AC49DA2E2107B67A';
_: '12345678901234567890123456789' + '012345678901234567890123456789012345678901234567890'
));
shift: array of UInt32 = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
table: array[0..63] of UInt32;
procedure Init();
var
i: integer;
function fAbs(x: Extended): Extended;
begin
if x < 0 then
exit(-x);
exit(x);
end;
begin
for i := 0 to High(table) do
table[i] := Trunc((UInt64(1) shl 32) * fAbs(Sin(i + 1.0)));
end;
function Md5(s: string): TBytes;
const
BUFFER_SIZE = 16;
var
binary: TBytesStream;
buffer: Tarray<UInt32>;
messageLenBits: UInt64;
i, j, bufferIndex, count: integer;
byte_data: byte;
string_data: ansistring;
k, k1: Tarray<UInt32>;
f, rnd, sa: UInt32;
tmp: UInt64;
begin
k := [$67452301, $EFCDAB89, $98BADCFE, $10325476];
binary := TBytesStream.Create();
if not s.IsEmpty then
begin
string_data := Utf8ToAnsi(s);
binary.Write(Tbytes(string_data), length(string_data));
end;
byte_data := $80;
binary.Write(byte_data, 1);
messageLenBits := UInt64(s.Length * 8);
count := s.Length + 1;
while (count mod 64) <> 56 do
begin
byte_data := $00;
binary.Write(byte_data, 1);
inc(count);
end;
binary.Write(messageLenBits, sizeof(messageLenBits));
SetLength(buffer, BUFFER_SIZE);
SetLength(k1, length(k));
binary.Seek(0, soFromBeginning);
while binary.Read(buffer[0], BUFFER_SIZE * 4) > 0 do
begin
for i := 0 to 3 do
k1[i] := k[i];
for i := 0 to 63 do
begin
f := 0;
bufferIndex := i;
rnd := i shr 4;
case rnd of
0:
f := (k1[1] and k1[2]) or (not k1[1] and k1[3]);
1:
begin
f := (k1[1] and k1[3]) or (k1[2] and not k1[3]);
bufferIndex := (bufferIndex * 5 + 1) and $0F
end;
2:
begin
f := k1[1] xor k1[2] xor k1[3];
bufferIndex := (bufferIndex * 3 + 5) and $0F;
end;
3:
begin
f := k1[2] xor (k1[1] or not k1[3]);
bufferIndex := (bufferIndex * 7) and $0F;
end;
end;
sa := shift[(rnd shl 2) or (i and 3)];
k1[0] := k1[0] + f + buffer[bufferIndex] + table[i];
tmp := k1[0];
k1[0] := k1[3];
k1[3] := k1[2];
k1[2] := k1[1];
k1[1] := ((tmp shl sa) or (tmp shr (32 - sa))) + k1[1];
end;
for i := 0 to 3 do
k[i] := k[i] + k1[i];
end;
SetLength(result, BUFFER_SIZE);
binary.Clear;
for i := 0 to 3 do
binary.Write(k[i], 4);
binary.Seek(0, soBeginning);
binary.Read(Result, BUFFER_SIZE);
binary.Free;
end;
function BytesToString(b: TBytes): string;
var
v: byte;
begin
Result := '';
for v in b do
Result := Result + v.ToHexString(2);
end;
var
tc: TTestCase;
begin
Init;
for tc in testCases do
Writeln(Format('%s'#10'%s'#10, [tc.hashCode, BytesToString(md5(tc._))]));
Readln;
end. |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Maple | Maple | a := Array( 1 .. 10^6, datatype = integer[1] ):
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
A = zeros(1000); % allocates memory for a 1000x1000 double precision matrix.
clear A; % deallocates memory
b = zeros(1,100000); % pre-allocate memory to improve performance
for k=1:100000,
b(k) = 5*k*k-3*k+2;
end
|
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #REXX | REXX | /* REXX */
patients='patients.csv'
l=linein(patients)
Parse Var l h1 ',' h2
n=0
idl=''
Do n=1 By 1 While lines(patients)>0
l=linein(patients)
Parse Var l id ',' lastname.id
idl=idl id
End
n=n-1 /* number of patients */
visits='visits.csv'
l=linein(visits) /* skip the header line of this file */
h3='LAST_VISIT'
h4='SCORE_SUM'
h5='SCORE_AVG'
date.=''
score.=0
Say '|' h1 '|' h2 '|' h3 '|' h4 '|' h5 '|'
Do While lines(visits)>0
l=linein(visits)
Parse Var l id ',' date ',' score
if date>date.id Then date.id=date
If score>'' Then Do
z=score.id.0+1
score.id.z=score
score.id.0=z
End
end
idl=wordsort(idl)
Do While idl<>''
Parse Var idl id idl
If date.id='' Then date.id=copies(' ',10)
ol='|' left(id,length(h1)) '|' left(lastname.id,length(h2)),
'|' left(date.id,length(h3))
If score.id.0=0 Then Do
ol=ol '|' left(' ',length(h4)) '|',
left(' ',length(h5)) '|'
score_sum=copies(' ',length(h4))
score_avg=copies(' ',length(h4))
End
Else Do
score_sum=0
Do j=1 To score.id.0
score_sum=score_sum+score.id.j
End
score_avg=score_sum/score.id.0
ol=ol '|' left(format(score_sum,2,1),length(h4)) '|',
left(format(score_avg,2,1),length(h5)) '|'
End
Say ol
End
Exit
wordsort: Procedure
/**********************************************************************
* Sort the list of words supplied as argument. Return the sorted list
**********************************************************************/
Parse Arg wl
wa.=''
wa.0=0
Do While wl<>''
Parse Var wl w wl
Do i=1 To wa.0
If wa.i>w Then Leave
End
If i<=wa.0 Then Do
Do j=wa.0 To i By -1
ii=j+1
wa.ii=wa.j
End
End
wa.i=w
wa.0=wa.0+1
End
swl=''
Do i=1 To wa.0
swl=swl wa.i
End
Return strip(swl) |
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.
| #Delphi | Delphi |
class
APPLICATION
create
make
feature
make
-- Test of middle_three_digits.
local
test_1, test_2: ARRAY [INTEGER]
do
test_1 := <<123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345>>
test_2 := <<1, 2, -1, -10, 2002, -2002, 0>>
across
test_1 as t
loop
io.put_string ("The middle three digits of " + t.item.out + " are: %T ")
io.put_string (middle_three_digits (t.item) + "%N")
end
across
test_2 as t
loop
io.put_string ("The middle three digits of " + t.item.out + " are: %T")
io.put_string (middle_three_digits (t.item) + "%N")
end
end
middle_three_digits (n: INTEGER): STRING
-- The middle three digits of 'n'.
local
k, i: INTEGER
in: STRING
do
create in.make_empty
in := n.out
if n < 0 then
in.prune ('-')
end
create Result.make_empty
if in.count < 3 then
io.put_string (" Not enough digits. ")
elseif in.count \\ 2 = 0 then
io.put_string (" Even number of digits. ")
else
i := (in.count - 3) // 2
from
k := i + 1
until
k > i + 3
loop
Result.extend (in.at (k))
k := k + 1
end
end
ensure
length_is_three: Result.count = 3 or Result.count = 0
end
end
|
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Ruby | Ruby | puts <<EOS
Minesweeper game.
There is an n by m grid that has a random number of between 20% to 60%
of randomly hidden mines that need to be found.
Positions in the grid are modified by entering their coordinates
where the first coordinate is horizontal in the grid and the second
vertical. The top left of the grid is position 1,1; the bottom right is
at n,m.
* The total number of mines to be found is shown at the beginning of the
game.
* Each mine occupies a single grid point, and its position is initially
unknown to the player
* The grid is shown as a rectangle of characters between moves.
* You are initially shown all grids as obscured, by a single dot '.'
* You may mark what you think is the position of a mine which will show
as a '?'
* You can mark what you think is free space by entering its coordinates.
:* If the point is free space then it is cleared, as are any adjacent
points that are also free space- this is repeated recursively for
subsequent adjacent free points unless that point is marked as a mine
or is a mine.
::* Points marked as a mine show as a '?'.
::* Other free points show as an integer count of the number of adjacent
true mines in its immediate neighbourhood, or as a single space ' ' if the
free point is not adjacent to any true mines.
* Of course you loose if you try to clear space that starts on a mine.
* You win when you have correctly identified all mines.
When prompted you may:
Toggle where you think a mine is at position x, y:
m <x> <y>
Clear the grid starting at position x, y (and print the result):
c <x> <y>
Print the grid so far:
p
Quit
q
Resigning will first show the grid with an 'N' for unfound true mines, a
'Y' for found true mines and a '?' for where you marked clear space as a
mine
EOS
WIDTH, HEIGHT = 6, 4
PCT = 0.15
NUM_MINES = (WIDTH * HEIGHT * PCT).round
def create_mines sx, sy
arr = Array.new(WIDTH) { Array.new(HEIGHT, false) }
NUM_MINES.times do
x, y = rand(WIDTH), rand(HEIGHT)
# place it if it isn't at (sx, sy) and we haven't already placed a mine
redo if arr[x][y] or (x == sx and y == sy)
arr[x][y] = true
end
arr
end
def num_marks
$screen.inject(0) { |sum, row| sum + row.count("?") }
end
def show_grid revealed = false
if revealed
puts $mines.transpose.map { |row| row.map { |cell| cell ? "*" : " " }.join(" ") }
else
puts "Grid has #{NUM_MINES} mines, #{num_marks} marked."
puts $screen.transpose.map{ |row| row.join(" ") }
end
end
SURROUND = [-1,0,1].product([-1,0,1]) - [[0,0]] # surround 8
def surrounding x, y
# apply the passed block to each spot around (x, y)
SURROUND.each do |dx, dy|
# don't check if we're out of bounds, or at (0,0)
yield(x+dx, y+dy) if (0...WIDTH).cover?(x+dx) and (0...HEIGHT).cover?(y+dy)
end
end
def clear_space x, y
return unless $screen[x][y] == "."
# check nearby spaces
count = 0
surrounding(x, y) { |px, py| count += 1 if $mines[px][py] }
if count == 0
$screen[x][y] = " "
surrounding(x, y) { |px, py| clear_space px, py }
else
$screen[x][y] = count.to_s
end
end
def victory?
return false if $mines.nil? # first one, don't need to check
return false if num_marks != NUM_MINES
mines_left = NUM_MINES
WIDTH.times do |x|
HEIGHT.times do |y|
mines_left -= 1 if $mines[x][y] and $screen[x][y] == "?"
end
end
mines_left == 0
end
def check_input x, y
x, y = x.to_i - 1, y.to_i - 1
[x, y] if (0...WIDTH).cover?(x) and (0...HEIGHT).cover?(y)
end
$mines = nil
$screen = Array.new(WIDTH) { Array.new(HEIGHT, ".") }
puts "Welcome to Minesweeper!"
show_grid
loop do
print "> "
action = gets.chomp.downcase
case action
when "quit", "exit", "x", "q"
puts "Bye!"
break
when /^m (\d+) (\d+)$/
# mark this cell
x, y = check_input $1, $2
next unless x
if $screen[x][y] == "."
# mark it
$screen[x][y] = "?"
if victory?
show_grid
puts "You win!"
break
end
elsif $screen[x][y] == "?"
# unmark it
$screen[x][y] = "."
end
show_grid
when /^c (\d+) (\d+)$/
x, y = check_input $1, $2
next unless x
$mines ||= create_mines(x, y)
if $mines[x][y]
puts "You hit a mine!"
show_grid true
break
else
clear_space x, y
show_grid
if victory?
puts "You win!"
break
end
end
when "p"
show_grid
end
end |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Ursala | Ursala |
#import std
#import nat
table "n" =
~&plrTS(
~&xS pad` @xS <'x ','--'>-- --' | '*hS %nP* nrange/1 "n",
^CthPiC(`-!*h,~&) mat` *xSSK7 pad` *K7ihxPBSS (~&i&& %nP)** nleq&&product**iiK0lK2x nrange/1 "n")
#show+
main = table 12
|
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)
| #Haskell | Haskell | module Primes where
import System.Random
import System.IO.Unsafe
-- Miller-Rabin wrapped up as an (almost deterministic) pure function
isPrime :: Integer -> Bool
isPrime n = unsafePerformIO (isMillerRabinPrime 100 n)
isMillerRabinPrime :: Int -> Integer -> IO Bool
isMillerRabinPrime k n
| even n = return (n==2)
| n < 100 = return (n `elem` primesTo100)
| otherwise = do ws <- witnesses k n
return $ and [test n (pred n) evens (head odds) a | a <- ws]
where
(evens,odds) = span even (iterate (`div` 2) (pred n))
test :: Integral nat => nat -> nat -> [nat] -> nat -> nat -> Bool
test n n_1 evens d a = x `elem` [1,n_1] || n_1 `elem` powers
where
x = powerMod n a d
powers = map (powerMod n a) evens
witnesses :: (Num a, Ord a, Random a) => Int -> a -> IO [a]
witnesses k n
| n < 9080191 = return [31,73]
| n < 4759123141 = return [2,7,61]
| n < 3474749660383 = return [2,3,5,7,11,13]
| n < 341550071728321 = return [2,3,5,7,11,13,17]
| otherwise = do g <- newStdGen
return $ take k (randomRs (2,n-1) g)
primesTo100 :: [Integer]
primesTo100 = [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]
-- powerMod m x n = x^n `mod` m
powerMod :: Integral nat => nat -> nat -> nat -> nat
powerMod m x n = f (n - 1) x x `rem` m
where
f d a y = if d==0 then y else g d a y
g i b y | even i = g (i `quot` 2) (b*b `rem` m) y
| otherwise = f (i-1) b (b*y `rem` m)
|
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Go | Go | package main
import "fmt"
func mertens(to int) ([]int, int, int) {
if to < 1 {
to = 1
}
merts := make([]int, to+1)
primes := []int{2}
var sum, zeros, crosses int
for i := 1; i <= to; i++ {
j := i
cp := 0 // counts prime factors
spf := false // true if there is a square prime factor
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
sum++
} else {
sum--
}
}
merts[i] = sum
if sum == 0 {
zeros++
if i > 1 && merts[i-1] != 0 {
crosses++
}
}
}
return merts, zeros, crosses
}
func main() {
merts, zeros, crosses := mertens(1000)
fmt.Println("Mertens sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", merts[i])
}
fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000")
fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000")
} |
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.
| #D | D | import std.stdio, std.conv, std.string, std.array, std.typecons;
string menuSelect(in string[] entries) {
static Nullable!(int, -1) validChoice(in string input,
in int nEntries)
pure nothrow {
try {
immutable n = input.to!int;
return typeof(return)((n >= 0 && n <= nEntries) ? n : -1);
} catch (Exception e) // Very generic
return typeof(return)(-1); // Not valid.
}
if (entries.empty)
return "";
while (true) {
"Choose one:".writeln;
foreach (immutable i, const entry; entries)
writefln(" %d) %s", i, entry);
"> ".write;
immutable input = readln.chomp;
immutable choice = validChoice(input, entries.length - 1);
if (choice.isNull)
"Wrong choice.".writeln;
else
return entries[choice]; // We have a valid choice.
}
}
void main() {
immutable items = ["fee fie", "huff and puff",
"mirror mirror", "tick tock"];
writeln("You chose '", items.menuSelect, "'.");
} |
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.
| #F.23 | F# | let fxyz x y z : uint32 = (x &&& y) ||| (~~~x &&& z)
let gxyz x y z : uint32 = (z &&& x) ||| (~~~z &&& y)
let hxyz x y z : uint32 = x ^^^ y ^^^ z
let ixyz x y z : uint32 = y ^^^ (x ||| ~~~z)
let fghi = [ fxyz; gxyz; hxyz; ixyz ] |> List.collect (List.replicate 16)
let g1Idx = id
let g2Idx i = (5 * i + 1) % 16
let g3Idx i = (3 * i + 5) % 16
let g4Idx i = (7 * i) % 16
let gIdxs =
[ g1Idx; g2Idx; g3Idx; g4Idx ]
|> List.collect (List.replicate 16)
|> List.map2 (fun idx func -> func idx) [ 0..63 ]
let s =
[ [ 7; 12; 17; 22 ]
[ 5; 9; 14; 20 ]
[ 4; 11; 16; 23 ]
[ 6; 10; 15; 21 ] ]
|> List.collect (List.replicate 4)
|> List.concat
let k =
[ 1...64. ] |> List.map (sin
>> abs
>> ((*) (2. ** 32.))
>> floor
>> uint32)
type MD5 =
{ a : uint32
b : uint32
c : uint32
d : uint32 }
let initialMD5 =
{ a = 0x67452301u
b = 0xefcdab89u
c = 0x98badcfeu
d = 0x10325476u }
let md5round (msg : uint32 []) { MD5.a = a; MD5.b = b; MD5.c = c; MD5.d = d } i =
let rotateL32 r x = (x <<< r) ||| (x >>> (32 - r))
let f = fghi.[i] b c d
let a' = b + (a + f + k.[i] + msg.[gIdxs.[i]]
|> rotateL32 s.[i])
{ a = d
b = a'
c = b
d = c }
let md5plus m (bs : byte []) =
let msg =
bs
|> Array.chunkBySize 4
|> Array.take 16
|> Array.map (fun elt -> System.BitConverter.ToUInt32(elt, 0))
let m' = List.fold (md5round msg) m [ 0..63 ]
{ a = m.a + m'.a
b = m.b + m'.b
c = m.c + m'.c
d = m.d + m'.d }
let padMessage (msg : byte []) =
let msgLen = Array.length msg
let msgLenInBits = (uint64 msgLen) * 8UL
let lastSegmentSize =
let m = msgLen % 64
if m = 0 then 64
else m
let padLen =
64 - lastSegmentSize + (if lastSegmentSize >= 56 then 64
else 0)
[| yield 128uy
for i in 2..padLen - 8 do
yield 0uy
for i in 0..7 do
yield ((msgLenInBits >>> (8 * i)) |> byte) |]
|> Array.append msg
let md5sum (msg : string) =
System.Text.Encoding.ASCII.GetBytes msg
|> padMessage
|> Array.chunkBySize 64
|> Array.fold md5plus initialMD5
|> (fun { MD5.a = a; MD5.b = b; MD5.c = c; MD5.d = d } ->
System.BitConverter.GetBytes a
|> (fun x -> System.BitConverter.GetBytes b |> Array.append x)
|> (fun x -> System.BitConverter.GetBytes c |> Array.append x)
|> (fun x -> System.BitConverter.GetBytes d |> Array.append x))
|> Array.map (sprintf "%02X")
|> Array.reduce (+) |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #MATLAB_.2F_Octave | MATLAB / Octave |
A = zeros(1000); % allocates memory for a 1000x1000 double precision matrix.
clear A; % deallocates memory
b = zeros(1,100000); % pre-allocate memory to improve performance
for k=1:100000,
b(k) = 5*k*k-3*k+2;
end
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Maxima | Maxima | /* Maxima allocates memory dynamically and uses a garbage collector.
Here is how to check available memory */
room();
3221/3221 72.3% 2 CONS RATIO COMPLEX STRUCTURE
272/307 61.6% FIXNUM SHORT-FLOAT CHARACTER RANDOM-STATE READTABLE SPICE
226/404 90.8% SYMBOL STREAM
1/2 37.2% PACKAGE
127/373 44.9% ARRAY HASH-TABLE VECTOR BIT-VECTOR PATHNAME CCLOSURE CLOSURE
370/370 49.1% 1 STRING
325/440 8.2% CFUN BIGNUM LONG-FLOAT
31/115 98.9% SFUN GFUN VFUN AFUN CFDATA
1188/1447 contiguous (478 blocks)
11532 hole
5242 5.0% relocatable
4573 pages for cells
22535 total pages
97138 pages available
11399 pages in heap but not gc'd + pages needed for gc marking
131072 maximum pages |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #SAS | SAS | %let datefmt=E8601DA10.;
data patient;
infile "patient.csv" dsd dlm=',';
attrib
id length=4
lastname length=$10;
input id lastname;
data visit;
infile "visit.csv" dsd dlm=',';
attrib
id length=4
date informat=&datefmt format=&datefmt
score length=8;
input id date score;
proc sql;
select * from
(select id, max(date) format=&datefmt as max_date, sum(score) as sum_score,
avg(score) as avg_score from visit group by id)
natural right join patient
order by id; |
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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Test of middle_three_digits.
local
test_1, test_2: ARRAY [INTEGER]
do
test_1 := <<123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345>>
test_2 := <<1, 2, -1, -10, 2002, -2002, 0>>
across
test_1 as t
loop
io.put_string ("The middle three digits of " + t.item.out + " are: %T ")
io.put_string (middle_three_digits (t.item) + "%N")
end
across
test_2 as t
loop
io.put_string ("The middle three digits of " + t.item.out + " are: %T")
io.put_string (middle_three_digits (t.item) + "%N")
end
end
middle_three_digits (n: INTEGER): STRING
-- The middle three digits of 'n'.
local
k, i: INTEGER
in: STRING
do
create in.make_empty
in := n.out
if n < 0 then
in.prune ('-')
end
create Result.make_empty
if in.count < 3 then
io.put_string (" Not enough digits. ")
elseif in.count \\ 2 = 0 then
io.put_string (" Even number of digits. ")
else
i := (in.count - 3) // 2
from
k := i + 1
until
k > i + 3
loop
Result.extend (in.at (k))
k := k + 1
end
end
ensure
length_is_three: Result.count = 3 or Result.count = 0
end
end
|
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Rust | Rust | extern crate rand;
use std::io;
use std::io::Write;
fn main() {
use minesweeper::{MineSweeper, GameStatus};
let mut width = 6;
let mut height = 4;
let mut mine_perctg = 10;
let mut game = MineSweeper::new(width, height, mine_perctg);
loop {
let mut command = String::new();
println!(
"\n\
M I N E S W E E P E R\n\
\n\
Commands: \n\
line col - reveal line,col \n\
m line col - mark line,col \n\
q - quit\n\
n - new game\n\
n width height perc - new game size and mine percentage\n"
);
game.print();
print!("> ");
io::stdout().flush().unwrap();
while let Ok(_) = io::stdin().read_line(&mut command) {
let mut command_ok = false;
{
let values: Vec<&str> = command.trim().split(' ').collect();
if values.len() == 1 {
if values[0] == "q" {
println!("Goodbye");
return;
} else if values[0] == "n" {
println!("New game");
game = MineSweeper::new(width, height, mine_perctg);
command_ok = true;
}
} else if values.len() == 2 {
if let (Ok(x), Ok(y)) = (
values[0].parse::<usize>(),
values[1].parse::<usize>(),
)
{
game.play(x - 1, y - 1);
match game.game_status {
GameStatus::Won => println!("You won!"),
GameStatus::Lost => println!("You lost!"),
_ => (),
}
command_ok = true;
}
} else if values.len() == 3 {
if values[0] == "m" {
if let (Ok(x), Ok(y)) = (
values[1].parse::<usize>(),
values[2].parse::<usize>(),
)
{
game.mark(x - 1, y - 1);
command_ok = true;
}
}
} else if values.len() == 4 {
if values[0] == "n" {
if let (Ok(new_width), Ok(new_height), Ok(new_mines_perctg)) =
(
values[1].parse::<usize>(),
values[2].parse::<usize>(),
values[3].parse::<usize>(),
)
{
width = new_width;
height = new_height;
mine_perctg = new_mines_perctg;
game = MineSweeper::new(width, height, mine_perctg);
command_ok = true;
}
}
}
}
if command_ok {
game.print();
} else {
println!("Invalid command");
}
print!("> ");
io::stdout().flush().unwrap();
command.clear();
}
}
}
pub mod minesweeper {
pub struct MineSweeper {
cell: [[Cell; 100]; 100],
pub game_status: GameStatus,
mines: usize,
width: usize,
height: usize,
revealed_count: usize,
}
#[derive(Copy, Clone)]
struct Cell {
content: CellContent,
mark: Mark,
revealed: bool,
}
#[derive(Copy, Clone)]
enum CellContent {
Empty,
Mine,
MineNeighbour { count: u8 },
}
#[derive(Copy, Clone)]
enum Mark {
None,
Mine,
}
pub enum GameStatus {
InGame,
Won,
Lost,
}
extern crate rand;
use std::cmp::max;
use std::cmp::min;
use self::rand::Rng;
use self::CellContent::*;
use self::GameStatus::*;
impl MineSweeper {
pub fn new(width: usize, height: usize, percentage_of_mines: usize) -> MineSweeper {
let mut game = MineSweeper {
cell: [[Cell {
content: Empty,
mark: Mark::None,
revealed: false,
}; 100]; 100],
game_status: InGame,
mines: (width * height * percentage_of_mines) / 100,
width: width,
height: height,
revealed_count: 0,
};
game.put_mines();
game.calc_neighbours();
game
}
pub fn play(&mut self, x: usize, y: usize) {
match self.game_status {
InGame => {
if !self.cell[x][y].revealed {
match self.cell[x][y].content {
Mine => {
self.cell[x][y].revealed = true;
self.revealed_count += 1;
self.game_status = Lost;
}
Empty => {
self.flood_fill_reveal(x, y);
if self.revealed_count + self.mines == self.width * self.height {
self.game_status = Won;
}
}
MineNeighbour { .. } => {
self.cell[x][y].revealed = true;
self.revealed_count += 1;
if self.revealed_count + self.mines == self.width * self.height {
self.game_status = Won;
}
}
}
}
}
_ => println!("Game has ended"),
}
}
pub fn mark(&mut self, x: usize, y: usize) {
self.cell[x][y].mark = match self.cell[x][y].mark {
Mark::None => Mark::Mine,
Mark::Mine => Mark::None,
}
}
pub fn print(&self) {
print!("┌");
for _ in 0..self.width {
print!("─");
}
println!("┐");
for y in 0..self.height {
print!("│");
for x in 0..self.width {
self.cell[x][y].print();
}
println!("│");
}
print!("└");
for _ in 0..self.width {
print!("─");
}
println!("┘");
}
fn put_mines(&mut self) {
let mut rng = rand::thread_rng();
for _ in 0..self.mines {
while let (x, y, true) = (
rng.gen::<usize>() % self.width,
rng.gen::<usize>() % self.height,
true,
)
{
match self.cell[x][y].content {
Mine => continue,
_ => {
self.cell[x][y].content = Mine;
break;
}
}
}
}
}
fn calc_neighbours(&mut self) {
for x in 0..self.width {
for y in 0..self.height {
if !self.cell[x][y].is_bomb() {
let mut adjacent_bombs = 0;
for i in max(x as isize - 1, 0) as usize..min(x + 2, self.width) {
for j in max(y as isize - 1, 0) as usize..min(y + 2, self.height) {
adjacent_bombs += if self.cell[i][j].is_bomb() { 1 } else { 0 };
}
}
if adjacent_bombs == 0 {
self.cell[x][y].content = Empty;
} else {
self.cell[x][y].content = MineNeighbour { count: adjacent_bombs };
}
}
}
}
}
fn flood_fill_reveal(&mut self, x: usize, y: usize) {
let mut stack = Vec::<(usize, usize)>::new();
stack.push((x, y));
while let Some((i, j)) = stack.pop() {
if self.cell[i][j].revealed {
continue;
}
self.cell[i][j].revealed = true;
self.revealed_count += 1;
if let Empty = self.cell[i][j].content {
for m in max(i as isize - 1, 0) as usize..min(i + 2, self.width) {
for n in max(j as isize - 1, 0) as usize..min(j + 2, self.height) {
if !self.cell[m][n].is_bomb() && !self.cell[m][n].revealed {
stack.push((m, n));
}
}
}
}
}
}
}
impl Cell {
pub fn print(&self) {
print!(
"{}",
if self.revealed {
match self.content {
Empty => ' ',
Mine => '*',
MineNeighbour { count } => char::from(count + b'0'),
}
} else {
match self.mark {
Mark::Mine => '?',
Mark::None => '.',
}
}
);
}
pub fn is_bomb(&self) -> bool {
match self.content {
Mine => true,
_ => false,
}
}
}
} |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #VBA | VBA |
Option Explicit
Sub Multiplication_Tables()
Dim strTemp As String, strBuff As String
Dim i&, j&, NbDigits As Byte
'You can adapt the following const :
Const NB_END As Byte = 12
Select Case NB_END
Case Is < 10: NbDigits = 3
Case 10 To 31: NbDigits = 4
Case 31 To 100: NbDigits = 5
Case Else: MsgBox "Number too large": Exit Sub
End Select
strBuff = String(NbDigits, " ")
For i = 1 To NB_END
strTemp = Right(strBuff & i, NbDigits)
For j = 2 To NB_END
If j < i Then
strTemp = strTemp & strBuff
Else
strTemp = strTemp & Right(strBuff & j * i, NbDigits)
End If
Next j
Debug.Print strTemp
Next i
End Sub
|
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)
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every n := !A do write(n," is ",(mrp(n,5),"probably prime")|"composite")
end
procedure mrp(n, k)
if n = 2 then return ""
if n%2 = 0 then fail
nm1 := decompose(n-1)
s := nm1[1]
d := nm1[2]
every !k do {
a := ?(n-2)+1
x := (a^d)%n
if x = (1|(n-1)) then next
every !(s-1) do {
x := (x*x)%n
if x = 1 then fail
if x = (n-1) then break next
}
fail
}
return ""
end
procedure decompose(nm1)
s := 1
d := nm1
while d%2 = 0 do {
d /:= 2
s +:= 1
}
return [s,d]
end |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Haskell | Haskell | import Data.List.Split (chunksOf)
import qualified Data.MemoCombinators as Memo
import Math.NumberTheory.Primes (unPrime, factorise)
import Text.Printf (printf)
moebius :: Integer -> Int
moebius = product . fmap m . factorise
where
m (p, e)
| unPrime p == 0 = 0
| e == 1 = -1
| otherwise = 0
mertens :: Integer -> Int
mertens = Memo.integral (\n -> sum $ fmap moebius [1..n])
countZeros :: [Integer] -> Int
countZeros = length . filter ((==0) . mertens)
crossesZero :: [Integer] -> Int
crossesZero = length . go . fmap mertens
where
go (x:y:xs)
| y == 0 && x /= 0 = y : go (y:xs)
| otherwise = go (y:xs)
go _ = []
main :: IO ()
main = do
printf "The first 99 terms for M(1..99):\n\n "
mapM_ (printf "%3d" . mertens) [1..9] >> printf "\n"
mapM_ (\row -> mapM_ (printf "%3d" . mertens) row >> printf "\n") $ chunksOf 10 [10..99]
printf "\nM(n) is zero %d times for 1 <= n <= 1000.\n" $ countZeros [1..1000]
printf "M(n) crosses zero %d times for 1 <= n <= 1000.\n" $ crossesZero [1..1000] |
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.
| #Delphi | Delphi |
program Menu;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function ChooseMenu(Options: TArray<string>; Prompt: string): string;
var
index: Integer;
value: string;
begin
if Length(Options) = 0 then
exit('');
repeat
writeln;
for var i := 0 to length(Options) - 1 do
writeln(i + 1, '. ', Options[i]);
write(#10, Prompt, ' ');
Readln(value);
index := StrToIntDef(value, -1);
until (index > 0) and (index <= length(Options));
Result := Options[index];
end;
begin
writeln('You picked ', ChooseMenu(['fee fie', 'huff and puff', 'mirror mirror',
'tick tock'], 'Enter number: '));
readln;
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.
| #FreeBASIC | FreeBASIC | ' version 19-10-2016
' MD5 from the Wikipedia page "MD5"
' compile with: fbc -s console
' macro for a rotate left
#Macro ROtate_Left (x, n) ' rotate left
(x) = (x) Shl (n) + (x) Shr (32 - (n))
#EndMacro
Function MD5(test_str As String) As String
Dim As String message = test_str ' strings are passed as ByRef's
Dim As UByte sx, s(0 To ...) = { 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 }
Dim As UInteger<32> K(0 To ...) = { &Hd76aa478, &He8c7b756, &H242070db, _
&Hc1bdceee, &Hf57c0faf, &H4787c62a, &Ha8304613, &Hfd469501, &H698098d8, _
&H8b44f7af, &Hffff5bb1, &H895cd7be, &H6b901122, &Hfd987193, &Ha679438e, _
&H49b40821, &Hf61e2562, &Hc040b340, &H265e5a51, &He9b6c7aa, &Hd62f105d, _
&H02441453, &Hd8a1e681, &He7d3fbc8, &H21e1cde6, &Hc33707d6, &Hf4d50d87, _
&H455a14ed, &Ha9e3e905, &Hfcefa3f8, &H676f02d9, &H8d2a4c8a, &Hfffa3942, _
&H8771f681, &H6d9d6122, &Hfde5380c, &Ha4beea44, &H4bdecfa9, &Hf6bb4b60, _
&Hbebfbc70, &H289b7ec6, &Heaa127fa, &Hd4ef3085, &H04881d05, &Hd9d4d039, _
&He6db99e5, &H1fa27cf8, &Hc4ac5665, &Hf4292244, &H432aff97, &Hab9423a7, _
&Hfc93a039, &H655b59c3, &H8f0ccc92, &Hffeff47d, &H85845dd1, &H6fa87e4f, _
&Hfe2ce6e0, &Ha3014314, &H4e0811a1, &Hf7537e82, &Hbd3af235, &H2ad7d2bb, _
&Heb86d391 }
' Initialize variables
Dim As UInteger<32> A, a0 = &H67452301
Dim As UInteger<32> B, b0 = &Hefcdab89
Dim As UInteger<32> C, c0 = &H98badcfe
Dim As UInteger<32> D, d0 = &H10325476
Dim As UInteger<32> dtemp, F, g, temp
Dim As Long i, j
Dim As ULongInt l = Len(message)
' set the first bit after the message to 1
message = message + Chr(1 Shl 7)
' add one char to the length
Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
' check if we have enough room for inserting the length
If padding < 8 Then padding = padding + 64
message = message + String(padding, Chr(0)) ' adjust length
Dim As ULong l1 = Len(message) ' new length
l = l * 8 ' orignal length in bits
' create ubyte ptr to point to l ( = length in bits)
Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
For i = 0 To 7 'copy length of message to the last 8 bytes
message[l1 -8 + i] = ub_ptr[i]
Next
For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes
A = a0 : B = b0 : C = c0 : D = d0
' break chunk into 16 32bit uinteger
Dim As UInteger<32> Ptr M = Cast(UInteger<32> Ptr, @message[j * 64])
For i = 0 To 63
Select Case As Const i
Case 0 To 15
F = (B And C) Or ((Not B) And D)
g = i
Case 16 To 31
F = (B And D) Or (C And (Not D))
g = (i * 5 +1) Mod 16
Case 32 To 47
F = (B Xor C Xor D)
g = (i * 3 +5) Mod 16
Case 48 To 63
F = C Xor (B Or (Not D))
g = (i * 7) Mod 16
End Select
dtemp = D
D = C
C = B
temp = A + F + K(i)+ M[g] : ROtate_left(temp, s(i))
B = B + temp
A = dtemp
Next
a0 += A : b0 += B : c0 += C : d0 += D
Next
Dim As String answer
' convert a0, b0, c0 and d0 in hex, then add, low order first
Dim As String s1 = Hex(a0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
s1 = Hex(b0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
s1 = Hex(c0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
s1 = Hex(d0, 8)
For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next
Return LCase(answer)
End Function
' ------=< MAIN >=------
Dim As String test, hash, md5_hash
Dim As ULong i
For i = 1 To 7
Read hash, test
md5_hash = MD5(test)
Print
Print test
Print hash
Print md5_hash;
If hash = md5_hash Then
Print " PASS"
Else
Print " FAIL"
Beep
End If
Next
' testdata
Data "d41d8cd98f00b204e9800998ecf8427e", ""
Data "0cc175b9c0f1b6a831c399e269772661", "a"
Data "900150983cd24fb0d6963f7d28e17f72", "abc"
Data "f96b697d7cb7938d525a2f31aaf161d0", "message digest"
Data "c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"
Data "d174ab98d277d9f5a5611c2c9f419d9f"
Data "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Data "57edf4a22be3c955ac49da2e2107b67a"
Data "123456789012345678901234567890123456789012345678901234567890" _
+ "12345678901234567890"
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Nanoquery | Nanoquery | import native
// allocate 26 bytes
ptr = native.allocate(26)
// store the uppercase alphabet
for i in range(0, 25)
native.poke(ptr + i, ord("A") + i)
end
// output the allocated memory
for i in range(0, 25)
print chr(native.peek(ptr + i))
end
// free the allocated memory
native.free(ptr) |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Nim | Nim | # Allocate thread local heap memory
var a = alloc(1000)
dealloc(a)
# Allocate memory block on shared heap
var b = allocShared(1000)
deallocShared(b)
# Allocate and Dellocate a single int on the thread local heap
var p = create(int, sizeof(int)) # allocate memory
# create zeroes memory; createU does not.
echo p[] # 0
p[] = 123 # assign a value
echo p[] # 123
discard resize(p, 0) # deallocate it
# p is now invalid. Let's set it to nil
p = nil # set pointer to nil
echo isNil(p) # true
|
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #SPSS | SPSS | * set working directory to location of .csv files
CD 'C:\Temp\csv\'.
* load patients csv data
GET DATA /TYPE=TXT
/FILE="patients.csv"
/ENCODING='UTF8'
/DELCASE=LINE
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/IMPORTCASE=ALL
/VARIABLES=
PATIENT_ID F5.0
LASTNAME A20
.
CACHE.
EXECUTE.
* sort cases is needed to match files
SORT CASES BY PATIENT_ID (A).
DATASET NAME Patients WINDOW=FRONT.
* load visits csv data
GET DATA /TYPE=TXT
/FILE="visit.csv"
/ENCODING='UTF8'
/DELCASE=LINE
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/IMPORTCASE=ALL
/VARIABLES=
PATIENT_ID F5.0
VISIT_DATE SDATE10
SCORE F4.1
.
CACHE.
EXECUTE.
* sort cases is needed, else match files will raise error "Files out of order"
SORT CASES BY PATIENT_ID (A) VISIT_DATE (A).
DATASET NAME Visits WINDOW=FRONT.
* load visits csv data
* merge datasets, one to many, FILE is the 'one', TABLE is 'many'
MATCH FILES TABLE = Patients / FILE = Visits
/BY PATIENT_ID.
EXECUTE.
* aggregate visit date and scores, group by and order (A)=ascending or (D)=descending
AGGREGATE OUTFILE *
/BREAK=PATIENT_ID(A)
/last_visit = MAX(VISIT_DATE)
/score_avg = MEAN(SCORE)
/score_sum = SUM(SCORE). |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #SQL | SQL | -- drop tables
DROP TABLE IF EXISTS tmp_patients;
DROP TABLE IF EXISTS tmp_visits;
-- create tables
CREATE TABLE tmp_patients(
PATIENT_ID INT,
LASTNAME VARCHAR(20)
);
CREATE TABLE tmp_visits(
PATIENT_ID INT,
VISIT_DATE DATE,
SCORE NUMERIC(4,1)
);
-- load data from csv files
/*
-- Note: LOAD DATA LOCAL requires `local-infile` enabled on both the client and server else you get error "#1148 command is not allowed.."
LOAD DATA LOCAL INFILE '/home/csv/patients.csv' INTO TABLE `tmp_patients` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES;
LOAD DATA LOCAL INFILE '/home/csv/visits.csv' INTO TABLE `tmp_visits` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES;
*/
-- load data hard coded
INSERT INTO tmp_patients(PATIENT_ID, LASTNAME)
VALUES
(1001, 'Hopper'),
(4004, 'Wirth'),
(3003, 'Kemeny'),
(2002, 'Gosling'),
(5005, 'Kurtz');
INSERT INTO tmp_visits(PATIENT_ID, VISIT_DATE, SCORE)
VALUES
(2002, '2020-09-10', 6.8),
(1001, '2020-09-17', 5.5),
(4004, '2020-09-24', 8.4),
(2002, '2020-10-08', NULL),
(1001, NULL, 6.6),
(3003, '2020-11-12', NULL),
(4004, '2020-11-05', 7.0),
(1001, '2020-11-19', 5.3);
-- join tables and group
SELECT
p.PATIENT_ID,
p.LASTNAME,
MAX(VISIT_DATE) AS LAST_VISIT,
SUM(SCORE) AS SCORE_SUM,
CAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG
FROM
tmp_patients p
LEFT JOIN tmp_visits v
ON v.PATIENT_ID = p.PATIENT_ID
GROUP BY
p.PATIENT_ID,
p.LASTNAME
ORDER BY
p.PATIENT_ID; |
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.
| #Elena | Elena | import system'routines;
import extensions;
middleThreeDigits(int n)
{
string s := n.Absolute.toString();
int len := s.Length;
if(len<3)
{
InvalidArgumentException.new:"n must have 3 digits or more".raise()
}
else if(len.isEven())
{
InvalidArgumentException.new:"n must have an odd number of digits".raise()
};
int mid := len / 2;
^ s.Substring(mid-1,3)
}
public program()
{
new int[]{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}
.forEach:(n)
{
console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) | on:(e => e.Message))
}
} |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Tcl | Tcl | package require Tcl 8.5
fconfigure stdout -buffering none
# Set up the grid and fill it with some mines
proc makeGrid {n m} {
global grid mine
unset -nocomplain grid mine
set grid(size) [list $n $m]
set grid(shown) 0
set grid(marked) 0
for {set j 1} {$j <= $m} {incr j} {
for {set i 1} {$i <= $n} {incr i} {
set grid($i,$j) .
}
}
set squares [expr {$m * $n}]
set mine(count) [expr {int((rand()*0.4+0.2) * $squares)}]
for {set count 0} {$count < $mine(count)} {incr count} {
while 1 {
set i [expr {1+int(rand()*$n)}]
set j [expr {1+int(rand()*$m)}]
if {![info exist mine($i,$j)]} {
set mine($i,$j) x
break
}
}
}
return $mine(count)
}
# Print out the grid
proc displayGrid {} {
global grid
lassign $grid(size) n m
for {set j 1} {$j <= $m} {incr j} {
set row "\t"
for {set i 1} {$i <= $n} {incr i} {
append row $grid($i,$j)
}
puts $row
}
}
# Toggle the possible-mine flag on a cell
proc markCell {x y} {
global grid
if {![info exist grid($x,$y)]} return
if {$grid($x,$y) eq "."} {
set grid($x,$y) "?"
incr grid(marked)
} elseif {$grid($x,$y) eq "?"} {
set grid($x,$y) "."
incr grid(marked) -1
}
}
# Helper procedure that iterates over the 9 squares centered on a location
proc foreachAround {x y xv yv script} {
global grid
upvar 1 $xv i $yv j
foreach i [list [expr {$x-1}] $x [expr {$x+1}]] {
foreach j [list [expr {$y-1}] $y [expr {$y+1}]] {
if {[info exist grid($i,$j)]} {uplevel 1 $script}
}
}
}
# Reveal a cell; returns if it was a mine
proc clearCell {x y} {
global grid mine
if {![info exist grid($x,$y)] || $grid($x,$y) ne "."} {
return 0; # Do nothing...
}
if {[info exist mine($x,$y)]} {
set grid($x,$y) "!"
revealGrid
return 1; # Lose...
}
set surround 0
foreachAround $x $y i j {incr surround [info exist mine($i,$j)]}
incr grid(shown)
if {$surround == 0} {
set grid($x,$y) " "
foreachAround $x $y i j {clearCell $i $j}
} else {
set grid($x,$y) $surround
}
return 0
}
# Check the winning condition
proc won? {} {
global grid mine
lassign $grid(size) n m
expr {$grid(shown) + $mine(count) == $n * $m}
}
# Update the grid to show mine locations (marked or otherwise)
proc revealGrid {} {
global grid mine
lassign $grid(size) n m
for {set j 1} {$j <= $m} {incr j} {
for {set i 1} {$i <= $n} {incr i} {
if {![info exist mine($i,$j)]} continue
if {$grid($i,$j) eq "."} {
set grid($i,$j) "x"
} elseif {$grid($i,$j) eq "?"} {
set grid($i,$j) "X"
}
}
}
}
# The main game loop
proc play {n m} {
set m [makeGrid $n $m]
puts "There are $m true mines of fixed position in the grid\n"
displayGrid
while 1 {
puts -nonewline "m x y/c x y/p/r: "
if {[gets stdin line] < 0} break; # check for eof too!
switch -nocase -regexp [string trim $line] {
{^m\s+\d+\s+\d+$} {
markCell [lindex $line 1] [lindex $line 2]
}
{^c\s+\d+\s+\d+$} {
if {[clearCell [lindex $line 1] [lindex $line 2]]} {
puts "KABOOM!"
displayGrid
break
} elseif {[won?]} {
puts "You win!"
displayGrid
break
}
}
{^p$} {
displayGrid
}
{^r$} {
puts "Resigning..."
revealGrid
displayGrid
break
}
}
}
}
play 6 4 |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Visual_Basic | Visual Basic | Sub Main()
Const nmax = 12, xx = 3
Const x = xx + 1
Dim i As Integer, j As Integer, s As String
s = String(xx, " ") & " |"
For j = 1 To nmax
s = s & Right(String(x, " ") & j, x)
Next j
Debug.Print s
s = String(xx, "-") & " +"
For j = 1 To nmax
s = s & " " & String(xx, "-")
Next j
Debug.Print s
For i = 1 To nmax
s = Right(String(xx, " ") & i, xx) & " |"
For j = 1 To nmax
If j >= i _
Then s = s & Right(String(x, " ") & i * j, x) _
Else s = s & String(x, " ")
Next j
Debug.Print s
Next i
End Sub 'Main |
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)
| #J | J | import java.math.BigInteger;
public class MillerRabinPrimalityTest {
public static void main(String[] args) {
BigInteger n = new BigInteger(args[0]);
int certainty = Integer.parseInt(args[1]);
System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite"));
}
} |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #J | J | mu =: 0:`(1 - 2 * 2|#@{.)@.(1: = */@{:)@(2&p:)"0
M =: +/@([: mu 1:+i.)
m1000 =: (M"0) 1+i.1000
zero =: +/ m1000 = 0
cross =: +/ (-.*.1:|]) m1000 ~: 0
echo 'The first 99 Merten numbers are'
echo 10 10$ __, 99{.m1000
echo 'M(N) is zero ',(":zero),' times.'
echo 'M(N) crosses zero ',(":cross),' times.'
exit'' |
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.
| #Elixir | Elixir | defmodule Menu do
def select(_, []), do: ""
def select(prompt, items) do
IO.puts ""
Enum.with_index(items) |> Enum.each(fn {item,i} -> IO.puts " #{i}. #{item}" end)
answer = IO.gets("#{prompt}: ") |> String.strip
case Integer.parse(answer) do
{num, ""} when num in 0..length(items)-1 -> Enum.at(items, num)
_ -> select(prompt, items)
end
end
end
# test empty list
response = Menu.select("Which is empty", [])
IO.puts "empty list returns: #{inspect response}"
# "real" test
items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
response = Menu.select("Which is from the three pigs", items)
IO.puts "you chose: #{inspect response}" |
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.
| #ERRE | ERRE |
PROCEDURE Selection(choices$[],prompt$->sel$)
IF UBOUND(choices$,1)-LBOUND(choices$,1)=0 THEN
sel$=""
EXIT PROCEDURE
END IF
ret$=""
REPEAT
FOR i=LBOUND(choices$,1) TO UBOUND(choices$,1) DO
PRINT(i;": ";choices$[i])
END FOR
PRINT(prompt$;)
INPUT(index)
IF index<=UBOUND(choices$,1) AND index>=LBOUND(choices$,1) THEN ret$=choices$[index] END IF
UNTIL ret$<>""
sel$=ret$
END PROCEDURE
|
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.
| #Go | Go | package main
import (
"fmt"
"math"
"bytes"
"encoding/binary"
)
type testCase struct {
hashCode string
string
}
var testCases = []testCase{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
{"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
{"d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"},
}
func main() {
for _, tc := range testCases {
fmt.Printf("%s\n%x\n\n", tc.hashCode, md5(tc.string))
}
}
var shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}
var table [64]uint32
func init() {
for i := range table {
table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))
}
}
func md5(s string) (r [16]byte) {
padded := bytes.NewBuffer([]byte(s))
padded.WriteByte(0x80)
for padded.Len() % 64 != 56 {
padded.WriteByte(0)
}
messageLenBits := uint64(len(s)) * 8
binary.Write(padded, binary.LittleEndian, messageLenBits)
var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476
var buffer [16]uint32
for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { // read every 64 bytes
a1, b1, c1, d1 := a, b, c, d
for j := 0; j < 64; j++ {
var f uint32
bufferIndex := j
round := j >> 4
switch round {
case 0:
f = (b1 & c1) | (^b1 & d1)
case 1:
f = (b1 & d1) | (c1 & ^d1)
bufferIndex = (bufferIndex*5 + 1) & 0x0F
case 2:
f = b1 ^ c1 ^ d1
bufferIndex = (bufferIndex*3 + 5) & 0x0F
case 3:
f = c1 ^ (b1 | ^d1)
bufferIndex = (bufferIndex * 7) & 0x0F
}
sa := shift[(round<<2)|(j&3)]
a1 += f + buffer[bufferIndex] + table[j]
a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1
}
a, b, c, d = a+a1, b+b1, c+c1, d+d1
}
binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})
return
} |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Objeck | Objeck | foo := Object->New(); // allocates an object on the heap
foo_array := Int->New[size]; // allocates an integer array on the heap
x := 0; // allocates an integer on the stack |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Oforth | Oforth |
'ALLOCATING MEMORY FROM DIFFERENT MEMORY SOURCES
sys p
static byte b[0x1000] 'global memory
p=@b
function f()
local byte b[0x1000] 'stack memory in a procedure
p=@b
end function
p=getmemory 0x1000 'heap memory
...
freememory p 'to disallocate
sub rsp,0x1000 'stack memory direct
p=rsp
...
rsp=p 'to disallocate
'Named Memory shared between processes is
'also available using the Windows API (kernel32.dll)
'see MSDN:
'CreateFileMapping
'OpenFileMapping
'MapViewOfFile
'UnmapViewOfFile
'CloseHandle |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #Transd | Transd | #lang transd
MainModule: {
tbl: `1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz`,
tbl1: `
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3`,
cols: `@key_PATIENT_ID:Int,
LASTNAME:String,
VISIT_DATE:DateTime,
SCORE:Double,
SCORE_AVG:Double,
NUM_VISITS:Int`,
Record : typealias(Tuple<Int DateTime Double>()),
_start: (λ (with base TSDBase()
(load-table base tbl colNames: cols)
(build-index base "PATIENT_ID")
(with vizs Vector<Record>()
(load-table vizs tbl1 :mixedTypes fieldSep: "," rowSep: "\n" )
(for viz in vizs do
(tsd-query base
:update set:
(lambda PATIENT_ID Int() VISIT_DATE DateTime()
SCORE Double() SCORE_AVG Double() NUM_VISITS Int()
(+= NUM_VISITS 1)
(set VISIT_DATE (get viz 1))
(set SCORE (+ SCORE (get viz 2)))
(set SCORE_AVG (/ SCORE NUM_VISITS)))
where: (lambda PATIENT_ID Int() (eq PATIENT_ID (get viz 0))))
))
(with cols ["PATIENT_ID","LASTNAME","VISIT_DATE","SCORE","SCORE_AVG"]
(with recs (tsd-query base select: cols
as: [[Int(), String(), DateTime(), Double(), Double()]]
where: (lambda PATIENT_ID Int() true)
)
(for i in cols do (textout width: 10 i "|")) (lout "")
(for rec in recs do
(for-each rec (λ i :Data() (textout width: 10 i "|" )))
(lout ""))
))
))
} |
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.
| #Elixir | Elixir | defmodule Middle do
def three(num) do
n = num |> abs |> to_string
case {n,String.length(n) > 2,even?(n)} do
{n, true, false} ->
cut(n)
{_, false, _} ->
raise "Number must have at least three digits"
{_, _, true} ->
raise "Number must have an odd number of digits"
end
end
defp even?(n), do: rem(String.length(n),2) == 0
defp cut(n), do: String.slice(n,(div(String.length(n),2) - 1),3)
end
valids = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
Enum.each(valids, fn n -> :io.format "~10w : ~s~n", [n, Middle.three(n)] end)
errors = [1, 2, -1, -10, 2002, -2002, 0]
Enum.each(errors, fn n ->
:io.format "~10w : ", [n]
try do
IO.puts Middle.three(n)
rescue
e -> IO.puts e.message
end
end) |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #VBA | VBA | In your Vbaproject, insert :
- 1 Module
- 1 Class Module (Name it cMinesweeper) |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Wren | Wren | import "/fmt" for Fmt
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Fmt.print(" x | $4d", nums)
System.print("----+%("-" * 60)")
for (i in 1..12) {
var nums2 = nums.map { |n| (n >= i) ? (n * i).toString : " " }.toList
Fmt.print("$3d | $4s", i, nums2)
} |
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)
| #Java | Java | import java.math.BigInteger;
public class MillerRabinPrimalityTest {
public static void main(String[] args) {
BigInteger n = new BigInteger(args[0]);
int certainty = Integer.parseInt(args[1]);
System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite"));
}
} |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Java | Java |
public class MertensFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the merten function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", mertenFunction(n));
if ( (n+1) % 20 == 0 ) {
System.out.printf("%n");
}
}
for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {
int zeroCount = 0;
int zeroCrossingCount = 0;
int positiveCount = 0;
int negativeCount = 0;
int mSum = 0;
int mMin = Integer.MAX_VALUE;
int mMinIndex = 0;
int mMax = Integer.MIN_VALUE;
int mMaxIndex = 0;
int nMax = (int) Math.pow(10, exponent);
for ( int n = 1 ; n <= nMax ; n++ ) {
int m = mertenFunction(n);
mSum += m;
if ( m < mMin ) {
mMin = m;
mMinIndex = n;
}
if ( m > mMax ) {
mMax = m;
mMaxIndex = n;
}
if ( m > 0 ) {
positiveCount++;
}
if ( m < 0 ) {
negativeCount++;
}
if ( m == 0 ) {
zeroCount++;
}
if ( m == 0 && mertenFunction(n - 1) != 0 ) {
zeroCrossingCount++;
}
}
System.out.printf("%nFor M(x) with x from 1 to %,d%n", nMax);
System.out.printf("The maximum of M(x) is M(%,d) = %,d.%n", mMaxIndex, mMax);
System.out.printf("The minimum of M(x) is M(%,d) = %,d.%n", mMinIndex, mMin);
System.out.printf("The sum of M(x) is %,d.%n", mSum);
System.out.printf("The count of positive M(x) is %,d, count of negative M(x) is %,d.%n", positiveCount, negativeCount);
System.out.printf("M(x) has %,d zeroes in the interval.%n", zeroCount);
System.out.printf("M(x) has %,d crossings in the interval.%n", zeroCrossingCount);
}
}
private static int MU_MAX = 100_000_000;
private static int[] MU = null;
private static int[] MERTEN = null;
// Compute mobius and merten function via sieve
private static int mertenFunction(int n) {
if ( MERTEN != null ) {
return MERTEN[n];
}
// Populate array
MU = new int[MU_MAX+1];
MERTEN = new int[MU_MAX+1];
MERTEN[1] = 1;
int sqrt = (int) Math.sqrt(MU_MAX);
for ( int i = 0 ; i < MU_MAX ; i++ ) {
MU[i] = 1;
}
for ( int i = 2 ; i <= sqrt ; i++ ) {
if ( MU[i] == 1 ) {
// for each factor found, swap + and -
for ( int j = i ; j <= MU_MAX ; j += i ) {
MU[j] *= -i;
}
// square factor = 0
for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
MU[j] = 0;
}
}
}
int sum = 1;
for ( int i = 2 ; i <= MU_MAX ; i++ ) {
if ( MU[i] == i ) {
MU[i] = 1;
}
else if ( MU[i] == -i ) {
MU[i] = -1;
}
else if ( MU[i] < 0 ) {
MU[i] = 1;
}
else if ( MU[i] > 0 ) {
MU[i] = -1;
}
sum += MU[i];
MERTEN[i] = sum;
}
return MERTEN[n];
}
}
|
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.
| #Euphoria | Euphoria | include get.e
function menu_select(sequence items, object prompt)
if length(items) = 0 then
return ""
else
for i = 1 to length(items) do
printf(1,"%d) %s\n",{i,items[i]})
end for
if atom(prompt) then
prompt = "Choice?"
end if
return items[prompt_number(prompt,{1,length(items)})]
end if
end function
constant items = {"fee fie", "huff and puff", "mirror mirror", "tick tock"}
constant prompt = "Which is from the three pigs? "
printf(1,"You chose %s.\n",{menu_select(items,prompt)}) |
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.
| #Groovy | Groovy |
class MD5 {
private static final int INIT_A = 0x67452301
private static final int INIT_B = (int)0xEFCDAB89L
private static final int INIT_C = (int)0x98BADCFEL
private static final int INIT_D = 0x10325476
private static final int[] SHIFT_AMTS = [
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
]
private static final int[] TABLE_T = new int[64]
static
{
for (int i in 0..63)
TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)))
}
static byte[] computeMD5(byte[] message)
{
int messageLenBytes = message.length
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1
int totalLen = numBlocks << 6
byte[] paddingBytes = new byte[totalLen - messageLenBytes]
paddingBytes[0] = (byte)0x80
long messageLenBits = (long)messageLenBytes << 3
for (int i in 0..7)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits
messageLenBits >>>= 8
}
int a = INIT_A
int b = INIT_B
int c = INIT_C
int d = INIT_D
int[] buffer = new int[16]
for (int i in 0..(numBlocks - 1))
{
int index = i << 6
for (int j in 0..63) {
buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8)
index++
}
int originalA = a
int originalB = b
int originalC = c
int originalD = d
for (int j in 0..63)
{
int div16 = j >>> 4
int f = 0
int bufferIndex = j
switch (div16)
{
case 0:
f = (b & c) | (~b & d)
break
case 1:
f = (b & d) | (c & ~d)
bufferIndex = (bufferIndex * 5 + 1) & 0x0F
break
case 2:
f = b ^ c ^ d
bufferIndex = (bufferIndex * 3 + 5) & 0x0F
break
case 3:
f = c ^ (b | ~d)
bufferIndex = (bufferIndex * 7) & 0x0F
break
}
int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)])
a = d
d = c
c = b
b = temp
}
a += originalA
b += originalB
c += originalC
d += originalD
}
byte[] md5 = new byte[16]
int count = 0
for (int i in 0..3)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d))
for (int j in 0..3)
{
md5[count++] = (byte)n
n >>>= 8
}
}
return md5
}
static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder()
for (int i in 0..(b.length - 1))
{
sb.append(String.format("%02X", b[i] & 0xFF))
}
return sb.toString()
}
static void main(String[] args)
{
String[] testStrings = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890" ]
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"")
}
}
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #OxygenBasic | OxygenBasic |
'ALLOCATING MEMORY FROM DIFFERENT MEMORY SOURCES
sys p
static byte b[0x1000] 'global memory
p=@b
function f()
local byte b[0x1000] 'stack memory in a procedure
p=@b
end function
p=getmemory 0x1000 'heap memory
...
freememory p 'to disallocate
sub rsp,0x1000 'stack memory direct
p=rsp
...
rsp=p 'to disallocate
'Named Memory shared between processes is
'also available using the Windows API (kernel32.dll)
'see MSDN:
'CreateFileMapping
'OpenFileMapping
'MapViewOfFile
'UnmapViewOfFile
'CloseHandle |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #PARI.2FGP | PARI/GP | allocatemem(100<<20) |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #TutorialD | TutorialD | BEGIN;
TYPE Date UNION;
TYPE DateValid IS {Date POSSREP {year INTEGER, month INTEGER, day INTEGER}};
TYPE DateNone IS {Date POSSREP {}};
TYPE DateUnknown IS {Date POSSREP {}};
END;
VAR patient REAL RELATION {id INT, lastname CHAR} KEY {id};
INSERT patient RELATION
{TUPLE {id 1001, lastname 'Hopper'},
TUPLE {id 4004, lastname 'Wirth'},
TUPLE {id 3003, lastname 'Kemeny'},
TUPLE {id 2002, lastname 'Gosling'},
TUPLE {id 5005, lastname 'Kurtz'}
};
VAR visit REAL RELATION {id INT, date Date, score RATIONAL} KEY {id, date};
INSERT visit RELATION
{
TUPLE {id 2002, date DateValid(2020,09,10), score 6.8},
TUPLE {id 1001, date DateValid(2020,09,17), score 5.5},
TUPLE {id 4004, date DateValid(2020,09,24), score 8.4},
TUPLE {id 2002, date DateValid(2020,10,08), score NAN},
TUPLE {id 1001, date DateNone(), score 6.6},
TUPLE {id 3003, date DateValid(2020,11,12), score NAN},
TUPLE {id 4004, date DateValid(2020,11,05), score 7.0},
TUPLE {id 1001, date DateValid(2020,11,19), score 5.3}
};
((SUMMARIZE (visit WHERE score>0.0) BY {id}: {sumscore := SUM(score), avgscore := AVG(score)}) UNION
(EXTEND (patient {id} MINUS ((visit WHERE score>0.0) {id})): {sumscore := NaN, avgscore := NaN})) JOIN
(SUMMARIZE visit BY {id}: {maxdate := MAX(date)} UNION
(EXTEND (patient {id} MINUS (visit {id})): {maxdate := DateUnknown()})) JOIN
patient |
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.
| #Erlang | Erlang | %
-module(middle_three_digits).
-export([main/0]).
main() ->
digits(123),
digits(12345),
digits(1234567),
digits(987654321),
digits(10001),
digits(-10001),
digits(-123),
digits(-100),
digits(100),
digits(-12345),
digits(1),
digits(2),
digits(-1),
digits(-10),
digits(2002),
digits(-2002),
digits(0).
digits(N) when N < 0 ->
digits(-N);
digits(N) when (N div 100) =:= 0 ->
io:format("too small\n");
digits(N) ->
K=length(integer_to_list(N)),
if (K rem 2) =:= 0 ->
io:format("even number of digits\n");
true ->
loop((K-3) div 2 , N)
end.
loop(0, N) ->
io:format("~3..0B~n",[N rem 1000]);
loop(X,N) when X>0 ->
loop(X-1, N div 10).
|
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Wren | Wren | import "/dynamic" for Struct
import "/fmt" for Fmt
import "random" for Random
import "/ioutil" for Input
import "/str" for Str
var Cell = Struct.create("Cell", ["isMine", "display"])
var lMargin = 4
var grid = []
var mineCount = 0
var minesMarked = 0
var isGameOver = false
var rand = Random.new()
var makeGrid = Fn.new { |n, m|
if ( n <= 0 || m <= 0) Fiber.abort("Grid dimensions must be positive.")
grid = List.filled(n, null)
for (i in 0...n) {
grid[i] = List.filled(m, null)
for (j in 0...m) grid[i][j] = Cell.new(false, ".")
}
var min = (n * m * 0.1).round // 10% of tiles
var max = (n * m * 0.2).round // 20% of tiles
mineCount = min + rand.int(max - min + 1)
var rm = mineCount
while (rm > 0) {
var x = rand.int(n)
var y = rand.int(m)
if (!grid[x][y].isMine) {
rm = rm - 1
grid[x][y].isMine = true
}
}
minesMarked = 0
isGameOver = false
}
var displayGrid = Fn.new { |isEndOfGame|
if (!isEndOfGame) {
System.print("Grid has %(mineCount) mine(s), %(minesMarked) mine(s) marked.")
}
var margin = " " * lMargin
System.write("%(margin) ")
for (i in 1..grid.count) System.write(i)
System.print()
System.print("%(margin) %("-" * grid.count)")
for (y in 0...grid[0].count) {
Fmt.write("$*d:", lMargin, y+1)
for (x in 0...grid.count) System.write(grid[x][y].display)
System.print()
}
}
var endGame = Fn.new { |msg|
isGameOver = true
System.print(msg)
var ans = Input.option("Another game (y/n)? : ", "ynYN")
if (ans == "n" || ans == "N") return
makeGrid.call(6, 4)
displayGrid.call(false)
}
var resign = Fn.new {
var found = 0
for (y in 0...grid[0].count) {
for (x in 0...grid.count) {
if (grid[x][y].isMine) {
if (grid[x][y].display == "?") {
grid[x][y].display = "Y"
found = found + 1
} else if (grid[x][y].display != "x") {
grid[x][y].display = "N"
}
}
}
}
displayGrid.call(true)
var msg = "You found %(found), out of %(mineCount) mine(s)."
endGame.call(msg)
}
var usage = Fn.new {
System.print("h or ? - this help,")
System.print("c x y - clear cell (x,y),")
System.print("m x y - marks (toggles) cell (x,y),")
System.print("n - start a new game,")
System.print("q - quit/resign the game,")
System.print("where x is the (horizontal) column number and y is the (vertical) row number.\n")
}
var markCell = Fn.new { |x, y|
if (grid[x][y].display == "?") {
minesMarked = minesMarked - 1
grid[x][y].display = "."
} else if (grid[x][y].display == ".") {
minesMarked = minesMarked + 1
grid[x][y].display = "?"
}
}
var countAdjMines = Fn.new { |x, y|
var count = 0
for (j in y-1..y+1) {
if (j >= 0 && j < grid[0].count) {
for (i in x-1..x+1) {
if (i >= 0 && i < grid.count) {
if (grid[i][j].isMine) count = count + 1
}
}
}
}
return count
}
var clearCell // recursive function
clearCell = Fn.new { |x, y|
if (x >= 0 && x < grid.count && y >= 0 && y < grid[0].count) {
if (grid[x][y].display == ".") {
if (!grid[x][y].isMine) {
var count = countAdjMines.call(x, y)
if (count > 0) {
grid[x][y].display = String.fromByte(48 + count)
} else {
grid[x][y].display = " "
clearCell.call(x+1, y)
clearCell.call(x+1, y+1)
clearCell.call(x, y+1)
clearCell.call(x-1, y+1)
clearCell.call(x-1, y)
clearCell.call(x-1, y-1)
clearCell.call(x, y-1)
clearCell.call(x+1, y-1)
}
} else {
grid[x][y].display = "x"
System.print("Kaboom! You lost!")
return false
}
}
}
return true
}
var testForWin = Fn.new {
var isCleared = false
if (minesMarked == mineCount) {
isCleared = true
for (x in 0...grid.count) {
for (y in 0...grid[0].count) {
if (grid[x][y].display == ".") isCleared = false
}
}
}
if (isCleared) System.print("You won!")
return isCleared
}
var splitAction = Fn.new { |action|
var fields = action.split(" ").where{ |s| s != "" }.toList
if (fields.count != 3) return [0, 0, false]
var x = Num.fromString(fields[1])
if (x < 1 || x > grid.count) return [0, 0, false]
var y = Num.fromString(fields[2])
if (y < 1 || y > grid[0].count) return [0, 0, false]
return [x, y, true]
}
usage.call()
makeGrid.call(6, 4)
displayGrid.call(false)
while (!isGameOver) {
var action = Str.lower(Input.text("\n>", 1))
var first = action[0]
if (first == "h" || first == "?") {
usage.call()
} else if (first == "n") {
makeGrid.call(6, 4)
displayGrid.call(false)
} else if (first == "c") {
var res = splitAction.call(action)
if (!res[2]) continue
var x = res[0]
var y = res[1]
if (clearCell.call(x-1, y-1)) {
displayGrid.call(false)
if (testForWin.call()) resign.call()
} else {
resign.call()
}
} else if (first == "m") {
var res = splitAction.call(action)
if (!res[2]) continue
var x = res[0]
var y = res[1]
markCell.call(x-1, y-1)
displayGrid.call(false)
if (testForWin.call()) resign.call()
} else if (first == "q") {
resign.call()
} else {
System.print("Invalid option, try again")
}
} |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #XBasic | XBasic |
PROGRAM "multiplicationtables"
VERSION "0.0001"
DECLARE FUNCTION Entry()
FUNCTION Entry()
$N = 12
FOR j@@ = 1 TO $N - 1
PRINT FORMAT$("### ", j@@);
NEXT j@@
PRINT FORMAT$("###", $N)
FOR j@@ = 0 TO $N - 1
PRINT "----";
NEXT j@@
PRINT "+"
FOR i@@ = 1 TO $N
FOR j@@ = 1 TO $N
IF j@@ < i@@ THEN
PRINT " ";
ELSE
PRINT FORMAT$("### ", i@@ * j@@);
END IF
NEXT j@@
PRINT "|"; FORMAT$(" ##", i@@)
NEXT i@@
END FUNCTION
END PROGRAM
|
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)
| #JavaScript | JavaScript | function probablyPrime(n) {
if (n === 2 || n === 3) return true
if (n % 2 === 0 || n < 2) return false
// Write (n - 1) as 2^s * d
var s = 0,
d = n - 1
while ((d & 1) == 0) {
d >>= 1
++s
}
let base = 2
var x = Math.pow(base, d) % n
if (x == 1 || x == n - 1) return true
for (var i = 1; i <= s; i++) {
x = (x * x) % n
if (x === n - 1) return true
}
return false
} |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #jq | jq |
def sum(s): reduce s as $x (null; . + $x);
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# input: an array
# output: number of crossings at $value
def count_crossings($value):
. as $a
| reduce range(0; length) as $i ({};
if $a[$i] == $value
then if $i == 0 or .prev != $value then .count += 1 else . end
else .
end
| .prev = $a[$i] )
| .count; |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Julia | Julia | using Primes, Formatting
function moebius(n::Integer)
@assert n > 0
m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0
return reduce(*, m(p, e) for (p, e) in factor(n) if p ≥ 0; init=1)
end
μ(n) = moebius(n)
mertens(x) = sum(n -> μ(n), 1:x)
M(x) = mertens(x)
print("First 99 terms of the Mertens function for positive integers:\n ")
for n in 1:99
print(lpad(M(n), 3), n % 10 == 9 ? "\n" : "")
end
function maximinM(N)
z, cros, lastM, maxi, maxM, mini, minM, sumM, pos, neg = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
for i in 1:N
m = μ(i) + lastM
if m == 0 && lastM != 0
cros += 1
end
sumM += m
lastM = m
if m > maxM
maxi = i
maxM = m
elseif m < minM
mini = i
minM = m
end
if m > 0
pos += 1
elseif m < 0
neg += 1
else
z += 1
end
end
println("\nFor M(x) with x from 1 to $(format(N, commas=true)):")
println("The maximum of M(x) is M($(format(maxi, commas=true)) = $maxM.")
println("The minimum of M(x) is M($(format(mini, commas=true))) = $minM.")
println("The sum of M(x) is $(format(sumM, commas=true)).")
println("The count of positive M(x) is $(format(pos, commas=true)), count of negative M(x) is $(format(neg, commas=true)).")
println("M(x) has $(format(z, commas=true)) zeroes in the interval.")
println("M(x) has $(format(cros, commas=true)) crossings in the interval.")
diff = pos - neg
if diff > 0
println("Positive M(x) exceed negative ones by $(format(diff, commas=true)).")
else
println("Negative M(x) exceed positive ones by $(format(-diff, commas=true)).")
end
end
foreach(maximinM, (1000, 1_000_000, 1_000_000_000))
|
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.
| #F.23 | F# | open System
let rec menuChoice (options : string list) prompt =
if options = [] then ""
else
for i = 0 to options.Length - 1 do
printfn "%d. %s" (i + 1) options.[i]
printf "%s" prompt
let input = Int32.TryParse(Console.ReadLine())
match input with
| true, x when 1 <= x && x <= options.Length -> options.[x - 1]
| _, _ -> menuChoice options prompt
[<EntryPoint>]
let main _ =
let menuOptions = ["fee fie"; "huff and puff"; "mirror mirror"; "tick tock"]
let choice = menuChoice menuOptions "Choose one: "
printfn "You chose: %s" choice
0 |
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.
| #Haskell | Haskell | import Control.Monad (replicateM)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import Data.Array (Array, listArray, (!))
import Data.List (foldl)
import Data.Word (Word32)
import Numeric (showHex)
-- functions
type Fun = Word32 -> Word32 -> Word32 -> Word32
funF, funG, funH, funI :: Fun
funF x y z = (x .&. y) .|. (complement x .&. z)
funG x y z = (x .&. z) .|. (complement z .&. y)
funH x y z = x `xor` y `xor` z
funI x y z = y `xor` (complement z .|. x)
idxF, idxG, idxH, idxI :: Int -> Int
idxF i = i
idxG i = (5 * i + 1) `mod` 16
idxH i = (3 * i + 5) `mod` 16
idxI i = 7 * i `mod` 16
-- arrays
funA :: Array Int Fun
funA = listArray (1,64) $ replicate 16 =<< [funF, funG, funH, funI]
idxA :: Array Int Int
idxA = listArray (1,64) $ zipWith ($) (replicate 16 =<< [idxF, idxG, idxH, idxI]) [0..63]
rotA :: Array Int Int
rotA = listArray (1,64) $ concat . replicate 4 =<<
[[7, 12, 17, 22], [5, 9, 14, 20], [4, 11, 16, 23], [6, 10, 15, 21]]
sinA :: Array Int Word32
sinA = listArray (1,64) $ map (floor . (*mult) . abs . sin) [1..64]
where mult = 2 ** 32 :: Double
-- to lazily calculate MD5 sum for standart input:
-- main = putStrLn . md5sum =<< BL.getContents
main :: IO ()
main = mapM_ (putStrLn . md5sum . BLC.pack)
[ ""
, "a"
, "abc"
, "message digest"
, "abcdefghijklmnopqrstuvwxyz"
, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
, "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
]
md5sum :: BL.ByteString -> String
md5sum input =
let MD5 a b c d = getMD5 initial `runGet` input
in foldr hex [] . BL.unpack . runPut $ mapM_ putWord32le [a,b,c,d]
where
initial = MD5 0x67452301 0xEFCDAB89 0x98BADCFE 0x10325476
hex x s | x < 16 = '0' : showHex x s -- quick hack: like "%02x"
| otherwise = showHex x s
data MD5 = MD5
{ a :: {-# UNPACK #-} !Word32
, b :: {-# UNPACK #-} !Word32
, c :: {-# UNPACK #-} !Word32
, d :: {-# UNPACK #-} !Word32
}
getMD5 :: MD5 -> Get MD5
getMD5 md5 = do
chunk <- getLazyByteString 64
let len = BL.length chunk
if len == 64
then getMD5 $! md5 <+> chunk -- apply and process next chunk
else do -- input is totally eaten, finalize
bytes <- bytesRead
let fin = runPut . putWord64le $ fromIntegral (bytes - 64 + len) * 8
pad n = chunk `BL.append` (0x80 `BL.cons` BL.replicate (n - 1) 0x00)
return $ if len >= 56
then md5 <+> pad (64 - len) <+> BL.replicate 56 0x00 `BL.append` fin
else md5 <+> pad (56 - len) `BL.append` fin
(<+>) :: MD5 -> BL.ByteString -> MD5
infixl 5 <+>
md5@(MD5 a b c d) <+> bs =
let datA = listArray (0,15) $ replicateM 16 getWord32le `runGet` bs
MD5 a' b' c' d' = foldl' (md5round datA) md5 [1..64]
in MD5 (a + a') (b + b') (c + c') (d + d')
md5round :: Array Int Word32 -> MD5 -> Int -> MD5
md5round datA (MD5 a b c d) i =
let f = funA ! i
w = datA ! (idxA ! i)
a' = b + (a + f b c d + w + sinA ! i) `rotateL` rotA ! i
in MD5 d a' b c |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Pascal | Pascal | type
TByteArray = array of byte;
var
A: TByteArray;
begin
setLength(A,1000);
...
setLength(A,0);
end; |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Perl | Perl | atom addr = allocate(512) -- limit is 1,610,612,728 bytes on 32-bit systems
...
free(addr)
atom addr2 = allocate(512,1) -- automatically freed when addr2 drops out of scope or re-assigned
atom addr3 = allocate_string("a string",1) -- automatically freed when addr3 drops out of scope or re-assigned
|
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #Wren | Wren | import "/fmt" for Fmt
import "/sort" for Sort
class Patient {
construct new(id, lastName) {
_id = id
_lastName = lastName
if (!__dir) __dir = {}
__dir[id] = lastName
if (!__ids) {
__ids = [id]
} else {
__ids.add(id)
Sort.insertion(__ids)
}
}
id { _id }
lastName { _lastName }
// maps an id to a lastname
static dir { __dir }
// maintains a sorted list of ids
static ids { __ids }
}
class Visit {
construct new(id, date, score) {
_id = id
_date = date || "0000-00-00"
_score = score
if (!__dir) __dir = {}
if (!__dir[id]) {
__dir[id] = [ [_date], [score] ]
} else {
__dir[id][0].add(_date)
__dir[id][1].add(score)
}
}
id { _id }
date { _date }
score { _score }
// maps an id to lists of dates and scores
static dir { __dir }
}
class Merge {
construct new(id) {
_id = id
}
id { _id }
lastName { Patient.dir[_id] }
dates { Visit.dir[_id][0] }
scores { Visit.dir[_id][1] }
lastVisit { Sort.merge(dates)[-1] }
scoreSum { scores.reduce(0) { |acc, s| s ? acc + s : acc } }
scoreAvg { scoreSum / scores.count { |s| s } }
static print(merges) {
System.print("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |")
var fmt = "| $d | $-7s | $s | $4s | $4s |"
for (m in merges) {
if (Visit.dir[m.id]) {
var lv = (m.lastVisit != "0000-00-00") ? m.lastVisit : " "
var ss = (m.scoreSum > 0) ? Fmt.f(4, m.scoreSum, 1) : " "
var sa = (!m.scoreAvg.isNan) ? Fmt.f(4, m.scoreAvg, 2) : " "
Fmt.print(fmt, m.id, m.lastName, lv, ss, sa)
} else {
Fmt.print(fmt, m.id, m.lastName, " ", " ", " ")
}
}
}
}
Patient.new(1001, "Hopper")
Patient.new(4004, "Wirth")
Patient.new(3003, "Kemeny")
Patient.new(2002, "Gosling")
Patient.new(5005, "Kurtz")
Visit.new(2002, "2020-09-10", 6.8)
Visit.new(1001, "2020-09-17", 5.5)
Visit.new(4004, "2020-09-24", 8.4)
Visit.new(2002, "2020-10-08", null)
Visit.new(1001, null , 6.6)
Visit.new(3003, "2020-11-12", null)
Visit.new(4004, "2020-11-05", 7.0)
Visit.new(1001, "2020-11-19", 5.3)
var merges = Patient.ids.map { |id| Merge.new(id) }.toList
Merge.print(merges) |
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.
| #ERRE | ERRE |
PROGRAM MIDDLE
!$DOUBLE
FUNCTION LUNG(N)
LUNG=LEN(STR$(INT(ABS(N))))+1
END FUNCTION
FUNCTION NCNT(N)
NCNT=VAL(MID$(STR$(INT(ABS(N))),(LUNG(N)-1)/2,3))
END FUNCTION
FUNCTION EVEN(N)
EVEN=INT(N/2)=N/2
END FUNCTION
PROCEDURE NUMBER_EXAM(N->R$)
R$="" LG%=LUNG(N)-2
IF EVEN(LG%) THEN R$="?EVEN," END IF
IF LG%<3 THEN
R$=R$+"ONLY"+STR$(LG%)+" DIGIT"
IF LG%=1 THEN
R$=R$+"S"
END IF
END IF
IF RIGHT$(R$,1)="," THEN R$=LEFT$(R$,LEN(R$)-1) EXIT PROCEDURE END IF
IF LEFT$(R$,1)="?" THEN EXIT PROCEDURE END IF
IF R$<>"" THEN R$="?"+R$ EXIT PROCEDURE END IF
R$=STR$(NCNT(N))
IF LEFT$(R$,1)=" " THEN R$=MID$(R$,2) END IF
IF LEN(R$)=1 THEN R$="00"+R$ END IF
IF LEN(R$)=2 THEN R$="0"+R$ END IF
END PROCEDURE
BEGIN
DATA(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)
DATA(1,2,-1,-10,2002,-2002,0)
FOR I%=1 TO 17 DO
READ(N)
PRINT(N;" ",)
NUMBER_EXAM(N->R$)
PRINT(R$)
END FOR
END PROGRAM
|
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int X, Y;
[Format(4, 0);
Text(0, " |"); for X:= 1 to 12 do RlOut(0, float(X));
CrLf(0);
Text(0, " --+"); for X:= 1 to 12 do Text(0, "----");
CrLf(0);
for Y:= 1 to 12 do
[RlOut(0, float(Y)); ChOut(0, ^|);
for X:= 1 to 12 do
if X>=Y then RlOut(0, float(X*Y)) else Text(0, " . .");
CrLf(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)
| #Julia | Julia |
witnesses(n::Union(Uint8,Int8,Uint16,Int16)) = (2,3)
witnesses(n::Union(Uint32,Int32)) = n < 1373653 ? (2,3) : (2,7,61)
witnesses(n::Union(Uint64,Int64)) =
n < 1373653 ? (2,3) :
n < 4759123141 ? (2,7,61) :
n < 2152302898747 ? (2,3,5,7,11) :
n < 3474749660383 ? (2,3,5,7,11,13) :
(2,325,9375,28178,450775,9780504,1795265022)
function isprime(n::Integer)
n == 2 && return true
(n < 2) | iseven(n) && return false
s = trailing_zeros(n-1)
d = (n-1) >>> s
for a in witnesses(n)
a < n || break
x = powermod(a,d,n)
x == 1 && continue
t = s
while x != n-1
(t-=1) <= 0 && return false
x = oftype(n, Base.widemul(x,x) % n)
x == 1 && return false
end
end
return true
end
|
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION M(1000)
M(1) = 1
THROUGH GENMRT, FOR N=2, 1, N.G.1000
M(N) = 1
THROUGH GENMRT, FOR K=2, 1, K.G.N
GENMRT M(N) = M(N) - M(N/K)
PRINT COMMENT $ FIRST 99 MERTEN NUMBERS ARE$
VECTOR VALUES F9 = $S3,9(I2,S1)*$
VECTOR VALUES F10 = $10(I2,S1)*$
PRINT FORMAT F9, M(1), M(2), M(3), M(4), M(5), M(6),
0 M(7), M(8), M(9)
THROUGH SHOW, FOR N=10, 10, N.GE.100
SHOW PRINT FORMAT F10, M(N), M(N+1), M(N+2), M(N+3), M(N+4),
0 M(N+5), M(N+6), M(N+7), M(N+8), M(N+9), M(N+10)
ZERO = 0
CROSS = 0
THROUGH ZC, FOR N=1, 1, N.G.1000
WHENEVER M(N).E.0, ZERO = ZERO + 1
ZC WHENEVER M(N).E.0 .AND. M(N-1).NE.0, CROSS = CROSS + 1
VECTOR VALUES FZ = $13HM(N) IS ZERO ,I2,S1,5HTIMES*$
PRINT FORMAT FZ, ZERO
VECTOR VALUES FC = $18HM(N) CROSSES ZERO ,I2,S1,5HTIMES*$
PRINT FORMAT FC, CROSS
END OF PROGRAM |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Mertens]
Mertens[n_] := Total[MoebiusMu[Range[n]]]
Grid[Partition[Mertens /@ Range[99], UpTo[10]]]
Count[Mertens /@ Range[1000], 0]
SequenceCount[Mertens /@ Range[1000], {Except[0], 0}] |
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.
| #Factor | Factor | USING: formatting io kernel math math.parser sequences ;
: print-menu ( seq -- )
[ 1 + swap "%d - %s\n" printf ] each-index
"Your choice? " write flush ;
: (select) ( seq -- result )
dup print-menu readln string>number dup integer? [
drop 1 - swap 2dup bounds-check?
[ nth ] [ nip (select) ] if
] [ drop (select) ] if* ;
: select ( seq -- result ) [ "" ] [ (select) ] if-empty ; |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main() # validate against the RFC test strings and more
testMD5("The quick brown fox jumps over the lazy dog", 16r9e107d9d372bb6826bd81d3542a419d6)
testMD5("The quick brown fox jumps over the lazy dog.", 16re4d909c290d0fb1ca068ffaddf22cbd0)
testMD5("", 16rd41d8cd98f00b204e9800998ecf8427e) #R = MD5 test suite from RFC
testMD5("a", 16r0cc175b9c0f1b6a831c399e269772661) #R
testMD5("abc", 16r900150983cd24fb0d6963f7d28e17f72) #R
testMD5("message digest", 16rf96b697d7cb7938d525a2f31aaf161d0) #R
testMD5("abcdefghijklmnopqrstuvwxyz", 16rc3fcd3d76192e4007dfb496cca67e13b) #R
testMD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 16rd174ab98d277d9f5a5611c2c9f419d9f) #R
testMD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890", 16r57edf4a22be3c955ac49da2e2107b67a) #R
end
procedure testMD5(s,rh) # compute the MD5 hash and compare it to reference value
write("Message(length=",*s,") = ",image(s))
write("Digest = ",hexstring(h := MD5(s)),if h = rh then " matches reference hash" else (" does not match reference hash = " || hexstring(rh)),"\n")
end
link hexcvt # for testMD5
$define B32 4 # 32 bits
$define B64 8 # 64 bits in bytes
$define B512 64 # 512 bits in bytes
$define M32 16r100000000 # 2^32
$define M64 16r10000000000000000 # 2^64
procedure MD5(s) #: return MD5 hash of message s
local w,a,b,c,d,i,t,m
local mlength,message,hash
static rs,ks,istate,maxpad,g
initial {
every (rs := []) |||:=
(t := [ 7, 12, 17, 22] | [ 5, 9, 14, 20] | [ 4, 11, 16, 23] | [ 6, 10, 15, 21]) ||| t ||| t ||| t
every put(ks := [],integer(M32 * abs(sin(i := 1 to 64))))
istate := [ 16r67452301, 16rEFCDAB89, 16r98BADCFE, 16r10325476 ] # "Magic" IV
maxpad := left(char(16r80),B512+B64,char(16r00)) # maximum possible padding
g := []
every i := 0 to 63 do # precompute offsets
case round := i/16 of {
0 : put(g,i + 1)
1 : put(g,(5*i+1) % 16 + 1)
2 : put(g,(3*i+5) % 16 + 1)
3 : put(g,(7*i) % 16 + 1)
}
if not (*rs = *ks = 64) then runerr(500,"MD5 setup error")
}
# 1. Construct prefix
t := (*s*8)%M64 # original message length
s ||:= maxpad # append maximum padding
s[0-:*s%B512] := "" # trim to final length
s[0-:B64] := reverse(unsigned2string(t,B64) ) # as little endian length
message := [] # 2. Subdivide message
s ? while put(message,move(B512)) # into 512 bit blocks
# 3. Transform message ...
state := copy(istate) # Initialize hashes
every m := !message do { # For each message block
w := []
m ? while put(w,unsigned(reverse(move(B32)))) # break into little-endian words
a := state[1] # pick up hashes
b := state[2]
c := state[3]
d := state[4]
every i := 1 to 64 do { # Process 4 rounds of hashes
case round := (i-1)/16 of {
0 : a +:= ixor(d, iand(b,ixor(c,d))) # 0..15 - alternate F
1 : a +:= ixor(c,iand(d,ixor(b,c))) # 16..31 - alternate G
2 : a +:= ixor(b,ixor(c,d)) # 32..47 - H
3 : a +:= ixor(c,ior(b,ixor(d,16rffffffff))) # 48..64 - alternate I
} # Core of FF, GG, HH, II
a +:= ks[i] + w[g[i]] # and the rest
a %:= M32
a := ior( ishift(a,rs[i]), ishift(a,-(32-rs[i]))) # 32bit rotate
a +:= b
a :=: b :=: c :=: d # rotate variables
}
state[1] +:= a # Add back new hashes
state[2] +:= b
state[3] +:= c
state[4] +:= d
every !state %:= M32 # mod 2^32
}
every (hash := "") ||:= reverse(unsigned2string(!state,4)) # little-endian digest
return unsigned(hash)
end
procedure unsigned2string(i,w) # uint to string pad to w bytes
local s
if i < 0 then runerr(500,i)
s := ""
while (0 < i) | (*s < \w) do {
s ||:= char(i % 256)
i /:= 256
}
return reverse(s)
end
link unsigned # string to unsigned integer |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Phix | Phix | atom addr = allocate(512) -- limit is 1,610,612,728 bytes on 32-bit systems
...
free(addr)
atom addr2 = allocate(512,1) -- automatically freed when addr2 drops out of scope or re-assigned
atom addr3 = allocate_string("a string",1) -- automatically freed when addr3 drops out of scope or re-assigned
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #PicoLisp | PicoLisp |
mainproc: proc options(main) reorder;
subproc: proc;
dcl subvar char init ('X');
put skip data(subvar);
subvar = 'Q';
end subproc;
call subproc();
call subproc();
end mainproc; |
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.