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/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Haskell
Haskell
  modPow :: Integer -> Integer -> Integer -> Integer -> Integer modPow b e 1 r = 0 modPow b 0 m r = r modPow b e m r | e `mod` 2 == 1 = modPow b' e' m (r * b `mod` m) | otherwise = modPow b' e' m r where b' = b * b `mod` m e' = e `div` 2   main = do print (modPow 2988348162058574136915891421498819466320...
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...
#AutoHotkey
AutoHotkey
bpm = 120 ; Beats per minute pattern = 4/4 ; duration = 100 ; Milliseconds beats = 0 ; internal counter   Gui -Caption   StringSplit, p, pattern, /   Start := A_TickCount   Loop { Gui Color, 0xFF0000 Gui Show, w200 h200 Na SoundBeep 750, duration beats++ Sleep 1000 * 60 / bpm - duration Loop % p1 -1 {...
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 ...
#C.23
C#
using System; using System.Threading; using System.Threading.Tasks;   namespace RosettaCode { internal sealed class Program { private static void Worker(object arg, int id) { var sem = arg as SemaphoreSlim; sem.Wait(); Console.WriteLine("Thread {0} has a semaphore & is now working.", id); ...
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 ...
#C.2B.2B
C++
#include <chrono> #include <iostream> #include <format> #include <semaphore> #include <thread>   using namespace std::literals;   void Worker(std::counting_semaphore<>& semaphore, int id) { semaphore.acquire(); std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); // response message ...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Python
Python
import operator import functools   @functools.total_ordering class Mod: __slots__ = ['val','mod']   def __init__(self, val, mod): if not isinstance(val, int): raise ValueError('Value must be integer') if not isinstance(mod, int) or mod<=0: raise ValueError('Modulo must be...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Yabasic
Yabasic
DOCU The N Queens Problem: DOCU Place N Queens on an NxN chess board DOCU such that they don't threaten each other.   N = 8 // try some other sizes   sub threat(q1r, q1c, q2r, q2c) // do two queens threaten each other?   if q1c = q2c then return true elsif (q1r - q1c) = (q2r - q2c) then return true elsif (q...
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Yabasic
Yabasic
// User defined functions sub F(n) if n = 0 return 1 return n - M(F(n-1)) end sub     sub M(n) if n = 0 return 0 return n - F(M(n-1)) end sub     for i = 0 to 20 print F(i) using "###"; next print for i = 0 to 20 print M(i) using "###"; next print
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.
#PowerShell
PowerShell
# For clarity $Tab = "`t"   # Create top row $Tab + ( 1..12 -join $Tab )   # For each row ForEach ( $i in 1..12 ) { $( # The number in the left column $i   # An empty slot for the bottom triangle @( "" ) * ( $i - 1 )   # Calculate the top triangle $i..12 | ForEach ...
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...
#F.23
F#
  //Be boggled? Nigel Galloway: September 19th., 2018 let N=System.Random() let fN=List.unfold(function |(0,0)->None |(n,g)->let ng=N.Next (n+g) in Some (if ng>=n then ("Black",(n,g-1)) else ("Red",(n-1,g))))(26,26) let fG n=let (n,n')::(g,g')::_=List.countBy(fun (n::g::_)->if n=g then n else g) n in sprintf "%d %s car...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq;   static class Program { static int[] MianChowla(int n) { int[] mc = new int[n - 1 + 1]; HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>(); int sum; mc[0] = 1; sums.Add(2); for ...
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#Arturo
Arturo
sumThemUp: function [x,y][ x+y ]   alias.infix '--> 'sumThemUp   do [ print 3 --> 4 ]
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#C
C
  // http://stackoverflow.com/questions/3385515/static-assert-in-c #define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1] // token pasting madness: #define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L) #define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L) #de...
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...
#C.2B.2B
C++
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream>   const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };   template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " <<...
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;...
#11l
11l
F middle_three_digits(i) V s = String(abs(i)) assert(s.len >= 3 & s.len % 2 == 1, ‘Need odd and >= 3 digits’) R s[s.len I/ 2 - 1 .+ 3]   V passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] V failing = [1, 2, -1, -10, 2002, -2002, 0] L(x) passing [+] failing X.try V ans...
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...
#Clojure
Clojure
(defn take-random [n coll] (->> (repeatedly #(rand-nth coll)) distinct (take n ,)))   (defn postwalk-fs "Depth first post-order traversal of form, apply successive fs at each level. (f1 (map f2 [..]))" [[f & fs] form] (f (if (and (seq fs) (coll? form)) (into (empty form) (map (partial po...
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...
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   // Title: Minimum positive multiple in base 10 using only 0 and 1   public class MinimumNumberOnlyZeroAndOne {   public static void main(String[] args) { for ( int n : getTestCases() ) { BigInteger result = get...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() a := 2988348162058574136915891421498819466320163312926952423791023078876139 b := 2351399303373464486466122544523690094744975233415544072992656881240319 write("last 40 digits = ",mod_power(a,b,(10^40)) end   procedure mod_power(base, exponent, modulus) # fast modular exponentation ...
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...
#AWK
AWK
  # syntax: GAWK -f METRONOME.AWK @load "time" BEGIN { metronome(120,6,10) metronome(72,4) exit(0) } function metronome(beats_per_min,beats_per_bar,limit, beats,delay,errors) { print("") if (beats_per_min+0 <= 0) { print("error: beats per minute is invalid") ; errors++ } if (beats_per_bar+0 <= ...
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 ...
#D
D
module meteredconcurrency ; import std.stdio ; import std.thread ; import std.c.time ;   class Semaphore { private int lockCnt, maxCnt ; this(int count) { maxCnt = lockCnt = count ;} void acquire() { if(lockCnt < 0 || maxCnt <= 0) throw new Exception("Negative Lock or Zero init. Lock") ; while(lockC...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Quackery
Quackery
[ stack ] is modulus ( --> s )   [ this ] is modular ( --> [ )   [ modulus share mod modular nested join ] is modularise ( n --> N )   [ dup nest? iff [ -1 peek modular oats ] else [ drop false ] ] is modul...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Racket
Racket
#lang racket (require racket/require  ;; grab all "mod*" names, but get them without the "mod", so  ;; `+' and `expt' is actually `mod+' and `modexpt' (filtered-in (λ(n) (and (regexp-match? #rx"^mod" n) (regexp-replace #rx"^mod" n ""))) mat...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream();   var board = [_]i8{-1} ** 8;   inline fn abs(x: var) @TypeOf(x) { return if (x < 0) -x else x; }   fn safe(c: i32, r: i32) bool { var i: i32 = 0; return while (i < c) : (i += 1) { const q = board[@intCast(u3, i)]; ...
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#zkl
zkl
fcn f(n){ if(n==0)return(1); n-m(f(n-1,m),f) } fcn m(n){ if(n==0)return(0); n-f(m(n-1,f),m) } [0..19].apply(f).println(); // or foreach n in ([0..19]){ print(f(n)," ") } [0..19].apply(m).println(); // or foreach n in ([0..19]){ print(m(n)," ") }
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.
#Prolog
Prolog
make_table(S,E) :- print_header(S,E), make_table_rows(S,E), fail. make_table(_,_).   print_header(S,E) :- nl, write(' '), forall(between(S,E,X), print_num(X)), nl, Sp is E * 4 + 2, write(' '), forall(between(1,Sp,_), write('-')).   make_table_rows(S,E) :- between(S,E,N), nl, print_num(N), write(': ...
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...
#Factor
Factor
USING: accessors combinators.extras formatting fry generalizations io kernel math math.ranges random sequences sequences.extras ; IN: rosetta-code.mind-boggling-card-trick   SYMBOLS: R B ;   TUPLE: piles deck red black discard ;   : initialize-deck ( -- seq ) [ R ] [ B ] [ '[ 26 _ V{ } replicate-as ] call ] bi@ app...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() { // Create pack, half red, half black and shuffle it. var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { ...
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...
#C.2B.2B
C++
using namespace std;   #include <iostream> #include <ctime>   #define n 100 #define nn ((n * (n + 1)) >> 1)   bool Contains(int lst[], int item, int size) { for (int i = 0; i < size; i++) if (item == lst[i]) return true; return false; }   int * MianChowla() { static int mc[n]; mc[0] = 1; int sums[nn]; sums[0] = 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...
#C.23
C#
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) ...
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...
#Clojure
Clojure
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) ...
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...
#F.23
F#
  // Metallic Ration. Nigel Galloway: September 16th., 2020 let rec fN i g (e,l)=match i with 0->g |_->fN (i-1) (int(l/e)::g) (e,(l%e)*10I) let fI(P:int)=Seq.unfold(fun(n,g)->Some(g,((bigint P)*n+g,n)))(1I,1I) let fG fI fN=let _,(n,g)=fI|>Seq.pairwise|>Seq.mapi(fun n g->(n,fN g))|>Seq.pairwise|>Seq.find(fun((_...
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;...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT" INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit   PROC MiddleThreeDigits(REAL POINTER n CHAR ARRAY res) REAL r CHAR ARRAY s(15) BYTE i   RealAbs(n,r) StrR(r,s) i=s(0) IF i<3 OR (i&1)=0 THEN res(0)=0 ELSE i==RSH 1 SCopyS(res,s,i,i+2) FI RETURN   PROC Test(CHAR A...
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...
#Common_Lisp
Common Lisp
(defclass minefield () ((mines :initform (make-hash-table :test #'equal)) (width :initarg :width) (height :initarg :height) (grid :initarg :grid)))   (defun make-minefield (width height num-mines) (let ((minefield (make-instance 'minefield :width width ...
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...
#jq
jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def pp(a;b;c): "\(a|lpad(4)): \(b|lpad(28)) \(c|lpad(24))";   def b10: . as $n | if . == 1 then pp(1;1;1) else ($n + 1) as $n1 | { pow: [range(0;$n)|0], val: [range(0;$n)|0], count: 0, ten: 1, x: 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...
#J
J
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...
#Java
Java
import java.math.BigInteger;   public class PowMod { public static void main(String[] args){ BigInteger a = new BigInteger( "2988348162058574136915891421498819466320163312926952423791023078876139"); BigInteger b = new BigInteger( "235139930337346448646612254452369009474497523341554407299...
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...
#BBC_BASIC
BBC BASIC
BeatPattern$ = "HLLL" Tempo% = 100   *font Arial,36 REPEAT FOR beat% = 1 TO LEN(BeatPattern$) IF MID$(BeatPattern$, beat%, 1) = "H" THEN SOUND 1,-15,148,1 ELSE SOUND 1,-15,100,1 ENDIF VDU 30 COLOUR 2 PRIN...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <signal.h> #include <time.h> #include <sys/time.h>   struct timeval start, last;   inline int64_t tv_to_u(struct timeval s) { return s.tv_sec * 1000000 + s.tv_usec; }   inline struct timeval u_to_tv(int64_t x) { struct timeval s; ...
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 ...
#E
E
def makeSemaphore(maximum :(int > 0)) { var current := 0 def waiters := <elib:vat.makeQueue>() def notify() { while (current < maximum && waiters.hasMoreElements()) { current += 1 waiters.optDequeue().resolve(def released) when (released) -> { curr...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Raku
Raku
use Modular; sub f(\x) { x**100 + x + 1}; say f( 10 Mod 13 )
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Red
Red
Red ["Modular arithmetic"]   ; defining the modular integer class, and a constructor modulus: 13 m: function [n] [ either object? n [make n []] [context [val: n % modulus]] ] ; redefining operators +, -, *, / to include modular integers foreach [op fun][+ add - subtract * multiply / divide][...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#zkl
zkl
fcn isAttacked(q, x,y) // ( (r,c), x,y ) : is queen at r,c attacked by q@(x,y)? { r,c:=q; (r==x or c==y or r+c==x+y or r-c==x-y) } fcn isSafe(r,c,qs) // queen safe at (r,c)?, qs=( (r,c),(r,c)..) solution so far { ( not qs.filter1(isAttacked,r,c) ) } fcn queensN(N=8,row=1,queens=T){ qs:=[1..N].filter(isSafe.fpM...
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.
#PureBasic
PureBasic
Procedure PrintMultiplicationTable(maxx, maxy) sp = Len(Str(maxx*maxy)) + 1 trenner$ = "+" For l1 = 1 To maxx + 1 For l2 = 1 To sp trenner$ + "-" Next trenner$ + "+" Next header$ = "|" + RSet("x", sp) + "|" For a = 1 To maxx header$ + RSet(Str(a), sp) header$ + "|" Next ...
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...
#Haskell
Haskell
import System.Random (randomRIO) import Data.List (partition) import Data.Monoid ((<>))   main :: IO [Int] main = do   -- DEALT ns <- knuthShuffle [1 .. 52] let (rs_, bs_, discards) = threeStacks (rb <$> ns)   -- SWAPPED nSwap <- randomRIO (1, min (length rs_) (length bs_)) let (rs, bs) = exchange nSwap rs_...
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...
#F.23
F#
  // Generate Mian-Chowla sequence. Nigel Galloway: March 23rd., 2019 let mC=let rec fN i g l=seq{ let a=(l*2)::[for i in i do yield i+l]@g let b=[l+1..l*2]|>Seq.find(fun e->Seq.forall(fun g->(Seq.contains (g-e)>>not) i) a) yield b; yield! fN (l::i) (a|>List.filter(fun n->n>b)) b} seq{...
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...
#Common_Lisp
Common Lisp
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) ...
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...
#D
D
enum GenStruct(string name, string fieldName) = "struct " ~ name ~ "{ int " ~ fieldName ~ "; }";   // Equivalent to: struct Foo { int bar; } mixin(GenStruct!("Foo", "bar"));   void main() { Foo f; f.bar = 10; }
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...
#Factor
Factor
USING: combinators decimals formatting generalizations io kernel math prettyprint qw sequences ; IN: rosetta-code.metallic-ratios   : lucas ( n a b -- n a' b' ) tuck reach * + ;   : lucas. ( n -- ) 1 pprint bl 1 1 14 [ lucas over pprint bl ] times 3drop nl ;   : approx ( a b -- d ) swap [ 0 <decimal> ] bi@ 32 D/ ; ...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"}   func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") v...
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;...
#Ada
Ada
with Ada.Text_IO;   procedure Middle_Three_Digits is   Impossible: exception;   function Middle_String(I: Integer; Middle_Size: Positive) return String is S: constant String := Integer'Image(I); First: Natural := S'First; Full_Size, Border: Natural; begin while S(First) not in '0' .. '9...
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...
#D
D
len cell[] 56 len cnt[] 56 len flag[] 56 # subr initvars state = 0 ticks = 0 indx = -1 no_time = 0 . func getind r c . ind . ind = -1 if r >= 0 and r <= 6 and c >= 0 and c <= 7 ind = r * 8 + c . . func draw_cell ind h . . r = ind div 8 c = ind mod 8 x = c * 12 + 2.5 y = r * 12 + 14.5 move x...
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...
#Julia
Julia
function B10(n) for i in Int128(1):typemax(Int128) q, b10, place = i, zero(Int128), one(Int128) while q > 0 q, r = divrem(q, 2) if r != 0 b10 += place end place *= 10 end if b10 % n == 0 return b10 en...
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...
#Julia
Julia
a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = big(10) ^ 40 @show powermod(a, 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...
#Kotlin
Kotlin
// version 1.0.6   import java.math.BigInteger   fun main(args: Array<String>) { val a = BigInteger("2988348162058574136915891421498819466320163312926952423791023078876139") val b = BigInteger("2351399303373464486466122544523690094744975233415544072992656881240319") val m = BigInteger.TEN.pow(40) printl...
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...
#Common_Lisp
Common Lisp
(ql:quickload '(cl-openal cl-alc))   (defparameter *short-max* (- (expt 2 15) 1)) (defparameter *2-pi* (* 2 pi))   (defun make-sin (period) "Create a generator for a sine wave of the given PERIOD." (lambda (x) (sin (* *2-pi* (/ x period)))))   (defun make-tone (length frequency sampling-frequency) "Create a v...
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 ...
#EchoLisp
EchoLisp
  (require 'tasks) ;; tasks library   (define (task id) (wait S) ;; acquire, p-op (printf "task %d acquires semaphore @ %a" id (date->time-string (current-date))) (sleep 2000) (signal S) ;; release, v-op id)   (define S (make-semaphore 4)) ;; semaphore with init count 4   ;; run 10 // tasks (for ([i 10]) (task-run...
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 ...
#Erlang
Erlang
  -module(metered). -compile(export_all).   create_semaphore(N) -> spawn(?MODULE, sem_loop, [N,N]).   sem_loop(0,Max) -> io:format("Resources exhausted~n"), receive {release, PID} -> PID ! released, sem_loop(1,Max); {stop, _PID} -> ok end; sem_loop(N,N...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Ruby
Ruby
# stripped version of Andrea Fazzi's submission to Ruby Quiz #179   class Modulo include Comparable   def initialize(n = 0, m = 13) @n, @m = n % m, m end   def to_i @n end   def <=>(other_n) @n <=> other_n.to_i end   [:+, :-, :*, :**].each do |meth| define_method(meth) { |other_n| Modulo...
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.
#Python
Python
>>> size = 12 >>> width = len(str(size**2)) >>> for row in range(-1,size+1): if row==0: print("─"*width + "┼"+"─"*((width+1)*size-1)) else: print("".join("%*s%1s" % ((width,) + (("x","│") if row==-1 and col==0 else (row,"│") if row>0 and col==0 else (col,"") if row==-...
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...
#J
J
  NB. A failed assertion looks like this assert 0 |assertion failure: assert | assert 0  
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...
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => { const // DEALT [rs_, bs_, discards] = threeStacks( map(n => even(n) ? ( 'R' ) : 'B', knuthShuffle( enumFromTo(1, 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...
#Factor
Factor
USING: fry hash-sets io kernel math prettyprint sequences sets ;   : next ( seq sums speculative -- seq' sums' speculative' ) dup reach [ + ] with map over dup + suffix! >hash-set pick over intersect null? [ swapd union [ [ suffix! ] keep ] dip swap ] [ drop ] if 1 + ;   : mian-chowla ( n -- seq ) [...
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...
#FreeBASIC
FreeBASIC
redim as uinteger mian(0 to 1) redim as uinteger sums(0 to 2) mian(0) = 1 : mian(1) = 2 sums(0) = 2 : sums(1) = 3 : sums(2) = 4 dim as uinteger n_mc = 2, n_sm = 3, curr = 3, tempsum while n_mc < 101 for i as uinteger = 0 to n_mc - 1 tempsum = curr + mian(i) for j as uinteger = 0 to n_sm - 1 ...
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...
#E
E
\ BRANCH and LOOP COMPILERS   \ branch offset computation operators : AHEAD ( -- addr) HERE 0 , ; : BACK ( addr -- ) HERE - , ; : RESOLVE ( addr -- ) HERE OVER - SWAP ! ;   \ LEAVE stack is called L0. It is initialized by QUIT. : >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; : L> ( -- x ) ( 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...
#Erlang
Erlang
\ BRANCH and LOOP COMPILERS   \ branch offset computation operators : AHEAD ( -- addr) HERE 0 , ; : BACK ( addr -- ) HERE - , ; : RESOLVE ( addr -- ) HERE OVER - SWAP ! ;   \ LEAVE stack is called L0. It is initialized by QUIT. : >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; : L> ( -- x ) ( L: ...
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...
#11l
11l
F isProbablePrime(n, k = 10) I n < 2 | n % 2 == 0 R n == 2   V d = n - 1 V s = 0 L d % 2 == 0 d I/= 2 s++   assert(2 ^ s * d == n - 1)   L 0 .< k V a = random:(2 .< n) V x = pow(a, d, n) I x == 1 | x == n - 1 L.continue L 0 .< s - 1 x = pow(x...
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...
#Groovy
Groovy
class MetallicRatios { private static List<String> names = new ArrayList<>() static { names.add("Platinum") names.add("Golden") names.add("Silver") names.add("Bronze") names.add("Copper") names.add("Nickel") names.add("Aluminum") names.add("Iron") ...
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;...
#Aime
Aime
void m3(integer i) { text s;   s = itoa(i); if (s[0] == '-') { s = delete(s, 0); }   if (~s < 3) { v_integer(i); v_text(" has not enough digits\n"); } elif (~s & 1) { o_form("/w9/: ~\n", i, cut(s, ~s - 3 >> 1, 3)); } else { v_integer(i); v_text...
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...
#EasyLang
EasyLang
len cell[] 56 len cnt[] 56 len flag[] 56 # subr initvars state = 0 ticks = 0 indx = -1 no_time = 0 . func getind r c . ind . ind = -1 if r >= 0 and r <= 6 and c >= 0 and c <= 7 ind = r * 8 + c . . func draw_cell ind h . . r = ind div 8 c = ind mod 8 x = c * 12 + 2.5 y = r * 12 + 14.5 move x...
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...
#Kotlin
Kotlin
import java.math.BigInteger   fun main() { for (n in testCases) { val result = getA004290(n) println("A004290($n) = $result = $n * ${result / n.toBigInteger()}") } }   private val testCases: List<Int> get() { val testCases: MutableList<Int> = ArrayList() for (i in 1..10) { ...
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...
#Lambdatalk
Lambdatalk
  We will call the lib_BN library for big numbers:   {require lib_BN}   In this library {BN.compare a b} returns 1 if a > b, 0 if a = b and -1 if a < b. For a better readability we define three small functions   {def BN.= {lambda {:a :b} {= {BN.compare :a :b} 0}}} -> BN.= {def BN.even? {lambda {:n} {= {BN.compare {B...
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...
#Delphi
Delphi
  program Metronome;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils;   procedure StartMetronome(bpm: double; measure: Integer); var counter: Integer; begin counter := 0; while True do begin Sleep(Trunc(1000 * (60.0 / bpm))); inc(counter); if counter mod measure = 0 then writel...
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 ...
#Euphoria
Euphoria
sequence sems 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(task_self()) ...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Scala
Scala
object ModularArithmetic extends App { private val x = new ModInt(10, 13) private val y = f(x)   private def f[T](x: Ring[T]) = (x ^ 100) + x + x.one   private trait Ring[T] { def +(rhs: Ring[T]): Ring[T]   def *(rhs: Ring[T]): Ring[T]   def one: Ring[T]   def ^(p: Int): Ring[T] = { requir...
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.
#Quackery
Quackery
[ swap number$ tuck size - times sp echo$ ] is echo-rj ( n n --> )   say " * |" 12 times [ i^ 1+ 4 echo-rj ] cr say " ---+" char - 48 of echo$ cr [ 12 times [ i^ 1+ dup 3 echo-rj say " |" 12 times [ i^ 1+ 2dup > iff [ drop 4 times sp ] ...
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...
#Julia
Julia
const rbdeck = split(repeat('R', 26) * repeat('B', 26), "") shuffledeck() = shuffle(rbdeck)   function deal!(deck, dpile, bpile, rpile) while !isempty(deck) if (topcard = pop!(deck)) == "R" push!(rpile, pop!(deck)) else push!(bpile, pop!(deck)) end push!(dpile...
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...
#Kotlin
Kotlin
// Version 1.2.61   import java.util.Random   fun main(args: Array<String>) { // Create pack, half red, half black and shuffle it. val pack = MutableList(52) { if (it < 26) 'R' else 'B' } pack.shuffle()   // Deal from pack into 3 stacks. val red = mutableListOf<Char>() val black = mutableListOf<...
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...
#Go
Go
package main   import "fmt"   func contains(is []int, s int) bool { for _, i := range is { if s == i { return true } } return false }   func mianChowla(n int) []int { mc := make([]int, n) mc[0] = 1 is := []int{2} var sum int for i := 1; i < n; i++ { le...
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...
#Forth
Forth
\ BRANCH and LOOP COMPILERS   \ branch offset computation operators : AHEAD ( -- addr) HERE 0 , ; : BACK ( addr -- ) HERE - , ; : RESOLVE ( addr -- ) HERE OVER - SWAP ! ;   \ LEAVE stack is called L0. It is initialized by QUIT. : >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; : L> ( -- x ) ( 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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Macro ForAll(C, S) For _i as integer = 0 To Len(s) #Define C (Chr(s[_i])) #EndMacro   #Define In ,   Dim s As String = "Rosetta" ForAll(c in s) Print c; " "; Next   Print Sleep
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...
#Ada
Ada
generic type Number is range <>; package Miller_Rabin is   type Result_Type is (Composite, Probably_Prime);   function Is_Prime (N : Number; K : Positive := 10) return Result_Type;   end Miller_Rabin;
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...
#J
J
  258j256":%~/+/+/ .*~^:10 x:*i.2 2 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374847540880753868917521266338622235369317931800607667263544333890865959395829056383226613199282902678806752087668925017116962070322210432162695486262963136144  
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...
#Java
Java
  import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List;   public class MetallicRatios {   private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "T...
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;...
#ALGOL_68
ALGOL 68
# we define a UNION MODE so that our middle 3 digits PROC can # # return either an integer on success or a error message if # # the middle 3 digits couldn't be extracted # MODE EINT = UNION( INT # success value #, STRING # error message # ); # PROC to return the middle 3 digits of an integer. ...
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...
#FreeBASIC
FreeBASIC
'--- Declaration of global variables --- Type mina Dim mina As Byte Dim flag As Byte Dim ok As Byte Dim numero As Byte End Type   Dim Shared As Integer size = 16, NX = 20, NY = 20 Dim Shared As Double mina = 0.10   Dim Shared tablero(NX+1,NY+1) As mina Dim Shared As Integer GameOver, ddx, ddy, k...
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...
#Lua
Lua
function array1D(n, v) local tbl = {} for i=1,n do table.insert(tbl, v) end return tbl end   function array2D(h, w, v) local tbl = {} for i=1,h do table.insert(tbl, array1D(w, v)) end return tbl end   function mod(m, n) m = math.floor(m) local result = m % n i...
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...
#Maple
Maple
a := 2988348162058574136915891421498819466320163312926952423791023078876139: b := 2351399303373464486466122544523690094744975233415544072992656881240319: a &^ b mod 10^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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = 2988348162058574136915891421498819466320163312926952423791023078876139; b = 2351399303373464486466122544523690094744975233415544072992656881240319; m = 10^40; PowerMod[a, b, m] -> 1527229998585248450016808958343740453059
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...
#EchoLisp
EchoLisp
  ;; available preloaded sounds are : ok, ko, tick, tack, woosh, beep, digit . (lib 'timer)   (define (metronome) (blink) (play-sound 'tack)) (at-every 1000 'metronome) ;; every 1000 msec ;; CTRL-C to stop  
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...
#F.23
F#
open System open System.Threading // You can use .wav files for your clicks. // If used, make sure they are in the same file // as this program's executable file. let high_pitch = new System.Media.SoundPlayer("Ping Hi.wav") let low_pitch = new System.Media.SoundPlayer("Ping Low.wav") let factor x y = x / y /...
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 ...
#Factor
Factor
USING: calendar calendar.format concurrency.combinators concurrency.semaphores formatting kernel sequences threads ;   10 <iota> 2 <semaphore> [ [ dup now timestamp>hms "task %d acquired semaphore at %s\n" printf 2 seconds sleep ] with-semaphore "task %d released\n" printf ] curry p...
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 ...
#FreeBASIC
FreeBASIC
#define MaxThreads 10   Dim Shared As Any Ptr ttylock   ' Teletype unfurls some text across the screen at a given location Sub teletype(Byref texto As String, Byval x As Integer, Byval y As Integer) ' This MutexLock makes simultaneously running threads wait for each other, ' so only one at a time can continue ...
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Sidef
Sidef
class Modulo(n=0, m=13) {   method init { (n, m) = (n % m, m) }   method to_n { n }   < + - * ** >.each { |meth| Modulo.def_method(meth, method(n2) { Modulo(n.(meth)(n2.to_n), m) }) }   method to_s { "#{n} 「mod #{m}」" } }   func f(x) { x**100 + x + 1 } say f(Modulo(10, 13))
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.
#R
R
  multiplication_table <- function(n=12) { one_to_n <- 1:n x <- matrix(one_to_n) %*% t(one_to_n) x[lower.tri(x)] <- 0 rownames(x) <- colnames(x) <- one_to_n print(as.table(x), zero.print="") invisible(x) } multiplication_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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
s = RandomSample@Flatten[{Table[0, 26], Table[1, 26]}] g = Take[s, {1, -1, 2}] d = Take[s, {2, -1, 2}] a = b = {}; Table[If[g[[i]] == 1, AppendTo[a, d[[i]]], AppendTo[b, d[[i]]]], {i, Length@g}]; a b dice = RandomInteger[{1, 6}] ra = Sort@RandomSample[Range@Length@a, dice] a = {Delete[a, List /@ ra], a[[ra]]} rb = ...
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...
#Nim
Nim
import random, sequtils, strformat, strutils   type Color {.pure.} = enum Red = "R", Black = "B"   proc `$`(s: seq[Color]): string = s.join(" ")   # Create pack, half red, half black and shuffle it. var pack = newSeq[Color](52) for i in 0..51: pack[i] = Color(i < 26) pack.shuffle()   # Deal from pack into 3 stacks. var...
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...
#Haskell
Haskell
import Data.Set (Set, fromList, insert, member)   ------------------- MIAN-CHOWLA SEQUENCE ----------------- mianChowlas :: Int -> [Int] mianChowlas = reverse . snd . (iterate nextMC (fromList [2], [1]) !!) . subtract 1   nextMC :: (Set Int, [Int]) -> (Set Int, [Int]) nextMC (sumSet, mcs@(n:_)) = (foldr insert sumS...
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...
#Go
Go
package main   import "fmt"   type person struct{ name string age int }   func copy(p person) person { return person{p.name, p.age} }   func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) /* is := []int{1, 2, 3} it := make([]int, 3) copy(it, is) ...
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...
#Haskell
Haskell
macro dowhile(condition, block) quote while true $(esc(block)) if !$(esc(condition)) break end end end end   macro dountil(condition, block) quote while true $(esc(block)) if $(esc(condition)) ...
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...
#ALGOL_68
ALGOL 68
MODE LINT=LONG INT; MODE LOOPINT = INT;   MODE POWMODSTRUCT = LINT; PR READ "prelude/pow_mod.a68" PR;   PROC miller rabin = (LINT n, LOOPINT k)BOOL: ( IF n<=3 THEN TRUE ELIF NOT ODD n THEN FALSE ELSE LINT d := n - 1; INT s := 0; WHILE NOT ODD d DO d := d OVER 2; ...
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...
#Julia
Julia
using Formatting import Base.iterate, Base.IteratorSize, Base.IteratorEltype, Base.Iterators.take   const metallicnames = ["Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"]   struct Lucas b::Int end Base.IteratorSize(s::Lucas) = Base.IsInfinite() Base.IteratorEltype(s...