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/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... | #Java | Java | public class McNuggets {
public static void main(String... args) {
int[] SIZES = new int[] { 6, 9, 20 };
int MAX_TOTAL = 100;
// Works like Sieve of Eratosthenes
int numSizes = SIZES.length;
int[] counts = new int[numSizes];
int maxFound = MAX_TOTAL + 1;
boo... |
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... | #BASIC | BASIC | 10 DEFINT A-Z: DIM L$(5)
15 FOR I=0 TO 5: READ L$(I): NEXT I
20 LINE INPUT I$
30 M=LEN(I$): DIM D(M)
40 FOR I=1 TO M: D(I)=VAL(MID$(I$,I,1)): NEXT I
50 FOR J=M-1 TO 1 STEP -1
60 FOR I=1 TO J
70 D(I+1) = D(I+1) + 10*(D(I) AND 1)
80 D(I) = D(I)\2
90 NEXT I,J
100 S=1
110 IF D(S)=0 AND S<M THEN S=S+1: GOTO 110
120 FOR I=S ... |
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... | #BCPL | BCPL | get "libhdr"
let reads(v) be
$( v%0 := 0
$( let ch = rdch()
if ch = '*N' | ch = endstreamch break
v%0 := v%0 + 1
v%(v%0) := ch
$) repeat
$)
let digits(v) = valof
$( for i=1 to v%0
$( unless '0' <= v%i <= '9' resultis false
v%i := v%i - '0'
$)
resultis true
$)... |
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.
| #D | D | import std.stdio, std.random, std.string, std.array, std.algorithm,
std.file, std.conv;
enum int cx = 4, cy = 2; // Cell size x and y.
enum int cx2 = cx / 2, cy2 = cy / 2;
enum pathSymbol = '.';
struct V2 { int x, y; }
bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc {
if (s == ... |
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... | #C.23 | C# |
using System;
namespace RosetaCode
{
class MainClass
{
public static void Main (string[] args)
{
int[,] list = new int[18,19];
string input = @"55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 3... |
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... | #Java | Java | import org.bouncycastle.crypto.digests.MD4Digest;
import org.bouncycastle.util.encoders.Hex;
public class RosettaMD4
{
public static void main (String[] argv) throws Exception
{
byte[] r = "Rosetta Code".getBytes("US-ASCII");
MD4Digest d = new MD4Digest();
d.update (r, 0, r.length);
... |
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;... | #REXX | REXX | /* REXX ***************************************************************
* 03.02.2013 Walter Pachl
* 19.04.2013 mid 3 is now a function returning the middle 3 digits
* or an error indication
**********************************************************************/
sl='123 12345 1234567 987654321 10001 -10001 -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:... | #BASIC256 | BASIC256 | print MD5("")
print MD5("a")
print MD5("abc")
print MD5("message digest")
print MD5("abcdefghijklmnopqrstuvwxyz")
print MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
print MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
end |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #Ursa | Ursa | def _menu (string<> items)
for (decl int i) (< i (size items)) (inc i)
out " " i ") " items<i> endl console
end for
end _menu
def _ok (string reply, int itemcount)
try
decl int n
set n (int reply)
return (and (or (> n 0) (= n 0)) (< n itemcount))
catch
return false
end try
end _ok
def selector (stri... |
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 selecte... | #VBScript | VBScript | 'The Function
Function Menu(ArrList, Prompt)
Select Case False 'Non-standard usage hahaha
Case IsArray(ArrList)
Menu = "" 'Empty output string for non-arrays
Exit Function
Case UBound(ArrList) >= LBound(ArrList)
Menu = "" 'Empty output string for empty arrays
... |
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... | #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () => {
const
size = n => enumFromTo(0)(
quot(100, n)
),
nuggets = new Set(
size(6).flatMap(
x => size(9).flatMap(
y => size(20).flat... |
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... | #C | C | #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
/* Find base-20 digits. */
size_t base20(unsigned int n, uint8_t *out) {
/* generate digits */
uint8_t *start = out;
do {*out++ = n % 20;} whi... |
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.
| #Delphi | Delphi | procedure SolveMaze(var AMaze: TMaze; const S, E: TPoint);
var
Route : TRoute;
Position : TPoint;
V : TPoint; // delta vector
begin
ClearVisited(AMaze);
Position := S;
Route := TStack<TPoint>.Create;
with Position do
try
AMaze[x, y].Visited := True;
repeat
if (y > 0) a... |
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... | #C.2B.2B | C++ |
/* Algorithm complexity: n*log(n) */
#include <iostream>
int main( int argc, char* argv[] )
{
int triangle[] =
{
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58... |
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... | #JavaScript | JavaScript | const md4func = () => {
const hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
const b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
const chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
const tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno... |
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;... | #Ring | Ring |
n = 1234567
middle(n)
func middle nr
mnr = floor(len(string(nr))/2)
lennr = len(string(nr))
if lennr = 3 see "" + nr + nl
but lennr < 3 see "Number must have at least three digits"
but lennr%2=0 see "Number must have an odd number of digits"
else cnr = substr(string(nr),mnr,3) see cnr ... |
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:... | #BBC_BASIC | BBC BASIC | PRINT FN_MD5("")
PRINT FN_MD5("a")
PRINT FN_MD5("abc")
PRINT FN_MD5("message digest")
PRINT FN_MD5("abcdefghijklmnopqrstuvwxyz")
PRINT FN_MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
PRINT FN_MD5(STRING$(8,"1234567890"))
END
DEF FN_MD5(mes... |
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 selecte... | #Wren | Wren | import "/ioutil" for Input
var menu = Fn.new { |list|
var n = list.count
if (n == 0) return ""
var prompt = "\n M E N U\n\n"
for (i in 0...n) prompt = prompt + "%(i+1). %(list[i])\n"
prompt = prompt + "\nEnter your choice (1 - %(n)): "
var index = Input.integer(prompt, 1, n)
return list[... |
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... | #jq | jq | [
[range(18) as $n6 |
range(13) as $n9 |
range(6) as $n20 |
($n6 * 6 + $n9 * 9 + $n20 * 20)] |
unique |
. as $possible |
range(101) |
. as $n |
select($possible|contains([$n])|not)
] |
max |
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... | #CLU | CLU | % This program must be linked with PCLU's "misc.lib" and "useful.lib"
base20 = proc (n: bigint) returns (sequence[int])
own zero: bigint := bigint$i2bi(0)
own twenty: bigint := bigint$i2bi(20)
if n=zero then return(sequence[int]$[0]) end
digits: array[int] := array[int]$[]
while n>zero do
... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
include "argv.coh";
# convert number to base 20
sub base20(n: uint32, out: [uint8]): (n_digits: uint8) is
n_digits := 0;
loop
[out] := (n % 20) as uint8;
n := n / 20;
out := @next out;
n_digits := n_digits + 1;
if n == 0 then break; end if;
end... |
http://rosettacode.org/wiki/Maze_solving | Maze solving | Task
For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.
Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.
| #EasyLang | EasyLang | size = 20
n = 2 * size + 1
endpos = n * n - 2
startpos = n + 1
#
f = 100 / (n - 0.5)
len m[] n * n
#
background 000
func show_maze . .
clear
for i range len m[]
if m[i] = 0
x = i mod n
y = i div n
color 777
move x * f - f / 2 y * f - f / 2
rect f * 1.5 f * 1.5
.
.
sleep 0... |
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... | #Clojure | Clojure |
(ns clojure.examples.rosetta
(:gen-class)
(:require [clojure.string :as string]))
(def rosetta "55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
... |
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... | #Julia | Julia |
using Nettle
msg = "Rosetta Code"
h = HashState(MD4)
update!(h, msg)
h = hexdigest!(h)
println("\"", msg, "\" => ", h)
|
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;... | #Ruby | Ruby | def middle_three_digits(num)
# minus sign doesn't factor into digit count,
# and calling #abs acts as a duck-type assertion
num = num.abs
# convert to string and find length
length = (str = num.to_s).length
# check validity
raise ArgumentError, "Number must have at least three digits" if length < 3
... |
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:... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
const char *string = "The quick brown fox jumped over the lazy dog's back";
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
// output
for(i = 0; i < MD5_DIGEST_LENGTH; ... |
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 selecte... | #XPL0 | XPL0 | string 0;
func Menu(List);
int List;
int Size, I, C;
[Size:= List(0);
if Size < 1 then return List(0); \if empty list, return pointer to 0
for I:= 1 to Size-1 do
[IntOut(0, I); Text(0, ": ");
Text(0, List(I)); CrLf(0);
];
CrLf(0);
Text(0, List(Size)); \display prompt
loop [C:... |
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... | #Julia | Julia | function mcnuggets(max)
b = BitSet(1:max)
for i in 0:6:max, j in 0:9:max, k in 0:20:max
delete!(b, i + j + k)
end
maximum(b)
end
println(mcnuggets(100))
|
http://rosettacode.org/wiki/McNuggets_problem | McNuggets problem | Wikipedia
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number... | #Kotlin | Kotlin | // Version 1.2.71
fun mcnugget(limit: Int) {
val sv = BooleanArray(limit + 1) // all false by default
for (s in 0..limit step 6)
for (n in s..limit step 9)
for (t in n..limit step 20) sv[t] = true
for (i in limit downTo 0) {
if (!sv[i]) {
println("Maximum non-McN... |
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... | #F.23 | F# |
// Mayan numerals. Nigel Galloway: February 19th., 2021
let N=[|"│ ";"│. ";"│.. ";"│... ";"│....";"│~~~~"|]
let fN g=(fun(n)->if g=0 && n=0 then "│ Θ " else N.[let g=g-5*n in if g>4 then 5 else if g<0 then 0 else g])
let rec fG n g=match n/20L,n%20L with (0L,0L)->(g,List.length g) |(i,n)->fG i ((fN(int n))... |
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.
| #11l | 11l | F matrix_mul(m1, m2)
assert(m1[0].len == m2.len)
V r = [[0] * m2[0].len] * m1.len
L(j) 0 .< m1.len
L(i) 0 .< m2[0].len
V s = 0
L(k) 0 .< m2.len
s += m1[j][k] * m2[k][i]
r[j][i] = s
R r
F identity(size)
V rsize = 0 .< size
R rsize.map(j -> @rsize.map(i -> ... |
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.
| #EGL | EGL | program MazeGenAndSolve
// First and last columns/rows are "dead" cells. Makes generating
// a maze with border walls much easier. Therefore, a visible
// 20x20 maze has a maze size of 22.
mazeSize int = 22;
south boolean[][];
west boolean[][];
visited boolean[][];
// Solution va... |
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... | #Common_Lisp | Common Lisp | (defun find-max-path-sum (s)
(let ((triangle (loop for line = (read-line s NIL NIL)
while line
collect (with-input-from-string (str line)
(loop for n = (read str NIL NIL)
while n
... |
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... | #Kotlin | Kotlin | // version 1.0.6
import java.security.MessageDigest
class MD4() : MessageDigest("MD4"), Cloneable {
private val blockLength = 64
private var context = IntArray(4)
private var count = 0L
private var buffer = ByteArray(blockLength)
private var x = IntArray(16)
init {
engineReset()
... |
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;... | #Rust | Rust | fn middle_three_digits(x: i32) -> Result<String, String> {
let s: String = x.abs().to_string();
let len = s.len();
if len < 3 {
Err("Too short".into())
} else if len % 2 == 0 {
Err("Even number of digits".into())
} else {
Ok(s[len/2 - 1 .. len/2 + 2].to_owned())
}
}
fn ... |
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:... | #C.23 | C# | using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower()); |
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 selecte... | #Yabasic | Yabasic | // Rosetta Code problem: https://www.rosettacode.org/wiki/Menu
// by Jjuanhdez, 06/2022
dim choose$(5)
restore menudata
for a = 0 to 5 : read choose$(a) : next a
print menu$(choose$())
end
sub menu$(m$())
clear screen
repeat
print color("green","black") at(0,0) "Menu selection"
vc = 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 selecte... | #zkl | zkl | fcn teleprompter(options){
os:=T("exit").extend(vm.arglist); N:=os.len();
if(N==1) return("");
while(1){
Utils.zipWith(fcn(n,o){"%d) %s".fmt(n,o).println()},[0..],os);
a:=ask("Your choice: ");
try{ n:=a.toInt(); if(0<=n<N) return(os[n]); } catch{}
println("Ack, not good");
}
}
tele... |
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... | #Locomotive_Basic | Locomotive Basic | 100 CLEAR
110 DIM a(100)
120 FOR a=0 TO 100/6
130 FOR b=0 TO 100/9
140 FOR c=0 TO 100/20
150 n=a*6+b*9+c*20
160 IF n<=100 THEN a(n)=1
170 NEXT c
180 NEXT b
190 NEXT a
200 FOR n=0 TO 100
210 IF a(n)=0 THEN l=n
220 NEXT n
230 PRINT"The Largest non McNugget number is:";l
240 END |
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... | #Factor | Factor | USING: arrays formatting io kernel make math math.extras
sequences ;
IN: rosetta-code.mayan-numerals
: mayan-digit ( n -- m pair ) 20 /mod 5 /mod swap 2array ;
: integer>mayan ( n -- seq )
[ [ mayan-digit , ] until-zero ] { } make reverse ;
: ones ( n -- str ) [ CHAR: ● ] "" replicate-as ;
: fives ( n -- str ... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"strconv"
)
const (
ul = "╔"
uc = "╦"
ur = "╗"
ll = "╚"
lc = "╩"
lr = "╝"
hb = "═"
vb = "║"
)
var mayan = [5]string{
" ",
" ∙ ",
" ∙∙ ",
"∙∙∙ ",
"∙∙∙∙",
}
const (
m0 = " Θ "
m5 = "────"
)
func dec2vig(n uint64... |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Matrix is
generic
type Element is private;
Zero : Element;
One : Element;
with function "+" (A, B : Element) return Element is <>;
with function "*" (A, B : Element) return Element is <>;
with function Image (X : Element) retur... |
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.
| #Emacs_Lisp | Emacs Lisp | (require 'cl-lib)
(cl-defstruct maze rows cols data)
(defmacro maze-pt (w r c)
`(+ (* (mod ,r (maze-rows ,w)) (maze-cols ,w))
(mod ,c (maze-cols ,w))))
(defmacro maze-ref (w r c)
`(aref (maze-data ,w) (maze-pt ,w ,r ,c)))
(defun new-maze (rows cols)
(setq rows (1+ rows)
cols (1+ cols))
(le... |
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... | #D | D | void main() {
import std.stdio, std.algorithm, std.range, std.file, std.conv;
"triangle.txt".File.byLine.map!split.map!(to!(int[])).array.retro
.reduce!((x, y) => zip(y, x, x.dropOne)
.map!(t => t[0] + t[1 .. $].max)
.array)[0]
.writeln;
} |
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... | #Lasso | Lasso | cipher_digest('Rosetta Code', -digest='MD4')->encodeHex->asString |
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;... | #S-lang | S-lang | Educational Notes:
1) Array-style string manipulations (e.g. as = as[[1:]] ) always use bytes,
not UTF-8 characters. As digits and '-' are all ASCII, all is copacetic.
2) The task doesn't require 64-bit integer support, but I added it, dependant
on whether the S-Lang library compile supports them, which it gener... |
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:... | #C.2B.2B | C++ | #include <string>
#include <iostream>
#include "Poco/MD5Engine.h"
#include "Poco/DigestStream.h"
using Poco::DigestEngine ;
using Poco::MD5Engine ;
using Poco::DigestOutputStream ;
int main( ) {
std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ;
MD5Engine md5 ;
DigestOutputStr... |
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... | #Lua | Lua |
function range(A,B)
return function()
return coroutine.wrap(function()
for i = A, B do coroutine.yield(i) end
end)
end
end
function filter(stream, f)
return function()
return coroutine.wrap(function()
for i in stream() do
if f(i) then corou... |
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... | #Go | Go | package main
import (
"fmt"
"strconv"
)
const (
ul = "╔"
uc = "╦"
ur = "╗"
ll = "╚"
lc = "╩"
lr = "╝"
hb = "═"
vb = "║"
)
var mayan = [5]string{
" ",
" ∙ ",
" ∙∙ ",
"∙∙∙ ",
"∙∙∙∙",
}
const (
m0 = " Θ "
m5 = "────"
)
func dec2vig(n uint64... |
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... | #11l | 11l | F make_maze(w = 16, h = 8)
V vis = [[0] * w [+] [1]] * h [+] [[1] * (w + 1)]
V ver = [[‘| ’] * w [+] [String(‘|’)]] * h [+] [[String]()]
V hor = [[‘+--’] * w [+] [String(‘+’)]] * (h + 1)
F walk(Int x, Int y) -> N
@vis[y][x] = 1
V d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
rand... |
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.
| #ALGOL_68 | ALGOL 68 | INT default upb=3;
MODE VEC = [default upb]COSCAL;
MODE MAT = [default upb,default upb]COSCAL;
OP * = (VEC a,b)COSCAL: (
COSCAL result:=0;
FOR i FROM LWB a TO UPB a DO result+:= a[i]*b[i] OD;
result
);
OP * = (VEC a, MAT b)VEC: ( # overload vec times matrix #
[2 LWB b:2 UPB b]COSCAL result;
FO... |
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.
| #Erlang | Erlang |
-module( maze_solving ).
-export( [task/0] ).
cells( {Start_x, Start_y}, {Stop_x, Stop_y}, Maze ) ->
Start_pid = maze:cell_pid( Start_x, Start_y, Maze ),
Stop_pid = maze:cell_pid( Stop_x, Stop_y, Maze ),
{ok, Cells} = loop( Start_pid, Stop_pid, maze:cell_accessible_neighbours(Start_pid), [Start_pid]... |
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... | #Elena | Elena | import system'routines;
import extensions;
import extensions'math;
string input = "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 2... |
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... | #Lua | Lua | #!/usr/bin/lua
require "crypto"
print(crypto.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;... | #Scala | Scala | /**
* Optionally return the middle three digits of an integer.
*
* @example List(123,12345,-789,1234,12) flatMap (middleThree(_)), returns: List(123, 234, 789)
*/
def middleThree( s:Int ) : Option[Int] = s.abs.toString match {
case v if v.length % 2 == 0 => None // Middle three is undefined for even lengths
... |
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:... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>set hash=$System.Encryption.MD5Hash("The quick brown fox jumped over the lazy dog's back")
USER>zzdump hash
0000: E3 8C A1 D9 20 C4 B8 B8 D3 94 6B 2C 72 F0 16 80 |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
BOOLEAN NUGGET
DIMENSION NUGGET(101)
THROUGH CLEAR, FOR I=0, 1, I.G.100
CLEAR NUGGET(I) = 0B
THROUGH MARK, FOR A=0, 6, A.G.100
THROUGH MARK, FOR B=A, 9, B.G.100
THROUGH MARK, FOR C=B, 20, C.G.100
MARK ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FrobeniusNumber[{6, 9, 20}] |
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... | #Haskell | Haskell | import Data.Bool (bool)
import Data.List (intercalate, transpose)
import qualified Data.Map.Strict as M
import Data.Maybe (maybe)
--------------------------- MAIN -------------------------
main :: IO ()
main =
(putStrLn . unlines) $
mayanFramed
<$> [ 4005,
8017,
326205,
... |
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... | #Action.21 | Action! | DEFINE TOP="0"
DEFINE RIGHT="1"
DEFINE BOTTOM="2"
DEFINE LEFT="3"
DEFINE WIDTH="160"
DEFINE HEIGHT="96"
DEFINE STACK_SIZE="5000"
BYTE ARRAY stack(STACK_SIZE)
INT stackSize
PROC InitStack()
stackSize=0
RETURN
BYTE FUNC IsEmpty()
IF stackSize=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC IsFull()
IF stack... |
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.
| #BBC_BASIC | BBC BASIC | DIM matrix(1,1), output(1,1)
matrix() = 3, 2, 2, 1
FOR power% = 0 TO 9
PROCmatrixpower(matrix(), output(), power%)
PRINT "matrix()^" ; power% " = "
FOR row% = 0 TO DIM(output(), 1)
FOR col% = 0 TO DIM(output(), 2)
PRINT output(row%,col%);
NEXT
... |
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.
| #BQN | BQN | MatMul ← +˝∘×⎉1‿∞
MatEx ← {𝕨 MatMul⍟(𝕩-1) 𝕨}
(>⟨3‿2
2‿1⟩) MatEx 1‿2‿3‿4‿10 |
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... | #11l | 11l | T Optimizer
[Int] dims
[[Int]] m, s
F (dims)
.dims = dims
F findMatrixChainOrder()
V n = .dims.len - 1
.m = [[0] * n] * n
.s = [[0] * n] * n
L(lg) 1 .< n
L(i) 0 .< n - lg
V j = i + lg
.m[i][j] = 7FFF'FFFF
L(k) i .< j
... |
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.
| #Frege | Frege | module MazeSolver where
import frege.IO
import Data.Maybe
-- given two points, returns the average of them
average :: (Int, Int) -> (Int, Int) -> (Int, Int)
average (x, y) (x', y') = ((x + x') `div` 2, (y + y') `div` 2)
-- given a maze and a tuple of position and wall position, returns
-- true if the wall positio... |
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... | #Elixir | Elixir | defmodule Maximum do
def triangle_path(text) do
text
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
line
|> String.split()
|> Enum.map(&String.to_integer(&1))
end)
|> Enum.reduce([], fn x,total ->
[0]++total++[0]
|> Enum.chunk_every( 2, 1)
|> ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Hash["Rosetta Code", "MD4", "HexString"] |
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;... | #Seed7 | Seed7 | $include "seed7_05.s7i";
const func string: middle3 (in integer: number) is func
result
var string: middle3 is "";
begin
middle3 := str(abs(number));
if not odd(length(middle3)) or length(middle3) < 3 then
middle3 := "error";
else
middle3 := middle3[succ((length(middle3) - 3) div 2) le... |
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:... | #Clojure | Clojure | (apply str
(map (partial format "%02x")
(.digest (doto (java.security.MessageDigest/getInstance "MD5")
.reset
(.update (.getBytes "The quick brown fox jumps over the lazy dog")))))) |
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... | #Modula-2 | Modula-2 | MODULE McNuggets;
FROM InOut IMPORT WriteCard, WriteString, WriteLn;
CONST Max = 100;
VAR a, b, c: CARDINAL;
nugget: ARRAY [0..Max] OF BOOLEAN;
BEGIN
FOR a := 0 TO Max DO
nugget[a] := FALSE;
END;
FOR a := 0 TO Max BY 6 DO
FOR b := a TO Max BY 9 DO
FOR c := b TO Max BY 2... |
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... | #J | J | elems =: 6 4$' . .. ... ....----'
digit =: (elems{~5:<.0:>.15 10 5 0-~])`((4 4$_14{.'@')&[)@.(0&=)
mayan =: ":@(digit each@(20&#.^:_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... | #Java | Java |
import java.math.BigInteger;
public class MayanNumerals {
public static void main(String[] args) {
for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) {
displayMyan(BigInteger.valueOf(base10));
System.out.printf("%... |
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... | #Ada | Ada | generic
Height : Positive;
Width : Positive;
package Mazes is
type Maze_Grid is private;
procedure Initialize (Maze : in out Maze_Grid);
procedure Put (Item : Maze_Grid);
private
type Directions is (North, South, West, East);
type Cell_Walls is array (Directions) of Boolean;
type Cel... |
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.
| #Burlesque | Burlesque | blsq ) {{1 1} {1 0}} 10 .*{mm}r[
{{89 55} {55 34}} |
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.
| #C | C | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct squareMtxStruct {
int dim;
double *cells;
double **m;
} *SquareMtx;
/* function for initializing row r of a new matrix */
typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data);
SquareMtx NewSquareMtx( int dim, ... |
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... | #Ada | Ada |
package mat_chain is
type Vector is array (Natural range <>) of Integer;
procedure Chain_Multiplication (Dims : Vector);
end mat_chain;
|
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... | #C | C | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int **m;
int **s;
void optimal_matrix_chain_order(int *dims, int n) {
int len, i, j, k, temp, cost;
n--;
m = (int **)malloc(n * sizeof(int *));
for (i = 0; i < n; ++i) {
m[i] = (int *)calloc(n, sizeof(int));
}
s = (int **)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.
| #Go | Go | package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
type maze struct {
c2 [][]byte // cells by row
h2 [][]byte // horizontal walls by row (ignore first row)
v2 [][]byte // vertical walls by row (ignore first of each column)
}
func newMaze(rows, cols int) *maze {
c := make([]... |
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... | #Erlang | Erlang |
-mode(compile).
-import(lists, [foldl/3]).
main(_) ->
{ok, Tmat} = file:open("triangle.txt", [read, raw, {read_ahead, 16384}]),
Max = max_sum(Tmat, []),
io:format("The maximum total is ~b~n", [Max]).
max_sum(FD, Last) ->
case file:read_line(FD) of
eof -> foldl(fun erlang:max/2, 0, Last);
... |
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... | #Nim | Nim | import strutils
const MD4Len = 16
proc MD4(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: "libssl.so", importc.}
proc MD4(s: string): string =
result = ""
var s = MD4(s.cstring, s.len.culong)
for i in 0 ..< MD4Len:
result.add s[i].BiggestInt.toHex(2).toLower
echo 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;... | #SenseTalk | SenseTalk | set inputs to [123, 12345, 1234567, 987654321,
10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
repeat with each num in inputs
put num into output
put middle3digits of num into character 15 of output -- will autofill with "."s
put output
end repeat
to handle middle3digits of number
put e... |
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;... | #Sidef | Sidef | func middle_three(n) {
var l = n.len;
if (l < 3) {
"#{n} is too short"
} elsif (l.is_even) {
"#{n} has an even number of digits"
} else {
"The three middle digits of #{n} are: " + n.digits.ft(l-3 / 2, l/2 + 1).join
}
}
var nums = %n(
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12... |
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:... | #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. MD5.
AUTHOR. Bill Gunshannon
INSTALLATION. Home.
DATE-WRITTEN. 16 December 2021.
************************************************************
** Program Abstract:
** Use the md5sum utility and pass the HASH back using
... |
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... | #MiniZinc | MiniZinc |
%McNuggets. Nigel Galloway, August 27th., 2019
var 0..99: n;
constraint forall(x in 0..16,y in 0..11,z in 0..5)(6*x + 9*y + 20*z!=n);
solve maximize n;
output [show(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... | #JavaScript | JavaScript | (() => {
'use strict';
const main = () =>
unlines(
map(mayanFramed,
[4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000]
)
);
// MAYAN NUMBERS --------------------------------------
// mayanFramed :: Int -> String
const mayanFram... |
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... | #Aime | Aime | grid_maze(data b, integer N)
{
data d;
N.times(bb_cast, d, "+---");
bb_cast(d, "+\n");
N.times(bb_cast, d, "| * ");
bb_cast(d, "|\n");
N.times(bb_copy, b, d);
b_size(d, N * 4 + 2);
bb_copy(b, d);
}
void
walk_cell(data b, integer N, line_size, x, y, list x_offsets, y_offsets)
... |
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.
| #C.23 | C# | using System;
using System.Collections;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class MatrixExponentation
{
public static double[,] Identity(int size) {
double[,] matrix = new double[size, size];
for (int i = 0; i < size; i++) matrix[i, i] = 1;
... |
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.
| #Ada | Ada | with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
procedure Digital_Rain is
type Column_Type is range 0 .. 150;
type Row_Type is range 0 .. 25;
type Character_Range is new Character range 'A' .. 'Z';
subtype Delay_Range is Integer range 2 .. 6;
package Column_Ra... |
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 (... | #11l | 11l | F encode(correct, guess)
[String] output_arr
L(i) 0 .< correct.len
output_arr [+]= I guess[i] == correct[i] {‘X’} E I guess[i] C correct {‘O’} E ‘-’
R output_arr
F safe_int_input(prompt, min_val, max_val)
L
V user_input_str = input(prompt)
X.try
V user_input = Int(user_inp... |
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... | #C.23 | C# | using System;
class MatrixChainOrderOptimizer {
private int[,] m;
private int[,] s;
void OptimalMatrixChainOrder(int[] dims) {
int n = dims.Length - 1;
m = new int[n, n];
s = new int[n, n];
for (int len = 1; len < n; ++len) {
for (int i = 0; i < n - len; ++i) ... |
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.
| #Haskell | Haskell | #!/usr/bin/runhaskell
import Data.Maybe (fromMaybe)
-- given two points, returns the average of them
average :: (Int, Int) -> (Int, Int) -> (Int, Int)
average (x, y) (x_, y_) = ((x + x_) `div` 2, (y + y_) `div` 2)
-- given a maze and a tuple of position and wall position, returns
-- true if the wall position is n... |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #ERRE | ERRE |
PROGRAM TRIANGLE_PATH
CONST ROW=18
DIM TRI[200]
!
! for rosettacode,org
!
FUNCTION MAX(X,Y)
MAX=-X*(X>=Y)-Y*(X<Y)
END FUNCTION
BEGIN
DATA(55)
DATA(94,48)
DATA(95,30,96)
DATA(77,71,26,67)
DATA(97,13,76,38,45)
DATA(7,36,79,16,37,68)
DATA(48,7,9,18,70,26,6)
DATA(18,... |
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... | #PARI.2FGP | PARI/GP | #include <pari/pari.h>
#include <openssl/md4.h>
#define HEX(x) (((x) < 10)? (x)+'0': (x)-10+'a')
/*
* PARI/GP func: MD4 hash
*
* gp code: install("plug_md4", "s", "MD4", "<library path>");
*/
GEN plug_md4(char *text)
{
char md[MD4_DIGEST_LENGTH];
char hash[sizeof(md) * 2 + 1];
int i;
MD4((unsigned ch... |
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;... | #SQL | SQL | ;WITH DATA
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
LEN(CAST(ABS(NUMBER) AS NVARCHAR(MAX))) LcharNum
FROM TABLE1)
SELECT CASE
WHEN ( LCHARNUM >= 3
AND LCHARNUM % 2 = 1 ) THEN SUBSTRING(CHARNUM, LCHARNUM / 2, 3)
... |
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:... | #Common_Lisp | Common Lisp | (ql:quickload 'ironclad)
(defun md5 (str)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :md5
(ironclad:ascii-string-to-byte-array str))))
(defvar *tests* '(""
"a"
"abc"
"message digest"
"abcdefgh... |
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... | #Nim | Nim | const Limit = 100
var mcnuggets: array[0..Limit, bool]
for a in countup(0, Limit, 6):
for b in countup(a, Limit, 9):
for c in countup(b, Limit, 20):
mcnuggets[c] = true
for n in countdown(Limit, 0):
if not mcnuggets[n]:
echo "The largest non-McNuggets number is: ", n
break |
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... | #jq | jq | def m:
{ ul: "╔",
uc: "╦",
ur: "╗",
ll: "╚",
lc: "╩",
lr: "╝",
hb: "═",
vb: "║",
m0: " Θ ",
m5: "────"
};
def mayan: [
" ",
" ∙ ",
" ∙∙ ",
"∙∙∙ ",
"∙∙∙∙"
];
# decimal number to base-20 array, most significant digit first
def dec2vig:
[recurse(if . > 0 then ./20|floor ... |
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... | #Julia | Julia | using Gumbo
mayan_glyphs(x, y) = (x == 0 && y == 0) ? "\n<td>Θ</td>\n" : "<td>\n" * "●" ^ x * "<br />\n───" ^ y * "</td>\n"
inttomayan(n) = (s = string(n, base=20); map(ch -> reverse(divrem(parse(Int, ch, base=20), 5)), split(s, "")))
function testmayan()
startstring = """\n
<style>
table.roundedcorners {
... |
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... | #APL | APL |
This example shows how to use GNU APL scripting.
#!/usr/local/bin/apl --script --
⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝
⍝ ⍝
⍝ mazeGen.apl 2022-01-07 19:47:35 (GMT-8) ⍝
⍝ ... |
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.
| #C.2B.2B | C++ | #include <complex>
#include <cmath>
#include <iostream>
using namespace std;
template<int MSize = 3, class T = complex<double> >
class SqMx {
typedef T Ax[MSize][MSize];
typedef SqMx<MSize, T> Mx;
private:
Ax a;
SqMx() { }
public:
SqMx(const Ax &_a) { // constructor with pre-defined array
for (int r... |
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.
| #Batch_File | Batch File | :: Matrix Digital Rain Task from RosettaCode
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
rem escape character (for Windows 10 VT100 escape sequences)
rem info: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
for /f %%e in ('echo prompt $e^| cmd') do @set... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.