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, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#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 = true result[^1] = candidate # Check the sums. for val in result: if val + candidate in sums: # Failed to satisfy criterium. fit = false break # Add the new sums to the set of sums. for val in result: sums.incl val + candidate   let t0 = now() let seq100 = mianchowla(100) echo "The first 30 terms of the Mian-Chowla sequence are:" echo seq100[0..29].join(" ") echo "" echo "Terms 91 to 100 of the sequence are:" echo seq100[90..99].join(" ")   echo "" echo "Computation time: ", (now() - t0).inMilliseconds, " ms"
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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 (letq (name) ((lambda (var ...) . body)) name))) ((define name val) (setq name val)) ((define name a b . c) (define name (begin a b . c)))))  
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#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 == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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 col == 10 print() col = 0   V zeroes = sum(ms.map(x -> Int(x == 0))) V crosses = sum(zip(ms, ms[1..]).map((a, b) -> Int(a != 0 & b == 0))) print(‘M(N) equals zero #. times.’.format(zeroes)) print(‘M(N) crosses zero #. times.’.format(crosses))
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 selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#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 string is begin if m'length > 0 then loop put_line (prompt); for i in m'range loop put_line (i'img &") " & To_String (m(i))); end loop; begin return To_String (m(positive'value (get_line))); exception when others => put_line ("Try again !"); end; end loop; end if; return ""; end choice;   begin put_line ("You chose " & choice ((+"fee fie",+"huff and puff",+"mirror mirror",+"tick tock"),"Enter your choice ")); end menu;
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 load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#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 5005,Kurtz";   string visitsCsv = @" PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3";   string format = "yyyy-MM-dd"; var formatProvider = new DateTimeFormat(format).FormatProvider;   var patients = ParseCsv( patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => (PatientId: int.Parse(line[0]), LastName: line[1]));   var visits = ParseCsv( visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => ( PatientId: int.Parse(line[0]), VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?), Score: double.TryParse(line[2], out double score) ? score : default(double?) ) );   var results = patients.GroupJoin(visits, p => p.PatientId, v => v.PatientId, (p, vs) => ( p.PatientId, p.LastName, LastVisit: vs.Max(v => v.VisitDate), ScoreSum: vs.Sum(v => v.Score), ScoreAvg: vs.Average(v => v.Score) ) ).OrderBy(r => r.PatientId);   Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |"); foreach (var r in results) { Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |"); } }   private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor) { for (int i = 1; i < contents.Length; i++) { var line = contents[i].Split(','); yield return constructor(line); } }   }
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.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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 reveal the memory layout signalMemoryStructure: word absolute signal; {$if sizeOf(signal) <> sizeOf(word)} // just as safe-guard {$fatal signal size} {$endIf} begin signal := []; include(signal, signalGround); // equivalent to signal := signal + [signalGround]; // for demonstration purposes: obviously we know this is always `true` if signalGround in signal then begin writeLn(binStr(signalMemoryStructure, bitSizeOf(signal))); end; end.
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.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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 ringIndicator  : 1 As UByte End Type   Print SizeOf(RS232_Pin9) '' 2 bytes Sleep
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 the early Greeks, though was not named so until later as a nod to the Golden ratio to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name Metallic ratios (or Metallic means). Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold". Metallic ratios are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer b determines which specific one it is. Using the quadratic equation: ( -b ± √(b2 - 4ac) ) / 2a = x Substitute in (from the top equation) 1 for a, -1 for c, and recognising that -b is negated we get: ( b ± √(b2 + 4) ) ) / 2 = x We only want the real root: ( b + √(b2 + 4) ) ) / 2 = x When we set b to 1, we get an irrational number: the Golden ratio. ( 1 + √(12 + 4) ) / 2 = (1 + √5) / 2 = ~1.618033989... With b set to 2, we get a different irrational number: the Silver ratio. ( 2 + √(22 + 4) ) / 2 = (2 + √8) / 2 = ~2.414213562... When the ratio b is 3, it is commonly referred to as the Bronze ratio, 4 and 5 are sometimes called the Copper and Nickel ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, b can be 0 for a "smaller" ratio than the Golden ratio. We will refer to it here as the Platinum ratio, though it is kind-of a degenerate case. Metallic ratios where b > 0 are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten Metallic ratios are: Metallic ratios Name b Equation Value Continued fraction OEIS link Platinum 0 (0 + √4) / 2 1 - - Golden 1 (1 + √5) / 2 1.618033988749895... [1;1,1,1,1,1,1,1,1,1,1...] OEIS:A001622 Silver 2 (2 + √8) / 2 2.414213562373095... [2;2,2,2,2,2,2,2,2,2,2...] OEIS:A014176 Bronze 3 (3 + √13) / 2 3.302775637731995... [3;3,3,3,3,3,3,3,3,3,3...] OEIS:A098316 Copper 4 (4 + √20) / 2 4.23606797749979... [4;4,4,4,4,4,4,4,4,4,4...] OEIS:A098317 Nickel 5 (5 + √29) / 2 5.192582403567252... [5;5,5,5,5,5,5,5,5,5,5...] OEIS:A098318 Aluminum 6 (6 + √40) / 2 6.16227766016838... [6;6,6,6,6,6,6,6,6,6,6...] OEIS:A176398 Iron 7 (7 + √53) / 2 7.140054944640259... [7;7,7,7,7,7,7,7,7,7,7...] OEIS:A176439 Tin 8 (8 + √68) / 2 8.123105625617661... [8;8,8,8,8,8,8,8,8,8,8...] OEIS:A176458 Lead 9 (9 + √85) / 2 9.109772228646444... [9;9,9,9,9,9,9,9,9,9,9...] OEIS:A176522 There are other ways to find the Metallic ratios; one, (the focus of this task) is through successive approximations of Lucas sequences. A traditional Lucas sequence is of the form: xn = P * xn-1 - Q * xn-2 and starts with the first 2 values 0, 1. For our purposes in this task, to find the metallic ratios we'll use the form: xn = b * xn-1 + xn-2 ( P is set to b and Q is set to -1. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms 1, 1. The initial starting value has very little effect on the final ratio or convergence rate. Perhaps it would be more accurate to call it a Lucas-like sequence. At any rate, when b = 1 we get: xn = xn-1 + xn-2 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When b = 2: xn = 2 * xn-1 + xn-2 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the (n+1)th term by the nth. As n grows larger, the ratio will approach the b metallic ratio. For b = 1 (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the Golden ratio has the slowest possible convergence for any irrational number. Task For each of the first 10 Metallic ratios; b = 0 through 9: Generate the corresponding "Lucas" sequence. Show here, on this page, at least the first 15 elements of the "Lucas" sequence. Using successive approximations, calculate the value of the ratio accurate to 32 decimal places. Show the value of the approximation at the required accuracy. Show the value of n when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the value and number of iterations n, to approximate the Golden ratio to 256 decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. See also Wikipedia: Metallic mean Wikipedia: Lucas sequence
#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 = $this; $n++; } $last, $n }   sub display ($value, $n) { "Approximated value:", $value, "Reached after {$n} iterations: " ~ "{ordinal-digit $n}/{ordinal-digit $n - 1} element." }   for <Platinum Golden Silver Bronze Copper Nickel Aluminum Iron Tin Lead>.kv -> \b, $name { my $lucas = lucas b; print "\nLucas sequence for $name ratio; where b = {b}:\nFirst 15 elements: "; say join ', ', $lucas[^15]; say join ' ', display |metallic($lucas); }   # Stretch goal say join "\n", "\nGolden ratio to 256 decimal places:", display |metallic lucas(1), 256;
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 = [][]int{ {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}} kc = make([]uint16, len(ko)) mid = len(ko) / 2 }   func main() { // Example file used here is Lenna50.jpg from the task "Percentage // difference between images" converted with with the command // convert Lenna50.jpg -colorspace gray Lenna50.ppm // It shows very obvious compression artifacts when viewed at higher // zoom factors. b, err := raster.ReadPpmFile("Lenna50.ppm") if err != nil { fmt.Println(err) return } g0 = b.Grmap() w, h := g0.Extent() g1 = raster.NewGrmap(w, h) for y := 0; y < h; y++ { for x := 0; x < w; x++ { g1.SetPx(x, y, median(x, y)) } } // side by side comparison with input file shows compression artifacts // greatly smoothed over, although at some loss of contrast. err = g1.Bitmap().WritePpmFile("median.ppm") if err != nil { fmt.Println(err) } }   func median(x, y int) uint16 { var n int // construct sorted list as pixels are read. insertion sort can't be // beat for a small number of items, plus there would be lots of overhead // just to get numbers in and out of a library sort routine. for _, o := range ko { // read a pixel of the kernel c, ok := g0.GetPx(x+o[0], y+o[1]) if !ok { continue } // insert it in sorted order var i int for ; i < n; i++ { if c < kc[i] { for j := n; j > i; j-- { kc[j] = kc[j-1] } break } } kc[i] = c n++ } // compute median from sorted list switch { case n == len(kc): // the usual case, pixel with complete neighborhood return kc[mid] case n%2 == 1: // edge case, odd number of pixels return kc[n/2] } // else edge case, even number of pixels m := n / 2 return (kc[m-1] + kc[m]) / 2 }
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; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#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 ? -arr[i]:arr[i] len = length(num)   if (len < 3) { printf("%10s : invalid input: too few digits\n", arr[i]) continue }   if (len % 2 == 0) { printf("%10s : invalid input: even number of digits\n", arr[i]) continue }   printf("%10s : %s\n", arr[i], substr(num, len/2, 3)) } }  
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#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 = zeros(Bool, x, y) numbers = zeros(Int, x, y) visible = zeros(Bool, x, y) for i = 1:x for j = 1:y n = 0 for di = -1:1 for dj = -1:1 n += (0 < di+i <= x && 0 < dj+j <= y) ? (actual_mines[di+i, dj+j] ? 1 : 0) : 0 end end numbers[i, j] = n end end return Field(size, numbers, possible_mines, actual_mines, visible) end   function printfield(f::Field; showall = false) spaces = Int(floor(log(10, f.size[2])))   str = " "^(4+spaces) for i in 1:f.size[1] str *= string(" ", i, " ") end str *= "\n" * " "^(4+spaces) * "___"^f.size[1] * "\n" for j = 1:f.size[2] str *= " " * string(j) * " "^(floor(log(10, j)) > 0 ? 1 : spaces+1) * "|" for i = 1:f.size[1] if showall str *= f.actual_mines[i, j] ? " * " : " " else if f.visible[i, j] str *= " " * string(f.numbers[i, j] > 0 ? f.numbers[i, j] : " ") * " " elseif f.possible_mines[i, j] str *= " ? " else str *= " . " end end end str *= "\r\n" end println("Found " * string(length(f.possible_mines[f.possible_mines.==true])) * " of " * string(length(f.actual_mines[f.actual_mines.==true])) * " mines.\n") print(str) end   function parse_input(str::String) input = split(chomp(str), " ") mode = input[1] println(str) coords = length(input) > 1 ? (parse(Int,input[2]), parse(Int,input[3])) : (0, 0) return mode, coords end   function eval_input(f::Field, str::String) mode, coords = parse_input(str) (coords[1] > f.size[1] || coords[2] > f.size[2]) && return true if mode == "o" reveal(f, coords...) || return false elseif mode == "m" && f.visible[coords...] == false f.possible_mines[coords...] = !f.possible_mines[coords...] elseif mode == "close" error("You closed the game.") end return true end   function reveal(f::Field, x::Int, y::Int) (x > f.size[1] || y > f.size[2]) && return true # check for index out of bounds f.actual_mines[x, y] && return false # check for mines f.visible[x, y] = true if f.numbers[x, y] == 0 for di = -1:1 for dj = -1:1 if (0 < di+x <= f.size[1] && 0 < dj+y <= f.size[2]) && f.actual_mines[x+di, y+dj] == false && f.visible[x+di, y+dj] == false reveal(f, x+di, y+dj) end end end end return true end   function play() print("\nWelcome to Minesweeper\n\nEnter the gridsize x y:\n") s = split(readline(), " ") f = Field(parse.(Int,s)...) won = false while true printfield(f) print("\nWhat do you do? (\"o x y\" to reveal a field; \"m x y\" to toggle a mine; close)\n") eval_input(f, readline()) || break print("_"^80 * "\n") (f.actual_mines == f.possible_mines || f.visible == .!f.actual_mines) && (won = true; break) end println(won ? "You won the game!" : "You lost the game:\n") printfield(f, showall = true) end   play()  
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#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([arr[m - 1][k], arr[m - 1][k - 10 ** m % n]]) r = 10 ** m k = -r % n for j in range((m - 1), 0, -1): if arr[j - 1][k] == 0: r = r + 10 ** j k = (k - 10 ** j) % n if k == 1: r += 1 return r   for n in [i for i in range(1, 11)] + \ [i for i in range(95, 106)] + \ [297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]: result = getA004290(n) print(f"A004290({n}) = {result} = {n} * {result // 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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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 external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#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 external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#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() }   fun main(args: Array<String>) = metronome(120, 4, 20) // limit to 20 beats
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 concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#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)) ), % wait for the workers to finish forall( integer::between(1, Workers, Worker), threaded_exit(worker(Worker)) ), % tell the semaphore thread to stop threaded_notify(worker(stop, _)).   :- public(run/0). run :- % default values: 7 workers, 2 concurrent workers run(7, 2).   semaphore(N, Max) :- threaded_wait(worker(Action, Worker)), ( Action == acquire, N > 0 -> M is N - 1, threaded_notify(semaphore(acquired, Worker)), semaphore(M, Max) ; Action == release -> M is N + 1, threaded_notify(semaphore(released, Worker)), semaphore(M, Max) ; Action == stop -> true ; % Action == acquire, N =:= 0, threaded_wait(worker(release, OtherWorker)), threaded_notify(semaphore(released, OtherWorker)), threaded_notify(semaphore(acquired, Worker)), semaphore(N, Max) ).   worker(Worker) :- % use a random setup time for the worker random::random(0.0, 2.0, Setup), thread_sleep(Setup), threaded_notify(worker(acquire, Worker)), threaded_wait(semaphore(acquired, Worker)), write('Worker '), write(Worker), write(' acquired semaphore\n'), thread_sleep(2), threaded_notify(worker(release, Worker)), write('Worker '), write(Worker), write(' releasing semaphore\n'), threaded_wait(semaphore(released, Worker)).   :- end_object.  
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 concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#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 if sem_getvalue(sem.addr, c) != 0: raise newException(SemaphoreError, "unable to get value of semaphore") result = c   proc acquire(sem: var Sem) = if sem_wait(sem.addr) != 0: raise newException(SemaphoreError, "unable to acquire semaphore")   proc release(sem: var Sem) = if sem_post(sem.addr) != 0: raise newException(SemaphoreError, "unable to get release semaphore")   proc close(sem: var Sem) = if sem_destroy(sem.addr) != 0: raise newException(SemaphoreError, "unable to close the semaphore")   proc task(id: int) {.thread.} = echo &"Task {id} started." while running: sem.acquire() echo &"Task {id} acquired semaphore. Count is {sem.count()}." sleep(2000) sem.release() echo &"Task {id} released semaphore. Count is {sem.count()}." sleep(100) # Give time to other tasks. echo &"Task {id} terminated."   proc stop() {.noconv.} = running = false     var threads: array[10, Thread[int]]   sem.init(4) setControlCHook(stop) # Catch control-C to terminate gracefully.   for n in 0..9: createThread(threads[n], task, n) threads.joinThreads() sem.close()
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 the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#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 /* " " " " " " */ if shuffs=='' | shuffs=="," then shuffs= #%4 /* " " " " " " */ if datatype(seed, 'W') then call random ,,seed /*if integer, use this as a RANDOM seed*/ ok=0 /*the number of "expected" good trials.*/ do trials /*perform a number of trials to be safe*/ call create /*odd numbers≡RED, even numbers≡BLACK.*/ call shuffle /*shuffle the deck a number of times. */ call deal /*put cards into three piles of cards. */ call swap /*swap rand # of cards in R & B piles*/ call count /*count #blacks in B, #reds in R piles*/ end /*trials*/ /*#: is the number of cards in the deck*/ pc= (100*ok/trials)'%' /*calculate the  % asserted correctly.*/ say "Correctness of the mathematician's assertion:" pc ' (out of' commas(trials), "trial"s(trials)') using a deck of ' commas(#) , " card"s(#)', and doing ' commas(shuffs) ' shuffle's(shuffs). exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ?: return random(1, word( arg(1) #, 1) ) /*gen a random number from 1 ──► arg. */ commas: parse arg _; do j=length(_)-3 to 1 by -3; _=insert(',', _, j); end; return _ create: @.=; k=0; do j=1 by 4 for #; k=k+1; @.k= j; if k//13==0 then j=j+1; end; return isRed: return arg(1) // 2 /*if arg(1) is odd, the card is RED.*/ s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1) /*pluralizer.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ count: Rn=0; Bn=0; do j=1 for words(R); Rn=Rn+ isRed(word(R,j)) ; end do k=1 for words(B); Bn=Bn+ (\isRed(word(B,k))); end if Rn==Bn then ok= ok+1; return /*Was it a good trial? Bump OK counter*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ deal: R=; B=; D=; do j=1 for #%2 by 2 /*deal all the cards. */ next= j+1; card= @.next /*obtain the next card. */ if isRed(@.j) then R=R card /*add to the RED pile?*/ else B=B card /* " " " BLACK " */ D= D @.j /* " " " discard " */ end /*j*/ return /*discard pile not used.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ shuffle: do j=1 for shuffs; x=?(); do until y\==x | #==1; y=?(); end /*until*/ parse value @.x @.y with @.y @.x; end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ swap: $= min( words(R), words(B) ); Rc=; Bc= /*ensure we can swap $ cards.*/ if $==0 then return /*A pile has no cards? return*/ do ?($) /*$: is the number of swaps.*/ R?= ?( words(R) ) /*a random card in RED pile.*/ B?= ?( words(B) ) /*" " " " BLACK " */ /* "reds" to be swapped.*/ Rc= Rc word(R, R?); R= delword(R, R?, 1) /*del card*/ /*"blacks" " " " */ Bc= Bc word(B, B?); B= delword(B, B?, 1) /* " " */ end /*?($)*/ R=R Bc; B=B Rc; return /*add swapped cards to piles.*/
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, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#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 ms 750 6265086 16632 1053 ms .. 1500 43205712 67697 6669 ms .. 3000 303314913 264489 65040 ms //2xn -> runtime x9,75 .. 6000 2189067236 1019161 719208 ms //2xn -> runtime x11,0 6250 2451223363 1047116 825486 ms .. 12000 15799915996 3589137 8180177 ms //2xn -> runtime x11,3 12250 16737557137 3742360 8783711 ms 12500 17758426186 4051041 9455371 ms .. 24000 115709049568 13738671 99959526 ms //2xn -> runtime x12 24250 119117015697 13492623 103691559 ms 24500 122795614247 14644721 107758962 ms 24750 126491059919 14708578 111875949 ms 25000 130098289096 14414457 115954691 ms //dt = 4078s ->16s/per number real 1932m34,698s => 1d8h12m35
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, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#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; $index++; return @mc if (push @mc, $test) > $max-1; } }   my @mian_chowla = generate_mc(100); say "First 30 terms in the Mian–Chowla sequence:\n", join(' ', @mian_chowla[ 0..29]), "\nTerms 91 through 100:\n", join(' ', @mian_chowla[90..99]);
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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 end macro    
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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#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; int temp = s; long mod = 1; for (int j = 0; j < temp; ++j) mod = (mod * a) % n; while (temp != n - 1 && mod != 1 && mod != n - 1) { mod = (mod * mod) % n; temp *= 2; }   if (mod != n - 1 && temp % 2 == 0) return false; } return true; } }
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 == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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 2 ;;; Now we need to find BC/DE, but there is no hardware divide ;;; We also need to be somewhat clever so it doesn't take forever inner: push d ; Keep both loop counters safe on the stack push b xchg ; Divisor in HL mov d,b ; Dividend in DE mov e,c lxi b,100h ; B = counter, C = zero double: dad h ; Double divisor inr b ; Increment counter call cdehl ; Dividend <= divisor? jnc double ; If so, keep doubling mov a,b ; Keep counter mov b,c ; BC = 0 push b ; Push result variable on stakc (initial 0) mov b,a ; Restore counter xchg ; HL = dividend, DE = doubled divisor subtr: mov a,l ; Try HL -= DE sub e mov l,a mov a,h sbb d mov h,a xthl ; Get result accumulator from stack cmc ; Flip borrow mov a,l ; Rotate into result ral mov l,a mov a,h ral mov h,a mov a,l ; Retrieve flag rar xthl ; Retrieve rest of divisor jc $+4 ; If borrow, dad d ; Add dividend back into divisor xra a  ; DE >> 1 ora d rar mov d,a mov a,e rar mov e,a dcr b  ; Are we there yet? jnz subtr  ; If not, try another subtraction pop h ; HL = quotient ;;; Division is done, do lookup and subraction lxi d,MM ; Look up M[outer/inner] dad d mov e,m ; E = M[BC/DE] pop b ; Restore BC (n) lxi h,MM dad b mov a,m ; A = M[BC] sub e ; A = M[BC] - M[BC/DE] mov m,a ; M[BC] = A pop d ; Restore DE (k) ;;; Update loops inx d ; k++ call cbcde ; DE <= BC? jnc inner lxi h,MAX call chlbc ; BC <= MAX? jnc outer ;;; Print table lxi d,frst99 call puts lxi h,MM+1 ; Start of Merten numbers mvi c,9 ; Column counter table: mov a,m ; Get Merten number ana a ; Set flags mvi b,' ' ; Space jp prtab ; If positive, print space-number-space mvi b,'-' ; Otherwise, print minus sign cma ; And negate the number (make positive) inr a prtab: adi '0' ; Make ASCII digit mov d,a ; Keep number mov a,b ; Print space or minus sign call putc mov a,d ; Restore number call putc ; Print number mvi a,' ' ; Print space call putc dcr c ; Decrement column counter jnz tnext lxi d,nl ; End of columns - print newline call puts mvi c,10 ; Column counter tnext: inx h ; Table done? mov a,l cpi 100 jnz table ; If not, keep going ;;; Find zeroes and crossings lxi b,0 ; B=zeroes, C=crossings lxi d,MAX ; Counter lxi h,MM+1 count: mov a,m ; Get number ana a ; Zero? jnz cnext inr b ; If so, add zero dcx h ; Previous number also zero? mov a,m inx h ana a jz cnext inr c ; If not, add crossiong cnext: inx h dcx d mov a,d ora e jnz count lxi d,zero ; Print zeroes call puts mov a,b call puta lxi d,cross ; Print crossings call puts mov a,c call puta lxi d,tms jmp puts ;;; Print character in A using CP/M, keeping registers putc: push b push d push h mov e,a mvi c,2 call 5 jmp resrgs ;;; Print number in A, keeping registers puta: push b push d push h lxi h,num putad: mvi c,-1 putal: inr c sui 10 jnc putal adi 10+'0' dcx h mov m,a mov a,c ana a jnz putad xchg mvi c,9 call 5 jmp resrgs ;;; Print string in DE using CP/M, keeping registers puts: push b push d push h mvi c,9 call 5 resrgs: pop h pop d pop b ret cdehl: mov a,d cmp h rnz mov a,e cmp l ret cbcde: mov a,b cmp d rnz mov a,c cmp e ret chlbc: mov a,h cmp b rnz mov a,l cmp c ret ;;; Strings db '***' num: db '$' frst99: db 'First 99 Mertens numbers:',13,10,' $' nl: db 13,10,'$' zero: db 'M(N) is zero $' cross: db ' times.',13,10,'M(N) crosses zero $' tms: db ' times.$' ;;; Numbers are stored page-aligned after program MM: equ ($/256)*256+256
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 == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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+bx],byte 1 ; First Mertens number is 1 outer: inc si ; Next Mertens number mov [si+bx],byte 1 ; Starts out at 1... mov cx,2 ; CX = from 2 to current number, inner: mov ax,si ; Divide current number, xor dx,dx div cx ; By CX mov di,ax mov al,[di+bx] ; Get value at that location sub [si+bx],al ; Subtract from current number inc cx cmp cx,si jbe inner cmp si,MAX jbe outer ;;; Print the table mov dx,frst99 ; First string call outstr mov si,1 ; Start at index 1 mov dh,9 ; Column count table: mov cl,[si+bx] ; Get item test cl,cl mov dl,' ' jns .print ; Positive? mov dl,'-' ; Otherwise, it is negative, neg cl ; print ' ' and negate .print: call putc ; Print space or minus add cl,'0' ; Add ASCII 0 mov dl,cl call putc ; Print number mov dl,' ' call putc ; Print space dec dh ; One less column left jnz .next mov dx,nl ; Print newline call outstr mov dh,10 .next: inc si ; Done yet? cmp si,100 jb table ; If not, print next item from table ;;; Calculate zeroes and crossings xor cx,cx ; CL = zeroes, CH = crossings mov si,1 mov al,[si+bx] ; AL = current item zc: inc si mov ah,al ; AH = previous item mov al,[si+bx] test al,al ; Zero? jnz .next inc cx ; Then increment zero counter test ah,ah ; Previous one also zero? jz .next inc ch ; Then increment crossing counter .next: cmp si,MAX ; Done yet? jbe zc ;;; Print zeroes and crossings mov dx,zero call outstr mov al,cl call putal mov dx,cross call outstr mov al,ch call putal mov dx,tms jmp outstr putc: mov ah,putch ; Print character int 21h ret ;;; Print AL in decimal format putal: mov di,num .loop: aam ; Extract digit add al,'0' ; Store digit dec di mov [di],al mov al,ah ; Rest of number test al,al ; Done? jnz .loop ; If not, get more digits mov dx,di ; Otherwise, print string outstr: mov ah,puts int 21h ret section .data db '***' ; Number output placeholder num: db '$' frst99: db 'First 99 Mertens numbers:',13,10,' $' nl: db 13,10,'$' zero: db 'M(N) is zero $' cross: db ' times.',13,10,'M(N) crosses zero $' tms: db ' times.$' section .bss mm: resb MAX ; Mertens numbers M: equ mm-1 ; 1-based indexing
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 selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#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; CASE prompt IN (STRING prompt):printf(($g" "$, prompt)), (VOID):printf($"Choice ? "$) ESAC; read((choice, new line)); # WHILE # 1 > choice OR choice > UPB items DO SKIP OD; items[choice] ELSE "" FI );   test:( FLEX[0]STRING items := ("fee fie", "huff and puff", "mirror mirror", "tick tock"); STRING prompt := "Which is from the three pigs : ";   printf(($"You chose "g"."l$, menu select(items, prompt))) )
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 load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#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.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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 set ready RTS9 // Request to send CTS9 // Clear to send RI9 // Ring indicator )   func main() { // set some nonsense bits just for example p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
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.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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 the early Greeks, though was not named so until later as a nod to the Golden ratio to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name Metallic ratios (or Metallic means). Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold". Metallic ratios are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer b determines which specific one it is. Using the quadratic equation: ( -b ± √(b2 - 4ac) ) / 2a = x Substitute in (from the top equation) 1 for a, -1 for c, and recognising that -b is negated we get: ( b ± √(b2 + 4) ) ) / 2 = x We only want the real root: ( b + √(b2 + 4) ) ) / 2 = x When we set b to 1, we get an irrational number: the Golden ratio. ( 1 + √(12 + 4) ) / 2 = (1 + √5) / 2 = ~1.618033989... With b set to 2, we get a different irrational number: the Silver ratio. ( 2 + √(22 + 4) ) / 2 = (2 + √8) / 2 = ~2.414213562... When the ratio b is 3, it is commonly referred to as the Bronze ratio, 4 and 5 are sometimes called the Copper and Nickel ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, b can be 0 for a "smaller" ratio than the Golden ratio. We will refer to it here as the Platinum ratio, though it is kind-of a degenerate case. Metallic ratios where b > 0 are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten Metallic ratios are: Metallic ratios Name b Equation Value Continued fraction OEIS link Platinum 0 (0 + √4) / 2 1 - - Golden 1 (1 + √5) / 2 1.618033988749895... [1;1,1,1,1,1,1,1,1,1,1...] OEIS:A001622 Silver 2 (2 + √8) / 2 2.414213562373095... [2;2,2,2,2,2,2,2,2,2,2...] OEIS:A014176 Bronze 3 (3 + √13) / 2 3.302775637731995... [3;3,3,3,3,3,3,3,3,3,3...] OEIS:A098316 Copper 4 (4 + √20) / 2 4.23606797749979... [4;4,4,4,4,4,4,4,4,4,4...] OEIS:A098317 Nickel 5 (5 + √29) / 2 5.192582403567252... [5;5,5,5,5,5,5,5,5,5,5...] OEIS:A098318 Aluminum 6 (6 + √40) / 2 6.16227766016838... [6;6,6,6,6,6,6,6,6,6,6...] OEIS:A176398 Iron 7 (7 + √53) / 2 7.140054944640259... [7;7,7,7,7,7,7,7,7,7,7...] OEIS:A176439 Tin 8 (8 + √68) / 2 8.123105625617661... [8;8,8,8,8,8,8,8,8,8,8...] OEIS:A176458 Lead 9 (9 + √85) / 2 9.109772228646444... [9;9,9,9,9,9,9,9,9,9,9...] OEIS:A176522 There are other ways to find the Metallic ratios; one, (the focus of this task) is through successive approximations of Lucas sequences. A traditional Lucas sequence is of the form: xn = P * xn-1 - Q * xn-2 and starts with the first 2 values 0, 1. For our purposes in this task, to find the metallic ratios we'll use the form: xn = b * xn-1 + xn-2 ( P is set to b and Q is set to -1. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms 1, 1. The initial starting value has very little effect on the final ratio or convergence rate. Perhaps it would be more accurate to call it a Lucas-like sequence. At any rate, when b = 1 we get: xn = xn-1 + xn-2 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When b = 2: xn = 2 * xn-1 + xn-2 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the (n+1)th term by the nth. As n grows larger, the ratio will approach the b metallic ratio. For b = 1 (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the Golden ratio has the slowest possible convergence for any irrational number. Task For each of the first 10 Metallic ratios; b = 0 through 9: Generate the corresponding "Lucas" sequence. Show here, on this page, at least the first 15 elements of the "Lucas" sequence. Using successive approximations, calculate the value of the ratio accurate to 32 decimal places. Show the value of the approximation at the required accuracy. Show the value of n when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the value and number of iterations n, to approximate the Golden ratio to 256 decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. See also Wikipedia: Metallic mean Wikipedia: Lucas sequence
#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 /* " " " " " " */ if bHI=='' | bHI=="," then bHI= 9 /* " " " " " " */ if digs=='' | digs=="," then digs= 32 /* " " " " " " */ numeric digits digs + length(.) /*specify number of decimal digs to use*/ metals= 'platinum golden silver bronze copper nickel aluminum iron tin lead' @decDigs= ' decimal digits past the decimal point:' /*a literal used in SAY.*/ !.= /*the default name for a metallic ratio*/ do k=0 to 9;  !.k= word(metals, k+1) /*assign the (ten) metallic ratio names*/ end /*k*/   do m=bLO to bHI; @.= 1; $= 1 1 /*compute the sequence numbers & ratios*/ r=. /*the ratio (so far). */ do #=2 until r=old; old= r /*compute sequence numbers & the ratio.*/ #_1= #-1; #_2= #-2 /*use variables for previous numbers. */ @.#= m * @.#_1 + @.#_2 /*calculate a number i the sequence. */ if #<n then $= $ @.# /*build a sequence list of N numbers.*/ r= @.# / @.#_1 /*calculate ratio of the last 2 numbers*/ end /*#*/   if words($)<n then $= subword($ copies('1 ', n), 1, n) /*extend list if too short*/ L= max(108, length($) ) /*ensure width of title. */ say center(' Lucas sequence for the'  !.m "ratio, where B is " m' ', L, "═") if n>0 then do; say 'the first ' n " elements are:"; say $ end /*if N is positive, then show N nums.*/ @approx= 'approximate' /*literal (1 word) that is used for SAY*/ r= format(r,,digs) /*limit decimal digits for R to digs.*/ if datatype(r, 'W') then do; r= r/1; @approx= "exact"; end say 'the' @approx "value reached after" #-1 " iterations with " digs @DecDigs say r; say /*display the ration plus a blank line.*/ end /*m*/ /*stick a fork in it, we're all done. */
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; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#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," 220 IF FN L(N) < 3 THEN R$ = R$ + "ONLY " + STR$(FN L(N)) + " DIGIT" + MID$("S",FN L(N) - 1, 1) 230 IF RIGHT$(R$, 1) = "," THEN R$ = LEFT$(R$, LEN(R$) - 1) : RETURN 240 IF LEFT$(R$, 1) = "?" THEN RETURN 250 IF R$ <> "" THEN R$ = "?" + R$ : RETURN 260 R$ = STR$(FN N(N)) 270 IF LEN(R$) = 1 THEN R$ = "00" + R$ 280 IF LEN(R$) = 2 THEN R$ = "0" + R$ 290 RETURN 300 DATA123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345 310 DATA1,2,-1,-10,2002,-2002,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 and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#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)=64 140 for xx=xp to xp+2 150 for yy=yp to yp+2 160 c(xx,yy)=c(xx,yy)+1 170 next yy 180 next xx 190 next i 200 gosub 350 210 x=1:y=1 220 gosub 600 230 ' wait for key press 240 k$=lower$(inkey$) 250 if k$="" then 240 260 if k$="q" and y>1 then gosub 660:y=y-1:gosub 600 270 if k$="a" and y<boardy then gosub 660:y=y+1:gosub 600 280 if k$="o" and x>1 then gosub 660:x=x-1:gosub 600 290 if k$="p" and x<boardx then gosub 660:x=x+1:gosub 600 300 if k$="m" then a(x,y)=a(x,y) xor 128:gosub 600:gosub 1070 310 if k$=" " then a(x,y)=a(x,y) or 512:gosub 700:sx=x:sy=y:gosub 450:x=sx:y=sy:gosub 600 320 goto 240 330 end 340 ' print board 350 mode 1 360 gosub 450 370 locate 1,12 380 print "Move on the board with the Q,A,O,P keys" 390 print "Press Space to clear" 400 print "Press M to mark as a potential mine" 410 print 420 print "There are"nmines"mines." 430 return 440 ' update board 450 for y=1 to boardy 460 for x=1 to boardx 470 locate 2*x,y 480 gosub 530 490 next 500 next 510 return 520 ' print tile 530 if a(x,y) and 128 then print "?":return 540 if c(x+1,y+1)=0 then d$=" " else d$=chr$(c(x+1,y+1)+48) 550 if a(x,y) and 256 then print d$:return 560 'if a(x,y) and 64 then print "M":return 570 print "." 580 return 590 ' turn on tile 600 locate 2*x,y 610 pen 0:paper 1 620 gosub 530 630 pen 1:paper 0 640 return 650 ' turn off tile 660 locate 2*x,y 670 gosub 530 680 return 690 ' clear tile 700 if a(x,y) and 64 then locate 15,20:print "*** BOOM! ***":end 710 locate 1,25:print "-WAIT-"; 720 for x2=1 to boardx 730 for y2=1 to boardy 740 c2(x2+1,y2+1)=a(x2,y2) 750 next 760 next 770 ' iterate clearing 780 cl=0 790 for x2=1 to boardx 800 for y2=1 to boardy 810 if c2(x2+1,y2+1) and 512 then gosub 940:cl=cl+1 820 next y2 830 next x2 840 if cl then 780 850 for x2=1 to boardx 860 for y2=1 to boardy 870 vv=c2(x2+1,y2+1) 880 if vv>1000 then a(x2,y2)=vv xor 1024 890 next y2 900 next x2 910 locate 1,25:print " "; 920 return 930 ' find neighbors 940 c2(x2+1,y2+1)=(c2(x2+1,y2+1) xor 512) or 256 or 1024 950 for ii=0 to 2 960 for jj=0 to 2 970 if ii=0 and jj=0 then 1030 980 if c2(x2+ii,y2+jj) and 64 then 1030 990 if c2(x2+ii,y2+jj) and 128 then 1030 1000 if c2(x2+ii,y2+jj) and 1024 then 1030 1010 c2(x2+ii,y2+jj)=c2(x2+ii,y2+jj) or 512 1020 ' next tile 1030 next jj 1040 next ii 1050 return 1060 ' update discovered mine count 1070 mm=0 1080 for x2=1 to boardx 1090 for y2=1 to boardy 1100 if (a(x2,y2) and 128)>0 and (a(x2,y2) and 64)>0 then mm=mm+1 1110 next 1120 next 1130 if mm=nmines then locate 5,22:print "Congratulations, you've won!":end 1140 return
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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 external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#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 "fill darkblue ; backcolor darkblue ; color white"   tempo = 60 ' per minute interval =1000 /(tempo /60) ' timer works in ms tickCount = 0 ' cycle counter running = 1 ' flag for state bar$ = "HLLL" ' initially strong-weak-weak-weak count = len( bar$)   wait   sub quit w$ close #w$ end end sub   [start] if running =1 then running =0 #w.b1 "Stop" #w.b2 "!disable" #w.b3 "!disable" else running =1 #w.b1 "Start" #w.b2 "!enable" #w.b3 "!enable" end if if running =0 then timer interval, [tick] else timer 0 wait   [tempo] prompt "New tempo 30...360"; tempo$ tempo =val( tempo$) tempo =min( tempo, 360) tempo =max( tempo, 30) interval =int( 1000 /(tempo /60)) wait   [pattern] prompt "New Pattern, eg 'HLLL' "; bar$ count =len( bar$) if count <2 or count >8 then goto [pattern]   wait   [tick] 'beep and flash #w "place 115 40"   if mid$( bar$, tickCount +1, 1) ="H" then playwave "mHi.wav", async #w "backcolor blue ; color white ; circlefilled "; 20 -tickCount *2 else playwave "mLo.wav", async #w "backcolor cyan ; circlefilled "; 20 -tickCount *2 end if   #w "place 50 140 ; backcolor darkblue ; color white" #w "\ "; tempo; " beats /min." #w "place 85 160" #w "\"; bar$   #w "place 85 120" #w "\Beat # "; tickCount +1   #w "place 115 40" #w "color darkblue"   tickCount =( tickCount +1) mod count   #w "flush"   wait
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 concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#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 concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#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 Acquired = false end end if {Not Acquired} then {Wait Sync} {Acquire Sem} end end   proc {Release sem(count:C 'lock':L sync:S ...)} lock L then C := @C - 1 @S = unit %% wake up waiting threads S := _ %% prepare for new waiters end end   proc {WithSemaphore Sem Proc} {Acquire Sem} try {Proc} finally {Release Sem} end end   S = {NewSemaphore 4}   proc {StartWorker Name} thread for do {WithSemaphore S proc {$} {System.showInfo Name#" acquired semaphore"} {Delay 2000} end } {Delay 100} end end end in for I in 1..10 do {StartWorker I} end
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 the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#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.size )) } black_bunch = x.times.map{ black_pile.delete_at( rand( black_pile.size )) }   black_pile += red_bunch red_pile += black_bunch   puts "The magician predicts there will be #{black_pile.count( :black )} red cards in the other pile. Drumroll... There were #{red_pile.count( :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, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#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_is and is[s] then isx = {} exit end if isx = append(isx,s) end for if length(isx) then s = isx[$] if s>len_is then is &= repeat(false,s-len_is) len_is = length(is) end if for k=1 to length(isx) do is[isx[k]] = true end for exit end if j += 1 mc[i] = j end while end for return mc end function atom t0 = time() sequence mc = mian_chowla(100) printf(1,"The first 30 terms of the Mian-Chowla sequence are:\n %V\n",{mc[1..30]}) printf(1,"Terms 91 to 100 of the Mian-Chowla sequence are:\n %V\n",{mc[91..100]}) printf(1,"completed in %s\n",{elapsed(time()-t0)})
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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#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] (if (zero? e) x (if (even? e) (recur (m* b b m) (quot e 2) x) (recur (m* b b m) (quot e 2) (m* b x m))))))   ; Sequence of random numbers to use in the test (defn rand-num [n] " random number between 2 and n-2 " (bigint (math/floor (+' 2 (*' (- n 4) (rand))))))   ; Unique set of random numbers (defn unique-random-numbers [n k] " k unique random numbers between 2 and n-2 " (loop [a-set #{}] (cond (>= (count a-set) k) a-set :else (recur (conj a-set (rand-num n))))))   (defn find-d-s [n] " write n − 1 as 2s·d with d odd " (loop [d (dec n), s 0] (if (odd? d) [d s] (recur (quot d 2) (inc s)))))   (defn random-test ([n] (random-test n (min 1000 (bigint (/ n 2))))) ([n k] " Random version of primality test" (let [[d s] (find-d-s n) ; Individual Primality Test single-test (fn [a s] (let [z (power a d n)] (if (some #{z} [1 (dec n)]) WITNESSLOOP (loop [x (power z 2 n), r s] (cond (= x 1) COMPOSITE (= x (dec n)) WITNESSLOOP (= r 0) COMPOSITE :else (recur (power x 2 n) (dec r)))))))] ; Apply Test ;(not-any? #(= COMPOSITE (local-test % s)) ; (unique-random-numbers n k)))) (not-any? #(= COMPOSITE (single-test % s)) (unique-random-numbers n k)))))   ;; Testing (println "Primes beteen 900-1000:") (doseq [q (range 900 1000) :when (random-test q)] (print " " q)) (println) (println "Is Prime?" 4547337172376300111955330758342147474062293202868155909489 (random-test 4547337172376300111955330758342147474062293202868155909489)) (println "Is Prime?" 4547337172376300111955330758342147474062293202868155909393 (random-test 4547337172376300111955330758342147474062293202868155909393)) (println "Is Prime?" 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 (random-test 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153))   (println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 (random-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153))  
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 == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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 numbers:%E ",count) col=1 FOR i=1 TO count DO StrI(m(i),s) PrintF("%3S",s) col==+1 IF col=10 THEN col=0 PutE() FI OD RETURN   PROC Main() DEFINE MAX="1001" INT ARRAY m(MAX) INT i,zeroCnt=[0],crossCnt=[0],prev=[0]   Put(125) PutE() ;clear the screen PrintF("Calculation of Mertens numbers,%E please wait...") MertensNumbers(m,MAX)   Put(125) PutE() ;clear the screen PrintMertens(m,99)   FOR i=1 TO MAX DO IF m(i)=0 THEN zeroCnt==+1 IF prev THEN crossCnt==+1 FI FI prev=m(i) OD PrintF("%EM(n) is zero %I times for 1<=n<=%I.%E",zeroCnt,MAX-1) PrintF("%EM(n) crosses zero %I times for 1<=n<=%I.%E",crossCnt,MAX-1) RETURN
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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 # print( ( "The first 99 Mertens numbers are:", newline ) ); print( ( " " ) ); INT k := 9; FOR n TO 99 DO print( ( whole( m[ n ], -3 ) ) ); IF ( k -:= 1 ) = 0 THEN k := 10; print( ( newline ) ) FI OD; # Calculate zeroes and crossings # INT zero := 0; INT cross := 0; FOR n FROM 2 TO UPB m DO IF m[ n ] = 0 THEN zero +:= 1; IF m[ n - 1 ] /= 0 THEN cross +:= 1 FI FI OD; print( ( newline ) ); print( ( "M(N) is zero ", whole( zero, -4 ), " times.", newline ) ); print( ( "M(N) crosses zero ", whole( cross, -4 ), " times.", newline ) ) END
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 selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#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 puff" "mirror mirror" "tick tock"]
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 original could now be garbage collected % X := Element( 2, "Helium" )  % the memory allocated will now be garbage collected - there is no explicit de-allocation % end.
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#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 load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#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") |> Seq.groupBy(fun n->n.[0]) |> Map.ofSeq let fN n i g e l=printfn "| %-10s | %-8s | %10s |  %-9s | %-9s |" n i g e l let fG n g=let z=G.[n]|>Seq.sumBy(fun n->try float n.[2] with :? System.FormatException->0.0) fN n g (G.[n]|>Seq.sort|>Seq.last).[1] (if z=0.0 then "" else string z) (if z=0.0 then "" else string(z/(float(Seq.length G.[n]))))  
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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 signalGround : Boolean = OFF, var dataSetReady : Boolean = OFF, var requestToSend : Boolean = OFF, var clearToSend : Boolean = OFF, var ringIndicator : Boolean = OFF ) { fun setPin(n: Int, v: Boolean) { when (n) { 1 -> carrierDetect = v 2 -> receivedData = v 3 -> transmittedData = v 4 -> dataTerminalReady = v 5 -> signalGround = v 6 -> dataSetReady = v 7 -> requestToSend = v 8 -> clearToSend = v 9 -> ringIndicator = v } } }   fun main(args: Array<String>) { val plug = Rs232Pins9(carrierDetect = ON, receivedData = ON) // set first two pins, say println(toOnOff(plug.component2())) // print value of pin 2 by number plug.transmittedData = ON // set pin 3 by name plug.setPin(4, ON) // set pin 4 by number println(toOnOff(plug.component3())) // print value of pin 3 by number println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name }
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 the early Greeks, though was not named so until later as a nod to the Golden ratio to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name Metallic ratios (or Metallic means). Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold". Metallic ratios are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer b determines which specific one it is. Using the quadratic equation: ( -b ± √(b2 - 4ac) ) / 2a = x Substitute in (from the top equation) 1 for a, -1 for c, and recognising that -b is negated we get: ( b ± √(b2 + 4) ) ) / 2 = x We only want the real root: ( b + √(b2 + 4) ) ) / 2 = x When we set b to 1, we get an irrational number: the Golden ratio. ( 1 + √(12 + 4) ) / 2 = (1 + √5) / 2 = ~1.618033989... With b set to 2, we get a different irrational number: the Silver ratio. ( 2 + √(22 + 4) ) / 2 = (2 + √8) / 2 = ~2.414213562... When the ratio b is 3, it is commonly referred to as the Bronze ratio, 4 and 5 are sometimes called the Copper and Nickel ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, b can be 0 for a "smaller" ratio than the Golden ratio. We will refer to it here as the Platinum ratio, though it is kind-of a degenerate case. Metallic ratios where b > 0 are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten Metallic ratios are: Metallic ratios Name b Equation Value Continued fraction OEIS link Platinum 0 (0 + √4) / 2 1 - - Golden 1 (1 + √5) / 2 1.618033988749895... [1;1,1,1,1,1,1,1,1,1,1...] OEIS:A001622 Silver 2 (2 + √8) / 2 2.414213562373095... [2;2,2,2,2,2,2,2,2,2,2...] OEIS:A014176 Bronze 3 (3 + √13) / 2 3.302775637731995... [3;3,3,3,3,3,3,3,3,3,3...] OEIS:A098316 Copper 4 (4 + √20) / 2 4.23606797749979... [4;4,4,4,4,4,4,4,4,4,4...] OEIS:A098317 Nickel 5 (5 + √29) / 2 5.192582403567252... [5;5,5,5,5,5,5,5,5,5,5...] OEIS:A098318 Aluminum 6 (6 + √40) / 2 6.16227766016838... [6;6,6,6,6,6,6,6,6,6,6...] OEIS:A176398 Iron 7 (7 + √53) / 2 7.140054944640259... [7;7,7,7,7,7,7,7,7,7,7...] OEIS:A176439 Tin 8 (8 + √68) / 2 8.123105625617661... [8;8,8,8,8,8,8,8,8,8,8...] OEIS:A176458 Lead 9 (9 + √85) / 2 9.109772228646444... [9;9,9,9,9,9,9,9,9,9,9...] OEIS:A176522 There are other ways to find the Metallic ratios; one, (the focus of this task) is through successive approximations of Lucas sequences. A traditional Lucas sequence is of the form: xn = P * xn-1 - Q * xn-2 and starts with the first 2 values 0, 1. For our purposes in this task, to find the metallic ratios we'll use the form: xn = b * xn-1 + xn-2 ( P is set to b and Q is set to -1. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms 1, 1. The initial starting value has very little effect on the final ratio or convergence rate. Perhaps it would be more accurate to call it a Lucas-like sequence. At any rate, when b = 1 we get: xn = xn-1 + xn-2 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When b = 2: xn = 2 * xn-1 + xn-2 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the (n+1)th term by the nth. As n grows larger, the ratio will approach the b metallic ratio. For b = 1 (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the Golden ratio has the slowest possible convergence for any irrational number. Task For each of the first 10 Metallic ratios; b = 0 through 9: Generate the corresponding "Lucas" sequence. Show here, on this page, at least the first 15 elements of the "Lucas" sequence. Using successive approximations, calculate the value of the ratio accurate to 32 decimal places. Show the value of the approximation at the required accuracy. Show the value of n when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the value and number of iterations n, to approximate the Golden ratio to 256 decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. See also Wikipedia: Metallic mean Wikipedia: Lucas sequence
#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(xn1) } end end   # Compute the Metallic Ratio to 'precision' from the Lucas Sequence for 'b'. # (Uses the lucas(b) iterator, above.) # The metallic ratio is approximated by x(n) / x(n-1). # Returns a struct of the approximate metallic ratio (.ratio) and the # number of terms required to achieve the given precision (.terms).   def metallic_ratio(b, precision) xn2 = xn1 = prev = this = 0 lucas(b).each.with_index do |xn, inx| case inx when 0 xn2 = BigDecimal(xn) when 1 xn1 = BigDecimal(xn) prev = xn1.div(xn2, 2 * precision).round(precision) else xn2, xn1 = xn1, BigDecimal(xn) this = xn1.div(xn2, 2 * precision).round(precision) return Struct.new(:ratio, :terms).new(prev, inx - 1) if prev == this prev = this end end end   NAMES = [ 'Platinum', 'Golden', 'Silver', 'Bronze', 'Copper', 'Nickel', 'Aluminum', 'Iron', 'Tin', 'Lead' ]   puts puts('Lucas Sequences...') puts('%1s  %s' % ['b', 'sequence']) (0..9).each do |b| puts('%1d  %s' % [b, lucas(b).first(15)]) end   puts puts('Metallic Ratios to 32 places...') puts('%-9s %1s %3s  %s' % ['name', 'b', 'n', 'ratio']) (0..9).each do |b| rn = metallic_ratio(b, 32) puts('%-9s %1d %3d  %s' % [NAMES[b], b, rn.terms, rn.ratio.to_s('F')]) end   puts puts('Golden Ratio to 256 places...') puts('%-9s %1s %3s  %s' % ['name', 'b', 'n', 'ratio']) gold_rn = metallic_ratio(1, 256) puts('%-9s %1d %3d  %s' % [NAMES[1], 1, gold_rn.terms, gold_rn.ratio.to_s('F')])
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 = image.graphics g.color = c g.fillRect(0, 0, image.width, image.height) }   fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())   fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))   fun medianFilter(windowWidth: Int, windowHeight: Int) { val window = Array(windowWidth * windowHeight) { Color.black } val edgeX = windowWidth / 2 val edgeY = windowHeight / 2 val compareByLuminance = { c: Color -> 0.2126 * c.red + 0.7152 * c.green + 0.0722 * c.blue } for (x in edgeX until image.width - edgeX) { for (y in edgeY until image.height - edgeY) { var i = 0 for (fx in 0 until windowWidth) { for (fy in 0 until windowHeight) { window[i] = getPixel(x + fx - edgeX, y + fy - edgeY) i++ } } window.sortBy(compareByLuminance) setPixel(x, y, window[windowWidth * windowHeight / 2]) } } } }   fun main(args: Array<String>) { val img = ImageIO.read(File("Medianfilterp.png")) val bbs = BasicBitmapStorage(img.width / 2, img.height) with (bbs) { for (y in 0 until img.height) { for (x in 0 until img.width / 2) { setPixel(x, y, Color(img.getRGB(x, y))) } } medianFilter(3, 3) val mfFile = File("Medianfilterp2.png") ImageIO.write(image, "png", mfFile) } }
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; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#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 Procedure ==% :middle3   set str=%1 %== Making sure that str is positive ==% if !str! lss 0 set /a str*=-1   %== Alternative for finding the string length ==% %== But this has a limit of 1000 characters ==% set leng=0&if not "!str!"=="" for /l %%. in (0,1,1000) do if not "!str:~%%.,1!"=="" set /a leng+=1   if !leng! lss 3 ( echo.%~1: [ERROR] Input too small. goto :EOF )   set /a "test2=leng %% 2,trimmer=(leng - 3) / 2"   if !test2! equ 0 ( echo.%~1: [ERROR] Even number of digits. goto :EOF )   %== Passed the tests. Now, really find the middle 3 digits... ==% if !trimmer! equ 0 ( echo.%~1: !str! ) else ( echo.%~1: !str:~%trimmer%,-%trimmer%! ) goto :EOF %==/The Procedure ==%
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 and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#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%, i%, j%, used%, acc%, n%, m% mines%=max.data(random(int(columns*rows*.1),int(columns*rows*.2)-1), 1) For i%=1 to rows:For j%=1 to columns Board$(i%,j%)=". " Next j%:Next i% used%=mines% While used% used%-- Do i%=random(1,rows) j%=random(1, columns) Until right$(Board$(i%,j%),1)=" " Board$(i%,j%)=".*" End While used%=rows*columns-mines% \\ remove rem so to never loose from first open Rem : swap_first%=used% \\ when mines%=0 or used%=0 then player win Report {Minesweeper - rosettacode task Commands: -  ? 1 2 flag/unflag 1 2 - 1 2 open 1 2 - q to quit You can pass multiple commands in a line, but q erase all before execute } top_where=Row While not End_Game {GameLoop()} End Sub PrintBoard() Cls, top_where Print Print " X "; For j%=1 to columns { Print format$("{0::-3} ", j%); } Print For i%=1 to rows { Print format$(" {0::-3} ", i%); For j%=1 to columns { Print " ";Left$(Board$(i%,j%),1);" "; \\ rem above and unrem follow line to display mines Rem: Print " ";Board$(i%,j%)+" "; } Print } End Sub Sub PrintMines() Cls, top_where Print Print " X "; For j%=1 to columns { Print format$("{0::-3} ", j%); } Print For i%=1 to rows { Print format$(" {0::-3} ", i%); For j%=1 to columns { Print " ";Right$(Board$(i%,j%),1);" "; } Print } End Sub Sub GameLoop() Local com$, loopagain as boolean PrintBoard() InputCommand() do loopagain=true while not empty \\ process game command Read com$ if com$="q " Then Print "Quit" : end_game=True : exit Else.if com$="o " Then OpenCell() Else.if com$="n " Then OpenCell2() Else.if com$="? " Then SwapCell() Else.if com$="c " Then Exit Sub End if End While If mines%=0 or used%=0 then PrintBoard(): Print "Player Win": end_game=True: Exit Sub End if If mines%=-1 then if swap_first%=used% then mines%=rows*columns-used% Local n%, m% While mines% Let n%=random(1,rows), m%=random(1, columns) If Board$(n%, m%)=". " then Board$(n%, m%)=".*" : mines%=0 End While Board$(i%, j%)=". " mines%=rows*columns-used% swap_first%=-100 Push i%, j%, "o " loopagain=false else PrintMines(): Print "Player Loose": end_game=True : Exit Sub end if End If Until loopagain Flush Refresh if(End_Game->10,1000) End Sub Sub InputCommand() where=row While com$="" cls, where Print "x x | ? x x | q >"; Refresh 10 Try { Input "", com$ } End While x=1 Flush While com$<>"" com_label$="" ParseCommand() if len(com_label$)<>2 then com$="" : Print com_label$ : Flush Refresh 10 push key$ : drop else Data com_label$, b_col, b_row End if End While Refresh 1000 End Sub Sub ParseCommand() com_label$="o " skiptest=true ReadColumn() if len(com_label$)<>2 then com$="" Else.if x=-1 then com_label$=lcase$(Left$(com$,1))+" " com$=mid$(com$, 2) x=1 if len(com_label$)<>2 then com_label$="no command found" else.if com_label$="? " then ReadColumn() if x>-1 then ReadRow() else.if com_label$="c " then cheat=true else.if com_label$="q " then flush com$="" else com_label$="Use q or ? for commands" com$="" End if else ReadRow() if x>-1 then com_label$="o " End if End Sub Sub ReadRow() com$=mid$(com$,x) b_row=val(com$, "??", x) if x=-1 then com_label$="Need a row" else.if b_row<1 or b_row>rows then com_label$="Need a row from 1 to "+str$(rows) x=-1 else com$=mid$(com$,x+1) x=1 End if End Sub Sub ReadColumn() com$=mid$(com$,x) b_col=val(com$, "??", x) if x=-1 then if not skiptest then com_label$="Need a column" else.if b_col<1 or b_col>columns then com_label$="Need a column from 1 to"+str$(columns) else com$=mid$(com$,x+1) x=1 End if skiptest=false End Sub Sub SwapCell() Read j%, i% If left$(Board$(i%,j%),1)="?" then Board$(i%,j%) ="."+Right$(Board$(i%,j%),1) If cheat Then if Right$(Board$(i%,j%),1)="*" then mines%++ Else.If left$(Board$(i%,j%),1)="." then Board$(i%,j%) ="?"+Right$(Board$(i%,j%),1) If cheat Then if Right$(Board$(i%,j%),1)="*" then mines%-- End if End Sub Sub OpenCell() Read j%, i% If left$(Board$(i%,j%),1)="." then { if Right$(Board$(i%,j%),1)="*" then mines%=-1 : flush : exit acc%=0 used%-- Local n%, m% For n%=i%-1 to i%+1 { For m%=j%-1 to j%+1 { If Right$(Board$(n%,m%),1)="*" then acc%++ } } For n%=i%-1 to i%+1 { For m%=j%-1 to j%+1 { if not (n%=i% and m%=j%) then if not Right$(Board$(n%,m%),1)="*" then If left$(Board$(n%,m%),1)="." then Push n%, m%, "n " ' reverse to stack Rem : Print stack.size : Refresh End If End If End If } } Board$(i%,j%)=if$(acc%=0->" ",str$(acc%, "# ")) } End Sub Sub OpenCell2() Read J%, i% If left$(Board$(i%,j%),1)="." then { if Right$(Board$(i%,j%),1)="*" then exit acc%=0 used%-- For n%=i%-1 to i%+1 { For m%=j%-1 to j%+1 { If Right$(Board$(n%,m%),1)="*" then acc%++ } } \\ if cell has no mines around then we check all if acc%=0 then Local n%, m% For n%=i%-1 to i%+1 For m%=j%-1 to j%+1 if not (n%=i% and m%=j%) then if not Right$(Board$(n%,m%),1)="*" then If left$(Board$(n%,m%),1)="." then Push n%, m%, "o " ' reverse to stack Rem : Print stack.size : Refresh End If End If End If Next m% Next n% End If Board$(i%,j%)=if$(acc%=0->" ",str$(acc%, "# ")) } End Sub } Minesweeper  
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#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 ', w, "─")   do i=1 for words(list) z= word(list, i); LO= z; HI= z if pos(.., z)\==0 then parse var z LO '..' HI   do n=LO to HI; m= B10(n) say right(commas(n), 9) right(commas(n*m), w) left(commas(m), w) end /*n*/ end /*i*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do c=length(_)-3 to 1 by -3; _= insert(',', _, c); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ B10: parse arg #; inc= 1; start= 1; L= length(#) select when verify(#, 10)==0 then return 1 when verify(#, 9)==0 then do; start= do k= 1 for 8 start= start || copies(k, L) end /*k*/ end when #//2==0 then do; start=5; inc= 5; end when right(z, 1)==7 then do; start=3; inc= 10; end otherwise nop end /*select*/ q= length(start) if q>digits() then numeric digits q do m=start by inc until verify(p, 10)==0; p= # * m end /*m*/ return 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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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 2351399303373464486466122544523690094744975233415544072992656881240319 10 40 ** **mod echo
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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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 external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#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 concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#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(task_self()) sems[id][QUEUE] &= task_self() task_yield() end if sems[id][COUNTER] -= 1 end procedure procedure release(integer id) sems[id][COUNTER] += 1 if length(sems[id][QUEUE])>0 then task_schedule(sems[id][QUEUE][1],1) sems[id][QUEUE] = sems[id][QUEUE][2..$] end if end procedure function count(integer id) return sems[id][COUNTER] end function procedure delay(atom delaytime) atom t = time() while time()-t<delaytime do task_yield() end while end procedure integer sem = semaphore(4) procedure worker() acquire(sem) printf(1,"- Task %d acquired semaphore.\n",task_self()) delay(2) release(sem) printf(1,"+ Task %d released semaphore.\n",task_self()) end procedure for i=1 to 10 do integer task = task_create(routine_id("worker"),{}) task_schedule(task,1) task_yield() end for integer sc = 0 atom t0 = time()+1 while length(task_list())>1 do task_yield() integer scnew = count(sem) if scnew!=sc or time()>t0 then sc = scnew printf(1,"Semaphore count now %d\n",{sc}) t0 = time()+2 end if end while ?"done" {} = wait_key()
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 { print!(" ") } else { print!("{:3} ", j * i) } } println!("| {}", 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 the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#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)) .collect();   rng.shuffle(&mut deck);   let mut black_stack = vec![]; let mut red_stack = vec![]; let mut discarded = vec![];   //Deal our cards. print!("Discarding:"); while let (Some(card), Some(next)) = (deck.pop(), deck.pop()) { print!(" {}", if card == Black { "B" } else { "R" }); match card { Red => red_stack.push(next), Black => black_stack.push(next), } discarded.push(card); } println!();   // Choose how many to swap. let max = red_stack.len().min(black_stack.len()); let num = rng.gen_range(1, max); println!("Exchanging {} cards", num);   // Actually swap our cards. for _ in 0..num { let red = rng.choose_mut(&mut red_stack).unwrap(); let black = rng.choose_mut(&mut black_stack).unwrap(); std::mem::swap(red, black); }   //Count how many are red and black. let num_black = black_stack.iter() .filter(|&c| c == &Black) .count(); let num_red = red_stack.iter() .filter(|&c| c == &Red) .count();   println!("Number of black cards in black stack: {}", num_black); println!("Number of red cards in red stack: {}", num_red); }
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 the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#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 = [] var black = [] var discard = [] var i = 0 while (i < 51) { if (pack[i] == B) { black.add(pack[i+1]) } else { red.add(pack[i+1]) } discard.add(pack[i]) i = i + 2 } var lr = red.count var lb = black.count var ld = discard.count System.print("After dealing the cards the state of the stacks is:") Fmt.print(" Red  : $2d cards -> $c", lr, red) Fmt.print(" Black  : $2d cards -> $c", lb, black) Fmt.print(" Discard: $2d cards -> $c", ld, discard)   // Swap the same, random, number of cards between the red and black stacks. var min = (lr < lb) ? lr : lb var n = rand.int(1, min + 1) var rp = [0] * lr var bp = [0] * lb for (i in 0...lr) rp[i] = i for (i in 0...lb) bp[i] = i rand.shuffle(rp) rand.shuffle(bp) rp = rp[0...n] bp = bp[0...n] System.print("\n%(n) card(s) are to be swapped.\n") System.print("The respective zero-based indices of the cards(s) to be swapped are:") Fmt.print(" Red  : $2d", rp) Fmt.print(" Black  : $2d", bp) for (i in 0...n) { var t = red[rp[i]] red[rp[i]] = black[bp[i]] black[bp[i]] = t } System.print("\nAfter swapping, the state of the red and black stacks is:") Fmt.print(" Red  : $c", red) Fmt.print(" Black  : $c", black)   // Check that the number of black cards in the black stack equals // the number of red cards in the red stack. var rcount = red.count { |c| c == R } var bcount = black.count { |c| c == B } System.print("\nThe number of red cards in the red stack = %(rcount)") System.print("The number of black cards in the black stack = %(bcount)") if (rcount == bcount) { System.print("So the asssertion is correct!") } else { System.print("So the asssertion is incorrect!") }
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, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#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() break newsums.add(sum) else: psums |= newsums newsums.clear() mc.append(trial) yield trial   def pretty(p, t, s, f): print(p, t, " ".join(str(n) for n in (islice(mian_chowla(), s, f))))   if __name__ == '__main__': st = time.time() ts = "of the Mian-Chowla sequence are:\n" pretty("The first 30 terms", ts, 0, 30) pretty("\nTerms 91 to 100", ts, 90, 100) print("\nComputation time was", (time.time()-st) * 1000, "ms")
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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#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 primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#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 190 S = 0 200 D = D / 2: S = S + 1 210 IF 0 = (D AND 1) THEN 200 220 P = 1 230 FOR I = 1 TO K 240 : A = INT(RND(.) * (N - 2)) + 2 250 : X = 1 260 : FOR J = 1 TO D 270 : X = FNMD(X * A) 280 : NEXT J 290 : IF (X = 1) OR (X = (N - 1)) THEN 360 300 : FOR J = 1 TO S - 1 310 : X = FNMD(X * X) 320 : IF X = 1 THEN P = 0: GOTO 370 330 : IF X = N - 1 THEN 360 340 : NEXT J 350 : P = 0: GOTO 370 360 NEXT I 370 P = P * (1 - 1 / (4 * K)) 380 IF P THEN PRINT "PROBABLY PRIME ( P >="; P; ")": END 390 PRINT "COMPOSITE."
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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 ) := M( n ) - M( n div k ) end for_n ;  % Print table  % write( "The first 99 Mertens numbers are:" ); write( " " ); k := 9; for n := 1 until 99 do begin writeon( i_w := 3, s_w := 0, M( n ) ); k := k - 1; if k = 0 then begin k := 10; write() end if_k_eq_0 end for_n ;  % Calculate zeroes and crossings  % zero  := 0; cross := 0; for n :=2 until 1000 do begin if M( n ) = 0 then begin zero := zero + 1; if M( n - 1 ) not = 0 then cross := cross + 1 end if_M_n_eq_0 end for_n ; write( i_w := 2, s_w := 0, "M(N) is zero ", zero, " times." ); write( i_w := 2, s_w := 0, "M(N) crosses zero ", cross, " times." ) end.
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 == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#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 selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#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 ? len*7 , % 120 + x.count()*20 return x[Choice] }
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 load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#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] = lastName patientIds = append(patientIds, id) sort.Ints(patientIds) return Patient{id, lastName} }   type DS struct { dates []string scores []float64 }   type Visit struct { id int date string score float64 }   // maps an id to lists of dates and scores var visitDir = make(map[int]DS)   func visitNew(id int, date string, score float64) Visit { if date == "" { date = "0000-00-00" } v, ok := visitDir[id] if ok { v.dates = append(v.dates, date) v.scores = append(v.scores, score) visitDir[id] = DS{v.dates, v.scores} } else { visitDir[id] = DS{[]string{date}, []float64{score}} } return Visit{id, date, score} }   type Merge struct{ id int }   func (m Merge) lastName() string { return patientDir[m.id] } func (m Merge) dates() []string { return visitDir[m.id].dates } func (m Merge) scores() []float64 { return visitDir[m.id].scores }   func (m Merge) lastVisit() string { dates := m.dates() dates2 := make([]string, len(dates)) copy(dates2, dates) sort.Strings(dates2) return dates2[len(dates2)-1] }   func (m Merge) scoreSum() float64 { sum := 0.0 for _, score := range m.scores() { if score != -1 { sum += score } } return sum }   func (m Merge) scoreAvg() float64 { count := 0 for _, score := range m.scores() { if score != -1 { count++ } } return m.scoreSum() / float64(count) }   func mergePrint(merges []Merge) { fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |") f := "| %d | %-7s | %s | %4s | %4s |\n" for _, m := range merges { _, ok := visitDir[m.id] if ok { lv := m.lastVisit() if lv == "0000-00-00" { lv = " " } scoreSum := m.scoreSum() ss := fmt.Sprintf("%4.1f", scoreSum) if scoreSum == 0 { ss = " " } scoreAvg := m.scoreAvg() sa := " " if !math.IsNaN(scoreAvg) { sa = fmt.Sprintf("%4.2f", scoreAvg) } fmt.Printf(f, m.id, m.lastName(), lv, ss, sa) } else { fmt.Printf(f, m.id, m.lastName(), " ", " ", " ") } } }   func main() { patientNew(1001, "Hopper") patientNew(4004, "Wirth") patientNew(3003, "Kemeny") patientNew(2002, "Gosling") patientNew(5005, "Kurtz")   visitNew(2002, "2020-09-10", 6.8) visitNew(1001, "2020-09-17", 5.5) visitNew(4004, "2020-09-24", 8.4) visitNew(2002, "2020-10-08", -1) // -1 signifies no score visitNew(1001, "", 6.6) // "" signifies no date visitNew(3003, "2020-11-12", -1) visitNew(4004, "2020-11-05", 7.0) visitNew(1001, "2020-11-19", 5.3)   merges := make([]Merge, len(patientIds)) for i, id := range patientIds { merges[i] = Merge{id} } mergePrint(merges) }
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.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#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))   rs232 =   carrier_detect: 1 received_data: 1 transmitted_data: 1 data_terminal_ready: 1 signal_ground: 1 data_set_ready: 1 request_to_send: 1 clear_to_send: 1 ring_indicator: 1   >> struct2cell(rs232)   ans =   [1] [1] [1] [1] [1] [1] [1] [1] [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 the early Greeks, though was not named so until later as a nod to the Golden ratio to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name Metallic ratios (or Metallic means). Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold". Metallic ratios are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer b determines which specific one it is. Using the quadratic equation: ( -b ± √(b2 - 4ac) ) / 2a = x Substitute in (from the top equation) 1 for a, -1 for c, and recognising that -b is negated we get: ( b ± √(b2 + 4) ) ) / 2 = x We only want the real root: ( b + √(b2 + 4) ) ) / 2 = x When we set b to 1, we get an irrational number: the Golden ratio. ( 1 + √(12 + 4) ) / 2 = (1 + √5) / 2 = ~1.618033989... With b set to 2, we get a different irrational number: the Silver ratio. ( 2 + √(22 + 4) ) / 2 = (2 + √8) / 2 = ~2.414213562... When the ratio b is 3, it is commonly referred to as the Bronze ratio, 4 and 5 are sometimes called the Copper and Nickel ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, b can be 0 for a "smaller" ratio than the Golden ratio. We will refer to it here as the Platinum ratio, though it is kind-of a degenerate case. Metallic ratios where b > 0 are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten Metallic ratios are: Metallic ratios Name b Equation Value Continued fraction OEIS link Platinum 0 (0 + √4) / 2 1 - - Golden 1 (1 + √5) / 2 1.618033988749895... [1;1,1,1,1,1,1,1,1,1,1...] OEIS:A001622 Silver 2 (2 + √8) / 2 2.414213562373095... [2;2,2,2,2,2,2,2,2,2,2...] OEIS:A014176 Bronze 3 (3 + √13) / 2 3.302775637731995... [3;3,3,3,3,3,3,3,3,3,3...] OEIS:A098316 Copper 4 (4 + √20) / 2 4.23606797749979... [4;4,4,4,4,4,4,4,4,4,4...] OEIS:A098317 Nickel 5 (5 + √29) / 2 5.192582403567252... [5;5,5,5,5,5,5,5,5,5,5...] OEIS:A098318 Aluminum 6 (6 + √40) / 2 6.16227766016838... [6;6,6,6,6,6,6,6,6,6,6...] OEIS:A176398 Iron 7 (7 + √53) / 2 7.140054944640259... [7;7,7,7,7,7,7,7,7,7,7...] OEIS:A176439 Tin 8 (8 + √68) / 2 8.123105625617661... [8;8,8,8,8,8,8,8,8,8,8...] OEIS:A176458 Lead 9 (9 + √85) / 2 9.109772228646444... [9;9,9,9,9,9,9,9,9,9,9...] OEIS:A176522 There are other ways to find the Metallic ratios; one, (the focus of this task) is through successive approximations of Lucas sequences. A traditional Lucas sequence is of the form: xn = P * xn-1 - Q * xn-2 and starts with the first 2 values 0, 1. For our purposes in this task, to find the metallic ratios we'll use the form: xn = b * xn-1 + xn-2 ( P is set to b and Q is set to -1. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms 1, 1. The initial starting value has very little effect on the final ratio or convergence rate. Perhaps it would be more accurate to call it a Lucas-like sequence. At any rate, when b = 1 we get: xn = xn-1 + xn-2 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When b = 2: xn = 2 * xn-1 + xn-2 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the (n+1)th term by the nth. As n grows larger, the ratio will approach the b metallic ratio. For b = 1 (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the Golden ratio has the slowest possible convergence for any irrational number. Task For each of the first 10 Metallic ratios; b = 0 through 9: Generate the corresponding "Lucas" sequence. Show here, on this page, at least the first 15 elements of the "Lucas" sequence. Using successive approximations, calculate the value of the ratio accurate to 32 decimal places. Show the value of the approximation at the required accuracy. Show the value of n when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the value and number of iterations n, to approximate the Golden ratio to 256 decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. See also Wikipedia: Metallic mean Wikipedia: Lucas sequence
#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 say "Lucas sequence U_n(#{k},-1) for #{v} ratio" var f = {|n| lucasu(k, -1, n) } say ("First 15 elements: ", 15.of(f).join(', ')) var (n, r) = seqRatio(f) say "Approximated value: #{r} reached after #{n} iterations" say '' }   with (seqRatio({|n| fib(n) }, 256)) {|n,v| say "Golden ratio to 256 decimal places:" say "Approximated value: #{v}" say "Reached after #{n} iterations" }
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 edgeY = windowHeight div 2   for x in edgeX..<(img.width - edgeX): for y in edgeY..<(img.height - edgeY): var i = 0 for fx in 0..<windowWidth: for fy in 0..<windowHeight: window[i] = img[x + fx - edgeX, y + fy - edgeY] inc i window = window.sortedByIt(luminance(it)) img[x, y] = window[windowWidth * windowHeight div 2]     when isMainModule: let fullImage = loadImage[ColorRGBF64]("Medianfilterp.png") # Extract left part of the image. var image = fullImage[0..<(fullImage.width div 2), 0..<fullImage.height] image.applyMedianFilter(3, 3) savePNG(image, "Medianfilterp_3x3.png")
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#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 and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#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 = ArrayPad[ Total[RotateLeft[ ArrayPad[minesdata, 1], #] & /@ {{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}], -1]; grid = Array[{If[minesdata[[#1, #2]] == 1, "*", adjacentmines[[#1, #2]]], ".", 1} &, {m, n}]; win = ""]; clear[i_, j_] := If[grid[[i, j, 1]] == "*", win = "You lost."; grid = grid /. {{n_Integer, "?", _} :> {n, "x", 0}, {"*", ".", _} :> {"*", "*", 0}}, grid[[i, j]] = {grid[[i, j, 1]], grid[[i, j, 1]], 0}; If[grid[[i, j, 2]] == 0, grid[[i, j, 2]] = ""; clear[i + #[[1]], j + #[[2]]] & /@ {{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}]] /; 1 <= i <= m && 1 <= j <= n && grid[[i, j, 2]] == "."; checkwin[] := If[FreeQ[grid, {_Integer, "?", _} | {_, "*", _} | {_Integer, ".", _}], win = "You win."; grid = grid /. {{"*", ".", _} :> {"*", "?", 1}}]; reset[]; Panel@Column@{Row@{Dynamic@minecount, "\t", Button["Reset", reset[]]}, Grid[Table[ With[{i = i, j = j}, EventHandler[ Button[Dynamic[grid[[i, j, 2]]], Null, ImageSize -> {17, 17}, Appearance -> Dynamic[If[grid[[i, j, 3]] == 0, "Pressed", "DialogBox"]]], {{"MouseClicked", 1} :> If[win == "", clear[i, j]; checkwin[]], {"MouseClicked", 2} :> If[win == "", Switch[grid[[i, j, 2]], ".", grid[[i, j, 2]] = "?"; minecount--, "?", grid[[i, j, 2]] = "."; minecount++]; checkwin[]]}]], {i, 1, m}, {j, 1, n}], Spacings -> {0, 0}], Dynamic[win]}]
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 positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#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 nplus = nplus + 1 if nplus < lenplus+1 n = plus[nplus] else exit ok ok for m = 1 to limit2 flag = 1 prod = n*m pstr = string(prod) for p = 1 to len(pstr) if not(pstr[p] = "0" or pstr[p] = "1") flag = 0 exit ok next if flag = 1 see "" + n + " * " + m + " = " + pstr + nl exit ok next if n = 10 n = 94 ok next   see "done..." + nl  
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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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, 2351399303373464486466122544523690094744975233415544072992656881240319, 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 = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#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= 2351399303373464486466122544523690094744975233415544072992656881240319 if m ='' | m ="," then m= 40 /*Not specified? Then use default.*/ say 'a=' a " ("length(a) 'digits)' /*display the value of A (&length)*/ say 'b=' b " ("length(b) 'digits)' /* " " " " B " */ do j=1 for words(m); y= word(m, j) /*use one of the MM powers (list).*/ say copies('═', linesize() - 1) /*show a nice separator fence line*/ say 'a**b (mod 10**'y")=" powerMod(a,b,10**y) /*display the answer ───► console.*/ end /*j*/ exit 0 /*stick a fork in it, we're done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ powerMod: procedure; parse arg x,p,mm /*fast modular exponentiation code*/ parse value max(x*x, p, mm)'E0' with "E" e /*obtain the biggest of the three.*/ numeric digits max(40, e+e) /*ensure big enough to handle A².*/ $= 1 /*use this for the first value. */ do until p==0 /*perform until P is equal to zero*/ if p // 2 then $= $ * x // mm /*is P odd? (is ÷ remainder ≡ 1?)*/ p= p % 2; x= x * x // mm /*halve P; calculate x² mod n */ end /*until*/; return $ /* [↑] keep mod'ing until P=zero.*/
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 external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#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] , EmitSound[s] ]; Pause[slp]; ]
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 external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#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 concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#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(task_self()) sems[id][QUEUE] &= task_self() task_yield() end if sems[id][COUNTER] -= 1 end procedure procedure release(integer id) sems[id][COUNTER] += 1 if length(sems[id][QUEUE])>0 then task_schedule(sems[id][QUEUE][1],1) sems[id][QUEUE] = sems[id][QUEUE][2..$] end if end procedure function count(integer id) return sems[id][COUNTER] end function procedure delay(atom delaytime) atom t = time() while time()-t<delaytime do task_yield() end while end procedure integer sem = semaphore(4) procedure worker() acquire(sem) printf(1,"- Task %d acquired semaphore.\n",task_self()) delay(2) release(sem) printf(1,"+ Task %d released semaphore.\n",task_self()) end procedure for i=1 to 10 do integer task = task_create(routine_id("worker"),{}) task_schedule(task,1) task_yield() end for integer sc = 0 atom t0 = time()+1 while length(task_list())>1 do task_yield() integer scnew = count(sem) if scnew!=sc or time()>t0 then sc = scnew printf(1,"Semaphore count now %d\n",{sc}) t0 = time()+2 end if end while ?"done" {} = wait_key()
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 the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#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:=(1).random(1000); // do lots of swaps do(numSwaps){ blkStk.append(redStk.pop(0)); redStk.append(blkStk.pop(0)); } println("Post %d swaps:\n Black stack: %s\n Red stack:  %s" .fmt(numSwaps,redBlack(blkStk),redBlack(redStk)));   numBlack,numRed := blkStk.filter('==(0)).len(), redStk.sum(0); if(numBlack==numRed) println("Agreed, black stack has same number of black cards\n " "as red stack has number of red cards: ",numRed); else println("Boo, different stack lenghts");   fcn redBlack(cards){ cards.pump(String,fcn(c){ c and "R " or "B " }) }
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, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#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 over witheach [ over + bit makeable take | makeable put ] ] over size temp share = until ] makeable release temp release drop ] is mian-chowla ( n --> [ )   100 mian-chowla 30 split swap echo cr -10 split nip echo