task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #CoffeeScript | CoffeeScript |
# Array sum helper function.
sum = (array) ->
array.reduce (x, y) -> x + y
md5 = do ->
# Per-round shift amounts.
s = [738695, 669989, 770404, 703814]
s = (s[i >> 4] >> i % 4 * 5 & 31 for i in [0..63])
# Constants cache generated by sine.
K = (Math.floor 2**32 * Math.abs Math.sin i for i in [1..64])
... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #J | J | require 'dll'
mema 1000
57139856 |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Java | Java | //All of these objects will be deallocated automatically once the program leaves
//their scope and there are no more pointers to the objects
Object foo = new Object(); //Allocate an Object and a reference to it
int[] fooArray = new int[size]; //Allocate all spaces in an array and a reference to it
int x = 0; //Allocate... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #PureBasic | PureBasic | Structure Person
Name$
EndStructure
Structure Visits
Datum$
Score$
EndStructure
Structure Merge
Patient.Person
List PVisit.Visits()
EndStructure
NewMap P.Merge()
NewList ID$()
If ReadFile(1,"./Data/patients.csv")=0 : End 1 : EndIf
header=1
While Not Eof(1)
buf1$=ReadString(1)
If header=1 : header=... |
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;... | #D | D | import std.stdio, std.traits, std.conv;
string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) {
auto s = n < 0 ? n.text[1 .. $] : n.text;
auto len = s.length;
if (len < 3 || len % 2 == 0)
return "Need odd and >= 3 digits";
auto mid = len / 2;
return s[mid - 1 .. mid + 2];
}
... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Python | Python |
'''
Minesweeper game.
There is an n by m grid that has a random number of between 20% to 60%
of randomly hidden mines that need to be found.
Positions in the grid are modified by entering their coordinates
where the first coordinate is horizontal in the grid and the second
vertical. The top l... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
x=y="1'2'3'4'5'6'7'8'9'10'11'12"
LOOP n,col=x,cnt=""
skip=n-1
LOOP m,row=y
IF (m==skip) THEN
td=""
ELSE
td=col*row
coleqrow=col*n
IF (td.lt.#coleqrow) td=""
ENDIF
td=CENTER (td,+3," ")
cnt=APPEND (cnt,td," ")
ENDLOOP
col=CENTER (col,+3," ")
PRINT col,cnt
ENDLOOP
|
http://rosettacode.org/wiki/Metaprogramming | Metaprogramming | Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effect... | #Z80_Assembly | Z80 Assembly | macro xchg,regpair1,regpair2
;swaps the contents of two registers.
push regpair1
push regpair2
pop regpair1
pop regpair2
endm |
http://rosettacode.org/wiki/Metaprogramming | Metaprogramming | Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effect... | #zkl | zkl | #define name [0|1]
#if [0|1|name]
#else, #endif |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #FreeBASIC | FreeBASIC | ' version 29-11-2016
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function mul_mod(a As ULongInt, b As ULongInt, modulus As ULongInt) As ULongInt
' retur... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Factor | Factor | USING: formatting grouping io kernel math math.extras
math.ranges math.statistics prettyprint sequences ;
! Take the cumulative sum of the mobius sequence to avoid
! summing lower terms over and over.
: mertens-upto ( n -- seq ) [1,b] [ mobius ] map cum-sum ;
"The first 199 terms of the Mertens sequence:" print
199... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Forth | Forth | : AMOUNT 1000 ;
variable mertens AMOUNT cells allot
: M 1- cells mertens + ; \ 1-indexed array
: make-mertens
1 1 M !
2 begin dup AMOUNT <= while
1 over M !
2 begin over over >= while
over over / M @
2 pick M @ swap -
2 pick M !
1+ repeat
drop
1+ repeat
drop
;
: print... |
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... | #Clojure | Clojure | (defn menu [prompt choices]
(if (empty? choices)
""
(let [menutxt (apply str (interleave
(iterate inc 1)
(map #(str \space % \newline) choices)))]
(println menutxt)
(print prompt)
(flush)
(let [index (read-string (read-line))... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #Common_Lisp | Common Lisp | (defpackage #:md5
(:use #:cl))
(in-package #:md5)
(require :babel)
(deftype word () '(unsigned-byte 32))
(deftype octet () '(unsigned-byte 8))
(deftype octets () '(vector octet))
(defparameter *s*
(make-array 16 :element-type 'word
:initial-contents '(7 12 17 22
... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Julia | Julia |
matrix = Array{Float64,2}(100,100)
matrix[31,42] = pi
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Kotlin | Kotlin | // version 1.1.2
class MyClass(val myInt: Int) {
// in theory this method should be called automatically prior to GC
protected fun finalize() {
println("MyClass being finalized...")
}
}
fun myFun() {
val mc: MyClass = MyClass(2) // new non-nullable MyClass object allocated on the heap
... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #Python | Python | # to install pandas library go to cmd prompt and type:
# cd %USERPROFILE%\AppData\Local\Programs\Python\Python38-32\Scripts\
# pip install pandas
import pandas as pd
# load data from csv files
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decima... |
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;... | #Dart | Dart |
import'dart:math';
int length(int x)
{
int i,y;
for(i=0;;i++)
{
y=pow(10,i);
if(x%y==x)
break;
}
return i;
}
int middle(int x,int l)
{
int a=(x/10)-((x%10)/10);
int b=a%(pow(10,l-2));
int l2=length(b);
if(l2==3)
{
return b;
}
if(l2!=3)
{
... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Racket | Racket |
#lang racket
(require math/array)
;board uses arrays directly, but maintaining an abstraction is nice
(define (board-ref b row col) (array-ref b (vector row col)))
(define (board-rows b) (vector-ref (array-shape b) 0))
(define (board-cols b) (vector-ref (array-shape b) 1))
(define (on-board? b row col)
(and (<= 0 r... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #TypeScript | TypeScript |
// Multiplication tables
function intToString(n: number, wdth: number): string {
sn = Math.floor(n).toString();
len = sn.length;
return (wdth < len ? "#".repeat(wdth) : " ".repeat(wdth - len) + sn);
}
var n = 12;
console.clear();
for (j = 1; j < n; j++)
process.stdout.write(intToString(j, 3) + " ");
conso... |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #FunL | FunL | import util.rnd
def isProbablyPrimeMillerRabin( n, k ) =
d = n - 1
s = 0
while 2|d
s++
d /= 2
repeat k
a = rnd( 2, n )
x = a^d mod n
if x == 1 or x == n - 1 then continue
repeat s - 1
x = x^2 mod n
if x == 1 then return false
if x == n - 1 then break
e... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Fortran | Fortran | program Mertens
implicit none
integer M(1000), n, k, zero, cross
C Generate Mertens numbers
M(1) = 1
do 10 n=2, 1000
M(n) = 1
do 10 k=2, n
M(n) = M(n) - M(n/k)
10 continue
C Print table
write (*,"('The first 99 Mertens numbers ... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Test-Prompt-Menu.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num-Options USAGE UNSIGNED-INT VALUE 4.
01 Example-Menu.
03 Example-Options-Data.
05 FILLER PIC X(30) VALUE "fee fie".
05 FILLE... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #D | D | import std.bitmanip, core.stdc.string, std.conv, std.math, std.array,
std.string;
version (D_InlineAsm_X86) {} else {
static assert(false, "For X86 machine only.");
}
// CTFE construction of transform expressions.
uint S(in uint n) pure nothrow @safe @nogc {
static immutable aux = [7u, 12, 17, 22, 5,... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Lingo | Lingo | -- Create a ByteArray of 100 Kb (pre-filled with 0 bytes)
ba = byteArray(102400)
-- Lingo uses garbage-collection, so allocated memory is released when no more references exist.
-- For the above variable ba, this can be achieved by calling:
ba = VOID |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Buffer Clear Mem1 as Byte*12345
Print Len(Mem1)
Hex Mem1(0) ' print in Hex address of first element
Print Mem1(Len(Mem1)-1)-Mem1(0)+1=12345
Buffer Mem1 as Byte*20000 ' redim block
Print Mem1(Len(Mem1)-1)-Mem1(0)+1=20000
Try {
Print Mem1(20000) '... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #R | R | # load data from csv files
# setwd("C:\Temp\csv\")
# df_patient <- read.csv(file="patients.csv", header = TRUE, sep = ",")
# df_visits <- read.csv(file="visits.csv", header = TRUE, sep = ",", dec = ".", colClasses=c("character","character","numeric"))
# load data hard coded, create data frames
df_patient <- read.tabl... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #Raku | Raku | my @names = map { ( <PATIENT_ID LASTNAME> Z=> .list ).hash },
( 1001, 'Hopper' ),
( 4004, 'Wirth' ),
( 3003, 'Kemeny' ),
( 2002, 'Gosling' ),
( 5005, 'Kurtz' ),
;
my @visits = map { ( <PATIENT_ID VISIT_DATE SCORE> Z=> .list ).hash },
( 2002, '2020-09-10', 6.8 ),
( 1001, '2020-09-17', 5... |
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;... | #DCL | DCL | $ list = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
$ i = 0
$ loop:
$ number = f$element( i, ",", list )
$ if number .eqs. "," then $ exit
$ abs_number = number - "-"
$ len = f$length( abs_number )
$ if len .lt. 3 .or. .not. len
$ then
$ write sys$output f$fao( "!9SL... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Raku | Raku | enum Tile-Type <Empty Mine>;
class Tile {
has Tile-Type $.type;
has $.face is rw;
method Str { with $!face { ~$!face } else { '.' } }
}
class Field {
has @.grid;
has Int $.width;
has Int $.height;
has Int $.mine-spots;
has Int $.empty-spots;
method new (Int $height, Int $width,... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #uBasic.2F4tH | uBasic/4tH | For R = 1 To 12
Print R;Tab(R * 5);
For C = R To 12
Print Using "_____";R * C;
Next
Print
Next |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #Go | Go | package main
import "log"
func main() {
// max uint32 is not prime
c := uint32(1<<32 - 1)
// a few primes near the top of the range. source: prime pages.
for _, p := range []uint32{1<<32 - 5, 1<<32 - 17, 1<<32 - 65, 1<<32 - 99} {
for ; c > p; c-- {
if prime(c) {
... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #FreeBASIC | FreeBASIC | function padto( i as ubyte, j as integer ) as string
return wspace(i-len(str(j)))+str(j)
end function
dim as integer M( 1 to 1000 ), n, col, k, psum
dim as integer num_zeroes = 0, num_cross = 0
dim as string outstr
M(1) = 1
for n = 2 to 1000
psum = 0
for k = 2 to n
psum += M(int(n/k))
next k... |
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... | #Common_Lisp | Common Lisp | (defun select (prompt choices)
(if (null choices)
""
(do (n)
((and n (<= 0 n (1- (length choices))))
(nth n choices))
(format t "~&~a~%" prompt)
(loop for n from 0
for c in choices
do (format t " ~d) ~a~%" n c))
(force-output)
(setf n (parse-in... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #Delphi | Delphi |
program MD5Implementation;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes;
type
TTestCase = record
hashCode: string;
_: string;
end;
var
testCases: array[0..6] of TTestCase = ((
hashCode: 'D41D8CD98F00B204E9800998ECF8427E';
_: ''
), (
hashCode: '0CC175B9C0F1B6A831C399E... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Maple | Maple | a := Array( 1 .. 10^6, datatype = integer[1] ):
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
A = zeros(1000); % allocates memory for a 1000x1000 double precision matrix.
clear A; % deallocates memory
b = zeros(1,100000); % pre-allocate memory to improve performance
for k=1:100000,
b(k) = 5*k*k-3*k+2;
end
|
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #REXX | REXX | /* REXX */
patients='patients.csv'
l=linein(patients)
Parse Var l h1 ',' h2
n=0
idl=''
Do n=1 By 1 While lines(patients)>0
l=linein(patients)
Parse Var l id ',' lastname.id
idl=idl id
End
n=n-1 /* number of patients */
visits='visits.csv'
l=linein(visits) /* skip the header line of this file */
h3='LAST_VISIT... |
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;... | #Delphi | Delphi |
class
APPLICATION
create
make
feature
make
-- Test of middle_three_digits.
local
test_1, test_2: ARRAY [INTEGER]
do
test_1 := <<123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345>>
test_2 := <<1, 2, -1, -10, 2002, -2002, 0>>
across
test_1 as t
loop
io.put_str... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Ruby | Ruby | puts <<EOS
Minesweeper game.
There is an n by m grid that has a random number of between 20% to 60%
of randomly hidden mines that need to be found.
Positions in the grid are modified by entering their coordinates
where the first coordinate is horizontal in the grid and the second
vertical. ... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Ursala | Ursala |
#import std
#import nat
table "n" =
~&plrTS(
~&xS pad` @xS <'x ','--'>-- --' | '*hS %nP* nrange/1 "n",
^CthPiC(`-!*h,~&) mat` *xSSK7 pad` *K7ihxPBSS (~&i&& %nP)** nleq&&product**iiK0lK2x nrange/1 "n")
#show+
main = table 12
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #Haskell | Haskell | module Primes where
import System.Random
import System.IO.Unsafe
-- Miller-Rabin wrapped up as an (almost deterministic) pure function
isPrime :: Integer -> Bool
isPrime n = unsafePerformIO (isMillerRabinPrime 100 n)
isMillerRabinPrime :: Int -> Integer -> IO Bool
isMillerRabinPrime k n
| even n = return ... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Go | Go | package main
import "fmt"
func mertens(to int) ([]int, int, int) {
if to < 1 {
to = 1
}
merts := make([]int, to+1)
primes := []int{2}
var sum, zeros, crosses int
for i := 1; i <= to; i++ {
j := i
cp := 0 // counts prime factors
spf := false // true if the... |
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... | #D | D | import std.stdio, std.conv, std.string, std.array, std.typecons;
string menuSelect(in string[] entries) {
static Nullable!(int, -1) validChoice(in string input,
in int nEntries)
pure nothrow {
try {
immutable n = input.to!int;
return ty... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #F.23 | F# | let fxyz x y z : uint32 = (x &&& y) ||| (~~~x &&& z)
let gxyz x y z : uint32 = (z &&& x) ||| (~~~z &&& y)
let hxyz x y z : uint32 = x ^^^ y ^^^ z
let ixyz x y z : uint32 = y ^^^ (x ||| ~~~z)
let fghi = [ fxyz; gxyz; hxyz; ixyz ] |> List.collect (List.replicate 16)
let g1Idx = id
let g2Idx i = (5 * i + 1) % 16
let g3Idx... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #MATLAB_.2F_Octave | MATLAB / Octave |
A = zeros(1000); % allocates memory for a 1000x1000 double precision matrix.
clear A; % deallocates memory
b = zeros(1,100000); % pre-allocate memory to improve performance
for k=1:100000,
b(k) = 5*k*k-3*k+2;
end
|
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Maxima | Maxima | /* Maxima allocates memory dynamically and uses a garbage collector.
Here is how to check available memory */
room();
3221/3221 72.3% 2 CONS RATIO COMPLEX STRUCTURE
272/307 61.6% FIXNUM SHORT-FLOAT CHARACTER RANDOM-STATE READTABLE SPICE
226/404 90.8% SYMBOL STREAM
1/2 3... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #SAS | SAS | %let datefmt=E8601DA10.;
data patient;
infile "patient.csv" dsd dlm=',';
attrib
id length=4
lastname length=$10;
input id lastname;
data visit;
infile "visit.csv" dsd dlm=',';
attrib
id length=4
date informat=&datefmt format=&datefmt
... |
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;... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Test of middle_three_digits.
local
test_1, test_2: ARRAY [INTEGER]
do
test_1 := <<123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345>>
test_2 := <<1, 2, -1, -10, 2002, -2002, 0>>
across
test_1 as t
loop
io.put_str... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Rust | Rust | extern crate rand;
use std::io;
use std::io::Write;
fn main() {
use minesweeper::{MineSweeper, GameStatus};
let mut width = 6;
let mut height = 4;
let mut mine_perctg = 10;
let mut game = MineSweeper::new(width, height, mine_perctg);
loop {
let mut command = String::new();
... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #VBA | VBA |
Option Explicit
Sub Multiplication_Tables()
Dim strTemp As String, strBuff As String
Dim i&, j&, NbDigits As Byte
'You can adapt the following const :
Const NB_END As Byte = 12
Select Case NB_END
Case Is < 10: NbDigits = 3
Case 10 To 31: NbDigits = 4
Case 31 To 100: NbDigits = 5
... |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every n := !A do write(n," is ",(mrp(n,5),"probably prime")|"composite")
end
procedure mrp(n, k)
if n = 2 then return ""
if n%2 = 0 then fail
nm1 := decompose(n-1)
s := nm1[1]
d := nm1[2]
every !k do {
a := ?(n-2)+1
x := (a^d)%n
if x = (1|(n-1)) the... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Haskell | Haskell | import Data.List.Split (chunksOf)
import qualified Data.MemoCombinators as Memo
import Math.NumberTheory.Primes (unPrime, factorise)
import Text.Printf (printf)
moebius :: Integer -> Int
moebius = product . fmap m . factorise
where
m (p, e)
| unPrime p ... |
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... | #Delphi | Delphi |
program Menu;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function ChooseMenu(Options: TArray<string>; Prompt: string): string;
var
index: Integer;
value: string;
begin
if Length(Options) = 0 then
exit('');
repeat
writeln;
for var i := 0 to length(Options) - 1 do
writeln(i + 1, '. ', Op... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #FreeBASIC | FreeBASIC | ' version 19-10-2016
' MD5 from the Wikipedia page "MD5"
' compile with: fbc -s console
' macro for a rotate left
#Macro ROtate_Left (x, n) ' rotate left
(x) = (x) Shl (n) + (x) Shr (32 - (n))
#EndMacro
Function MD5(test_str As String) As String
Dim As String message = test_str ' strings are passed as ByRef... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Nanoquery | Nanoquery | import native
// allocate 26 bytes
ptr = native.allocate(26)
// store the uppercase alphabet
for i in range(0, 25)
native.poke(ptr + i, ord("A") + i)
end
// output the allocated memory
for i in range(0, 25)
print chr(native.peek(ptr + i))
end
// free the allocated memory
native.free(ptr) |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Nim | Nim | # Allocate thread local heap memory
var a = alloc(1000)
dealloc(a)
# Allocate memory block on shared heap
var b = allocShared(1000)
deallocShared(b)
# Allocate and Dellocate a single int on the thread local heap
var p = create(int, sizeof(int)) # allocate memory
# create zeroes memory; createU does not.
echo p[] ... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #SPSS | SPSS | * set working directory to location of .csv files
CD 'C:\Temp\csv\'.
* load patients csv data
GET DATA /TYPE=TXT
/FILE="patients.csv"
/ENCODING='UTF8'
/DELCASE=LINE
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/IMPORTCASE=ALL
/VARIABLES=
PATIENT_ID F5.0
LASTNAME A20
.
CACHE... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #SQL | SQL | -- drop tables
DROP TABLE IF EXISTS tmp_patients;
DROP TABLE IF EXISTS tmp_visits;
-- create tables
CREATE TABLE tmp_patients(
PATIENT_ID INT,
LASTNAME VARCHAR(20)
);
CREATE TABLE tmp_visits(
PATIENT_ID INT,
VISIT_DATE DATE,
SCORE NUMERIC(4,1)
);
-- load data from csv files
/*
-- Note: LOAD DATA LOCAL requir... |
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;... | #Elena | Elena | import system'routines;
import extensions;
middleThreeDigits(int n)
{
string s := n.Absolute.toString();
int len := s.Length;
if(len<3)
{
InvalidArgumentException.new:"n must have 3 digits or more".raise()
}
else if(len.isEven())
{
InvalidArgumentException.new:"n must have ... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Tcl | Tcl | package require Tcl 8.5
fconfigure stdout -buffering none
# Set up the grid and fill it with some mines
proc makeGrid {n m} {
global grid mine
unset -nocomplain grid mine
set grid(size) [list $n $m]
set grid(shown) 0
set grid(marked) 0
for {set j 1} {$j <= $m} {incr j} {
for {set i 1} {$i <= ... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Visual_Basic | Visual Basic | Sub Main()
Const nmax = 12, xx = 3
Const x = xx + 1
Dim i As Integer, j As Integer, s As String
s = String(xx, " ") & " |"
For j = 1 To nmax
s = s & Right(String(x, " ") & j, x)
Next j
Debug.Print s
s = String(xx, "-") & " +"
For j = 1 To nmax
s = s & " " & String(xx,... |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #J | J | import java.math.BigInteger;
public class MillerRabinPrimalityTest {
public static void main(String[] args) {
BigInteger n = new BigInteger(args[0]);
int certainty = Integer.parseInt(args[1]);
System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite"));
... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #J | J | mu =: 0:`(1 - 2 * 2|#@{.)@.(1: = */@{:)@(2&p:)"0
M =: +/@([: mu 1:+i.)
m1000 =: (M"0) 1+i.1000
zero =: +/ m1000 = 0
cross =: +/ (-.*.1:|]) m1000 ~: 0
echo 'The first 99 Merten numbers are'
echo 10 10$ __, 99{.m1000
echo 'M(N) is zero ',(":zero),' times.'
echo 'M(N) crosses zero ',(":cross),' times.'
exit'' |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #Elixir | Elixir | defmodule Menu do
def select(_, []), do: ""
def select(prompt, items) do
IO.puts ""
Enum.with_index(items) |> Enum.each(fn {item,i} -> IO.puts " #{i}. #{item}" end)
answer = IO.gets("#{prompt}: ") |> String.strip
case Integer.parse(answer) do
{num, ""} when num in 0..length(items)-1 -> Enum.at... |
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... | #ERRE | ERRE |
PROCEDURE Selection(choices$[],prompt$->sel$)
IF UBOUND(choices$,1)-LBOUND(choices$,1)=0 THEN
sel$=""
EXIT PROCEDURE
END IF
ret$=""
REPEAT
FOR i=LBOUND(choices$,1) TO UBOUND(choices$,1) DO
PRINT(i;": ";choices$[i])
END FOR
PRINT(prompt$;)
INPUT(index)
I... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #Go | Go | package main
import (
"fmt"
"math"
"bytes"
"encoding/binary"
)
type testCase struct {
hashCode string
string
}
var testCases = []testCase{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Objeck | Objeck | foo := Object->New(); // allocates an object on the heap
foo_array := Int->New[size]; // allocates an integer array on the heap
x := 0; // allocates an integer on the stack |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Oforth | Oforth |
'ALLOCATING MEMORY FROM DIFFERENT MEMORY SOURCES
sys p
static byte b[0x1000] 'global memory
p=@b
function f()
local byte b[0x1000] 'stack memory in a procedure
p=@b
end function
p=getmemory 0x1000 'heap memory
...
freememory p 'to disallocate
sub rsp,0x1000 'stack memory direct
p=rsp
...
rsp=p ... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #Transd | Transd | #lang transd
MainModule: {
tbl: `1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz`,
tbl1: `
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3`,
cols: `@key_PATIENT_ID:Int,
LASTNAME:String,
VIS... |
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;... | #Elixir | Elixir | defmodule Middle do
def three(num) do
n = num |> abs |> to_string
case {n,String.length(n) > 2,even?(n)} do
{n, true, false} ->
cut(n)
{_, false, _} ->
raise "Number must have at least three digits"
{_, _, true} ->
raise "Number must have an odd number of digits"
... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #VBA | VBA | In your Vbaproject, insert :
- 1 Module
- 1 Class Module (Name it cMinesweeper) |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Wren | Wren | import "/fmt" for Fmt
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Fmt.print(" x | $4d", nums)
System.print("----+%("-" * 60)")
for (i in 1..12) {
var nums2 = nums.map { |n| (n >= i) ? (n * i).toString : " " }.toList
Fmt.print("$3d | $4s", i, nums2)
} |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #Java | Java | import java.math.BigInteger;
public class MillerRabinPrimalityTest {
public static void main(String[] args) {
BigInteger n = new BigInteger(args[0]);
int certainty = Integer.parseInt(args[1]);
System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite"));
... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Java | Java |
public class MertensFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the merten function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", mertenFunction(n));
if ( (n+1) % 20 == 0 ) {
... |
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... | #Euphoria | Euphoria | include get.e
function menu_select(sequence items, object prompt)
if length(items) = 0 then
return ""
else
for i = 1 to length(items) do
printf(1,"%d) %s\n",{i,items[i]})
end for
if atom(prompt) then
prompt = "Choice?"
end if
return i... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #Groovy | Groovy |
class MD5 {
private static final int INIT_A = 0x67452301
private static final int INIT_B = (int)0xEFCDAB89L
private static final int INIT_C = (int)0x98BADCFEL
private static final int INIT_D = 0x10325476
private static final int[] SHIFT_AMTS = [
7, 12, 17, 22,
5, 9, 14... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #OxygenBasic | OxygenBasic |
'ALLOCATING MEMORY FROM DIFFERENT MEMORY SOURCES
sys p
static byte b[0x1000] 'global memory
p=@b
function f()
local byte b[0x1000] 'stack memory in a procedure
p=@b
end function
p=getmemory 0x1000 'heap memory
...
freememory p 'to disallocate
sub rsp,0x1000 'stack memory direct
p=rsp
...
rsp=p ... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #PARI.2FGP | PARI/GP | allocatemem(100<<20) |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #TutorialD | TutorialD | BEGIN;
TYPE Date UNION;
TYPE DateValid IS {Date POSSREP {year INTEGER, month INTEGER, day INTEGER}};
TYPE DateNone IS {Date POSSREP {}};
TYPE DateUnknown IS {Date POSSREP {}};
END;
VAR patient REAL RELATION {id INT, lastname CHAR} KEY {id};
INSERT patient RELATION
{TUPLE {id 1001, lastname 'Hopper'},
TUP... |
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;... | #Erlang | Erlang | %
-module(middle_three_digits).
-export([main/0]).
main() ->
digits(123),
digits(12345),
digits(1234567),
digits(987654321),
digits(10001),
digits(-10001),
digits(-123),
digits(-100),
digits(100),
digits(-12345),
digits(1),
digits(2),
digits(-1),
digits(-10),
digits(2002),
digits(-2002),
digits(... |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid... | #Wren | Wren | import "/dynamic" for Struct
import "/fmt" for Fmt
import "random" for Random
import "/ioutil" for Input
import "/str" for Str
var Cell = Struct.create("Cell", ["isMine", "display"])
var lMargin = 4
var grid = []
var mineCount = 0
var minesMarked = 0
var isGameOver = false
var rand = Random.new()
var makeGrid = ... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #XBasic | XBasic |
PROGRAM "multiplicationtables"
VERSION "0.0001"
DECLARE FUNCTION Entry()
FUNCTION Entry()
$N = 12
FOR j@@ = 1 TO $N - 1
PRINT FORMAT$("### ", j@@);
NEXT j@@
PRINT FORMAT$("###", $N)
FOR j@@ = 0 TO $N - 1
PRINT "----";
NEXT j@@
PRINT "+"
FOR i@@ = 1 TO $N
FOR j@@ = 1 TO $N
IF j@@ ... |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #JavaScript | JavaScript | function probablyPrime(n) {
if (n === 2 || n === 3) return true
if (n % 2 === 0 || n < 2) return false
// Write (n - 1) as 2^s * d
var s = 0,
d = n - 1
while ((d & 1) == 0) {
d >>= 1
++s
}
let base = 2
var x = Math.pow(base, d) % n
if (x == 1 || x == n - 1) return true
for (var i... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #jq | jq |
def sum(s): reduce s as $x (null; . + $x);
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# input: an array
# output: number of crossings at $value
def count_crossings($value):
. as $a
| reduce rang... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Julia | Julia | using Primes, Formatting
function moebius(n::Integer)
@assert n > 0
m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0
return reduce(*, m(p, e) for (p, e) in factor(n) if p ≥ 0; init=1)
end
μ(n) = moebius(n)
mertens(x) = sum(n -> μ(n), 1:x)
M(x) = mertens(x)
print("First 99 terms of the Mertens function for posi... |
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... | #F.23 | F# | open System
let rec menuChoice (options : string list) prompt =
if options = [] then ""
else
for i = 0 to options.Length - 1 do
printfn "%d. %s" (i + 1) options.[i]
printf "%s" prompt
let input = Int32.TryParse(Console.ReadLine())
match input with
| true... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #Haskell | Haskell | import Control.Monad (replicateM)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import Data.Array (Array, listArray, (!))
import Data.List (foldl)
import Data.Word (Word32)
import Numeric (showHex)
... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Pascal | Pascal | type
TByteArray = array of byte;
var
A: TByteArray;
begin
setLength(A,1000);
...
setLength(A,0);
end; |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Perl | Perl | atom addr = allocate(512) -- limit is 1,610,612,728 bytes on 32-bit systems
...
free(addr)
atom addr2 = allocate(512,1) -- automatically freed when addr2 drops out of scope or re-assigned
atom addr3 = allocate_string("a string",1) -- automatically freed when addr3 drops out of scope or re... |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either lo... | #Wren | Wren | import "/fmt" for Fmt
import "/sort" for Sort
class Patient {
construct new(id, lastName) {
_id = id
_lastName = lastName
if (!__dir) __dir = {}
__dir[id] = lastName
if (!__ids) {
__ids = [id]
} else {
__ids.add(id)
Sort.insertion... |
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;... | #ERRE | ERRE |
PROGRAM MIDDLE
!$DOUBLE
FUNCTION LUNG(N)
LUNG=LEN(STR$(INT(ABS(N))))+1
END FUNCTION
FUNCTION NCNT(N)
NCNT=VAL(MID$(STR$(INT(ABS(N))),(LUNG(N)-1)/2,3))
END FUNCTION
FUNCTION EVEN(N)
EVEN=INT(N/2)=N/2
END FUNCTION
PROCEDURE NUMBER_EXAM(N->R$)
R$="" LG%=LUNG(N)-2
IF EVEN(LG%) THEN R$="?EVE... |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int X, Y;
[Format(4, 0);
Text(0, " |"); for X:= 1 to 12 do RlOut(0, float(X));
CrLf(0);
Text(0, " --+"); for X:= 1 to 12 do Text(0, "----");
CrLf(0);
for Y:= 1 to 12 do
[RlOut(0, float(Y)); ChOut(0, ^|);
for X:= 1 to 12 do
if X>=Y then RlOut(0, float(X*Y)) else Text(0, " . ... |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #Julia | Julia |
witnesses(n::Union(Uint8,Int8,Uint16,Int16)) = (2,3)
witnesses(n::Union(Uint32,Int32)) = n < 1373653 ? (2,3) : (2,7,61)
witnesses(n::Union(Uint64,Int64)) =
n < 1373653 ? (2,3) :
n < 4759123141 ? (2,7,61) :
n < 2152302898747 ? (2,3,5,7,11) :
n < 3474749660383 ? (2,3,5,7... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION M(1000)
M(1) = 1
THROUGH GENMRT, FOR N=2, 1, N.G.1000
M(N) = 1
THROUGH GENMRT, FOR K=2, 1, K.G.N
GENMRT M(N) = M(N) - M(N/K)
PRINT COMMENT $ FIRST 99 MERTEN NUMBERS ARE$
VECTOR VALUE... |
http://rosettacode.org/wiki/Mertens_function | Mertens function | The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number.
It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Mertens]
Mertens[n_] := Total[MoebiusMu[Range[n]]]
Grid[Partition[Mertens /@ Range[99], UpTo[10]]]
Count[Mertens /@ Range[1000], 0]
SequenceCount[Mertens /@ Range[1000], {Except[0], 0}] |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #Factor | Factor | USING: formatting io kernel math math.parser sequences ;
: print-menu ( seq -- )
[ 1 + swap "%d - %s\n" printf ] each-index
"Your choice? " write flush ;
: (select) ( seq -- result )
dup print-menu readln string>number dup integer? [
drop 1 - swap 2dup bounds-check?
[ nth ] [ nip (select... |
http://rosettacode.org/wiki/MD5/Implementation | MD5/Implementation | The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).
The implementation needs t... | #Icon_and_Unicon | Icon and Unicon | procedure main() # validate against the RFC test strings and more
testMD5("The quick brown fox jumps over the lazy dog", 16r9e107d9d372bb6826bd81d3542a419d6)
testMD5("The quick brown fox jumps over the lazy dog.", 16re4d909c290d0fb1ca068ffaddf22cbd0)
testMD5("", 16rd41d8cd98f00b204e9800998ecf8427e) #R = MD... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #Phix | Phix | atom addr = allocate(512) -- limit is 1,610,612,728 bytes on 32-bit systems
...
free(addr)
atom addr2 = allocate(512,1) -- automatically freed when addr2 drops out of scope or re-assigned
atom addr3 = allocate_string("a string",1) -- automatically freed when addr3 drops out of scope or re... |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #PicoLisp | PicoLisp |
mainproc: proc options(main) reorder;
subproc: proc;
dcl subvar char init ('X');
put skip data(subvar);
subvar = 'Q';
end subproc;
call subproc();
call subproc();
end mainproc; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.