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/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... | #Raku | Raku | my @mian-chowla = 1, |(2..Inf).map: -> $test {
state $index = 1;
state %sums = 2 => 1;
my $next;
my %these;
@mian-chowla[^$index].map: { ++$next and last if %sums{$_ + $test}:exists; ++%these{$_ + $test} };
next if $next;
++%sums{$test + $test};
%sums.push: %these;
++$index;
$t... |
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... | #Prolog | Prolog |
:- initialization(main).
main :- clause(less_than(1,2),B),writeln(B).
less_than(A,B) :- A<B.
|
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... | #Python | Python |
from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast, u
macros = Macros()
@macros.expr
def expand(tree, **kw):
addition = 10
return q[lambda x: x * ast[tree] + u[addition]]
|
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... | #Common_Lisp | Common Lisp | (defun factor-out (number divisor)
"Return two values R and E such that NUMBER = DIVISOR^E * R,
and R is not divisible by DIVISOR."
(do ((e 0 (1+ e))
(r number (/ r divisor)))
((/= (mod r divisor) 0) (values r e))))
(defun mult-mod (x y modulus) (mod (* x y) modulus))
(defun expt-mod (base expone... |
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... | #Arturo | Arturo | mobius: function [n][
if n=0 -> return ""
if n=1 -> return 1
f: factors.prime n
if f <> unique f -> return 0
if? odd? size f -> return neg 1
else -> return 1
]
mertens: function [z][sum map 1..z => mobius]
print "The first 99 Mertens numbers are:"
loop split.every:20 [""]++map 1..99 => 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... | #AWK | AWK |
# syntax: GAWK -f MENU.AWK
BEGIN {
print("you picked:",menu(""))
print("you picked:",menu("fee fie:huff and puff:mirror mirror:tick tock"))
exit(0)
}
function menu(str, ans,arr,i,n) {
if (str == "") {
return
}
n = split(str,arr,":")
while (1) {
print("")
for (i=1; i<=n; ... |
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.
| #Bracmat | Bracmat | ( alc$2000:?p {allocate 2000 bytes}
& pok$(!p,123456789,4) { poke a large value as a 4 byte integer }
& pok$(!p+4,0,4) { poke zeros in the next 4 bytes }
& out$(pee$(!p,1)) { peek the first byte }
& out$(pee$(!p+2,2)) { peek the short int located at the third and fourth byte }
& out$(pee$(!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.
| #C | C | #include <stdlib.h>
/* size of "members", in bytes */
#define SIZEOF_MEMB (sizeof(int))
#define NMEMB 100
int main()
{
int *ints = malloc(SIZEOF_MEMB*NMEMB);
/* realloc can be used to increase or decrease an already
allocated memory (same as malloc if ints is NULL) */
ints = realloc(ints, sizeof(int)*(NM... |
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... | #Haskell | Haskell | import Data.List
import Data.Maybe
import System.IO (readFile)
import Text.Read (readMaybe)
import Control.Applicative ((<|>))
------------------------------------------------------------
newtype DB = DB { entries :: [Patient] }
deriving Show
instance Semigroup DB where
DB a <> DB b = normalize $ a <> b
ins... |
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.)
___________________... | #Mercury | Mercury |
:- module rs232.
:- interface.
:- import_module bool, io, list, string.
:- type rs232_pin
---> carrier_detect
; received_data
; transmitted_data
; data_terminal_ready
; signal_ground
; data_set_ready
; request_to_send
; clear_to_send
; ring_indicator.
:- type... |
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.)
___________________... | #Nim | Nim | type
rs232Data = enum
carrierDetect,
receivedData,
transmittedData,
dataTerminalReady,
signalGround,
dataSetReady,
requestToSend,
clearToSend,
ringIndicator
# Bit vector of 9 bits
var bv = {carrierDetect, signalGround, ringIndicator}
echo cast[uint16](bv) # Conversion of bitvecto... |
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.)
___________________... | #OCaml | OCaml | open ExtLib
class rs232_data = object
val d = BitSet.create 9
method carrier_detect = BitSet.is_set d 0
method received_data = BitSet.is_set d 1
method transmitted_data = BitSet.is_set d 2
method data_terminal_ready = BitSet.is_set d 3
method signal_ground = BitSet.is_set d 4
method ... |
http://rosettacode.org/wiki/Metallic_ratios | Metallic ratios | Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series
of related ratios that are referred to as the "Metallic ratios".
The Golden ratio was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The Silver ratio was was
also known to th... | #Visual_Basic_.NET | Visual Basic .NET | Imports BI = System.Numerics.BigInteger
Module Module1
Function IntSqRoot(v As BI, res As BI) As BI
REM res is the initial guess
Dim term As BI = 0
Dim d As BI = 0
Dim dl As BI = 1
While dl <> d
term = v / res
res = (res + term) >> 1
dl... |
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)
| #OCaml | OCaml | let color_add (r1,g1,b1) (r2,g2,b2) =
( (r1 + r2),
(g1 + g2),
(b1 + b2) )
let color_div (r,g,b) d =
( (r / d),
(g / d),
(b / d) )
let compare_as_grayscale (r1,g1,b1) (r2,g2,b2) =
let v1 = (2_126 * r1 + 7_152 * g1 + 722 * b1)
and v2 = (2_126 * r2 + 7_152 * g2 + 722 * b2) in
(Pervasives.co... |
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;... | #Bracmat | Bracmat | ( ( middle3
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
& !x
| !arg
( !p:<3&"is too small"
| "has even number of digits"
)
)
& 123 12345 1234567 987654321 10001 -10001 -123 -100 100
-12345 1 2 -1 -10 2002 -2002 0
: ?L
& whl'(!L:%?e ?... |
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... | #MATLAB | MATLAB | xpbombs |
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... | #Ruby | Ruby | def mod(m, n)
result = m % n
if result < 0 then
result = result + n
end
return result
end
def getA004290(n)
if n == 1 then
return 1
end
arr = Array.new(n) { Array.new(n, 0) }
arr[0][0] = 1
arr[0][1] = 1
m = 0
while true
m = m + 1
if arr[m - 1... |
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... | #Ruby | Ruby | a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10**40
puts a.pow(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... | #Rust | Rust | /* Add this line to the [dependencies] section of your Cargo.toml file:
num = "0.2.0"
*/
use num::bigint::BigInt;
use num::bigint::ToBigInt;
// The modular_exponentiation() function takes three identical types
// (which get cast to BigInt), and returns a BigInt:
fn modular_exponentiation<T: ToBigInt>(n: &T, e: ... |
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... | #Perl | Perl | use Time::HiRes qw(sleep gettimeofday);
local $| = 1; # autoflush
my $beats_per_minute = shift || 72;
my $beats_per_bar = shift || 4;
my $i = 0;
my $duration = 60 / $beats_per_minute;
my $base_time = gettimeofday() + $duration;
for (my $next_time = $base_time ; ; $next_time += $duration) {
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 ... | #PicoLisp | PicoLisp | (let Sem (tmp "sem")
(for U 4 # Create 4 concurrent units
(unless (fork)
(ctl Sem
(prinl "Unit " U " aquired the semaphore")
(wait 2000)
(prinl "Unit " U " releasing the semaphore") )
(bye) ) ) ) |
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 ... | #PureBasic | PureBasic | #Threads=10
#Parallels=3
Global Semaphore=CreateSemaphore(#Parallels)
Procedure Worker(*arg.i)
WaitSemaphore(Semaphore)
Debug "Thread #"+Str(*arg)+" active."
Delay(Random(2000))
SignalSemaphore(Semaphore)
EndProcedure
; Start a multi-thread based work
Dim thread(#Threads)
For i=0 To #Threads
thread(i)=Cre... |
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.
| #Scheme | Scheme |
(define iota
(lambda (count start step)
(let loop ((result (list (+ start (* (- count 1) step)))))
(let ((acc (car result)))
(if (= acc start)
result
(loop (cons (- acc step) result)))))))
(define table
(lambda (x)
(let loop ((count 1)
(numbers (iot... |
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... | #REXX | REXX | do j=i for t-i+1; ···
|
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... | #Ruby | Ruby | require 'set'
n, ts, mc, sums = 100, [], [1], Set.new
sums << 2
st = Time.now
for i in (1 .. (n-1))
for j in mc[i-1]+1 .. Float::INFINITY
mc[i] = j
for k in (0 .. i)
if (sums.include?(sum = mc[k]+j))
ts.clear
break
end
ts << sum
end
if (ts.l... |
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... | #Quackery | Quackery |
( +---------------------------------------------------+ )
( | add inline comments ";" to Quackery with "builds" | )
( +---------------------------------------------------+ )
[ dup $ "" = not while
behead carriage =
until ] builds ; ( [ $ --> [ $ )
; +----------------------------------... |
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... | #R | R | '%C%' <- function(n, k) choose(n, k)
5 %C% 2 #Outputs 10. |
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... | #Crystal | Crystal | require "big"
module Primes
module MillerRabin
def prime?(k = 15) # increase k for more confidence
neg_one_mod = d = self - 1
s = 0
while d.even?; d >>= 1; s += 1 end # d is odd after s shifts
k.times do
b = 2 + rand(self - 4) # random witness base b
y ... |
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... | #BASIC | BASIC | 10 DEFINT C,Z,N,K,M: DIM M(1000)
20 M(1)=1
30 FOR N=2 TO 1000
40 M(N)=1
50 FOR K=2 TO N: M(N) = M(N)-M(INT(N/K)): NEXT
60 NEXT
70 PRINT "First 99 Mertens numbers:"
80 PRINT " ";
90 FOR N=1 TO 99
100 PRINT USING "###";M(N);
110 IF N MOD 10 = 9 THEN PRINT
120 NEXT
130 C=0: Z=0
140 FOR N=1 TO 1000
150 IF M(N)=0 THEN 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... | #Axe | Axe | "FEE FIE"→Str1
"HUFF AND PUFF"→Str2
"MIRROR MIRROR"→Str3
"TICK TOCK"→Str4
For(I,1,4)
Disp I▶Hex+3,":",strGet(Str1,I-1),i
End
Disp "NUMBER? "
input→A
{A}-'0'→N
If N<1 or N>4
Disp "BAD NUMBER",i
Return
End
Disp strGet(Str1,N-1),i |
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.
| #C.23 | C# | using System;
using System.Runtime.InteropServices;
public unsafe class Program
{
public static unsafe void HeapMemory()
{
const int HEAP_ZERO_MEMORY = 0x00000008;
const int size = 1000;
int ph = GetProcessHeap();
void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
i... |
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... | #J | J | NB. setup:
require'jd pacman'
load JDP,'tools/csv_load.ijs'
F=: jpath '~temp/rosettacode/example/CSV'
jdcreatefolder_jd_ CSVFOLDER=: F
assert 0<{{)n
PATIENTID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
}} fwrite F,'patients.csv'
assert 0<{{)n
PATIENTID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
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.)
___________________... | #Pascal | Pascal | use Bit::Vector::Minimal qw();
my $vec = Bit::Vector::Minimal->new(size => 24);
my %rs232 = reverse (
1 => 'PG Protective ground',
2 => 'TD Transmitted data',
3 => 'RD Received data',
4 => 'RTS Request to send',
5 => 'CTS Clear to send',
6 => 'DSR Data set ready',
7 => 'SG ... |
http://rosettacode.org/wiki/Metallic_ratios | Metallic ratios | Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series
of related ratios that are referred to as the "Metallic ratios".
The Golden ratio was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The Silver ratio was was
also known to th... | #Wren | Wren | import "/big" for BigInt, BigRat
import "/fmt" for Fmt
var names = ["Platinum", "Golden", "Silver", "Bronze", "Copper","Nickel", "Aluminium", "Iron", "Tin", "Lead"]
var lucas = Fn.new { |b|
Fmt.print("Lucas sequence for $s ratio, where b = $d:", names[b], b)
System.write("First 15 elements: ")
var x0 = ... |
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)
| #Perl | Perl | use strict 'vars';
use warnings;
use PDL;
use PDL::Image2D;
my $image = rpic 'plasma.png';
my $smoothed = med2d $image, ones(3,3), {Boundary => Truncate};
wpic $smoothed, 'plasma_median.png'; |
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)
| #Phix | Phix | -- demo\rosetta\Bitmap_Median_filter.exw
include ppm.e
constant neigh = {{-1,-1},{0,-1},{1,-1},
{-1, 0},{0, 0},{1, 0},
{-1, 1},{0, 1},{1, 1}}
--constant neigh = {{-2,-2},{-1,-2},{0,-2},{1,-2},{2,-2},
-- {-2,-1},{-1,-1},{0,-1},{1,-1},{2,-1},
-- {-2, 0... |
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;... | #Burlesque | Burlesque |
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
234
345
654
000
123
|
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... | #Nim | Nim | import random, sequtils, strformat, strscans, strutils
const LMargin = 4
type
Cell = object
isMine: bool
display: char
Grid = seq[seq[Cell]]
Game = object
grid: Grid
mineCount: Natural
minesMarked: Natural
isOver: bool
proc initGame(m, n: Positive): Game =
result.grid = new... |
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... | #Scala | Scala | import scala.collection.mutable.ListBuffer
object MinimumNumberOnlyZeroAndOne {
def main(args: Array[String]): Unit = {
for (n <- getTestCases) {
val result = getA004290(n)
println(s"A004290($n) = $result = $n * ${result / n}")
}
}
def getTestCases: List[Int] = {
val testCases = ListBu... |
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... | #Scala | Scala | import scala.math.BigInt
val a = BigInt(
"2988348162058574136915891421498819466320163312926952423791023078876139")
val b = BigInt(
"2351399303373464486466122544523690094744975233415544072992656881240319")
println(a.modPow(b, BigInt(10).pow(40))) |
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... | #Scheme | Scheme |
(define (square n)
(* n n))
(define (mod-exp a n mod)
(cond ((= n 0) 1)
((even? n)
(remainder (square (mod-exp a (/ n 2) mod))
mod))
(else (remainder (* a (mod-exp a (- n 1) mod))
mod))))
(define result
(mod-exp 29883481620585741369158... |
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... | #Phix | Phix | --
-- demo\rosetta\virtunome.exw
--
-- Originally by ghaberek
-- Translated from win32lib by Pete Lomax
--
-- I will note that accuracy drops sharply above 5 beats per second.
--
with javascript_semantics -- needs some work though, usual sizing stuff [DEV]
-- NB: don't break Morse_code.... |
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 ... | #Python | Python | import time
import threading
# Only 4 workers can run in the same time
sem = threading.Semaphore(4)
workers = []
running = 1
def worker():
me = threading.currentThread()
while 1:
sem.acquire()
try:
if not running:
break
print '%s acquired semaphore... |
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 ... | #Racket | Racket |
#lang racket
(define sema (make-semaphore 4)) ; allow 4 concurrent jobs
;; start 20 jobs and wait for all of them to end
(for-each
thread-wait
(for/list ([i 20])
(thread (λ() (semaphore-wait sema)
(printf "Job #~a acquired semaphore\n" i)
(sleep 2)
(printf "Job... |
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.
| #Scilab | Scilab | nmax=12, xx=3
s= blanks(xx)+" |"
for j=1:nmax
s=s+part(blanks(xx)+string(j),$-xx:$)
end
printf("%s\n",s)
s=strncpy("-----",xx)+" +"
for j=1:nmax
s=s+" "+strncpy("-----",xx)
end
printf("%s\n",s)
for i=1:nmax
s=part(blanks(xx)+string(i),$-xx+1:$)+" |"
... |
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... | #Sidef | Sidef | var (n, sums, ts, mc) = (100, Set([2]), [], [1])
var st = Time.micro_sec
for i in (1 ..^ n) {
for j in (mc[i-1]+1 .. Inf) {
mc[i] = j
for k in (0 .. i) {
var sum = mc[k]+j
if (sums.exists(sum)) {
ts.clear
break
}
ts << sum
}
if (ts.... |
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... | #Racket | Racket | #lang racket
(define-syntax-rule (list-when test body)
(if test
body
'()))
(let ([not-a-string 42])
(list-when (string? not-a-string)
(string->list not-a-string))) |
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... | #Raku | Raku | sub postfix:<!> { [*] 1..$^n }
say 5!; # prints 120 |
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... | #D | D | import std.random;
bool isProbablePrime(in ulong n, in uint k=10) /*nothrow*/ @safe /*@nogc*/ {
static ulong modPow(ulong b, ulong e, in ulong m)
pure nothrow @safe @nogc {
ulong result = 1;
while (e > 0) {
if ((e & 1) == 1)
result = (result * b) % m;
b ... |
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... | #Bash | Bash | #!/bin/bash
MAX=1000
m[1]=1
for n in `seq 2 $MAX`
do
m[n]=1
for k in `seq 2 $n`
do
m[n]=$((m[n]-m[n/k]))
done
done
echo 'The first 99 Mertens numbers are:'
echo -n ' '
for n in `seq 1 99`
do
printf '%2d ' ${m[n]}
test $((n%10)) -eq 9 && echo
done
zero=0
cross=0
for n in `seq 1 $M... |
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... | #BASIC | BASIC | FUNCTION sel$(choices$(), prompt$)
IF UBOUND(choices$) - LBOUND(choices$) = 0 THEN sel$ = ""
ret$ = ""
DO
FOR i = LBOUND(choices$) TO UBOUND(choices$)
PRINT i; ": "; choices$(i)
NEXT i
INPUT ;prompt$, index
IF index <= UBOUND(choices$) AND index >= LBOUND(choices$) THEN ret$ =... |
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.
| #C.2B.2B | C++ | #include <string>
int main()
{
int* p;
p = new int; // allocate a single int, uninitialized
delete p; // deallocate it
p = new int(2); // allocate a single int, initialized with 2
delete p; // deallocate it
std::string* p2;
p2 = new std::string; // allocate a single string, defaul... |
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.
| #COBOL | COBOL | PROGRAM-ID. memory-allocation.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 based-data PIC X(20) VALUE "Hello, World!"
BASED.
PROCEDURE DIVISION.
*> INITIALIZED sets the data item to the VALUE.
ALLOCATE based-dat... |
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... | #jq | jq |
# objectify/1 takes an array of atomic values as inputs, and packages
# these into an object with keys specified by the "headers" array and
# values obtained by trimming string values, replacing empty strings
# by null, and converting strings to numbers if possible.
def objectify(headers):
def tonumberq: tonumber? ... |
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... | #Julia | Julia | using CSV, DataFrames, Statistics
# load data from csv files
#df_patients = CSV.read("patients.csv", DataFrame)
#df_visits = CSV.read("visits.csv", DataFrame)
# create DataFrames from text that is hard coded, so use IOBuffer(String) as input
str_patients = IOBuffer("""PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003... |
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.)
___________________... | #Perl | Perl | use Bit::Vector::Minimal qw();
my $vec = Bit::Vector::Minimal->new(size => 24);
my %rs232 = reverse (
1 => 'PG Protective ground',
2 => 'TD Transmitted data',
3 => 'RD Received data',
4 => 'RTS Request to send',
5 => 'CTS Clear to send',
6 => 'DSR Data set ready',
7 => 'SG ... |
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.)
___________________... | #Phix | Phix | constant CD=1, RD=2, TD=3, DTR=4, ...
atom addr = allocate(2) -- or wherever
--read
sequence bits = int_to_bits(peek2u(addr),16)
integer dtr = bits[DTR]
--write
bits[DTR] = 1
poke2(addr,bits_to_int(bits))
|
http://rosettacode.org/wiki/Metallic_ratios | Metallic ratios | Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series
of related ratios that are referred to as the "Metallic ratios".
The Golden ratio was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The Silver ratio was was
also known to th... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn lucasSeq(b){
Walker.zero().tweak('wrap(xs){
xm2,xm1 := xs; // x[n-2], x[n-1]
xn:=xm1*b + xm2;
xs.append(xn).del(0);
xn
}.fp(L(BI(1),BI(1)))).push(1,1) // xn can get big so use BigInts
}
fcn metallicRatio(lucasSeq,digits=32,roundup=True){ ... |
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)
| #PicoLisp | PicoLisp | (de ppmMedianFilter (Radius Ppm)
(let Len (inc (* 2 Radius))
(make
(chain (head Radius Ppm))
(for (Y Ppm T (cdr Y))
(NIL (nth Y Len)
(chain (tail Radius Y)) )
(link
(make
(chain (head Radius (get Y (inc Radius))))
... |
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)
| #Python | Python | import Image, ImageFilter
im = Image.open('image.ppm')
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm') |
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 | C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// we return a static buffer; caller wants it, caller copies it
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, "%d", n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
... |
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... | #OCaml | OCaml | exception Lost
exception Won
let put_mines g m n mines_number =
let rec aux i =
if i < mines_number then
begin
let x = Random.int n
and y = Random.int m in
if g.(y).(x)
then aux i
else begin
g.(y).(x) <- true;
aux (succ i)
end
end
in
aux 0
let pr... |
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... | #Sidef | Sidef | func find_B10(n, b=10) {
return 0 if (n == 0)
var P = n.of(-1)
for (var m = 0; P[0] == -1; ++m) {
for r in (0..n) {
next if (P[r] == -1)
next if (P[r] == m)
with ((powmod(b, m, n) + r) % n) { |t|
P[t] = m if (P[t] == -1)
}
... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const proc: main is func
begin
writeln(modPow(2988348162058574136915891421498819466320163312926952423791023078876139_,
2351399303373464486466122544523690094744975233415544072992656881240319_,
10_ ** 40));
end func; |
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... | #Sidef | Sidef | say expmod(
2988348162058574136915891421498819466320163312926952423791023078876139,
2351399303373464486466122544523690094744975233415544072992656881240319,
10**40) |
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... | #PicoLisp | PicoLisp | (de metronome (Bpm)
(if (fork)
(let Pid @
(for Pendulum '(" /" . ("^H^H\\ " "^H^H /" .))
(tell Pid 'call "/usr/bin/beep" "-f" 440 "-l" 40)
(prin Pendulum)
(T (key (*/ 30000 Bpm)) (tell Pid 'bye)) )
(prinl) )
(wait) ) ) |
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... | #Pure_Data | Pure Data | #N canvas 553 78 360 608 10;
#X obj 20 20 cnv 15 320 140 empty empty empty 20 12 0 14 -228856 -66577 0;
#X obj 20 190 cnv 15 320 36 empty empty empty 20 12 0 14 -233017 -66577 0;
#X obj 67 30 vradio 20 1 0 6 empty beats empty 0 -8 0 10 -86277 -262144 -1 1;
#X text 40 33 1/1;
#X text 40 53 2/2;
#X text 40 73 3/4;
#X tex... |
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 ... | #Raku | Raku | class Semaphore {
has $.tickets = Channel.new;
method new ($max) {
my $s = self.bless;
$s.tickets.send(True) xx $max;
$s;
}
method acquire { $.tickets.receive }
method release { $.tickets.send(True) }
}
sub MAIN ($units = 5, $max = 2) {
my $sem = Semaphore.new($max);
... |
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 ... | #Raven | Raven | # four workers may be concurrent
4 semaphore as sem
thread worker
5 each as i
sem acquire
# tid is thread id
tid "%d acquired semaphore\n" print
2000 ms
sem release
# let others acquire
100 ms
# start 10 threads
group
10 each drop worker
list as worker... |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
const integer: n is 12;
var integer: i is 0;
var integer: j is 0;
begin
for j range 1 to n do
write(j lpad 3 <& " ");
end for;
writeln;
writeln("-" mult 4 * n);
for i range 1 to n do
for j range 1 to n do
... |
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... | #Swift | Swift | public func mianChowla(n: Int) -> [Int] {
var mc = Array(repeating: 0, count: n)
var ls = [2: true]
var sum = 0
mc[0] = 1
for i in 1..<n {
var lsx = [Int]()
jLoop: for j in (mc[i-1]+1)... {
mc[i] = j
for k in 0...i {
sum = mc[k] + j
if ls[sum] ?? false {
... |
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... | #VBScript | VBScript | ' Mian-Chowla sequence - VBScript - 15/03/2019
Const m = 100, mm=28000
ReDim r(mm), v(mm * 2)
Dim n, t, i, j, l, s1, s2, iterate_t
ReDim seq(m)
t0=Timer
s1 = "1": s2 = ""
seq(1) = 1: n = 1: t = 1
Do While n < m
t = t + 1
iterate_t = False
For i = 1 to t * 2
... |
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... | #Rascal | Rascal | extend ViewParseTree;
layout Whitespace = [\ \t\n]*;
syntax A = "a";
syntax B = "b";
start syntax C = "c" | A C B;
layout Whitespace = [\ \t\n]*;
lexical Integer = [0-9]+;
start syntax E1 = Integer
| E "*" E
> E "+" E
| "(" E ")"
; |
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... | #REXX | REXX | /*┌───────────────────────────────────────────────────────────────────┐
│ The REXX language doesn't allow for the changing or overriding of │
│ syntax per se, but any of the built-in-functions (BIFs) can be │
│ overridden by just specifying your own. │
│ ... |
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... | #E | E | def millerRabinPrimalityTest(n :(int > 0), k :int, random) :boolean {
if (n <=> 2 || n <=> 3) { return true }
if (n <=> 1 || n %% 2 <=> 0) { return false }
var d := n - 1
var s := 0
while (d %% 2 <=> 0) {
d //= 2
s += 1
}
for _ in 1..k {
def nextTrial := __continue
def a := random.nextIn... |
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... | #BCPL | BCPL | get "libhdr"
manifest $( limit = 1000 $)
let mertens(v, max) be
$( v!1 := 1
for n = 2 to max do
$( v!n := 1
for k = 2 to n do
v!n := v!n - v!(n/k)
$)
$)
let start() be
$( let m = vec limit
let eqz, crossz = 0, 0
writes("The first 99 Mertens numbers are:*N")
mertens... |
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... | #Batch_File | Batch File | @echo off & setlocal enabledelayedexpansion
set "menuChoices="fee fie","huff and puff","mirror mirror","tick tock""
call :menu
pause>nul & exit
:menu
if defined menuChoices (
set "counter=0" & for %%a in (%menuChoices%) do (
set /a "counter+=1"
set "currentMenuChoice=%%a"
set option[!counter!]=!cu... |
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... | #11l | 11l | -V
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 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.
| #Common_Lisp | Common Lisp | (defun show-allocation ()
(let ((a (cons 1 2))
(b (cons 1 2)))
(declare (dynamic-extent b))
(list a b))) |
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.
| #D | D | // D is a system language so its memory management is refined.
// D supports thread-local memory on default, global memory, memory
// allocated on the stack, the C heap, or the D heap managed by a
// garbage collector, both manually and automatically.
// This program looks scary because its purpose is to show all the... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | a = ImportString["PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz", "CSV"];
b = ImportString["PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3", "CSV"];
a = <|a[[1, 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.)
___________________... | #PicoLisp | PicoLisp | # Define bit constants
(for (N . Mask) '(CD RD TD DTR SG DSR RTS CTS RI)
(def Mask (>> (- 1 N) 1)) )
# Test if Clear to send
(when (bit? CTS Data)
... ) |
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.)
___________________... | #PL.2FI | PL/I |
declare 1 RS232_layout,
2 Carrier_Detect Bit(1),
2 Received_Data Bit(1),
2 Transmitted_Data Bit(1),
2 Data_Terminal_ready Bit(1),
2 Signal_Ground Bit(1),
2 Data_Set_Ready Bit(1),
2 Request_To_Send Bit(1),
2 Clear_To_Send Bit(1),
2 Ring_Indicator ... |
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.)
___________________... | #Python | Python | from ctypes import Structure, c_int
rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg"
"_11 SCD SCS STD TC SRD RC"
"_18 SRS DTR SQD RI DRS XTC" ).split()
class RS232_9pin(Structure):
_fields_ = [(__, c_int, 1) ... |
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)
| #Racket | Racket |
#lang racket
(require images/flomap math)
(define lena <<paste image of Lena here>> )
(define bm (send lena get-bitmap))
(define fm (bitmap->flomap bm))
(flomap->bitmap
(build-flomap
4 (send bm get-width) (send bm get-height)
(λ (k x y)
(define (f x y) (flomap-ref fm k x y))
(median < (list (f (- x ... |
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)
| #Raku | Raku | use PDL:from<Perl5>;
use PDL::Image2D:from<Perl5>;
my $image = rpic 'plasma.png';
my $smoothed = med2d($image, ones(3,3), {Boundary => 'Truncate'});
wpic $smoothed, 'plasma_median.png'; |
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.2B.2B | C++ | #include <iostream>
std::string middleThreeDigits(int n)
{
auto number = std::to_string(std::abs(n));
auto length = number.size();
if (length < 3) {
return "less than three digits";
} else if (length % 2 == 0) {
return "even number of digits";
} else {
return number.subst... |
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... | #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
{ package Local::Field;
use constant {
REAL => 0,
SHOW => 1,
COUNT => 2,
};
sub new {
my ($class, $width, $height, $percent) = @_;
my $field;
for my $x (1 .. $width) {
for my $y (1 .. $height) {
... |
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... | #Tcl | Tcl |
package require Tcl 8.5
## power of ten, modulo --> (10**expo % modval) suited for large expo
proc potmod {expo modval} {
if {$expo < 0} { return 0 }
if {$modval < 2} { return 0 } ;# x mod 1 = 0
set r 1
set p [expr {10 % $modval}]
while {$expo} {
set half [expr {$expo / ... |
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... | #Swift | Swift | import BigInt
func modPow<T: BinaryInteger>(n: T, e: T, m: T) -> T {
guard e != 0 else {
return 1
}
var res = T(1)
var base = n % m
var exp = e
while true {
if exp & 1 == 1 {
res *= base
res %= m
}
if exp == 1 {
return res
}
exp /= 2
base *= base
b... |
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... | #Tcl | Tcl | package require Tcl 8.5
# Algorithm from http://introcs.cs.princeton.edu/java/78crypto/ModExp.java.html
# but Tcl has arbitrary-width integers and an exponentiation operator, which
# helps simplify the code.
proc tcl::mathfunc::modexp {a b n} {
if {$b == 0} {return 1}
set c [expr {modexp($a, $b / 2, $n)**2 % ... |
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... | #PureBasic | PureBasic | Structure METRONOMEs
msPerBeat.i
BeatsPerMinute.i
BeatsPerCycle.i
volume.i
canvasGadget.i
w.i
h.i
originX.i
originY.i
radius.i
activityStatus.i
EndStructure
Enumeration ;gadgets
#TEXT_MSPB ;milliseconds per beat
#STRING_MSPB ;milliseconds per beat
#TEXT_BPM ;beats per ... |
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 ... | #Ruby | Ruby |
require 'thread'
# Simple Semaphore implementation
class Semaphore
def initialize(size = 1)
@queue = SizedQueue.new(size)
size.times { acquire }
end
def acquire
tap { @queue.push(nil) }
end
def release
tap { @queue.pop }
end
# @return [Integer]
def count
@queue.length
end... |
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 ... | #Rust | Rust |
//! Rust has a perfectly good Semaphore type already. It lacks count(), though, so we can't use it
//! directly.
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread::{self, spawn};
use std::time::Duration;
pub struct Counti... |
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.
| #Sidef | Sidef | var max = 12
var width = (max**2 -> len+1)
func fmt_row(*items) {
items.map {|s| "%*s" % (width, s) }.join
}
say fmt_row('x┃', (1..max)...)
say "#{'━' * (width - 1)}╋#{'━' * (max * width)}"
{ |i|
say fmt_row("#{i}┃", {|j| i <= j ? i*j : ''}.map(1..max)...)
} << 1..max |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function MianChowla(ByVal n As Integer) As Integer()
Dim mc(n - 1) As Integer, sums, ts As New HashSet(Of Integer),
sum As Integer : mc(0) = 1 : sums.Add(2)
For i As Integer = 1 To n - 1
For j As Integer = mc(i - 1) + 1 To Integer.MaxValue
mc(i) = j
... |
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... | #Ring | Ring |
o1 = new point { x=10 y=20 z=30 }
addmethod(o1,"print", func { see x + nl + y + nl + z + nl } )
o1.print()
Class point
x y z
|
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... | #Ruby | Ruby | class IDVictim
# Create elements of this man, woman, or child's identification.
attr_accessor :name, :birthday, :gender, :hometown
# Allows you to put in a space for anything which is not covered by the
# preexisting elements.
def self.new_element(element)
attr_accessor element
end
end |
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... | #EchoLisp | EchoLisp |
(lib 'bigint)
;; output : #t if n probably prime
(define (miller-rabin n (k 7) (composite #f)(x))
(define d (1- n))
(define s 0)
(define a 0)
(while (even? d)
(set! s (1+ s))
(set! d (quotient d 2)))
(for [(i k)]
(set! a (+ 2 (random (- n 3))))
(set! x (powmod a d n))
#:continue (or (= x 1) (= x (1- n)))
(s... |
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 | C | #include <stdio.h>
#include <stdlib.h>
int* mertens_numbers(int max) {
int* m = malloc((max + 1) * sizeof(int));
if (m == NULL)
return m;
m[1] = 1;
for (int n = 2; n <= max; ++n) {
m[n] = 1;
for (int k = 2; k <= n; ++k)
m[n] -= m[n/k];
}
return m;
}
int ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.