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/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #Action.21 | Action! | DEFINE MINCOLORS="2"
DEFINE MAXCOLORS="20"
DEFINE MINLENGTH="4"
DEFINE MAXLENGTH="10"
DEFINE MINGUESS="7"
DEFINE MAXGUESS="20"
TYPE Score=[BYTE spot,corr,err]
TYPE Settings=[BYTE colors,length,guesses,repeat]
PROC GetSettings(Settings POINTER s)
CHAR ARRAY tmp(10)
DO
PrintF("Enter number of colors (%B-%B):"... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Fortran | Fortran | module optim_mod
implicit none
contains
subroutine optim(a)
implicit none
integer :: a(:), n, i, j, k
integer, allocatable :: u(:, :)
integer(8) :: c
integer(8), allocatable :: v(:, :)
n = ubound(a, 1) - 1
allocate (u(n, n), v(n, n))
v = huge(v)
... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
/mh := \A[1] | 12
/mw := \A[2] | 16
mz := DisplayMaze(GenerateMaze(mh,mw))
WriteImage(mz.filename) # save file
WAttrib(mz.window,"canvas=normal") # show it
until Event() == &lpress # wait for left mouse press
Solver(mz.maze)
DisplayMazeSolution(mz)
WriteImage(... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Factor | Factor | USING: grouping.extras io.encodings.utf8 io.files kernel
math.order math.parser math.vectors prettyprint sequences
splitting ;
IN: rosetta-code.maximum-triangle-path-sum
: parse-triangle ( path -- seq )
utf8 file-lines [ " " split harvest ] map
[ [ string>number ] map ] map ;
: max-triangle-path-sum ( seq -... |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifi... | #Perl | Perl | sub md4(@) {
my @input = grep { defined && length > 0 } split /(.{64})/s, join '', @_;
push @input, '' if !@input || length($input[$#input]) >= 56;
my @A = (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476); # initial regs
my @T = (0, 0x5A827999, 0x6ED9EBA1);
my @L = qw(3 7 11 19 3 5 9 13 3 9 11 15)... |
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;... | #Swift | Swift | var num:Int = \\enter your number here
if num<0{num = -num}
var numArray:[Int]=[]
while num>0{
var temp:Int=num%10
numArray.append(temp)
num=num/10
}
var i:Int=numArray.count
if i<3||i%2==0{
print("Invalid Input")
}
else{
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
} |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Crystal | Crystal | require "digest/md5"
puts Digest::MD5.hexdigest("The quick brown fox jumped over the lazy dog's back") |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Perl | Perl | use ntheory qw/forperm gcd vecmin/;
sub Mcnugget_number {
my $counts = shift;
return 'No maximum' if 1 < gcd @$counts;
my $min = vecmin @$counts;
my @meals;
my @min;
my $a = -1;
while (1) {
$a++;
for my $b (0..$a) {
for my $c (0..$b) {
my @... |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[MakeLengthFive, MayanNumeral]
MakeLengthFive[ci_String] := Module[{c},
c = If[EvenQ[StringLength[ci]], ci <> " ", ci];
While[StringLength[c] < 5, c = " " <> c <> " "];
c
]
MayanNumeral[n_Integer?Positive] := Module[{nums, q, r, c},
nums = IntegerDigits[n, 20];
Row[Table[
{q, r} = QuotientRemain... |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #Nim | Nim |
import algorithm
type Border = enum UL = "╔", UC = "╦", UR = "╗", LL = "╚", LC = "╩", LR = "╝", HB = "═", VB = "║"
const
Mayan = [" ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙"]
M0 = " Θ "
M5 = "────"
type
Digit = range[0..19]
Numeral = array[4, string]
MayanNumber = seq[Numeral]
func toBase20(n: N... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #11l | 11l | F transpose(&matrix)
V toRet = [[0] * matrix.len] * matrix[0].len
L(row) (0 .< matrix.len)
L(col) (0 .< matrix[row].len)
toRet[col][row] = matrix[row][col]
R toRet
V m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print("Original")
print(m)
print("After Transposition")
print(transpos... |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #AutoHotkey | AutoHotkey | ; Initially build the board
Width := 11
Height := 8
Loop % height*2+1
{
Outer := A_Index
Loop % Width
maze .= Outer & 1 ? "+-" : "|0"
maze .= (Outer & 1 ? "+" : "|") "`n"
}
StringTrimRight, maze, maze, 1 ; removes trailing newline
Clipboard := Walk(maze)
Walk(S, x=0, y=0){
If !x{ ; --Start at a random cell...
... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Chapel | Chapel | proc **(a, e) {
// create result matrix of same dimensions
var r:[a.domain] a.eltType;
// and initialize to identity matrix
forall ij in r.domain do
r(ij) = if ij(1) == ij(2) then 1 else 0;
for 1..e do
r *= a;
return r;
} |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Common_Lisp | Common Lisp | (defun multiply-matrices (matrix-0 matrix-1)
"Takes two 2D arrays and returns their product, or an error if they cannot be multiplied"
(let* ((m0-dims (array-dimensions matrix-0))
(m1-dims (array-dimensions matrix-1))
(m0-dim (length m0-dims))
(m1-dim (length m1-dims)))
(if (or (/= 2 ... |
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #C | C | $ sudo apt install libncurses5-dev
|
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #Ada | Ada | with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Ada.Containers.Ordered_Sets;
use Ada.Strings.Fixed;
procedure MasterMind
is
subtype Color_Number is Positive range 2 .. 20;
subtype Code_Size is Positive range 4 .. 10;
subtype Guesses_Number is Positive range 7 .. 20;
sub... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Go | Go | package main
import "fmt"
// PrintMatrixChainOrder prints the optimal order for chain
// multiplying matrices.
// Matrix A[i] has dimensions dims[i-1]×dims[i].
func PrintMatrixChainOrder(dims []int) {
n := len(dims) - 1
m, s := newSquareMatrices(n)
// m[i,j] will be minimum number of scalar multiplactions
// ... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #J | J |
maze=:4 :0
assert.0<:n=.<:x*y
horiz=. 0$~x,y-1
verti=. 0$~(x-1),y
path=.,:here=. ?x,y
unvisited=.0 (<here+1)} 0,0,~|:0,0,~1$~y,x
while.n do.
neighbors=. here+"1 (,-)=0 1
neighbors=. neighbors #~ (<"1 neighbors+1) {unvisited
if.#neighbors do.
n=.n-1
next=. ({~ ?@#) neighbors
u... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Forth | Forth |
\ Triangle representation; words created by this defining word return the address of element
\ specified by its row number and position within that row, both indexed from 0.
: TRIANGLE ( "name" -- |DOES: row pos -- addr )
CREATE DOES> ROT DUP 1+ * 2/ CELLS + SWAP CELLS +
;
18 CONSTANT #ROWS \ total number of ... |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifi... | #Phix | Phix | --
-- demo\rosetta\md4.exw
-- ====================
--
-- Non-optimised. If there is a genuine need for something faster, I can give #ilASM a bash.
-- MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
-- Even the replacement, MD5 is now considered sever... |
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;... | #Tcl | Tcl | proc middleThree n {
if {$n < 0} {
set n [expr {-$n}]
}
set idx [expr {[string length $n] - 2}]
if {$idx % 2 == 0} {
error "no middle three digits: input is of even length"
}
if {$idx < 1} {
error "no middle three digits: insufficient digits"
}
set idx [expr {$idx / 2}]
string ran... |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #D | D | void main() {
import std.stdio, std.digest.md;
auto txt = "The quick brown fox jumped over the lazy dog's back";
writefln("%-(%02x%)", txt.md5Of);
} |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Phix | Phix | with javascript_semantics
constant limit=100
sequence nuggets = repeat(false,limit+1)
for sixes=0 to limit by 6 do
for nines=sixes to limit by 9 do
for twenties=nines to limit by 20 do
nuggets[twenties+1] = true
end for
end for
end for
printf(1,"Maximum non-McNuggets number is %d\n",... |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #Perl | Perl | use ntheory qw/fromdigits todigitstring/;
my $t_style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"';
my $c_style = '"border: solid black 2px;background-color: #fffff0;border-bottom: double 6px;'.
'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'.
'vertical-al... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #360_Assembly | 360 Assembly | ...
KN EQU 3
KM EQU 5
N DC AL2(KN)
M DC AL2(KM)
A DS (KN*KM)F matrix a(n,m)
B DS (KM*KN)F matrix b(m,n)
...
* b(j,i)=a(i,j)
* transposition using Horner's formula
LA R4,0 i,from 1
... |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #AWK | AWK | #!/usr/bin/awk -f
# Remember: AWK is 1-based, for better or worse.
BEGIN {
# The maze dimensions.
width = 20; # Global
height = 20; # Global
resetMaze();
# Some constants.
top = 1;
bottom = 2;
left = 3;
right = 4;
# Randomize the PRNG.
randomize();
# Visit all ... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #D | D | import std.stdio, std.string, std.math, std.array, std.algorithm;
struct SquareMat(T = creal) {
public static string fmt = "%8.3f";
private alias TM = T[][];
private TM a;
public this(in size_t side) pure nothrow @safe
in {
assert(side > 0);
} body {
a = new TM(side, side);
... |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #11l | 11l | F maprange(a, b, s)
R b[0] + (Float(s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]))
L(s) 0..10
print(‘#2 maps to #.’.format(s, maprange((0, 10), (-1, 0), s))) |
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #Common_Lisp | Common Lisp |
(defun matrix-digital-rain ()
(with-screen (scr :input-echoing nil :input-blocking nil :cursor-visible nil)
(let* ((width (width scr))
(height (height scr))
;; start at a random height in each column.
(positions (loop repeat width collect (random height)))
;; run each... |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #APL | APL | #!/usr/local/bin/apl -s -f --
⍝ Define the alphabet
A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
⍝ Make ASCII values upper case
∇n←AscUp c
n←c-32×(c≥97)∧(c≤122)
∇
⍝ Does a list have repeated values?
∇r←Rpts l
r←(l⍳l)≢⍳⍴l
∇
⍝ Keyboard input using ⎕ and ⍞ doesn't work well using GNU APL in script mode,
⍝ so yo... |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #AutoHotkey | AutoHotkey | w := h := 32, maxRows := 10, numPegs := 8
ww := floor(w/2-2), hh := floor(h/2-2)
grid := [], dx := w*4.5
gosub, Decode
Gui, Font, S18, Consolas
loop, 4
{
i := A_Index-1
Gui, add, button, % "x" (Mod(i, 4)?"+0":"30") " y"
. (Mod(i, 4)?"10" : "10") " w" w " h" h " vGoal" A_Index , ?
}
Gui, Add, Text, % "sectio... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Haskell | Haskell | import Data.List (elemIndex)
import Data.Char (chr, ord)
import Data.Maybe (fromJust)
mats :: [[Int]]
mats =
[ [5, 6, 3, 1]
, [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
, [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
]
cost :: [Int] -> Int -> Int -> (Int, Int)
cost a i j
| i < j =
let m =... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Java | Java | import java.io.*;
import java.util.*;
public class MazeSolver
{
/**
* Reads a file into an array of strings, one per line.
*/
private static String[] readLines (InputStream f) throws IOException
{
BufferedReader r =
new BufferedReader (new InputStreamReader (f, "US-ASCII"));
... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Fortran | Fortran |
MODULE PYRAMIDS !Produces a pyramid of numbers in 1-D array.
INTEGER MANY !The usual storage issues.
PARAMETER (MANY = 666) !This should suffice.
INTEGER BRICK(MANY),IN,LAYERS !Defines a pyramid.
CONTAINS
SUBROUTINE IMHOTEP(PLAN)!The architect.
Counting is from the apex down... |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifi... | #PHP | PHP |
echo hash('md4', "Rosetta Code"), "\n";
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values;... | #UNIX_Shell | UNIX Shell | function middle3digits
{
typeset -i n="${1#-}"
typeset -i l=${#n}
if (( l < 3 )); then
echo >&2 "$1 has less than 3 digits"
return 1
elif (( l % 2 == 0 )); then
echo >&2 "$1 has an even number of digits"
return 1
else
echo ${n:$((l/2-1)):3}
return 0
fi
}
# test
testdata=(123 1234... |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Delphi | Delphi | program MD5Hash;
{$APPTYPE CONSOLE}
uses
SysUtils,
IdHashMessageDigest;
function MD5(aValue: string): string;
begin
with TIdHashMessageDigest5.Create do
begin
Result:= HashStringAsHex(aValue);
Free;
end;
end;
begin
Writeln(MD5(''));
Writeln(MD5('a'));
Writeln(MD5('abc'));
Writeln(MD5('... |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Picat | Picat | import cp.
go =>
N :: 0..100,
foreach(X in 0..16, Y in 0..11, Z in 0..5)
6*X + 9*Y + 20*Z #!= N
end,
solve($[max(N)],N),
println(n=N). |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #PL.2FM | PL/M | /* MAYAN NUMERALS IN PL/M
THIS PROGRAM RUNS UNDER CP/M AND TAKES THE NUMBER ON THE COMMAND LINE */
100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* C... |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #11l | 11l | F matrix_mul(m1, m2)
assert(m1[0].len == m2.len)
V r = [[0.0] * m2[0].len] * m1.len
L(j) 0 .< m1.len
L(i) 0 .< m2[0].len
V s = 0.0
L(k) 0 .< m2.len
s += m1[j][k] * m2[k][i]
r[j][i] = s
R r
F to_str(m)
V result = ‘([’
L(r) m
I result.len > 2
... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #68000_Assembly | 68000 Assembly | Transpose2DArray_B:
;INPUT:
;A0 = POINTER TO SOURCE ARRAY
;A1 = POINTER TO BACKUP AREA
; (YOU NEED THE SAME AMOUNT OF FREE SPACE AS THE SOURCE ARRAY.)
; (IT'S YOUR RESPONSIBILITY TO KNOW WHERE THAT IS.)
;D0.W = ARRAY ROW LENGTH-1
;D1.W = ARRAY COLUMN HEIGHT-1
MOVEM.L D2-D7,-(SP)
MOVE.W D0,D4 ;width ... |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #BASIC | BASIC | OPTION BASE 0
RANDOMIZE TIMER
REM must be even
width% = 40
height% = 20
REM make array and fill
DIM maze$(width%, height%)
FOR x% = 0 TO width%
FOR y% = 0 TO height%
maze$(x%, y%) = "#"
NEXT y%
NEXT x%
REM initial start location
currentx% = INT(RND * (width% - 1))
currenty% = INT(RND * (height% - ... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Delphi | Delphi |
program Matrix_exponentiation_operator;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TCells = array of array of double;
TMatrix = record
private
FCells: TCells;
function GetCells(r, c: Integer): Double;
procedure SetCells(r, c: Integer; const Value: Double);
class operato... |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #ACL2 | ACL2 | (defun mapping (a1 a2 b1 b2 s)
(+ b1 (/ (* (- s a1)
(- b2 b1))
(- a2 a1))))
(defun map-each (a1 a2 b1 b2 ss)
(if (endp ss)
nil
(cons (mapping a1 a2 b1 b2 (first ss))
(map-each a1 a2 b1 b2 (rest ss)))))
(map-each 0 10 -1 0 '(0 1 2 3 4 5 6 7 8 9 10))
;; (-... |
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #Go | Go | package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
// Time between row updates in microseconds.
// Controls the speed of the digital rain effect.
const rowDelay = 40000
func main() {
start := time.Now()
rand.Seed(time.Now().UnixNano())
// Characte... |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #C.2B.2B | C++ | #include <iostream>
#include <algorithm>
#include <ctime>
#include <string>
#include <vector>
typedef std::vector<char> vecChar;
class master {
public:
master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {
std::string color = "ABCDEFGHIJKLMNOPQRST";
if( code_len < 4 ) cod... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #J | J | moo =: verb define
s =. m =. 0 $~ ,~ n=._1+#y
for_lmo. 1+i.<:n do.
for_i. i. n-lmo do.
j =. i + lmo
m =. _ (<i;j)} m
for_k. i+i.j-i do.
cost =. ((<i;k){m) + ((<(k+1);j){m) + */ y {~ i,(k+1),(j+1)
if. cost < ((<i;j){m) do.
m =. cost (<i;j)} m
s =. k (<i;j)} s... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Java | Java |
import java.util.Arrays;
public class MatrixChainMultiplication {
public static void main(String[] args) {
runMatrixChainMultiplication(new int[] {5, 6, 3, 1});
runMatrixChainMultiplication(new int[] {1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2});
runMatrixChainMultiplication(new... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #JavaScript | JavaScript |
var ctx, wid, hei, cols, rows, maze, stack = [], start = {x:-1, y:-1}, end = {x:-1, y:-1}, grid = 8;
function drawMaze() {
for( var i = 0; i < cols; i++ ) {
for( var j = 0; j < rows; j++ ) {
switch( maze[i][j] ) {
case 0: ctx.fillStyle = "black"; break;
case 1: ... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #FreeBASIC | FreeBASIC | ' version 21-06-2015
' compile with: fbc -s console
Data " 55"
Data " 94 48"
Data " 95 30 96"
Data " 77 71 26 67"
Data " 97 13 76 38 45"
Data " 07 36 79 16 37 68"
Data " 48 07 09 18 70 26 06"
Data " 18 72 79 46... |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifi... | #PicoLisp | PicoLisp | (de *Md4-W .
(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16
1 9 5 13 3 11 7 15 2 10 6 14 4 12 8 16 .))
(de *Md4-R1 . (3 7 11 19 .))
(de *Md4-R2 . (3 5 9 13 .))
(de *Md4-R3 . (3 9 11 15 .))
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de not32 (N)
... |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values;... | #VBA | VBA |
Option Explicit
Sub Main_Middle_three_digits()
Dim Numbers, i&
Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _
100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
For i = 0 To 16
Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i)))
Next
End Sub
Funct... |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #E | E | def makeMessageDigest := <import:java.security.makeMessageDigest>
def sprintf := <import:java.lang.makeString>.format
def digest := makeMessageDigest.getInstance("MD5") \
.digest("The quick brown fox jumped over the lazy dog's back".getBytes("iso-8859-1"))
for b in digest {
print(sprintf("%02x", [b]))
}
println... |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #PicoLisp | PicoLisp | (de nuggets1 (M)
(let Lst (range 0 M)
(for A (range 0 M 6)
(for B (range A M 9)
(for C (range B M 20)
(set (nth Lst (inc C))) ) ) )
(apply max Lst) ) ) |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #PL.2FI | PL/I | mcnugget: procedure options(main);
declare nugget(0:100) bit, (a, b, c) fixed;
do a=0 to 100; nugget(a) = '0'b; end;
do a=0 to 100 by 6;
do b=a to 100 by 9;
do c=b to 100 by 20;
nugget(c) = '1'b;
end;
end;
end;
do a=100 to 0 by -1;
... |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #Phix | Phix | -- demo\rosetta\Mayan_numerals.exw
without js -- (file i/o [when as_html is true])
constant as_html = true, -- false == nasty ascii
inline_css = true -- also uses wiki tables ({| etc) if false
string html = ""
constant t_style = "border-collapse: separate; text-align: center; border-spacing: 3px ... |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #360_Assembly | 360 Assembly | * Matrix multiplication 06/08/2015
MATRIXRC CSECT Matrix multiplication
USING MATRIXRC,R13
SAVEARA B STM-SAVEARA(R15)
DC 17F'0'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
LA R7,1 ... |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return succe... | #11l | 11l | fs:create_dirs(path) |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #ACL2 | ACL2 | (defun cons-each (xs xss)
(if (or (endp xs) (endp xss))
nil
(cons (cons (first xs) (first xss))
(cons-each (rest xs) (rest xss)))))
(defun list-each (xs)
(if (endp xs)
nil
(cons (list (first xs))
(list-each (rest xs)))))
(defun transpose-list (xss)
(if ... |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #Batch_File | Batch File | :amaze Rows Cols [wall char]
:: A stack-less, iterative, depth-first maze generator in native WinNT batch.
:: Rows and Cols must each be >1 and Rows*Cols cannot exceed 2096.
:: Default wall character is #, [wall char] is used if provided.
@ECHO OFF
SETLOCAL EnableDelayedExpansion
:: check for valid input, else GOTO ... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #ERRE | ERRE | 10
This example calculates | 3 2 |
| 2 1 |
|
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Factor | Factor | USING: kernel math math.matrices sequences ;
: my-m^n ( m n -- m' )
dup 0 < [ "no negative exponents" throw ] [
[ drop length identity-matrix ]
[ swap '[ _ m. ] times ] 2bi
] if ; |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Map(REAL POINTER a1,a2,b1,b2,s,res)
REAL tmp1,tmp2,tmp3
RealSub(s,a1,tmp1) ;tmp1=s-a1
RealSub(b2,b1,tmp2) ;tmp2=b2-b1
RealMult(tmp1,tmp2,tmp3) ;tmp3=(s-a1)*(b2-b1)
RealSub(a2,a1,tmp1) ;tmp1=a2-a1
RealDiv(tmp3,tmp1,tmp2) ;tmp2=(s-a1)*(b2-b1)/(a2-a1)
... |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #Ada | Ada | with Ada.Text_IO;
procedure Map is
type First_Range is new Float range 0.0 .. 10.0;
type Second_Range is new Float range -1.0 .. 0.0;
function Translate (Value : First_Range) return Second_Range is
B1 : Float := Float (Second_Range'First);
B2 : Float := Float (Second_Range'Last);
A1 : Float ... |
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #J | J | require'ide/qt/gl2'
coinsert'jgl2'
junk=: 7 u:;48 65 16b30a1(+i.)&.>10 26 90
sz=:40 25
len=: <.1.4*{:sz
heat=: (224 255 255),~(<.0.5+255*(%>./)(-<./)^>:(% >./)i.len)*/0 1 0
cols=: i.0
rows=: i.0
scale=: 24
live=: (#heat)#<i.3 0
update=: {{
try. glfill 0 0 0 255 catch. wd'timer 0' return. end.
glfont font=.'co... |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #EasyLang | EasyLang | col[] = [ 802 990 171 229 950 808 ]
len code[] 4
len guess[] 4
#
subr init_vars
row = 7
.
func draw_rate r black white . .
for j range 2
for c range 2
move c * 3.5 + 71.5 r * 11.5 + 10.4 + j * 3.5
if black > 0
color 000
circle 1.4
black -= 1
elif white > 0
colo... |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #FreeBASIC | FreeBASIC | '--- Declaration of global variables ---
Dim As String colors(1 To 4) => {"A", "B", "C", "D"}
Dim Shared As Integer nr, ub', numlet=4, lencod=4
Dim Shared As String*4 master, pz
ub = Ubound(colors)
nr = 0
'--- SUBroutines and FUNCtions ---
Sub Encabezado
Dim As String dup
Color 11: Print "Welcome to Mastermin... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #jq | jq | # Input: array of dimensions
# output: {m, s}
def optimalMatrixChainOrder:
. as $dims
| (($dims|length) - 1) as $n
| reduce range(1; $n) as $len ({m: [], s: []};
reduce range(0; $n-$len) as $i (.;
($i + $len) as $j
| .m[$i][$j] = infinite
| reduce range($i; $j) as $k (.;
... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Julia | Julia | module MatrixChainMultiplications
using OffsetArrays
function optim(a)
n = length(a) - 1
u = fill!(OffsetArray{Int}(0:n, 0:n), 0)
v = fill!(OffsetArray{Int}(0:n, 0:n), typemax(Int))
u[:, 1] .= -1
v[:, 1] .= 0
for j in 2:n, i in 1:n-j+1, k in 1:j-1
c = v[i, k] + v[i+k, j-k] + a[i] * a... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Kotlin | Kotlin | // Version 1.2.31
lateinit var m: List<IntArray>
lateinit var s: List<IntArray>
fun optimalMatrixChainOrder(dims: IntArray) {
val n = dims.size - 1
m = List(n) { IntArray(n) }
s = List(n) { IntArray(n) }
for (len in 1 until n) {
for (i in 0 until n - len) {
val j = i + len
... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Julia | Julia | """
+ +---+---+
| 1 2 3 |
+---+ + +
| 4 5 | 6
+---+---+---+
julia> const graph = [
0 1 0 0 0 0;
1 0 1 0 1 0;
0 1 0 0 0 1;
0 0 0 0 1 0;
0 1 0 1 0 0;
0 0 1 0 0 0]
julia> dist, path = dijkstra(graph, 1)
... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Go | Go | package main
import (
"fmt"
"strconv"
"strings"
)
const t = ` 55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 ... |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifi... | #Python | Python | import hashlib
print hashlib.new("md4",raw_input().encode('utf-16le')).hexdigest().upper() |
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;... | #VBScript | VBScript | 'http://rosettacode.org/wiki/Middle_three_digits
Function mid3n(n)
'Remove the number's sign.
n = CStr(Abs(n))
If Len(n) < 3 Or Len(n) Mod 2 = 0 Then
mid3n = "Invalid: Either the length of n < 3 or an even number."
ElseIf Round(Len(n)/2) > Len(n)/2 Then
mid3n = Mid(n,Round(Len(n)/2)-1,3)
Else
mid3n = Mid(n,... |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Emacs_Lisp | Emacs Lisp | (md5 "The quick brown fox jumped over the lazy dog's back") ;=> "e38ca1d920c4b8b8d3946b2c72f01680"
(secure-hash 'md5 "The quick brown fox jumped over the lazy dog's back") ;=> "e38ca1d920c4b8b8d3946b2c72f01680" |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('...',13,10,'$');
DECLARE P ADDRESS, (N, C BASED P) BYTE;
... |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #PowerShell | PowerShell | $possible = @{}
For ($i=0; $i -lt 18; $i++) {
For ($j=0; $j -lt 13; $j++) {
For ( $k=0; $k -lt 6; $k++ ) {
$possible[ $i*6 + $j*9 + $k*20 ] = $true
}
}
}
For ( $n=100; $n -gt 0; $n-- ) {
If ($possible[$n]) {
Continue
}
Else {
Break
}
}
Write-Host "Maximum non-McNuggets number is $n" |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #PureBasic | PureBasic | #START_X=-4 : #START_Y=2
Dim pl$(5)
pl$(0)=" Θ " : pl$(1)=" • " : pl$(2)=" •• "
pl$(3)="••• " : pl$(4)="••••" : pl$(5)="‒‒‒‒"
If OpenConsole() : EnableGraphicalConsole(1) : Else : End 1 : EndIf
Procedure.s Dec2Mayan(wert.i)
result$=""
If wert=0 : result$="0;" : EndIf
While wert : result$=Str(wert%20)+";"+resu... |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Action.21 | Action! | INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
DEFINE PTR="CARD"
TYPE Matrix=[
BYTE width,height
PTR data] ;INT ARRAY
PROC PrintMatrix(Matrix POINTER m)
BYTE i,j
INT ARRAY d
CHAR ARRAY s(10)
d=m.data
FOR j=0 TO m.height-1
DO
FOR i=0 TO m.width-1
DO
StrI(d(j*m.width+i),s)
... |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return succe... | #Ada | Ada | with Ada.Command_Line;
with Ada.Directories;
with Ada.Text_IO;
procedure Make_Directory_Path is
begin
if Ada.Command_Line.Argument_Count /= 1 then
Ada.Text_IO.Put_Line ("Usage: make_directory_path <path/to/dir>");
return;
end if;
declare
Path : String renames Ada.Command_Line.Argument (1)... |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return succe... | #Aime | Aime | void
mkdirp(text path)
{
list l;
text p, s;
file().b_affix(path).news(l, 0, 0, "/");
for (, s in l) {
p = p + s + "/";
trap_q(mkdir, p, 00755);
}
}
integer
main(void)
{
mkdirp("./path/to/dir");
0;
} |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return succe... | #AppleScript | AppleScript | use framework "Foundation"
use scripting additions
-- createOrFindDirectoryMay :: Bool -> FilePath -> Maybe IO ()
on createOrFindDirectoryMay(fp)
createDirectoryIfMissingMay(true, fp)
end createOrFindDirectoryMay
-- createDirectoryIfMissingMay :: Bool -> FilePath -> Maybe IO ()
on createDirectoryIfMissingMa... |
http://rosettacode.org/wiki/Matrix_transposition | Matrix transposition | Transpose an arbitrarily sized rectangular Matrix.
| #Action.21 | Action! | DEFINE PTR="CARD"
TYPE Matrix=[
BYTE width,height
PTR data] ;BYTE ARRAY
PROC PrintB2(BYTE b)
IF b<10 THEN Put(32) FI
PrintB(b)
RETURN
PROC PrintMatrix(Matrix POINTER m)
BYTE i,j
BYTE ARRAY d
d=m.data
FOR j=0 TO m.height-1
DO
FOR i=0 TO m.width-1
DO
PrintB2(d(j*m.width+i)) Put(32)... |
http://rosettacode.org/wiki/Maze_generation | Maze generation |
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Generate and show a maze, using the simple Depth... | #BBC_BASIC | BBC BASIC | MazeWidth% = 11
MazeHeight% = 9
MazeCell% = 50
VDU 23,22,MazeWidth%*MazeCell%/2+3;MazeHeight%*MazeCell%/2+3;8,16,16,128
VDU 23,23,3;0;0;0; : REM Line thickness
PROCgeneratemaze(Maze&(), MazeWidth%, MazeHeight%, MazeCell%)
END
DEF PROCgeneratemaze(RETURN m&(), w%, h%, ... |
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Fermat | Fermat |
Array a[2,2]; {illustrate with a 2x2 matrix}
[a]:=[(2/3, 1/3, 4/5, 1/5)];
[a]^-1; {matrix inverse}
[a]^0; {identity matrix}
[a]^2;
[a]^3;
[a]^10;
|
http://rosettacode.org/wiki/Matrix-exponentiation_operator | Matrix-exponentiation operator | Most programming languages have a built-in implementation of exponentiation for integers and reals only.
Task
Demonstrate how to implement matrix exponentiation as an operator.
| #Fortran | Fortran | module matmod
implicit none
! Overloading the ** operator does not work because the compiler cannot
! differentiate between matrix exponentiation and the elementwise raising
! of an array to a power therefore we define a new operator
interface operator (.matpow.)
module procedure matrix_exp
end interface
... |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #ALGOL_68 | ALGOL 68 | # maps a real s in the range [ a1, a2 ] to the range [ b1, b2 ] #
# there are no checks that s is in the range or that the ranges are valid #
PROC map range = ( REAL s, a1, a2, b1, b2 )REAL:
b1 + ( ( s - a1 ) * ( b2 - b1 ) ) / ( a2 - a1 );
# test the mapping #
FOR i FROM 0 TO 10 DO
print( ( whole( i... |
http://rosettacode.org/wiki/Map_range | Map range | Given two ranges:
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
and
[
b
1
,
b
2
]
{\displaystyle [b_{1},b_{2}]}
;
then a value
s
{\displaystyle s}
in range
[
a
1
,
a
2
]
{\displaystyle [a_{1},a_{2}]}
is linearly mapped to a value
t
{\di... | #Amazing_Hopper | Amazing Hopper |
double inc = (nHasta - nDesde) / ( nTotal - 1);
lista[0] = nDesde;
lista[nTotal] = nHasta;
for( n=1; n<nTotal; n++){
lista[n] = lista[n-1] + inc;
}
|
http://rosettacode.org/wiki/Matrix_digital_rain | Matrix digital rain | Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.
Provided is a reference implementation in Common Lisp to be run in a terminal.
| #JavaScript | JavaScript | var tileSize = 20;
// a higher fade factor will make the characters fade quicker
var fadeFactor = 0.05;
var canvas;
var ctx;
var columns = [];
var maxStackHeight;
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
// https://developer.mozilla.org/en-US/docs/Web/AP... |
http://rosettacode.org/wiki/Mastermind | Mastermind | Create a simple version of the board game: Mastermind.
It must be possible to:
choose the number of colors will be used in the game (2 - 20)
choose the color code length (4 - 10)
choose the maximum number of guesses the player has (7 - 20)
choose whether or not colors may be repeated in the code
The (... | #Go | Go | package main
import (
"errors"
"flag"
"fmt"
"log"
"math/rand"
"strings"
"time"
)
func main() {
log.SetPrefix("mastermind: ")
log.SetFlags(0)
colours := flag.Int("colours", 6, "number of colours to use (2-20)")
flag.IntVar(colours, "colors", 6, "alias for colours")
holes := flag.Int("holes", 4, "number o... |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Lua | Lua | -- Matrix A[i] has dimension dims[i-1] x dims[i] for i = 1..n
local function MatrixChainOrder(dims)
local m = {}
local s = {}
local n = #dims - 1;
-- m[i,j] = Minimum number of scalar multiplications (i.e., cost)
-- needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j]
-- The cost is zero whe... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #Kotlin | Kotlin | // Version 1.2.31
import java.io.File
typealias Maze = List<CharArray>
/**
* Makes the maze half as wide (i. e. "+---+" becomes "+-+"), so that
* each cell in the maze is the same size horizontally as vertically.
* (Versus the expanded version, which looks better visually.)
* Also, converts each l... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Haskell | Haskell | parse = map (map read . words) . lines
f x y z = x + max y z
g xs ys = zipWith3 f xs ys $ tail ys
solve = head . foldr1 g
main = readFile "triangle.txt" >>= print . solve . parse |
http://rosettacode.org/wiki/MD4 | MD4 | Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifi... | #Racket | Racket |
#lang racket
(require (planet soegaard/digest:1:2/digest))
(md4 #"Rosetta Code")
|
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values;... | #Vedit_macro_language | Vedit macro language | do {
#1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE)
Ins_Text("Input: ") Num_Ins(#1, COUNT, 10)
Call("MIDDLE_3_DIGITS")
Ins_Text(" Result: ") Reg_Ins(10) Ins_Newline
Update()
} while (#1);
Return
// Find middle 3 digits of a number
// in: #1 = numeric value
// out: @10 = the result, or ... |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Erlang | Erlang | -module(tests).
-export([md5/1]).
md5(S) ->
string:to_upper(
lists:flatten([io_lib:format("~2.16.0b",[N]) || <<N>> <= erlang:md5(S)])
). |
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Python | Python | >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
nuggets.discard(6*s + 9*n + 20*t)
>>> max(nuggets)
43
>>> |
http://rosettacode.org/wiki/Mayan_numerals | Mayan numerals | Task
Present numbers using the Mayan numbering system (displaying the Mayan numerals in a cartouche).
Mayan numbers
Normally, Mayan numbers are written vertically (top─to─bottom) with the most significant
numeral at the top (in the sense that decimal numbers are written left─to─right with the most signific... | #Python | Python | '''Mayan numerals'''
from functools import (reduce)
# -------------------- MAYAN NUMERALS --------------------
# mayanNumerals :: Int -> [[String]]
def mayanNumerals(n):
'''Rows of Mayan digit cells,
representing the integer n.
'''
return showIntAtBase(20)(
mayanDigit
)(n)([])
... |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
procedure Matrix_Product is
procedure Put (X : Real_Matrix) is
type Fixed is delta 0.01 range -100.0..100.0;
begin
for I in X'Range (1) loop
for J in X'Range (2) loop
... |
http://rosettacode.org/wiki/Make_directory_path | Make directory path | Task
Create a directory and any missing parents.
This task is named after the posix mkdir -p command, and several libraries which implement the same behavior.
Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect.
If the directory already exists, return succe... | #Arturo | Arturo | write.directory "path/to/some/directory" ø |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.