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/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... | #BBC_BASIC | BBC BASIC | DIM list$(4)
list$() = "fee fie", "huff and puff", "mirror mirror", "tick tock"
selected$ = FNmenu(list$(), "Please make a selection: ")
PRINT selected$
END
DEF FNmenu(list$(), prompt$)
LOCAL index%, select$
IF SUM(list$()) = "" THEN = ""
REPEAT
CLS
... |
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... | #Ada | Ada | package MD5 is
type Int32 is mod 2 ** 32;
type MD5_Hash is array (1 .. 4) of Int32;
function MD5 (Input : String) return MD5_Hash;
-- 32 hexadecimal characters + '0x' prefix
subtype MD5_String is String (1 .. 34);
function To_String (Item : MD5_Hash) return MD5_String;
end MD5; |
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.
| #Delphi | Delphi | ? <elib:tables.makeFlexList>.fromType(<type:java.lang.Byte>, 128)
# value: [].diverge() |
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.
| #E | E | ? <elib:tables.makeFlexList>.fromType(<type:java.lang.Byte>, 128)
# value: [].diverge() |
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... | #Mercury | Mercury | :- module rosetta.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, int, float, string, maybe, solutions.
:- pred patient(int::out, string::out) is multi.
patient(1001, "Hopper").
patient(4004, "Wirth").
patient(3003, "Kemeny").
patient(2002, "Gosli... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Racket | Racket |
#lang racket
(require ffi/unsafe)
(define (_autobitmask l)
(_bitmask (append* (for/list ([x l] [i (in-naturals)]) `(,x = ,(expt 2 i))))))
(define _rs232 (_autobitmask '(CD RD TD DTR SG DSR RTS CTS RI )))
;; Usually it will get used when using foreign functions automatically, but
;; this demonstrates the con... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Raku | Raku | enum T_RS232 <
carrier_detect
received_data
transmitted_data
data_terminal_ready
signal_ground
data_set_ready
request_to_send
clear_to_send
ring_indicator
>;
my bit @signal[T_RS232];
@signal[signal_ground] = 1; |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #REXX | REXX | /* REXX ***************************************************************
* Decode Memory structure of RS-232 Plug Definition
* Not sure if I understood it completely :-) Open for corrections
* You never stop learning (as long as you live)
* 03.08.2012 Walter Pachl
*******************************************************... |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #Ruby | Ruby | class Pixmap
def median_filter(radius=3)
radius += 1 if radius.even?
filtered = self.class.new(@width, @height)
pb = ProgressBar.new(@height) if $DEBUG
@height.times do |y|
@width.times do |x|
window = []
(x - radius).upto(x + radius).each do |win_x|
(y - radius).upto(y... |
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;... | #C_sharp | C_sharp | using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 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... | #Phix | Phix | constant help = """
Minesweeper
===========
Enter eg A1 to open a cell, FA1 to flag a cell, Q to quit.
The board is initially displayed with 10-20% of cells mined, as follows:
. - an unknown cell (unopened and not flagged)
_ - an empty cell, with no surrounding mines
1..8 - an empty cell, with some nearby mine... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #Visual_Basic_.NET | Visual Basic .NET | Imports System, System.Linq, System.Collections.Generic, System.Console
Module Module1
Dim fmt As String = "{0,4} * {1,31:n0} = {2,-28}" & vbLf
Sub B10(ByVal n As Integer)
If n <= 1 Then Return
Dim pow As Integer() = New Integer(n) {},
val As Integer() = New Integer(n) {},
... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #TXR | TXR | $ txr -p '(exptmod 2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
(expt 10 40)))'
1527229998585248450016808958343740453059 |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Visual_Basic_.NET | Visual Basic .NET | ' Modular exponentiation - VB.Net - 21/01/2019
Imports System.Numerics
Private Sub Main()
Dim a, b, m, x As BigInteger
a = BigInteger.Parse("2988348162058574136915891421498819466320163312926952423791023078876139")
b = BigInteger.Parse("23513993033734644864661225445236900947449752334155... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Python | Python |
#lang Python
import time
def main(bpm = 72, bpb = 4):
sleep = 60.0 / bpm
counter = 0
while True:
counter += 1
if counter % bpb:
print 'tick'
else:
print 'TICK'
time.sleep(sleep)
main()
|
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Racket | Racket |
#lang racket
(require racket/gui)
(define msec 500)
(define sounds '("hi.wav" "lo.wav"))
(define colors '("red" "green"))
(define f
(new frame% [label "Metronome"] [width 200] [height 200]))
(define c
(new (class canvas%
(define brushes
(map (λ(c) (new brush% [color c] [style 'solid])) c... |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #Scala | Scala | class CountingSemaphore(var maxCount: Int) {
private var lockCount = 0
def acquire(): Unit = {
while ( {
lockCount >= maxCount
}) wait()
lockCount += 1
}
def release(): Unit = {
if (lockCount > 0) {
lockCount -= 1
notifyAll()
}
}
def getCount: Int = lockCount
}
... |
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.
| #Simula | Simula | begin
integer i, j;
outtext( " " );
for i := 1 step 1 until 12 do outint( i, 4 );
outimage;
outtext( " +" );
for i := 1 step 1 until 12 do outtext( "----" );
outimage;
for i := 1 step 1 until 12 do
begin
outint( i, 3 );
outtext( "|" );
for j := 1 step 1 u... |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, fo... | #Wren | Wren | var mianChowla = Fn.new { |n|
var mc = List.filled(n, 0)
var sums = {}
var ts = {}
mc[0] = 1
sums[2] = true
for (i in 1...n) {
var j = mc[i-1] + 1
while (true) {
mc[i] = j
for (k in 0..i) {
var sum = mc[k] + j
if (sums[sum])... |
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... | #Run_BASIC | Run BASIC | ' ---------------------------------------------------
' create a file to be run
' RB can run the entire program
' or execute a function withing the RUNNED program
' ---------------------------------------------------
open "runned.bas" for output as #f ' open runned.bas as output
print #f, "text$... |
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... | #Rust | Rust | // dry.rs
use std::ops::{Add, Mul, Sub};
macro_rules! assert_equal_len {
// The `tt` (token tree) designator is used for
// operators and tokens.
($a:ident, $b: ident, $func:ident, $op:tt) => (
assert!($a.len() == $b.len(),
"{:?}: dimension mismatch: {:?} {:?} {:?}",
... |
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... | #Elixir | Elixir |
defmodule Prime do
use Application
alias :math, as: Math
alias :rand, as: Rand
def start( _type, _args ) do
primes = 5..1000
|> Enum.filter( fn( x ) -> (rem x, 2) == 1 end )
|> Enum.filter( fn( x ) -> miller_rabin?( x, 10) == True end )
IO.inspect( primes, label: "Primes: ", limit: :infi... |
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... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(mer... |
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... | #Brat | Brat | menu = { prompt, choices |
true? choices.empty?
{ "" }
{
choices.each_with_index { c, i |
p "#{i}. #{c}"
}
selection = ask prompt
true? selection.numeric?
{ selection = selection.to_i
true? selection < 0 || { selection >= choices.length }
{ p "Selection is out o... |
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... | #AutoHotkey | AutoHotkey | 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/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.
| #Erlang | Erlang | Pid = erlang:spawn_opt( Fun, [{min_heap_size, 1024}] ).
|
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.
| #Factor | Factor | 2000 malloc (...do stuff..) free |
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... | #Nim | Nim | import algorithm, parsecsv, strformat, strutils, tables
const NoValue = -1.0
type
Names = OrderedTable[Positive, string] # Mapping id -> last name.
Visit = tuple[date: string; score: float]
Visits = Table[Positive, seq[Visit]] # Mapping id -> list of visits.
proc readNames(path: string): N... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Ruby | Ruby | require 'bit-struct'
class RS232_9 < BitStruct
unsigned :cd, 1, "Carrier detect" #1
unsigned :rd, 1, "Received data" #2
unsigned :td, 1, "Transmitted data" #3
unsigned :dtr, 1, "Data terminal ready" #4
unsigned :sg, 1, "Signal ground" #5
unsigned :dsr, 1, "Data set ready" ... |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #Tcl | Tcl | package require Tk
# Set the color of a pixel
proc applyMedian {srcImage x y -> dstImage} {
set x0 [expr {$x==0 ? 0 : $x-1}]
set y0 [expr {$y==0 ? 0 : $y-1}]
set x1 $x
set y1 $y
set x2 [expr {$x+1==[image width $srcImage] ? $x : $x+1}]
set y2 [expr {$y+1==[image height $srcImage] ? $y : $y+1}... |
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;... | #Clojure | Clojure |
(defn middle3 [v]
(let [no (Math/abs v)
digits (str no)
len (count digits)]
(cond
(< len 3) :too_short
(even? len) :no_middle_in_even_no_of_digits
:else (let [mid (/ len 2)
start (- mid 2)]
(apply str
(take 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... | #PHP | PHP | <?php
define('MINEGRID_WIDTH', 6);
define('MINEGRID_HEIGHT', 4);
define('MINESWEEPER_NOT_EXPLORED', -1);
define('MINESWEEPER_MINE', -2);
define('MINESWEEPER_FLAGGED', -3);
define('MINESWEEPER_FLAGGED_MINE', -4);
define('ACTIVATED_MINE', -5);
function check_field($field) {
if ($field === ... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #Wren | Wren | import "/fmt" for Fmt
import "/big" for BigInt
var b10 = Fn.new { |n|
if (n == 1) {
Fmt.print("$4d: $28s $-24d", 1, "1", 1)
return
}
var n1 = n + 1
var pow = List.filled(n1, 0)
var val = List.filled(n1, 0)
var count = 0
var ten = 1
var x = 1
while (x < n1) {
... |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #Wren | Wren | import "/big" for BigInt
var a = BigInt.new("2988348162058574136915891421498819466320163312926952423791023078876139")
var b = BigInt.new("2351399303373464486466122544523690094744975233415544072992656881240319")
var m = BigInt.ten.pow(40)
System.print(a.modPow(b, m)) |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
235139930337346448646612254452369009474497523... | #zkl | zkl | var BN=Import("zklBigNum");
a:=BN("2988348162058574136915891421498819466320163312926952423791023078876139");
b:=BN("2351399303373464486466122544523690094744975233415544072992656881240319");
m:=BN(10).pow(40);
a.powm(b,m).println();
a.powm(b,m) : "%,d".fmt(_).println(); |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Raku | Raku | sub MAIN ($beats-per-minute = 72, $beats-per-bar = 4) {
my $duration = 60 / $beats-per-minute;
my $base-time = now + $duration;
my $i;
for $base-time, $base-time + $duration ... * -> $next-time {
if $i++ %% $beats-per-bar {
print "\nTICK";
}
else {
print... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #REXX | REXX | /*REXX program simulates a visual (textual) metronome (with no sound). */
parse arg bpm bpb dur . /*obtain optional arguments from the CL*/
if bpm=='' | bpm=="," then bpm=72 /*the number of beats per minute. */
if bpb=='' | bpb=="," then bpb= 4 ... |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #Tcl | Tcl | package require Tcl 8.6
package require Thread
# Create the global shared state of the semaphore
set handle semaphore0
tsv::set $handle mutex [thread::mutex create]
tsv::set $handle cv [thread::cond create]
tsv::set $handle count 0
tsv::set $handle max 3
# Make five worker tasks
for {set i 0} {$i<5} {incr 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.
| #Swift | Swift | import Foundation
let size = 12
func printRow(with:Int, upto:Int) {
print(String(repeating: " ", count: (with-1)*4), terminator: "")
for i in with...upto {
print(String(format: "%l4d", i*with), terminator: "")
}
print()
}
print(" ", terminator: ""); printRow( with: 1, upto: size... |
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... | #Scala | Scala | import scala.language.experimental.macros
import scala.reflect.macros.Context
object Macros {
def impl(c: Context) = {
import c.universe._
c.Expr[Unit](q"""println("Hello World")""")
}
def hello: Unit = macro impl
} |
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... | #Shen | Shen | (define make-list
[A|D] -> [cons (make-list A) (make-list D)]
X -> X)
(defmacro info-macro
[info Exp] -> [output "~A: ~A~%" (make-list Exp) Exp])
(info (* 5 6)) \\ outputs [* 5 6]: 30 |
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... | #Erlang | Erlang |
-module(miller_rabin).
-export([is_prime/1, power/2]).
is_prime(1) -> false;
is_prime(2) -> true;
is_prime(3) -> true;
is_prime(N) when N > 3, ((N rem 2) == 0) -> false;
is_prime(N) when ((N rem 2) ==1), N < 341550071728321 ->
is_mr_prime(N, proving_bases(N));
is_prime(N) when ((N rem 2) == 1) ->
is_mr_pri... |
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... | #CLU | CLU | % Generate Mertens numbers up to a given limit
mertens = proc (limit: int) returns (array[int])
M: array[int] := array[int]$fill(1,limit,0)
M[1] := 1
for n: int in int$from_to(2,limit) do
M[n] := 1
for k: int in int$from_to(2,n) do
M[n] := M[n] - M[n/k]
end
end
re... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. MERTENS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 M PIC S99 OCCURS 1000 TIMES.
03 N PIC 9(4).
03 K PIC 9(4).
03 V PIC 9(4).
03 IS-Z... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *menu_select(const char *const *items, const char *prompt);
int
main(void)
{
const char *items[] = {"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL};
const char *prompt = "Which is from the three pigs?";
printf("You chose %s.\... |
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... | #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/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.
| #Forth | Forth | unused . \ memory available for use in dictionary
here . \ current dictionary memory pointer
: mem, ( addr len -- ) here over allot swap move ;
: s, ( str len -- ) here over char+ allot place align ; \ built-in on some forths
: ," [char] " parse s, ;
variable num
create array 60 cells allot
create struct 0 , 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.
| #Fortran | Fortran | program allocation_test
implicit none
real, dimension(:), allocatable :: vector
real, dimension(:, :), allocatable :: matrix
real, pointer :: ptr
integer, parameter :: n = 100 ! Size to allocate
allocate(vector(n)) ! Allocate a vector
allocate(matrix(n, n)) ! Allocate a matrix
a... |
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... | #Phix | Phix | constant patients_txt = split("""
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz""",'\n'),
visits_txt = split("""
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Scala | Scala | object Rs232Pins9 extends App {
val (off: Boolean, on: Boolean) = (false, true)
val plug = new Rs232Pins9(carrierDetect = on, receivedData = on) // set first two pins, say
def toOnOff(b: Boolean) = if (b) "on" else "off"
class Rs232Pins9(
var carrierDetect: Boolean = off,
... |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #Wren | Wren | import "graphics" for Canvas, ImageData, Color
import "dome" for Window
class MedianFilter {
construct new(filename, filename2, windowWidth, windowHeight) {
Window.title = "Median filter"
var image = ImageData.loadFromFile(filename)
Window.resize(image.width, image.height)
Canvas.r... |
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;... | #CLU | CLU | middle_three_digits = proc (n: int) returns (string)
signals (too_small, even_length)
s: string := int$unparse(int$abs(n))
if string$size(s) < 3 then signal too_small end
if string$size(s) // 2 = 0 then signal even_length end
return(string$substr(s, string$size(s)/2, 3))
end middle... |
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... | #PicoLisp | PicoLisp | # NIL Hidden: Empty field
# T Hidden: Mine
# 0-8 Marked: Empty field
# ? Marked: Mine
(de minesweeper (DX DY Density)
(default Density 20)
(setq *Field (make (do DY (link (need DX)))))
(use (X Y)
(do (prinl "Number of mines: " (*/ DX DY Density 100))
(while
(get *Fi... |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #zkl | zkl | var [const]
B10_4=10*10*10*10,
HexB10=T(0000,0001,0010,0011,0100,0101,0110,0111,
1000,1001,1010,1011,1100,1101,1110,1111);
// Convert n from binary as if it is Base 10
// limited for Uint64 to 2^20-1= 1048575 ala 19 digits
// for int64, limited to 2^19-1= 524287, conv2B10()-->111111111111111111... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Ruby | Ruby |
#!/usr/bin/ruby
bpm = Integer(ARGV[0]) rescue 60 # sets BPM by the first command line argument, set to 60 if none provided
msr = Integer(ARGV[1]) rescue 4 # sets number of beats in a measure by the second command line argument, set to 4 if none provided
i = 0
loop do
(msr-1).times do
puts "\a"
sleep(60... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Scala | Scala | def metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MaxValue) {
val delay = 60000L / bpm
var beats = 0
do {
Thread.sleep(delay)
if (beats % bpb == 0) print("\nTICK ")
else print("tick ")
beats+=1
}
while (beats < maxBeats)
println()
}
metronome(120, 4, 20) // limit to 20 |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #UnixPipes | UnixPipes | rm -f sem ; mkfifo sem
acquire() {
x='';while test -z "$x"; do read x; done;
}
release() {
echo '1'
}
job() {
n=$1; echo "Job $n acquired Semaphore">&2 ; sleep 2; echo "Job $n released Semaphore">&2 ;
}
( acquire < sem ; job 1 ; release > sem ) &
( acquire < sem ; job 2 ; release > sem ) &
( acquire < ... |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #Visual_Basic_.NET | Visual Basic .NET | Dim sem As New Semaphore(5, 5) 'Indicates that up to 5 resources can be aquired
sem.WaitOne() 'Blocks until a resouce can be aquired
Dim oldCount = sem.Release() 'Returns a resource to the pool
'oldCount has the Semaphore's count before Release was called |
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.
| #Tailspin | Tailspin |
templates formatN&{width:}
[ 1..$width -> ' ', '$;'... ] -> '$(last-$width+1..last)...;' !
end formatN
' |$:1..12 -> formatN&{width: 4};
' -> !OUT::write
'--+$:1..12*4 -> '-';
' -> !OUT::write
1..12 -> \( def row: $;
'$ -> formatN&{width:2};|$:1..($-1)*4 -> ' ';$:$..12 -> $*$row -> formatN&{width:4};
' ! \) ->... |
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... | #Sidef | Sidef | class Number {
method ⊕(arg) {
self + arg
}
}
say (21 ⊕ 42) |
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... | #Smalltalk | Smalltalk | apiSyslog:priority format:format message:message
<cdecl: int 'syslog' (int char* char*) >
^ self primitiveFailed.
|
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... | #SNOBOL4 | SNOBOL4 |
OPSYN('SAME','IDENT')
OPSYN('$','*',1)
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller prima... | #F.23 | F# |
// Miller primality test for n<3317044064679887385961981. Nigel Galloway: April 1st., 2021
let a=[(2047I,[2I]);(1373653I,[2I;3I]);(9080191I,[31I;73I]);(25326001I,[2I;3I;5I]);(3215031751I,[2I;3I;5I;7I]);(4759123141I,[2I;7I;61I]);(1122004669633I,[2I;13I;23I;1662803I]);
(2152302898747I,[2I;3I;5I;7I;11I]);(3474749... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
const MAX := 1000;
# Table output
sub printtab(n: int8) is
if n<0 then
print_char('-');
n := -n;
else
print_char(' ');
end if;
print_char(n as uint8 + '0');
print_char(' ');
end sub;
# Generate Merten numbers
var M: int8[MAX+1];
M[0] := 0;
M[1] :... |
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... | #Delphi | Delphi |
program Mertens_function;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TMertens = record
merts: TArray<Integer>;
zeros, crosses: Integer;
class function Mertens(_to: Integer): TMertens; static;
end;
{ TMertens }
class function TMertens.Mertens(_to: Integer): TMertens;
var
sum, zeros, cr... |
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... | #C.23 | C# |
using System;
using System.Collections.Generic;
public class Menu
{
static void Main(string[] args)
{
List<string> menu_items = new List<string>() { "fee fie", "huff and puff", "mirror mirror", "tick tock" };
//List<string> menu_items = new List<string>();
Console... |
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... | #C | C |
/// Represent digest with ABCD
sealed public class Digest
{
public uint A;
public uint B;
public uint C;
public uint D;
public Digest()
{
A=(uint)MD5InitializerConstant.A;
B=(uint)MD5InitializerConstant.B;
C=(uint)MD5InitializerConstant.C;
D=(uint)MD5InitializerConstant.D;
... |
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.
| #FreeBASIC | FreeBASIC | Dim As Integer size = 12345
Dim As Integer mem = size-1
Print size; " bytes of heap allocated at " ; mem
Clear (mem, , 10)
Print size; " bytes of heap allocated at " ; mem |
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.
| #Go | Go | func inc(n int) {
x := n + 1
println(x)
} |
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... | #Perl | Perl | #!/usr/bin/perl
my $fmt = '| %-11s' x 5 . "|\n";
printf $fmt, qw( PATIENT_ID LASTNAME LAST_VISIT SCORE_SUM SCORE_AVG);
my ($names, $visits) = do { local $/; split /^\n/m, <DATA> };
my %score;
for ( $visits =~ /^\d.*/gm )
{
my ($id, undef, $score) = split /,/;
$score{$id} //= ['', ''];
$score and $score{$id}[0]+... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Tcl | Tcl | set rs232_bits {CD RD TD DTR SG DSR RTS CTS RI}
proc rs232_encode args {
set res 0
foreach arg $args {
set pos [lsearch $::rs232_bits $arg]
if {$pos >=0} {set res [expr {$res | 1<<$pos}]}
}
return $res
}
proc rs232_decode int {
set res {}
set i -1
foreach bit $::rs232_bits ... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Wren | Wren | import "/seq" for Lst
import "/fmt" for Fmt
var ON = true
var OFF = false
// Converts "ON"/"OFF" string to true/false.
var AsBool = Fn.new { |s| s == "ON" }
class RS232_9 {
static names { ["CD", "RD", "TD", "DTR", "SG", "DSR", "RTS", "CTS", "RI"] }
construct new() { _settings = [OFF] * 9 } // all pins ... |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #zkl | zkl | fcn medianFilter(img){ //-->new image
var [const] window=[-2..2].walk(), edge=(window.len()/2); // 5x5 window
MX,MY,new := img.w,img.h,PPM(MX,MY);
pixel,pixels:=List(),List();
foreach x,y in ([edge..MX-edge-1],[edge..MY-edge-1]){
pixels.clear();
foreach ox,oy in (window,window){ // constru... |
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;... | #COBOL | COBOL | identification division.
program-id. middle3.
environment division.
data division.
working-storage section.
01 num pic 9(9).
88 num-too-small values are -99 thru 99.
01 num-disp pic ---------9.
01 div pic 9(9).
01 mod pic 9(9).
01 mod-disp ... |
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... | #Prolog | Prolog | :- use_module(library(clpfd)).
% Play - run the minesweeper game with a specified width and height
play(W,H) :-
format('
Welcome to prolog minesweeper!
: o X Y exposes a cell of the grid
: m X Y marks bombs
Any else to quit.
'),
make_grid(W, H, Grid),
!,
play(Grid),
!.
play(Grid) :- % win condition is tr... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Sidef | Sidef | func metronome (beats_per_minute = 72, beats_per_bar = 4) {
var counter = 0
var duration = 60/beats_per_minute
var base_time = Time.micro+duration
STDOUT.autoflush(true)
for next_time in (base_time..Inf `by` duration) {
if (counter++ %% beats_per_bar) {
print "\nTICK"
... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Tcl | Tcl | package require Tcl 8.5
lassign $argv bpm bpb
if {$argc < 2} {set bpb 4}
if {$argc < 1} {set bpm 60}
fconfigure stdout -buffering none
set intervalMS [expr {round(60000.0 / $bpm)}]
set ctr 0
proc beat {} {
global intervalMS ctr bpb
after $intervalMS beat ;# Reschedule first, to encourage minimal drif... |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #Wren | Wren | import "scheduler" for Scheduler
import "timer" for Timer
import "/queue" for Queue
class CountingSemaphore {
construct new(numRes) {
_count = numRes
_queue = Queue.new()
}
count { _count }
acquire(task) {
if (_count > 0) {
_count = _count - 1
return... |
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.
| #Tcl | Tcl | puts " x\u2502 1 2 3 4 5 6 7 8 9 10 11 12"
puts \u0020\u2500\u2500\u253c[string repeat \u2500 48]
for {set i 1} {$i <= 12} {incr i} {
puts -nonewline [format "%3d" $i]\u2502[string repeat " " [expr {$i*4-4}]]
for {set j 1} {$j <= 12} {incr j} {
if {$j >= $i} {
puts -nonewline [format... |
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... | #Standard_ML | Standard ML |
fun to (a, b) = List.tabulate (b-a,fn i => a+i ) ;
infix 5 to ;
|
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... | #Tcl | Tcl | proc loopVar {var from lower to upper script} {
if {$from ne "from" || $to ne "to"} {error "syntax error"}
upvar 1 $var v
if {$lower <= $upper} {
for {set v $lower} {$v <= $upper} {incr v} {
uplevel 1 $script
}
} else {
# $upper and $lower really the other way round h... |
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... | #Forth | Forth |
\ modular multiplication and exponentiation
\
: 3rd s" 2 pick" evaluate ; immediate
: mod* ( a b m -- a*b {mod m} )
>r um* r> ud/mod 2drop ;
: mod^ ( x n m -- x^n {mod m} )
>r 1 swap
begin ?dup while
dup 1 and 1 =
if
swap 3rd r@ mod* swap 1-
then dup 0>
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... | #Draco | Draco | proc nonrec mertens([*] short m) void:
word n,k;
m[1] := 1;
for n from 2 upto dim(m,1)-1 do
m[n] := 1;
for k from 2 upto n do
m[n] := m[n] - m[n/k]
od
od
corp
proc nonrec main() void:
[1001] short m;
word x, y, eqz, crossz;
mertens(m);
writeln("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... | #Dyalect | Dyalect | func mertensNumbers(max) {
let mertens = Array.Empty(max + 1, 1)
for n in 2..max {
for k in 2..n {
mertens[n] -= mertens[n / k]
}
}
mertens
}
let max = 1000
let mertens = mertensNumbers(max)
let count = 200
let columns = 20
print("First \(count - 1) Mertens numbers:")
f... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <vector>
void print_menu(const std::vector<std::string>& terms)
{
for (size_t i = 0; i < terms.size(); i++) {
std::cout << i + 1 << ") " << terms[i] << '\n';
}
}
int parse_entry(const std::string& entry, int max_number)
{
int number = std::stoi(entr... |
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... | #C.23 | C# |
/// Represent digest with ABCD
sealed public class Digest
{
public uint A;
public uint B;
public uint C;
public uint D;
public Digest()
{
A=(uint)MD5InitializerConstant.A;
B=(uint)MD5InitializerConstant.B;
C=(uint)MD5InitializerConstant.C;
D=(uint)MD5InitializerConstant.D;
... |
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.
| #Haskell | Haskell | import Foreign
bytealloc :: IO ()
bytealloc = do
a0 <- mallocBytes 100 -- Allocate 100 bytes
free a0 -- Free them again
allocaBytes 100 $ \a -> -- Allocate 100 bytes; automatically
-- freed when closure finishes
poke (a::Ptr Word32) 0 |
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.
| #Icon_and_Unicon | Icon and Unicon |
t := table() # The table's memory is allocated
#... do things with t
t := &null # The table's memory can be reclaimed
|
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... | #Prolog | Prolog | patient(1001,'Hopper').
patient(4004,'Wirth').
patient(3003,'Kemeny').
patient(2002,'Gosling').
patient(5005,'Kurtz').
visit(2002,'2020-09-10',6.8).
visit(1001,'2020-09-17',5.5).
visit(4004,'2020-09-24',8.4).
visit(2002,'2020-10-08',nan).
visit(1001,'',6.6).
visit(3003,'2020-11-12',nan).
visit(4004,'2020-11-05',7.0).... |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
___________________... | #Z80_Assembly | Z80 Assembly | softRS232_LO equ &C000 ;%87654321 (each bit represents the state of a numbered pin)
softRS232_HI equ &C001 ;%-------9
ld hl,softRS232_LO ;memory location of soft RS232 port
ld c,&00 ;&00 = the port that the RS232 is connected to.
;This is just an example, the actual port number depends o... |
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;... | #Common_Lisp | Common Lisp |
(defun mid3 (n)
(let ((a (abs n))
(hmd)) ; how many digits
(labels ((give (fmt &optional x y) (return-from mid3 (format nil fmt x y)))
(need (x) (give "Need ~a digits, not ~d." x hmd))
(nbr (n) (give "~3,'0d" n)))
(when (zerop n) (give "Zero is 1 digit"))
(setq hmd ... |
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... | #PureBasic | PureBasic | Structure cell
isMine.i
display.c ;character to displays for cell, one of these {'.', '?', ' ', #)
EndStructure
Global Dim grid.cell(0,0)
Global mineCount, minesMarked, isGameOver
Procedure makeGrid(n, m)
Protected rm, x, y
Dim grid.cell(n - 1, m - 1)
mineCount = n * m * (Random(4) + 2) / 10
If mineCoun... |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext... | #Wren | Wren | import "timer" for Timer
import "io" for Stdout
var metronome = Fn.new { |bpm, bpb, maxBeats|
var delay = (60000/bpm).floor
var beats = 0
while (true) {
Timer.sleep(delay)
System.write((beats % bpb == 0) ? "\n\aTICK " : "\atick ")
Stdout.flush()
beats = beats + 1
if... |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ... | #zkl | zkl | fcn job(name,sem){
name.println(" wait"); sem.acquire();
name.println(" go"); Atomic.sleep(2);
sem.release(); name.println(" done")
}
// start 3 threads using the same semphore
s:=Thread.Semaphore(1);
job.launch("1",s); job.launch("2",s); job.launch("3",s); |
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.
| #True_BASIC | True BASIC | PRINT " X| 1 2 3 4 5 6 7 8 9 10 11 12"
PRINT "---+------------------------------------------------"
FOR i = 1 TO 12
LET nums$ = (" " & STR$(i))[LEN(" " & STR$(i))-3+1:maxnum] & "|"
FOR j = 1 TO 12
IF i <= j THEN
IF j >= 1 THEN LET nums$ = nums$ & (" ")[1:(4-LEN(ST... |
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... | #TXR | TXR | (defmacro whil ((condition : result) . body)
(let ((cblk (gensym "cnt-blk-"))
(bblk (gensym "brk-blk-")))
^(macrolet ((break (value) ^(return-from ,',bblk ,value)))
(symacrolet ((break (return-from ,bblk))
(continue (return-from ,cblk)))
(block ,bblk
(for () ... |
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... | #Wren | Wren | import "meta" for Meta
var genericClass = Fn.new { |cname, fname|
var s1 = "class %(cname) {\n"
var s2 = "construct new(%(fname)){\n_%(fname) = %(fname)\n}\n"
var s3 = "%(fname) { _%(fname) }\n"
var s4 = "}\nreturn %(cname)\n"
return Meta.compile(s1 + s2 + s3 + s4).call() // returns the Class obje... |
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... | #Fortran | Fortran |
module Miller_Rabin
use PrimeDecompose
implicit none
integer, parameter :: max_decompose = 100
private :: int_rrand, max_decompose
contains
function int_rrand(from, to)
integer(huge) :: int_rrand
integer(huge), intent(in) :: from, to
real :: o
call random_number(o)
int_rrand ... |
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... | #F.23 | F# |
// Mertens function. Nigel Galloway: January 31st., 2021
let mertens=mobius|>Seq.scan((+)) 0|>Seq.tail
mertens|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "\n####")
let n=mertens|>Seq.take 1000|>Seq.mapi(fun n g->(n+1,g))|>Seq.groupBy snd|>Map.ofSeq
n|>Map.iter(fun n g->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... | #Ceylon | Ceylon | "Run the module `menu`."
shared void run() {
value selection = menu("fee fie", "huff And puff", "mirror mirror", "tick tock");
print(selection);
}
String menu(String* strings) {
if(strings.empty) {
return "";
}
value entries = map(zipEntries(1..strings.size, strings));
while(true) {
for(index->string in e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.