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... | #Nim | Nim | import intsets, strutils, times
proc mianchowla(n: Positive): seq[int] =
result = @[1]
var sums = [2].toIntSet()
var candidate = 1
while result.len < n:
# Test successive candidates.
var fit = false
result.add 0 # Make room for next value.
while not fit:
inc candidate
fit = tr... |
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... | #Nim | Nim | proc `^`*[T: SomeInteger](base, exp: T): T =
var (base, exp) = (base, exp)
result = 1
while exp != 0:
if (exp and 1) != 0:
result *= base
exp = exp shr 1
base *= base
echo 2 ^ 10 # 1024 |
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... | #Ol | Ol |
(define-syntax define
(syntax-rules (lambda) ;λ
((define ((name . args) . more) . body)
(define (name . args) (lambda more . body)))
((define (name . args) . body)
(setq name (letq (name) ((lambda args . body)) name)))
((define name (lambda (var ...) . body))
(setq name... |
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... | #C | C | #ifndef _MILLER_RABIN_H_
#define _MILLER_RABIN_H
#include <gmp.h>
bool miller_rabin_test(mpz_t n, int j);
#endif |
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... | #11l | 11l | F mertens(count)
‘Generate Mertens numbers’
V m = [-1, 1]
L(n) 2 .. count
m.append(1)
L(k) 2 .. n
m[n] -= m[n I/ k]
R m
V ms = mertens(1000)
print(‘The first 99 Mertens numbers are:’)
print(‘ ’, end' ‘ ’)
V col = 1
L(n) ms[1.<100]
print(‘#2’.format(n), end' ‘ ’)
col++
I co... |
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... | #Ada | Ada | with ada.text_io,Ada.Strings.Unbounded; use ada.text_io, Ada.Strings.Unbounded;
procedure menu is
type menu_strings is array (positive range <>) of Unbounded_String ;
function "+" (s : string) return Unbounded_String is (To_Unbounded_String (s));
function choice (m : menu_strings; prompt : string) return strin... |
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.
| #6502_Assembly | 6502 Assembly | LDA #$FF ;load 255 into the accumulator
STA $00 ;store at zero page memory address $00
STA $0400 ;store at absolute memory address $0400 |
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.
| #Action.21 | Action! | SET EndProg=* |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
public static class MergeAndAggregateDatasets
{
public static void Main()
{
string patientsCsv = @"
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
500... |
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.)
___________________... | #Free_Pascal | Free Pascal | program rs232(input, output, stdErr);
type
{$packEnum 2}{$scopedEnums off}
pin = (carrierDetect, receivedData, transmittedData, dataTerminalReady,
signalGround, dataSetReady, requestToSend, clearToSend, ringIndicator);
{$packSet 2}
pins = set of pin;
var
signal: pins;
// for demonstration purposes, in order to ... |
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.)
___________________... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' using bit fields
Type RS232_Pin9
carrierDetect : 1 As UByte
receivedData : 1 As UByte
transmittedData : 1 As UByte
dataTerminalReady : 1 As UByte
signalGround : 1 As UByte
dataSetReady : 1 As UByte
requestToSend : 1 As UByte
clearToSend : 1 As UByte... |
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... | #Raku | Raku | use Rat::Precise;
use Lingua::EN::Numbers;
sub lucas ($b) { 1, 1, * + $b * * … * }
sub metallic ($seq, $places = 32) {
my $n = 0;
my $last = 0;
loop {
my $approx = FatRat.new($seq[$n + 1], $seq[$n]);
my $this = $approx.precise($places, :z);
last if $this eq $last;
$last =... |
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)
| #GDL | GDL |
FUNCTION MEDIANF,ARRAY,WINDOW
RET=fltarr(N_ELEMENTS(ARRAY),1)
EDGEX=WINDOW/2
FOR X=EDGEX, N_ELEMENTS(ARRAY)-EDGEX DO BEGIN
PRINT, "X", X
COLARRAY=fltarr(WINDOW,1)
FOR FX=0, WINDOW-1 DO BEGIN
COLARRAY[FX]=ARRAY[X + FX - EDGEX]
END
T=COLARRAY[SORT(COLARRAY)]
RET[X]=T[WINDOW/2]
END
RETURN, RET
END
|
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)
| #Go | Go | package main
// Files required to build supporting package raster are found in:
// * Bitmap
// * Grayscale image
// * Read a PPM file
// * Write a PPM file
import (
"fmt"
"raster"
)
var g0, g1 *raster.Grmap
var ko [][]int
var kc []uint16
var mid int
func init() {
// hard code box of 9 pixels
ko ... |
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;... | #AWK | AWK | #!/bin/awk -f
# use as: awk -f middle_three_digits.awk
BEGIN {
n = split("123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0", arr)
for (i=1; i<=n; i++) {
if (arr[i] !~ /^-?[0-9]+$/) {
printf("%10s : invalid input: not a number\n", arr[i])
continue
}
num = arr[i]<0... |
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... | #Julia | Julia |
# Minesweeper:
mutable struct Field
size::Tuple{Int, Int}
numbers::Array{Int, 2}
possible_mines::Array{Bool, 2}
actual_mines::Array{Bool, 2}
visible::Array{Bool, 2}
end
function Field(x, y)
size = (x, y)
actual_mines = convert(Array{Bool, 2}, rand(x, y) .< 0.15)
possible_mines = ze... |
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... | #Python | Python | def getA004290(n):
if n < 2:
return 1
arr = [[0 for _ in range(n)] for _ in range(n)]
arr[0][0] = 1
arr[0][1] = 1
m = 0
while True:
m += 1
if arr[m - 1][-10 ** m % n] == 1:
break
arr[m][0] = 1
for k in range(1, n):
arr[m][k] = max([... |
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... | #PHP | PHP | <?php
$a = '2988348162058574136915891421498819466320163312926952423791023078876139';
$b = '2351399303373464486466122544523690094744975233415544072992656881240319';
$m = '1' . str_repeat('0', 40);
echo bcpowmod($a, $b, $m), "\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... | #PicoLisp | PicoLisp | (de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) ) |
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... | #Julia | Julia | function metronome(bpm::Real=72, bpb::Int=4)
s = 60.0 / bpm
counter = 0
while true
counter += 1
if counter % bpb != 0
println("tick")
else
println("TICK")
end
sleep(s)
end
end |
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... | #Kotlin | Kotlin | // version 1.1.2
fun metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MAX_VALUE) {
val delay = 60_000L / bpm
var beats = 0
do {
Thread.sleep(delay)
if (beats % bpb == 0) print("\nTICK ")
else print("tick ")
beats++
}
while (beats < maxBeats)
println()
}
... |
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 ... | #Logtalk | Logtalk |
:- object(metered_concurrency).
:- threaded.
:- public(run/2).
run(Workers, Max) :-
% start the semaphore and the workers
threaded_ignore(semaphore(Max, Max)),
forall(
integer::between(1, Workers, Worker),
threaded_call(worker(Worker))
),
... |
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 ... | #Nim | Nim | import os, posix, strformat
type SemaphoreError = object of CatchableError
var
sem: Sem
running = true
proc init(sem: var Sem; count: Natural) =
if sem_init(sem.addr, 0, count.cint) != 0:
raise newException(SemaphoreError, "unable to initialize semaphore")
proc count(sem: var Sem): int =
var c: cint... |
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.
| #Ruby | Ruby | def multiplication_table(n)
puts " |" + (" %3d" * n) % [*1..n]
puts "----+" + "----" * n
1.upto(n) do |x|
print "%3d |" % x
1.upto(x-1) {|y| print " "}
x.upto(n) {|y| print " %3d" % (x*y)}
puts
end
end
multiplication_table 12 |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #REXX | REXX | /*REXX pgm mimics a boggling card trick; separates cards into 3 piles based on color ···*/
parse arg trials # shuffs seed . /*obtain optional arguments from the CL*/
if trials=='' | trials=="," then trials= 1000 /*Not specified? Then use the default.*/
if #=='' | #=="," then #= 52 ... |
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... | #Pascal | Pascal | const
deltaK = 250;
maxCnt = 25000;
Using
tElem = Uint64;
t_n_sum_all = array of tElem; //dynamic array
n mian-chowla[n] average dist runtime
250 317739 1270 429 ms// runtime setlength of 2.35 GB ~ 400ms
500 2085045 7055 589 m... |
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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub generate_mc {
my($max) = @_;
my $index = 0;
my $test = 1;
my %sums = (2 => 1);
my @mc = 1;
while ($test++) {
my %these = %sums;
map { next if ++$these{$_ + $test} > 1 } @mc[0..$index], $test;
%sums = %these;
... |
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... | #OxygenBasic | OxygenBasic |
'EQUATES
% half 0.5
$ title "My Metaprogram"
'CONDITIONAL BLOCKS
#ifdef ...
...
#elseif ...
...
#else
...
#endif
'MACROS
'msdos-like
def sum
%1 + %2
end def
'C-like
#define sum(a,b) a + b
'native
macro sum(a,b)
a + b
end macro
'native macro functions
macro sum int(r,a,b)
r = 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... | #PARI.2FGP | PARI/GP | Function: _@_
Help: x@y: compute the lesser of x and y, or 0, whichever is larger.
Section: symbolic_operators
C-Name: gmin0
Prototype: GG
Description:
(small, small):small smin0ss($1, $2)
(mp, mp):mp gmin0($1, $2)
(gen, gen):gen gmin0($1, $2) |
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... | #C.23 | C# | public static class RabinMiller
{
public static bool IsPrime(int n, int k)
{
if ((n < 2) || (n % 2 == 0)) return (n == 2);
int s = n - 1;
while (s % 2 == 0) s >>= 1;
Random r = new Random();
for (int i = 0; i < k; i++)
{
int a = r.Next(n - 1) + 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... | #8080_Assembly | 8080 Assembly | MAX: equ 1000 ; Amount of numbers to generate
org 100h
;;; Generate Mertens numbers
lxi b,1 ; Start at place 1; BC = current Mertens number
lxi h,MM ; First one is 1
dad b
mvi m,1
outer: inx b ; Next Mertens number
lxi h,MM
dad b
mvi m,1 ; Initialize at 1
lxi d,2 ; DE = inner loop counter ('k'), starts at ... |
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... | #8086_Assembly | 8086 Assembly | MAX: equ 1000 ; Amount of Mertens numbers to generate
puts: equ 9 ; MS-DOS syscall to print a string
putch: equ 2 ; MS-DOS syscall to print a character
cpu 8086
org 100h
section .text
;;; Generate Mertens numbers
mov bx,M ; BX = pointer to start of Mertens numbers
mov si,1 ; Current Mertens number
mov [si+b... |
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... | #ALGOL_68 | ALGOL 68 | PROC menu select := (FLEX[]STRING items, UNION(STRING, VOID) prompt)STRING:
(
INT choice;
IF LWB items <= UPB items THEN
WHILE
FOR i FROM LWB items TO UPB items DO
printf(($g(0)") "gl$, i, items[i]))
OD;
... |
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.
| #Ada | Ada | declare
X : Integer; -- Allocated on the stack
begin
...
end; -- X is freed |
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.
| #ALGOL_68 | ALGOL 68 | MODE MYSTRUCT = STRUCT(INT i, j, k, REAL r, COMPL c); |
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... | #Datalog | Datalog | // datetime.cpp
#include <ctime>
#include <cstdint>
extern "C" {
int64_t from date(const char* string) {
struct tm tmInfo = {0};
strptime(string, "%Y-%m-%d", &tmInfo);
return mktime(&tmInfo); // localtime
}
} |
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.)
___________________... | #Go | Go | package main
import "fmt"
type rs232p9 uint16
const (
CD9 rs232p9 = 1 << iota // Carrier detect
RD9 // Received data
TD9 // Transmitted data
DTR9 // Data terminal ready
SG9 // signal ground
DSR9 // Data s... |
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.)
___________________... | #J | J | labels=: <;._2]0 :0
CD Carrier detect
RD Received data
TD Transmitted data
DTR Data terminal ready
SG Signal ground
DSR Data set ready
RTS Request to send
CTS Clear to send
RI Ring indicator
) |
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... | #REXX | REXX | /*REXX pgm computes the 1st N elements of the Lucas sequence for Metallic ratios 0──►9. */
parse arg n bLO bHI digs . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 15 /*Not specified? Then use the default.*/
if bLO=='' | bLO=="," then bLO= 0 ... |
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)
| #J | J |
makeRGB=: 0&$: : (($,)~ ,&3)
toGray=: <. @: (+/) @: (0.2126 0.7152 0.0722 & *)"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)
| #Julia | Julia | using Images, ImageFiltering, FileIO
Base.isless(a::RGB{T}, b::RGB{T}) where T =
red(a) < red(b) || green(a) < green(b) || blue(a) < blue(b)
Base.middle(x::RGB) = x
img = load("data/lenna100.jpg")
mapwindow(median!, img, (3, 3)) |
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;... | #BASIC | BASIC | 100 DEF FN L(N) = LEN(STR$(INT(ABS(N))))
110 DEF FN N(N) = VAL(MID$(STR$(INT(ABS(N))),(FN L(N)-1)/2,3))
120 DEF FN EVEN(N) = INT(N/2) = N/2
130 FOR I = 1 TO 20
140 READ N
150 PRINT N":",
160 GOSUB 100"MIDDLE THREE DIGITS
170 PRINT R$
180 NEXT
190 END
200 R$ = ""
210 IF FN EVEN(FN L(N)) THEN R$ = "?EVEN,... |
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... | #Locomotive_Basic | Locomotive Basic | 10 mode 1:randomize time
20 defint a-z
30 boardx=6:boardy=4
40 dim a(boardx,boardy)
50 dim c(boardx+2,boardy+2)
60 dim c2(boardx+2,boardy+2)
70 nmines=int((rnd/3+.1)*boardx*boardy)
80 for i=1 to nmines
90 ' place random mines
100 xp=int(rnd*(boardx-1)+1)
110 yp=int(rnd*(boardy-1)+1)
120 if a(xp,yp) then 100
130 a(xp,yp... |
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... | #Raku | Raku | say $_ , ': ', (1..*).map( *.base(2) ).first: * %% $_ for flat 1..10, 95..105; # etc. |
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... | #Prolog | Prolog | main:-
A = 2988348162058574136915891421498819466320163312926952423791023078876139,
B = 2351399303373464486466122544523690094744975233415544072992656881240319,
M is 10 ** 40,
P is powm(A, B, M),
writeln(P). |
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... | #Python | Python | a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10 ** 40
print(pow(a, b, m)) |
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... | #Liberty_BASIC | Liberty BASIC | WindowWidth =230
WindowHeight =220
button #w.b1 "Start", [start], LR, 110, 90, 55, 20
button #w.b2 "Tempo", [tempo], LR, 180, 90, 55, 20
button #w.b3 "Pattern", [pattern], LR, 40, 90, 55, 20
open "Metronome" for graphics_nsb_nf as #w
#w "trapclose quit"
#w "down"
#w "... |
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 ... | #Oforth | Oforth | import: parallel
Object Class new: Semaphore(ch)
Semaphore method: initialize(n)
Channel newSize(n) dup := ch
#[ 1 over send drop ] times(n) drop ;
Semaphore method: acquire @ch receive drop ;
Semaphore method: release 1 @ch send drop ; |
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 ... | #Oz | Oz | declare
fun {NewSemaphore N}
sem(max:N count:{NewCell 0} 'lock':{NewLock} sync:{NewCell _})
end
proc {Acquire Sem=sem(max:N count:C 'lock':L sync:S)}
Sync
Acquired
in
lock L then
if @C < N then
C := @C + 1
Acquired = true
else
Sync = @S
A... |
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.
| #Run_BASIC | Run BASIC | html "<TABLE border=1 ><TR bgcolor=silver align=center><TD><TD>1<TD>2<TD>3<TD>4<TD>5<TD>6<TD>7<TD>8<TD>9<TD>10<TD>11<TD>12</td></TR>"
For i = 1 To 12
html "<TR align=right><TD>";i;"</td>"
For ii = 1 To 12
html "<td width=25>"
If ii >= i Then html i * ii
html "</td>"
Next ii
next i
html "</table>"
|
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #Ruby | Ruby | deck = ([:black, :red] * 26 ).shuffle
black_pile, red_pile, discard = [], [], []
until deck.empty? do
discard << deck.pop
discard.last == :black ? black_pile << deck.pop : red_pile << deck.pop
end
x = rand( [black_pile.size, red_pile.size].min )
red_bunch = x.times.map{ red_pile.delete_at( rand( red_pile.si... |
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... | #Phix | Phix | function mian_chowla(integer n)
sequence mc = {1},
is = {false,true}
integer len_is = 2, s
for i=2 to n do
sequence isx = {}
integer j = mc[i-1]+1
mc = append(mc,j)
while true do
for k=1 to length(mc) do
s = mc[k] + j
if s<=len... |
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... | #Perl | Perl | package UnicodeEllipsis;
use Filter::Simple;
FILTER_ONLY code => sub { s/…/../g }; |
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... | #Phix | Phix | object x
#isginfo{x,0b0101,5,7,integer,3}
-- {var,type,min,max,etype,len}
-- (0b0101 is dword sequence|integer)
x = {1,2,3} -- sequence of integer, length 3
x = 5 -- integer 5 (becomes min)
x = 7 -- integer 7 (becomes max) |
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... | #Clojure | Clojure | (ns test-p.core
(:require [clojure.math.numeric-tower :as math])
(:require [clojure.set :as set]))
(def WITNESSLOOP "witness")
(def COMPOSITE "composite")
(defn m* [p q m]
" Computes (p*q) mod m "
(mod (*' p q) m))
(defn power
"modular exponentiation (i.e. b^e mod m"
[b e m]
(loop [b b, e e, x 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... | #Action.21 | Action! | INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
PROC MertensNumbers(INT ARRAY m INT count)
INT n,k
m(1)=1
FOR n=2 TO count
DO
m(n)=1
FOR k=2 TO n
DO
m(n)==-m(n/k)
OD
OD
RETURN
PROC PrintMertens(INT ARRAY m INT count)
CHAR ARRAY s(6)
INT i,col
PrintF("First %I Mertens num... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN # compute values of the Mertens function #
# Generate Mertens numbers #
[ 1 : 1000 ]INT m;
m[ 1 ] := 1;
FOR n FROM 2 TO UPB m DO
m[ n ] := 1;
FOR k FROM 2 TO n DO m[ n ] -:= m[ n OVER k ] OD
OD;
# Print table ... |
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... | #Arturo | Arturo | menu: function [items][
selection: neg 1
while [not? in? selection 1..size items][
loop.with:'i items 'item -> print ~"|i+1|. |item|"
inp: input "Enter a number: "
if numeric? inp ->
selection: to :integer inp
]
print items\[selection-1]
]
menu ["fee fie" "huff and puf... |
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.
| #ALGOL_W | ALGOL W | begin
% define a record structure - instances must be created dynamically %
record Element ( integer atomicNumber; string(16) name );
reference(Element) X;
% allocate and initialise memory for X - heap storage is the only option %
X := Element( 1, "Hydrogen" );
% allocate new memory for X, the o... |
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.
| #AutoHotkey | AutoHotkey | VarSetCapacity(Var, 10240000) ; allocate 10 megabytes
VarSetCapacity(Var, 0) ; free it |
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... | #F.23 | F# |
// Merge and aggregate datasets. Nigel Galloway: January 6th., 2021
let rFile(fName)=seq{use n=System.IO.File.OpenText(fName)
n.ReadLine() |> ignore
while not n.EndOfStream do yield n.ReadLine().Split [|','|]}
let N=rFile("file1.txt") |> Seq.sort
let G=rFile("file2.txt") |> S... |
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.)
___________________... | #Julia | Julia | 1 2 3 4 5
6 7 8 9
9 pin
PG Protective ground
TD Transmitted data 3
RD Received data 2
RTS Request to send 7
CTS Clear to send 8
DSR Data set ready 6
SG Signal ground 5
CD Carrier detect 1
+ voltage (testing)
|
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.)
___________________... | #Kotlin | Kotlin | // version 1.0.6
const val OFF = false
const val ON = true
fun toOnOff(b: Boolean) = if (b) "ON" else "OFF"
data class Rs232Pins9(
var carrierDetect : Boolean = OFF,
var receivedData : Boolean = OFF,
var transmittedData : Boolean = OFF,
var dataTerminalReady : Boolean = OFF,
var si... |
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... | #Ruby | Ruby | require('bigdecimal')
require('bigdecimal/util')
# An iterator over the Lucas Sequence for 'b'.
# (The special case of: x(n) = b * x(n-1) + x(n-2).)
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1 ; yielder.yield(xn2)
xn1 = 1 ; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2 ; yielder.yield(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)
| #Kotlin | Kotlin | // Version 1.2.41
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g ... |
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;... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%== Initialization ==%
set "numbers=123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0"
%== The Main Thing ==%
for %%N in (%numbers%) do (
call :middle3 %%N
)
echo.
pause
exit /b 0
%==/The Main Thing ==%
%== The Proc... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module Minesweeper {
Font "Arial Black"
Bold 0
Form 60,40
Refresh 1000
Def com$, com_label$
Def x, b_row, b_col, where, top_where
Def rows=4, columns=6, swap_first%
Def boolean skiptest, end_game, cheat
Dim Board$(0 to rows+1, 0 to columns+1)="? "
Def mines%... |
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... | #REXX | REXX | /*REXX pgm finds minimum pos. integer that's a product of N that only has the digs 0 & 1*/
numeric digits 30; w= length( commas( copies(1, digits()))) /*for formatting numbers.*/
parse arg list
if list=='' then list= 1..10 95..105 297
say center(' N ', 9, "─") center(' B10 ', w, "─") center(' multiplier ... |
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... | #Quackery | Quackery | [ temp put 1 unrot
[ dup while
dup 1 & if
[ unrot tuck *
temp share mod
swap rot ]
1 >>
swap dup *
temp share mod
swap again ]
2drop temp release ] is **mod ( n n n --> n )
2988348162058574136915891421498819466320163312926952423791023078876139
235... |
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... | #Racket | Racket |
#lang racket
(require math)
(define a 2988348162058574136915891421498819466320163312926952423791023078876139)
(define b 2351399303373464486466122544523690094744975233415544072992656881240319)
(define m (expt 10 40))
(modular-expt a b m)
|
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... | #Locomotive_Basic | Locomotive Basic | 10 bpm=120:bpb=4
20 sleep=50*60/bpm
30 counter=0
40 every sleep gosub 100
50 goto 50
100 print counter+1;" ";
110 if counter=0 then print ">TICK<":sound 1,60,10,15 else print " tick ":sound 1,119,10
120 counter=counter+1
130 if counter=bpb then counter=0
140 return |
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 ... | #Perl | Perl | without js -- (tasks)
sequence sems = {}
constant COUNTER = 1, QUEUE = 2
function semaphore(integer n)
if n>0 then
sems = append(sems,{n,{}})
return length(sems)
else
return 0
end if
end function
procedure acquire(integer id)
if sems[id][COUNTER]=0 then
task_suspend(t... |
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.
| #Rust | Rust | const LIMIT: i32 = 12;
fn main() {
for i in 1..LIMIT+1 {
print!("{:3}{}", i, if LIMIT - i == 0 {'\n'} else {' '})
}
for i in 0..LIMIT+1 {
print!("{}", if LIMIT - i == 0 {"+\n"} else {"----"});
}
for i in 1..LIMIT+1 {
for j in 1..LIMIT+1 {
if j < i {
... |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #Rust | Rust | extern crate rand; // 0.5.5
use rand::Rng;
use std::iter::repeat;
#[derive(Debug, Eq, PartialEq, Clone)]
enum Colour {
Black,
Red,
}
use Colour::*;
fn main() {
let mut rng = rand::thread_rng();
//Create our deck.
let mut deck: Vec<_> = repeat(Black).take(26)
.chain(repeat(Red).take(26)... |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var R = 82 // ASCII 'R'
var B = 66 // ASCII 'B'
// Create pack, half red, half black and shuffle it.
var pack = [0] * 52
for (i in 0..25) {
pack[i] = R
pack[26+i] = B
}
var rand = Random.new()
rand.shuffle(pack)
// Deal from pack into 3 stacks.
var red = []... |
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... | #Python | Python | from itertools import count, islice, chain
import time
def mian_chowla():
mc = [1]
yield mc[-1]
psums = set([2])
newsums = set([])
for trial in count(2):
for n in chain(mc, [trial]):
sum = n + trial
if sum in psums:
newsums.clear()
br... |
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... | #PicoLisp | PicoLisp |
/ift {
4 dict begin
[/.if /.then] let*
count array astore /.stack exch def
/_restore {clear .stack aload pop}.
.stack aload pop .if {
_restore .then
} {
_restore
} ifelse
end}.
|
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... | #PostScript | PostScript |
/ift {
4 dict begin
[/.if /.then] let*
count array astore /.stack exch def
/_restore {clear .stack aload pop}.
.stack aload pop .if {
_restore .then
} {
_restore
} ifelse
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... | #Commodore_BASIC | Commodore BASIC | 100 PRINT CHR$(147); CHR$(18); "**** MILLER-RABIN PRIMALITY TEST ****": PRINT
110 INPUT "NUMBER TO TEST"; N$
120 N = VAL(N$): IF N < 2 THEN 110
130 IF 0 = (N AND 1) THEN PRINT "(EVEN)": GOTO 380
140 INPUT "ITERATIONS"; K$
150 K = VAL(K$): IF K < 1 THEN 140
160 PRINT
170 DEF FNMD(M) = M - N * INT(M / N)
180 D = N - 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... | #ALGOL_W | ALGOL W | begin % compute values of the Mertens function %
integer array M ( 1 :: 1000 );
integer k, zero, cross;
% Generate Mertens numbers %
M( 1 ) := 1;
for n := 2 until 1000 do begin
M( n ) := 1;
for k := 2 until n do M( n ) ... |
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... | #APL | APL | mertens←{
step ← {⍵,-⍨/⌽1,⍵[⌊n÷1↓⍳n←1+≢⍵]}
m1000 ← step⍣999⊢,1
zero ← m1000+.=0
cross ← +/(~∧1⌽⊢)m1000≠0
⎕←'First 99 Mertens numbers:'
⎕←10 10⍴'∘',m1000
⎕←'M(N) is zero ',(⍕zero),' times.'
⎕←'M(N) crosses zero ',(⍕cross),' times.'
} |
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... | #AutoHotkey | AutoHotkey | Menu(list:=""){
if !list ; if called with an empty list
return ; return an empty string
for i, v in x := StrSplit(list, "`n", "`r")
string .= (string?"`n":"") i "- " v
, len := StrLen(v) > len ? StrLen(v) : len
while !x[Choice]
InputBox , Choice, Please Select From Menu, % string ,, % 200<len*7 ? 200 ? l... |
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.
| #Axe | Axe | Buff(100)→Str1
.Str1 points to a 100-byte memory region allocated at compile time |
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.
| #BBC_BASIC | BBC BASIC | size% = 12345
DIM mem% size%-1
PRINT ; size% " bytes of heap allocated at " ; mem% |
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... | #Go | Go | package main
import (
"fmt"
"math"
"sort"
)
type Patient struct {
id int
lastName string
}
// maps an id to a lastname
var patientDir = make(map[int]string)
// maintains a sorted list of ids
var patientIds []int
func patientNew(id int, lastName string) Patient {
patientDir[id] = ... |
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.)
___________________... | #MATLAB_.2F_Octave | MATLAB / Octave | >> rs232 = struct('carrier_detect', logical(1),...
'received_data' , logical(1), ...
'transmitted_data', logical(1),...
'data_terminal_ready', logical(1),...
'signal_ground', logical(1),...
'data_set_ready', logical(1),...
'request_to_send', logical(1),...
'clear_to_send', logical(1),...
'ring_indicator', logical(1))
... |
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... | #Sidef | Sidef | func seqRatio(f, places = 32) {
1..Inf -> reduce {|t,n|
var r = (f(n+1)/f(n)).round(-places)
return(n, r.as_dec(places + r.abs.int.len)) if (r == t)
r
}
}
for k,v in (%w(Platinum Golden Silver Bronze Copper Nickel Aluminum Iron Tin Lead).kv) {
next if (k == 0) # undefined ratio
... |
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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | MedianFilter[img,n] |
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)
| #Nim | Nim | import algorithm
import imageman
func luminance(color: ColorRGBF64): float =
0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b
proc applyMedianFilter(img: var Image; windowWidth, windowHeight: Positive) =
var window = newSeq[ColorRGBF64](windowWidth * windowHeight)
let edgeX = windowWidth div 2
let edg... |
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;... | #Befunge | Befunge | >&>:0`2*1-*0>v
v+*86%+55:p00<
>\55+/:00g1+\|
v3_v#*%2\`2::<
->@>0".rorrE"v
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$< |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DynamicModule[{m = 6, n = 4, minecount, grid, win, reset, clear,
checkwin},
reset[] :=
Module[{minesdata, adjacentmines},
minecount = RandomInteger[Round[{.1, .2} m*n]];
minesdata =
Normal@SparseArray[# -> 1 & /@
RandomSample[Tuples[Range /@ {m, n}], minecount], {m, n}];
adjacentmines = ... |
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... | #Ring | Ring |
see "working..." + nl
see "Minimum positive multiple in base 10 using only 0 and 1:" + nl
limit1 = 1000
limit2 = 111222333444555666777889
plusflag = 0
plus = [297,576,594,891,909,999]
for n = 1 to limit1
if n = 106
plusflag = 1
nplus = 0
ok
lenplus = len(plus)
if plusflag = 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... | #Raku | Raku | sub expmod(Int $a is copy, Int $b is copy, $n) {
my $c = 1;
repeat while $b div= 2 {
($c *= $a) %= $n if $b % 2;
($a *= $a) %= $n;
}
$c;
}
say expmod
2988348162058574136915891421498819466320163312926952423791023078876139,
23513993033734644864661225445236900947449752334155440729... |
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... | #REXX | REXX | /*REXX program displays the modular exponentiation of: a**b mod m */
parse arg a b m /*obtain optional args from the CL*/
if a=='' | a=="," then a= 2988348162058574136915891421498819466320163312926952423791023078876139
if b=='' | b=="," then b= 2351399303373... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | s = Sound[Play[Sin[1000 t], {t, 0, 0.05}]];
ss = Sound[Play[Sin[2000 t], {t, 0, 0.05}]];
bpm = 180;
slp = 60/bpm;
color = White;
i = 0;
Dynamic[Graphics[{color, Disk[]}, ImageSize -> 50]]
While[True,
i = Mod[i + 1, 4, 1];
color = {Green, Red, Darker@Red, Red, Darker@Red}[[i]];
If[i == 1,
EmitSound[ss]
,
EmitSo... |
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... | #Nim | Nim | import os
proc metronome(tempo, pattern: Positive) =
let delay = 60_000 div tempo # In milliseconds.
var beats = 0
while true:
stdout.write if beats mod pattern == 0: "\nTICK" else: " tick"
stdout.flushFile
inc beats
sleep(delay)
metronome(72, 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 ... | #Phix | Phix | without js -- (tasks)
sequence sems = {}
constant COUNTER = 1, QUEUE = 2
function semaphore(integer n)
if n>0 then
sems = append(sems,{n,{}})
return length(sems)
else
return 0
end if
end function
procedure acquire(integer id)
if sems[id][COUNTER]=0 then
task_suspend(t... |
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.
| #Scala | Scala |
//Multiplication Table
print("%5s".format("|"))
for (i <- 1 to 12) print("%5d".format(i))
println()
println("-----" * 13)
for (i <- 1 to 12) {
print("%4d|".format(i))
for (j <- 1 to 12) {
if (i <= j)
print("%5d".format(i * j))
else
print("%5s".format(""))
}
println("")
}
|
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #zkl | zkl | cards:=[1..52].pump(List,"isEven","toInt").shuffle(); // red==1
stacks:=T(List(),List()); // black stack [0], red stack [1]
blkStk,redStk := stacks;
foreach card in (cards){ stacks[card].append(__cardWalker.next()) }
println("Stacks:\n Black stack: ",redBlack(blkStk),"\n Red stack: ",redBlack(redStk));
numSwaps... |
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... | #Quackery | Quackery | [ stack ] is makeable ( --> s )
[ temp put
1 bit makeable put
' [ 1 ] 1
[ true temp put
1+
over witheach
[ over + bit
makeable share & if
[ false temp replace
conclude ] ]
temp take if
[ dup dip join
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.