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
#Raku
Raku
my @mian-chowla = 1, |(2..Inf).map: -> $test { state $index = 1; state %sums = 2 => 1; my $next; my %these; @mian-chowla[^$index].map: { ++$next and last if %sums{$_ + $test}:exists; ++%these{$_ + $test} }; next if $next; ++%sums{$test + $test}; %sums.push: %these; ++$index; $test };   put "First 30 terms in the Mian–Chowla sequence:\n", @mian-chowla[^30]; put "\nTerms 91 through 100:\n", @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.
#Prolog
Prolog
  :- initialization(main). main :- clause(less_than(1,2),B),writeln(B). less_than(A,B) :- A<B.    
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#Python
Python
  from macropy.core.macros import * from macropy.core.quotes import macros, q, ast, u   macros = Macros()   @macros.expr def expand(tree, **kw): addition = 10 return q[lambda x: x * ast[tree] + u[addition]]  
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller 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)
#Common_Lisp
Common Lisp
(defun factor-out (number divisor) "Return two values R and E such that NUMBER = DIVISOR^E * R, and R is not divisible by DIVISOR." (do ((e 0 (1+ e)) (r number (/ r divisor))) ((/= (mod r divisor) 0) (values r e))))   (defun mult-mod (x y modulus) (mod (* x y) modulus))   (defun expt-mod (base exponent modulus) "Fast modular exponentiation by repeated squaring." (labels ((expt-mod-iter (b e p) (cond ((= e 0) p) ((evenp e) (expt-mod-iter (mult-mod b b modulus) (/ e 2) p)) (t (expt-mod-iter b (1- e) (mult-mod b p modulus)))))) (expt-mod-iter base exponent 1)))   (defun random-in-range (lower upper) "Return a random integer from the range [lower..upper]." (+ lower (random (+ (- upper lower) 1))))   (defun miller-rabin-test (n k) "Test N for primality by performing the Miller-Rabin test K times. Return NIL if N is composite, and T if N is probably prime." (cond ((= n 1) nil) ((< n 4) t) ((evenp n) nil) (t (multiple-value-bind (d s) (factor-out (- n 1) 2) (labels ((strong-liar? (a) (let ((x (expt-mod a d n))) (or (= x 1) (loop repeat s for y = x then (mult-mod y y n) thereis (= y (- n 1))))))) (loop repeat k always (strong-liar? (random-in-range 2 (- n 2)))))))))
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
#Arturo
Arturo
mobius: function [n][ if n=0 -> return "" if n=1 -> return 1 f: factors.prime n   if f <> unique f -> return 0 if? odd? size f -> return neg 1 else -> return 1 ]   mertens: function [z][sum map 1..z => mobius]   print "The first 99 Mertens numbers are:" loop split.every:20 [""]++map 1..99 => mertens 'a [ print map a 'item -> pad to :string item 2 ]   print ""   mertens1000: map 1..1000 => mertens print ["Times M(x) is zero between 1 and 1000:" size select mertens1000 => zero?]   crossed: new 0 fold mertens1000 [a,b][if and? zero? b not? zero? a -> inc 'crossed, b] print ["Times M(x) crosses zero between 1 and 1000:" crossed]
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.
#AWK
AWK
  # syntax: GAWK -f MENU.AWK BEGIN { print("you picked:",menu("")) print("you picked:",menu("fee fie:huff and puff:mirror mirror:tick tock")) exit(0) } function menu(str, ans,arr,i,n) { if (str == "") { return } n = split(str,arr,":") while (1) { print("") for (i=1; i<=n; i++) { printf("%d - %s\n",i,arr[i]) } printf("? ") getline ans if (ans in arr) { return(arr[ans]) } print("invalid 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.
#Bracmat
Bracmat
( alc$2000:?p {allocate 2000 bytes} & pok$(!p,123456789,4) { poke a large value as a 4 byte integer } & pok$(!p+4,0,4) { poke zeros in the next 4 bytes } & out$(pee$(!p,1)) { peek the first byte } & out$(pee$(!p+2,2)) { peek the short int located at the third and fourth byte } & out$(pee$(!p,4)) { peek the first four bytes } & out$(pee$(!p+6,2)) { peek the two bytes from the zeroed-out range } & out$(pee$(!p+1000,2)) { peek some uninitialized data } & fre$!p { free the memory } &);
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#C
C
#include <stdlib.h>   /* size of "members", in bytes */ #define SIZEOF_MEMB (sizeof(int)) #define NMEMB 100   int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); /* realloc can be used to increase or decrease an already allocated memory (same as malloc if ints is NULL) */ ints = realloc(ints, sizeof(int)*(NMEMB+1)); /* calloc set the memory to 0s */ int *int2 = calloc(NMEMB, SIZEOF_MEMB); /* all use the same free */ free(ints); free(int2); return 0; }
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
#Haskell
Haskell
import Data.List import Data.Maybe import System.IO (readFile) import Text.Read (readMaybe) import Control.Applicative ((<|>))   ------------------------------------------------------------   newtype DB = DB { entries :: [Patient] } deriving Show   instance Semigroup DB where DB a <> DB b = normalize $ a <> b   instance Monoid DB where mempty = DB []   normalize :: [Patient] -> DB normalize = DB . map mconcat . groupBy (\x y -> pid x == pid y) . sortOn pid   ------------------------------------------------------------   data Patient = Patient { pid :: String , name :: Maybe String , visits :: [String] , scores :: [Float] } deriving Show   instance Semigroup Patient where Patient p1 n1 v1 s1 <> Patient p2 n2 v2 s2 = Patient (fromJust $ Just p1 <|> Just p2) (n1 <|> n2) (v1 <|> v2) (s1 <|> s2)   instance Monoid Patient where mempty = Patient mempty mempty mempty mempty   ------------------------------------------------------------   readDB :: String -> DB readDB = normalize . mapMaybe readPatient . readCSV   readPatient r = do i <- lookup "PATIENT_ID" r let n = lookup "LASTNAME" r let d = lookup "VISIT_DATE" r >>= readDate let s = lookup "SCORE" r >>= readMaybe return $ Patient i n (maybeToList d) (maybeToList s) where readDate [] = Nothing readDate d = Just d   readCSV :: String -> [(String, String)] readCSV txt = zip header <$> body where header:body = splitBy ',' <$> lines txt splitBy ch = unfoldr go where go [] = Nothing go s = Just $ drop 1 <$> span (/= ch) s
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 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 -
#Mercury
Mercury
  :- module rs232.   :- interface.   :- import_module bool, io, list, string.   :- type rs232_pin ---> carrier_detect  ; received_data  ; transmitted_data  ; data_terminal_ready  ; signal_ground  ; data_set_ready  ; request_to_send  ; clear_to_send  ; ring_indicator.   :- type rs232.   :- func rs232_bits = rs232. :- func rs232_bits(bool) = rs232.   :- func rs232_set(rs232, rs232_pin) = rs232. :- func rs232_clear(rs232, rs232_pin) = rs232.   :- pred rs232_is_set(rs232::in, rs232_pin::in) is semidet. :- pred rs232_is_clear(rs232::in, rs232_pin::in) is semidet.   :- func rs232_set_bits(rs232, list(rs232_pin)) = rs232. :- func rs232_clear_bits(rs232, list(rs232_pin)) = rs232.   :- func to_string(rs232) = string.   :- pred write_rs232(rs232::in, io::di, io::uo) is det.   :- implementation.   :- import_module bitmap.   :- type rs232 == bitmap.   rs232_bits = rs232_bits(no). rs232_bits(Default) = bitmap.init(9, Default).   rs232_set(A, Pin) = unsafe_set(A, to_index(Pin)). rs232_clear(A, Pin) = unsafe_clear(A, to_index(Pin)).   rs232_is_set(A, Pin)  :- unsafe_is_set(A, to_index(Pin)). rs232_is_clear(A, Pin) :- unsafe_is_clear(A, to_index(Pin)).   rs232_set_bits(A, Pins) = foldl((func(Pin, B) = rs232_set(B, Pin)), Pins, A). rs232_clear_bits(A, Pins) = foldl((func(Pin, B) = rs232_clear(B, Pin)), Pins, A).   to_string(A) = bitmap.to_string(A).   write_rs232(A, !IO) :- write_bitmap(resize(A, 16, no), !IO).  % cannot write a bitmap that isn't byte-divisible   :- func to_index(rs232_pin) = bit_index. to_index(carrier_detect) = 0. to_index(received_data) = 1. to_index(transmitted_data) = 2. to_index(data_terminal_ready) = 3. to_index(signal_ground) = 4. to_index(data_set_ready) = 5. to_index(request_to_send) = 6. to_index(clear_to_send) = 7. to_index(ring_indicator) = 8.   :- end_module rs232.  
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 -
#Nim
Nim
type rs232Data = enum carrierDetect, receivedData, transmittedData, dataTerminalReady, signalGround, dataSetReady, requestToSend, clearToSend, ringIndicator   # Bit vector of 9 bits var bv = {carrierDetect, signalGround, ringIndicator} echo cast[uint16](bv) # Conversion of bitvector to 2 bytes for writing   let readValue: uint16 = 123 bv = cast[set[rs232Data]](readValue) # Conversion of a read value to bitvector echo bv
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 -
#OCaml
OCaml
open ExtLib class rs232_data = object val d = BitSet.create 9   method carrier_detect = BitSet.is_set d 0 method received_data = BitSet.is_set d 1 method transmitted_data = BitSet.is_set d 2 method data_terminal_ready = BitSet.is_set d 3 method signal_ground = BitSet.is_set d 4 method data_set_ready = BitSet.is_set d 5 method request_to_send = BitSet.is_set d 6 method clear_to_send = BitSet.is_set d 7 method ring_indicator = BitSet.is_set d 8   method set_carrier_detect b = (if b then BitSet.set else BitSet.unset) d 0 method set_received_data b = (if b then BitSet.set else BitSet.unset) d 1 method set_transmitted_data b = (if b then BitSet.set else BitSet.unset) d 2 method set_data_terminal_ready b = (if b then BitSet.set else BitSet.unset) d 3 method set_signal_ground b = (if b then BitSet.set else BitSet.unset) d 4 method set_data_set_ready b = (if b then BitSet.set else BitSet.unset) d 5 method set_request_to_send b = (if b then BitSet.set else BitSet.unset) d 6 method set_clear_to_send b = (if b then BitSet.set else BitSet.unset) d 7 method set_ring_indicator b = (if b then BitSet.set else BitSet.unset) d 8 end ;;
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
#Visual_Basic_.NET
Visual Basic .NET
Imports BI = System.Numerics.BigInteger   Module Module1   Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function   Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function   Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function   REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function   Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn   j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn   j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub   End Module
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#OCaml
OCaml
let color_add (r1,g1,b1) (r2,g2,b2) = ( (r1 + r2), (g1 + g2), (b1 + b2) )   let color_div (r,g,b) d = ( (r / d), (g / d), (b / d) )   let compare_as_grayscale (r1,g1,b1) (r2,g2,b2) = let v1 = (2_126 * r1 + 7_152 * g1 + 722 * b1) and v2 = (2_126 * r2 + 7_152 * g2 + 722 * b2) in (Pervasives.compare v1 v2)   let get_rgb img x y = let _, r_channel,_,_ = img in let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in if (x < 0) || (x >= width) then (0,0,0) else if (y < 0) || (y >= height) then (0,0,0) else (* feed borders with black *) (get_pixel img x y)     let median_value img radius = let samples = (radius*2+1) * (radius*2+1) in fun x y -> let sample = ref [] in   for _x = (x - radius) to (x + radius) do for _y = (y - radius) to (y + radius) do   let v = get_rgb img _x _y in   sample := v :: !sample; done; done;   let ssample = List.sort compare_as_grayscale !sample in let mid = (samples / 2) in   if (samples mod 2) = 1 then List.nth ssample (mid+1) else let median1 = List.nth ssample (mid) and median2 = List.nth ssample (mid+1) in (color_div (color_add median1 median2) 2)     let median img radius = let _, r_channel,_,_ = img in let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in   let _median_value = median_value img radius in   let res = new_img ~width ~height in for y = 0 to pred height do for x = 0 to pred width do let color = _median_value x y in put_pixel res color x y; done; done; (res)
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.
#Bracmat
Bracmat
( ( middle3 = x p . @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?) & !x |  !arg ( !p:<3&"is too small" | "has even number of digits" ) ) & 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0  : ?L & whl'(!L:%?e ?L&out$(middle3$!e)) & );  
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid 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)
#MATLAB
MATLAB
xpbombs
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum 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
#Ruby
Ruby
def mod(m, n) result = m % n if result < 0 then result = result + n end return result end   def getA004290(n) if n == 1 then return 1 end arr = Array.new(n) { Array.new(n, 0) } arr[0][0] = 1 arr[0][1] = 1 m = 0 while true m = m + 1 if arr[m - 1][mod(-10 ** m, n)] == 1 then break end arr[m][0] = 1 for k in 1 .. n - 1 arr[m][k] = [arr[m - 1][k], arr[m - 1][mod(k - 10 ** m, n)]].max end end r = 10 ** m k = mod(-r, n) (m - 1).downto(1) { |j| if arr[j - 1][k] == 0 then r = r + 10 ** j k = mod(k - 10 ** j, n) end } if k == 1 then r = r + 1 end return r end   testCases = Array(1 .. 10) testCases.concat(Array(95 .. 105)) testCases.concat([297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]) for n in testCases result = getA004290(n) print "A004290(%d) = %d = %d * %d\n" % [n, result, n, result / n] end
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} .
#Ruby
Ruby
a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = 10**40 puts a.pow(b, m)
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Rust
Rust
/* Add this line to the [dependencies] section of your Cargo.toml file: num = "0.2.0" */     use num::bigint::BigInt; use num::bigint::ToBigInt;     // The modular_exponentiation() function takes three identical types // (which get cast to BigInt), and returns a BigInt: fn modular_exponentiation<T: ToBigInt>(n: &T, e: &T, m: &T) -> BigInt { // Convert n, e, and m to BigInt: let n = n.to_bigint().unwrap(); let e = e.to_bigint().unwrap(); let m = m.to_bigint().unwrap();   // Sanity check: Verify that the exponent is not negative: assert!(e >= Zero::zero());   use num::traits::{Zero, One};   // As most modular exponentiations do, return 1 if the exponent is 0: if e == Zero::zero() { return One::one() }   // Now do the modular exponentiation algorithm: let mut result: BigInt = One::one(); let mut base = n % &m; let mut exp = e;   // Loop until we can return out result: loop { if &exp % 2 == One::one() { result *= &base; result %= &m; }   if exp == One::one() { return result }   exp /= 2; base *= base.clone(); base %= &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.
#Perl
Perl
use Time::HiRes qw(sleep gettimeofday);   local $| = 1; # autoflush   my $beats_per_minute = shift || 72; my $beats_per_bar = shift || 4;   my $i = 0; my $duration = 60 / $beats_per_minute; my $base_time = gettimeofday() + $duration;   for (my $next_time = $base_time ; ; $next_time += $duration) { if ($i++ % $beats_per_bar == 0) { print "\nTICK"; } else { print " tick"; } sleep($next_time - gettimeofday()); }
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.
#PicoLisp
PicoLisp
(let Sem (tmp "sem") (for U 4 # Create 4 concurrent units (unless (fork) (ctl Sem (prinl "Unit " U " aquired the semaphore") (wait 2000) (prinl "Unit " U " releasing the semaphore") ) (bye) ) ) )
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active 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.
#PureBasic
PureBasic
#Threads=10 #Parallels=3 Global Semaphore=CreateSemaphore(#Parallels)   Procedure Worker(*arg.i) WaitSemaphore(Semaphore) Debug "Thread #"+Str(*arg)+" active." Delay(Random(2000)) SignalSemaphore(Semaphore) EndProcedure   ; Start a multi-thread based work Dim thread(#Threads) For i=0 To #Threads thread(i)=CreateThread(@Worker(),i) Next Debug "Launcher done."   ; Wait for all threads to finish before closing down For i=0 To #Threads If IsThread(i) WaitThread(i) EndIf Next
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Scheme
Scheme
  (define iota (lambda (count start step) (let loop ((result (list (+ start (* (- count 1) step))))) (let ((acc (car result))) (if (= acc start) result (loop (cons (- acc step) result)))))))     (define table (lambda (x) (let loop ((count 1) (numbers (iota x 1 1))) (if (not (null? numbers)) (begin (display (make-string (* 6 (- count 1)) #\space)) (for-each (lambda (n) (let ((number (number->string (* n count)))) (display (string-append (make-string (- 6 (string-length number)) #\space) number)))) numbers) (newline) (loop (+ count 1) (cdr numbers)))))))  
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
#REXX
REXX
do j=i for t-i+1; ···
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, 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
#Ruby
Ruby
require 'set' n, ts, mc, sums = 100, [], [1], Set.new sums << 2 st = Time.now for i in (1 .. (n-1)) for j in mc[i-1]+1 .. Float::INFINITY mc[i] = j for k in (0 .. i) if (sums.include?(sum = mc[k]+j)) ts.clear break end ts << sum end if (ts.length > 0) sums = sums | ts break end end end et = (Time.now - st) * 1000 s = " of the Mian-Chowla sequence are:\n" puts "The first 30 terms#{s}#{mc.slice(0..29).join(' ')}\n\n" puts "Terms 91 to 100#{s}#{mc.slice(90..99).join(' ')}\n\n" puts "Computation time was #{et.round(1)}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.
#Quackery
Quackery
  ( +---------------------------------------------------+ ) ( | add inline comments ";" to Quackery with "builds" | ) ( +---------------------------------------------------+ )   [ dup $ "" = not while behead carriage = until ] builds ; ( [ $ --> [ $ )     ; +---------------------------------------------------+ ; | add switch to Quackery with ]else[ ]'[ & ]done[ | ; +---------------------------------------------------+   [ stack ] is switch.arg ( --> s ) protect switch.arg   [ switch.arg put ] is switch ( x --> )   [ switch.arg release ] is otherwise   [ switch.arg share  != iff ]else[ done otherwise ]'[ do ]done[ ] is case ( x --> )     [ switch 1 case [ say "The number 1." cr ] $ "two" case [ say 'The string "two".' cr ] otherwise [ say "Something else." cr ] ] is test ( x --> )     ' tally test  ; output should be: Something else. $ "two" test  ; output should be: The string "two". 1 test  ; output should be: The number 1.    
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#R
R
'%C%' <- function(n, k) choose(n, k) 5 %C% 2 #Outputs 10.
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller 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)
#Crystal
Crystal
require "big"   module Primes module MillerRabin   def prime?(k = 15) # increase k for more confidence neg_one_mod = d = self - 1 s = 0 while d.even?; d >>= 1; s += 1 end # d is odd after s shifts k.times do b = 2 + rand(self - 4) # random witness base b y = powmod(b, d, self) # y = (b**d) mod self next if y == 1 || y == neg_one_mod (s - 1).times do y = (y * y) % self # y = (y**2) mod self return false if y == 1 break if y == neg_one_mod end return false if y != neg_one_mod end true # prime (with high probability) end   # Compute b**e mod m private def powmod(b, e, m) r, b = 1, b.to_big_i while e > 0 r = (b * r) % m if e.odd? b = (b * b) % m e >>= 1 end r end end end   struct Int; include Primes::MillerRabin end   puts 341521.prime?(20) # => true puts 341531.prime? # => false
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
#BASIC
BASIC
10 DEFINT C,Z,N,K,M: DIM M(1000) 20 M(1)=1 30 FOR N=2 TO 1000 40 M(N)=1 50 FOR K=2 TO N: M(N) = M(N)-M(INT(N/K)): NEXT 60 NEXT 70 PRINT "First 99 Mertens numbers:" 80 PRINT " "; 90 FOR N=1 TO 99 100 PRINT USING "###";M(N); 110 IF N MOD 10 = 9 THEN PRINT 120 NEXT 130 C=0: Z=0 140 FOR N=1 TO 1000 150 IF M(N)=0 THEN Z=Z+1: IF M(N-1)<>0 THEN C=C+1 160 NEXT 170 PRINT "M(N) is zero";Z;"times." 180 PRINT "M(N) crosses zero";C;"times." 190 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.
#Axe
Axe
"FEE FIE"→Str1 "HUFF AND PUFF"→Str2 "MIRROR MIRROR"→Str3 "TICK TOCK"→Str4 For(I,1,4) Disp I▶Hex+3,":",strGet(Str1,I-1),i End Disp "NUMBER? " input→A {A}-'0'→N If N<1 or N>4 Disp "BAD NUMBER",i Return End Disp strGet(Str1,N-1),i
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#C.23
C#
using System; using System.Runtime.InteropServices;   public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (pointer == null) throw new OutOfMemoryException(); Console.WriteLine(HeapSize(ph, 0, pointer)); HeapFree(ph, 0, pointer); }   public static unsafe void StackMemory() { byte* buffer = stackalloc byte[1000]; // buffer is automatically discarded when the method returns } public static void Main(string[] args) { HeapMemory(); StackMemory(); } [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block);   }
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
#J
J
NB. setup: require'jd pacman' load JDP,'tools/csv_load.ijs' F=: jpath '~temp/rosettacode/example/CSV' jdcreatefolder_jd_ CSVFOLDER=: F   assert 0<{{)n PATIENTID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz }} fwrite F,'patients.csv'   assert 0<{{)n PATIENTID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 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 }} fwrite F,'visits.csv'   csvprepare 'patients';F,'patients.csv' csvprepare 'visits';F,'visits.csv'   csvload 'patients';1 csvload 'visits';1   jd'ref patients PATIENTID visits PATIENTID'
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 -
#Pascal
Pascal
use Bit::Vector::Minimal qw(); my $vec = Bit::Vector::Minimal->new(size => 24);   my %rs232 = reverse ( 1 => 'PG Protective ground', 2 => 'TD Transmitted data', 3 => 'RD Received data', 4 => 'RTS Request to send', 5 => 'CTS Clear to send', 6 => 'DSR Data set ready', 7 => 'SG Signal ground', 8 => 'CD Carrier detect', 9 => '+ voltage (testing)', 10 => '- voltage (testing)', 12 => 'SCD Secondary CD', 13 => 'SCS Secondary CTS', 14 => 'STD Secondary TD', 15 => 'TC Transmit clock', 16 => 'SRD Secondary RD', 17 => 'RC Receiver clock', 19 => 'SRS Secondary RTS', 20 => 'DTR Data terminal ready', 21 => 'SQD Signal quality detector', 22 => 'RI Ring indicator', 23 => 'DRS Data rate select', 24 => 'XTC External clock', );   $vec->set($rs232{'RD Received data'}, 1); $vec->get($rs232{'TC Transmit clock'});
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
#Wren
Wren
import "/big" for BigInt, BigRat import "/fmt" for Fmt   var names = ["Platinum", "Golden", "Silver", "Bronze", "Copper","Nickel", "Aluminium", "Iron", "Tin", "Lead"]   var lucas = Fn.new { |b| Fmt.print("Lucas sequence for $s ratio, where b = $d:", names[b], b) System.write("First 15 elements: ") var x0 = 1 var x1 = 1 Fmt.write("$d, $d", x0, x1) for (i in 1..13) { var x2 = b*x1 + x0 Fmt.write(", $d", x2) x0 = x1 x1 = x2 } System.print() }   var metallic = Fn.new { |b, dp| var x0 = BigInt.one var x1 = BigInt.one var x2 = BigInt.zero var bb = BigInt.new(b) var ratio = BigRat.new(BigInt.one, BigInt.one) var iters = 0 var prev = ratio.toDecimal(dp) while (true) { iters = iters + 1 x2 = bb*x1 + x0 ratio = BigRat.new(x2, x1) var curr = ratio.toDecimal(dp) if (prev == curr) { var plural = (iters == 1) ? " " : "s" Fmt.print("Value to $d dp after $2d iteration$s: $s\n", dp, iters, plural, curr) return } prev = curr x0 = x1 x1 = x2 } }   for (b in 0..9) { lucas.call(b) metallic.call(b, 32) } System.print("Golden ratio, where b = 1:") metallic.call(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)
#Perl
Perl
use strict 'vars'; use warnings;   use PDL; use PDL::Image2D;   my $image = rpic 'plasma.png'; my $smoothed = med2d $image, ones(3,3), {Boundary => Truncate}; wpic $smoothed, 'plasma_median.png';
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Phix
Phix
-- demo\rosetta\Bitmap_Median_filter.exw include ppm.e   constant neigh = {{-1,-1},{0,-1},{1,-1}, {-1, 0},{0, 0},{1, 0}, {-1, 1},{0, 1},{1, 1}}   --constant neigh = {{-2,-2},{-1,-2},{0,-2},{1,-2},{2,-2}, -- {-2,-1},{-1,-1},{0,-1},{1,-1},{2,-1}, -- {-2, 0},{-1, 0},{0, 0},{1, 0},{2, 0}, -- {-2, 1},{-1, 1},{0, 1},{1, 1},{2, 1}, -- {-2, 2},{-1, 2},{0, 2},{1, 2},{2, 2}}   sequence kn = repeat(0,length(neigh))   function median(sequence image) integer h = length(image), w = length(image[1]) for i=1 to length(image) do for j=1 to length(image[i]) do integer n = 0, c, p, x, y for k=1 to length(neigh) do x = i+neigh[k][1] y = j+neigh[k][2] if x>=1 and x<=h and y>=1 and y<=w then n += 1 c = image[x,j] p = n while p>1 do if c>kn[p-1] then exit end if kn[p] = kn[p-1] p -= 1 end while kn[p] = c end if end for if and_bits(n,1) then c = kn[(n+1)/2] else c = floor((kn[n/2]+kn[n/2+1])/2) end if image[i,j] = c end for end for return image end function   sequence img = read_ppm("Lena.ppm") img = median(img) write_ppm("LenaMedian.ppm",img)
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.
#Burlesque
Burlesque
  blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN 123 234 345 654 000 123  
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid 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)
#Nim
Nim
import random, sequtils, strformat, strscans, strutils   const LMargin = 4   type   Cell = object isMine: bool display: char   Grid = seq[seq[Cell]]   Game = object grid: Grid mineCount: Natural minesMarked: Natural isOver: bool     proc initGame(m, n: Positive): Game = result.grid = newSeqWith(m, repeat(Cell(isMine: false, display: '.'), n)) let min = (float(m * n) * 0.1).toInt let max = (float(m * n) * 0.2).toInt result.mineCount = min + rand(max - min) var rm = result.mineCount while rm > 0: let x = rand(m - 1) let y = rand(n - 1) if not result.grid[x][y].isMine: dec rm result.grid[x][y].isMine = true result.minesMarked = 0     template `[]`(grid: Grid; x, y: int): Cell = grid[x][y]     iterator cells(grid: var Grid): var Cell = for y in 0..grid[0].high: for x in 0..grid.high: yield grid[x, y]     proc display(game: Game; endOfGame: bool) = if not endOfGame: echo &"Grid has {game.mineCount} mine(s), {game.minesMarked} mine(s) marked." let margin = repeat(' ', LMargin) echo margin, toSeq(1..game.grid.len).join() echo margin, repeat('-', game.grid.len) for y in 0..game.grid[0].high: stdout.write align($(y + 1), LMargin) for x in 0..game.grid.high: stdout.write game.grid[x][y].display stdout.write '\n'     proc terminate(game: var Game; msg: string) = game.isOver = true echo msg var answer = "" while answer notin ["y", "n"]: stdout.write "Another game (y/n)? " answer = try: stdin.readLine().toLowerAscii except EOFError: "n" if answer == "y": game = initGame(6, 4) game.display(false)     proc resign(game: var Game) = var found = 0 for cell in game.grid.cells: if cell.isMine: if cell.display == '?': cell.display = 'Y' inc found elif cell.display == 'x': cell.display = 'N' game.display(true) let msg = &"You found {found} out of {game.mineCount} mine(s)." game.terminate(msg)     proc markCell(game: var Game; x, y: int) = if game.grid[x, y].display == '?': dec game.minesMarked game.grid[x, y].display = '.' elif game.grid[x, y].display == '.': inc game.minesMarked game.grid[x, y].display = '?'     proc countAdjMines(game: Game; x, y: Natural): int = for j in (y - 1)..(y + 1): if j in 0..game.grid[0].high: for i in (x - 1)..(x + 1): if i in 0..game.grid.high: if game.grid[i, j].isMine: inc result     proc clearCell(game: var Game; x, y: int): bool =   if x in 0..game.grid.high and y in 0..game.grid[0].high: if game.grid[x, y].display == '.':   if game.grid[x, y].isMine: game.grid[x][y].display = 'x' echo "Kaboom! You lost!" return false   let count = game.countAdjMines(x, y) if count > 0: game.grid[x][y].display = chr(ord('0') + count) else: game.grid[x][y].display = ' ' for dx in -1..1: for dy in -1..1: if dx != 0 or dy != 0: discard game.clearCell(x + dx, y + dy)   result = true     proc testForWin(game: var Game): bool = if game.minesMarked != game.mineCount: return false for cell in game.grid.cells: if cell.display == '.': return false result = true echo "You won!"     proc splitAction(game: Game; action: string): tuple[x, y: int; ok: bool] = var command: string if not action.scanf("$w $s$i $s$i$s$.", command, result.x, result.y): return if command.len != 1: return if result.x notin 1..game.grid.len or result.y notin 1..game.grid.len: return result.ok = true     proc printUsage() = echo "h or ? - this help," echo "c x y - clear cell (x,y)," echo "m x y - marks (toggles) cell (x,y)," echo "n - start a new game," echo "q - quit/resign the game," echo "where 'x' is the (horizontal) column number and 'y' is the (vertical) row number.\n"     randomize() printUsage() var game = initGame(6, 4) game.display(false)   while not game.isOver: stdout.write "\n>" let action = try: stdin.readLine().toLowerAscii except EOFError: "q" case action[0]   of 'h', '?': printUsage()   of 'n': game = initGame(6, 4) game.display(false)   of 'c': let (x, y, ok) = game.splitAction(action) if not ok: continue if game.clearCell(x - 1, y - 1): game.display(false) if game.testForwin(): game.resign() else: game.resign()   of 'm': let (x, y, ok) = game.splitAction(action) if not ok: continue game.markCell(x - 1, y - 1) game.display(false) if game.testForWin(): game.resign()   of 'q': game.resign()   else: continue
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
#Scala
Scala
import scala.collection.mutable.ListBuffer   object MinimumNumberOnlyZeroAndOne { def main(args: Array[String]): Unit = { for (n <- getTestCases) { val result = getA004290(n) println(s"A004290($n) = $result = $n * ${result / n}") } }   def getTestCases: List[Int] = { val testCases = ListBuffer.empty[Int] for (i <- 1 to 10) { testCases += i } for (i <- 95 to 105) { testCases += i } for (i <- Array(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) { testCases += i } testCases.toList }   def getA004290(n: Int): BigInt = { if (n == 1) { return 1 } val L = Array.ofDim[Int](n, n) for (i <- 2 until n) { L(0)(i) = 0 } L(0)(0) = 1 L(0)(1) = 1 var m = 0 val ten = BigInt(10) val nBi = BigInt(n) var loop = true while (loop) { m = m + 1 if (L(m - 1)(mod(-ten.pow(m), nBi).intValue()) == 1) { loop = false } else { L(m)(0) = 1 for (k <- 1 until n) { L(m)(k) = math.max(L(m - 1)(k), L(m - 1)(mod(BigInt(k) - ten.pow(m), nBi).toInt)) } } } var r = ten.pow(m) var k = mod(-r, nBi) for (j <- m - 1 to 1 by -1) { if (L(j - 1)(k.toInt) == 0) { r = r + ten.pow(j) k = mod(k - ten.pow(j), nBi) } } if (k == 1) { r = r + 1 } r }   def mod(m: BigInt, n: BigInt): BigInt = { var result = m % n if (result < 0) { result = result + n } result } }
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} .
#Scala
Scala
import scala.math.BigInt   val a = BigInt( "2988348162058574136915891421498819466320163312926952423791023078876139") val b = BigInt( "2351399303373464486466122544523690094744975233415544072992656881240319")   println(a.modPow(b, BigInt(10).pow(40)))
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Scheme
Scheme
  (define (square n) (* n n))   (define (mod-exp a n mod) (cond ((= n 0) 1) ((even? n) (remainder (square (mod-exp a (/ n 2) mod)) mod)) (else (remainder (* a (mod-exp a (- n 1) mod)) mod))))   (define result (mod-exp 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 (expt 10 40)))
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an 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.
#Phix
Phix
-- -- demo\rosetta\virtunome.exw -- -- Originally by ghaberek -- Translated from win32lib by Pete Lomax -- -- I will note that accuracy drops sharply above 5 beats per second. -- with javascript_semantics -- needs some work though, usual sizing stuff [DEV] -- NB: don't break Morse_code.exw when fixing this! include pGUI.e Ihandle dlg, frame_1, radio, frame_2, val_lbl, frame_3, bpm_lbl, spb_lbl, act_lbl, acc_lbl, onbtn, onoff, timer sequence notes function rle_decode_image(sequence data) -- (not my best work, may benefit from a rethink...) sequence img = {} for i=1 to length(data) do sequence rle = data[i], line = {}, val integer rpt = rle[1] for j=2 to length(rle)-1 by 2 do integer RGB = rle[j], count = rle[j+1] if RGB=-1 then string RGBs = IupGetGlobal("DLGBGCOLOR") {val} = scanf(RGBs,"%d %d %d") elsif RGB=0 then val = repeat(0,3) else ?9/0 end if val &= #FF line &= flatten(repeat(val,count)) end for img &= flatten(repeat(line,rpt)) end for return img end function constant Whole_note = { {13,-1,32}, {1,-1,12,0,9,-1,11}, {1,-1,10,0,4,-1,3,0,6,-1,9}, {1,-1,9,0,5,-1,4,0,6,-1,8}, {1,-1,8,0,5,-1,6,0,5,-1,8}, {2,-1,8,0,5,-1,6,0,6,-1,7}, {1,-1,8,0,6,-1,5,0,6,-1,7}, {1,-1,8,0,6,-1,5,0,5,-1,8}, {1,-1,9,0,6,-1,3,0,5,-1,9}, {1,-1,11,0,11,-1,10}, {9,-1,32}, }, Half_note = { {30,-1,21,0,1,-1,10}, {1,-1,14,0,8,-1,10}, {1,-1,12,0,10,-1,10}, {1,-1,11,0,6,-1,3,0,2,-1,10}, {1,-1,10,0,5,-1,5,0,2,-1,10}, {1,-1,10,0,4,-1,5,0,3,-1,10}, {1,-1,10,0,3,-1,5,0,4,-1,10}, {1,-1,10,0,2,-1,5,0,5,-1,10}, {1,-1,10,0,2,-1,3,0,6,-1,11}, {1,-1,10,0,10,-1,12}, {1,-1,11,0,7,-1,14} }, Eigth_note = { {2,-1,17,0,1,-1,14}, {2,-1,17,0,2,-1,13}, {1,-1,17,0,3,-1,12}, {1,-1,17,0,4,-1,11}, {1,-1,17,0,5,-1,10}, {1,-1,17,0,6,-1,9}, {1,-1,17,0,1,-1,1,0,5,-1,8}, {1,-1,17,0,1,-1,3,0,4,-1,7}, {1,-1,17,0,1,-1,4,0,4,-1,6}, {1,-1,17,0,1,-1,5,0,3,-1,6}, {1,-1,17,0,1,-1,6,0,3,-1,5}, {1,-1,17,0,1,-1,7,0,2,-1,5}, {1,-1,17,0,1,-1,7,0,3,-1,4}, {2,-1,17,0,1,-1,8,0,2,-1,4}, {4,-1,17,0,1,-1,9,0,1,-1,4}, {3,-1,17,0,1,-1,8,0,1,-1,5}, {6,-1,17,0,1,-1,14}, {1,-1,11,0,7,-1,14}, {1,-1,9,0,9,-1,14}, {1,-1,8,0,10,-1,14}, {1,-1,7,0,11,-1,14}, {2,-1,6,0,12,-1,14}, {2,-1,6,0,11,-1,15}, {1,-1,6,0,10,-1,16}, {1,-1,7,0,7,-1,18}, {1,-1,9,0,2,-1,21} }, Quarter_note = { {30,-1,21,0,1,-1,10}, {1,-1,15,0,7,-1,10}, {1,-1,13,0,9,-1,10}, {1,-1,12,0,10,-1,10}, {1,-1,11,0,11,-1,10}, {2,-1,10,0,12,-1,10}, {2,-1,10,0,11,-1,11}, {1,-1,10,0,10,-1,12}, {1,-1,11,0,7,-1,14}, {1,-1,13,0,2,-1,17} }, Sixteenth_note = { {2,-1,17,0,1,-1,14}, {2,-1,17,0,2,-1,13}, {1,-1,17,0,3,-1,12}, {1,-1,17,0,4,-1,11}, {1,-1,17,0,5,-1,10}, {1,-1,17,0,6,-1,9}, {1,-1,17,0,7,-1,8}, {1,-1,17,0,2,-1,2,0,4,-1,7}, {1,-1,17,0,2,-1,3,0,4,-1,6}, {1,-1,17,0,2,-1,4,0,3,-1,6}, {1,-1,17,0,3,-1,4,0,3,-1,5}, {1,-1,17,0,4,-1,4,0,2,-1,5}, {1,-1,17,0,5,-1,3,0,3,-1,4}, {1,-1,17,0,6,-1,3,0,2,-1,4}, {1,-1,17,0,7,-1,2,0,2,-1,4}, {1,-1,17,0,1,-1,2,0,5,-1,1,0,2,-1,4}, {1,-1,17,0,1,-1,4,0,6,-1,4}, {1,-1,17,0,1,-1,5,0,5,-1,4}, {1,-1,17,0,1,-1,6,0,4,-1,4}, {2,-1,17,0,1,-1,8,0,2,-1,4}, {1,-1,17,0,1,-1,9,0,1,-1,4}, {4,-1,17,0,1,-1,9,0,2,-1,3}, {2,-1,17,0,1,-1,9,0,1,-1,4}, {1,-1,11,0,7,-1,8,0,2,-1,4}, {1,-1,9,0,9,-1,8,0,1,-1,5}, {1,-1,8,0,10,-1,8,0,1,-1,5}, {1,-1,7,0,11,-1,14}, {2,-1,6,0,12,-1,14}, {2,-1,6,0,11,-1,15}, {1,-1,6,0,10,-1,16}, {1,-1,7,0,7,-1,18}, {1,-1,9,0,2,-1,21} } integer note = 4 -- quarter initially atom vLastTime = 0.0 -- for time resolution constant -- in bpm MIN_TEMPO = 1, DEF_TEMPO = 90, MAX_TEMPO = 200 integer vMSPB = 667 -- default milliseconds per beat constant Tempos = {"Grave", "Largo", "Adagio", "Lento", "Adante", "Moderato", "Allegretto", "Allegro", "Presto", "Vivance", "Prestissimo"} function set_tempo(integer pBPM, atom pNote) -- returns tempo index integer index = floor(((length(Tempos)-1)*pBPM)/(MAX_TEMPO-MIN_TEMPO))+1 atom lSPB = 60 / pBPM / pNote -- seconds per beat vMSPB = floor( lSPB * 1000 ) IupSetStrAttribute(spb_lbl,"TITLE","%.2f",{lSPB}) IupSetInt(timer,"TIME",vMSPB) if IupGetInt(timer,"RUN") then -- restart needed to apply new TIME (not doc?) IupSetInt(timer,"RUN",false) IupSetInt(timer,"RUN",true) end if return index end function procedure tempo_change() integer lBPM = IupGetInt(val_lbl,"TITLE"), lIndex = set_tempo(lBPM, note/4) IupSetStrAttribute(frame_2, "TITLE", "Tempo: %s ", {Tempos[lIndex]}) vLastTime = time() end procedure function toggle_state_cb(Ihandle ih, integer state) if state then note = power(2,find(ih,notes)-1) -- 1/2/4/8/16 tempo_change() end if -- and shift focus away, since it looks ugly w/o any text IupSetFocus(onbtn) return IUP_DEFAULT end function function valuechanged_cb(Ihandle val) integer v = IupGetInt(val,"VALUE") IupSetInt(val_lbl,"TITLE",v) IupSetStrAttribute(bpm_lbl,"TITLE","%.2f",{v}) tempo_change() return IUP_DEFAULT end function include builtins\beep.e function timer_cb(Ihandle /*ih*/) beep(#200,20) atom lThisTime = time() if vLastTime > 0.0 then atom lDiff = (lThisTime - vLastTime), lResolution = ((lDiff * 1000)/ vMSPB) * 100 IupSetStrAttribute(act_lbl, "TITLE", "%0.2f", {lDiff}) IupSetStrAttribute(acc_lbl, "TITLE", "%d%%", {lResolution}) end if vLastTime = lThisTime return IUP_DEFAULT end function function button_cb(Ihandle ih) bool active = not IupGetInt(timer,"RUN") IupSetInt(timer,"RUN",active) IupSetAttribute(ih,"TITLE",{"Off","On"}[active+1]) return IUP_DEFAULT end function IupOpen() notes = {IupImageRGBA(32, 32, rle_decode_image(Whole_note)), IupImageRGBA(32, 40, rle_decode_image(Half_note)), IupImageRGBA(32, 40, rle_decode_image(Quarter_note)), IupImageRGBA(32, 40, rle_decode_image(Eigth_note)), IupImageRGBA(32, 40, rle_decode_image(Sixteenth_note))} sequence btns = {} for i=1 to length(notes) do Ihandle btn = IupToggle(NULL, Icallback("toggle_state_cb"), "CANFOCUS=NO"), lbl = IupLabel() IupSetAttributeHandle(lbl,"IMAGE",notes[i]) btns &= {btn,lbl} notes[i] = btn end for radio = IupRadio(IupHbox(btns,"GAP=20")) frame_1 = IupFrame(radio,"MARGIN=20x10") IupSetAttribute(frame_1,"TITLE","Note ") val_lbl = IupLabel(" 200","ALIGNMENT=ARIGHT") Ihandle val = IupValuator("HORIZONTAL","EXPAND=HORIZONTAL, CANFOCUS=NO") IupSetInt(val,"MIN",MIN_TEMPO) IupSetInt(val,"MAX",MAX_TEMPO) IupSetInt(val,"VALUE",DEF_TEMPO) IupSetCallback(val, "VALUECHANGED_CB", Icallback("valuechanged_cb")) frame_2 = IupFrame(IupHbox({val_lbl,val}),`TITLE="Tempo: "`) bpm_lbl = IupLabel("90.00","ALIGNMENT=ARIGHT, EXPAND=HORIZONTAL") act_lbl = IupLabel("0.00","ALIGNMENT=ARIGHT, EXPAND=HORIZONTAL") spb_lbl = IupLabel("0.67","ALIGNMENT=ARIGHT, EXPAND=HORIZONTAL") acc_lbl = IupLabel("0%","ALIGNMENT=ARIGHT, EXPAND=HORIZONTAL") frame_3 = IupFrame(IupHbox({IupVbox({IupHbox({IupLabel("Beats Per Minute:"),bpm_lbl}), IupHbox({IupLabel("Seconds Per Beat:"),spb_lbl})}, "GAP=10,MARGIN=10x0"), IupVbox({IupHbox({IupLabel("Actual Seconds Per Beat:"),act_lbl}), IupHbox({IupLabel("Accuracy:"),acc_lbl})}, "GAP=10,MARGIN=10x0")}), `TITLE="Statistics ",MARGIN=4x8`) onbtn = IupButton("On",Icallback("button_cb"),"PADDING=30x0") onoff = IupHbox({IupFill(),onbtn},"MARGIN=0x20") dlg = IupDialog(IupVbox({frame_1, frame_2, frame_3, onoff}, "MARGIN=10x5, GAP=5"), -- `TITLE="Virtunome",RASTERSIZE=500x330`) `TITLE="Virtunome"`) IupShow(dlg) -- The TIME and RUN attributes are set dynamically: timer = IupTimer(Icallback("timer_cb"), vMSPB, active:=false) IupSetInt(val_lbl,"TITLE",DEF_TEMPO) IupSetAttributeHandle(radio,"VALUE",btns[5]) tempo_change() if platform()!=JS then IupMainLoop() IupClose() end if
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active 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.
#Python
Python
import time import threading   # Only 4 workers can run in the same time sem = threading.Semaphore(4)   workers = [] running = 1     def worker(): me = threading.currentThread() while 1: sem.acquire() try: if not running: break print '%s acquired semaphore' % me.getName() time.sleep(2.0) finally: sem.release() time.sleep(0.01) # Let others acquire   # Start 10 workers for i in range(10): t = threading.Thread(name=str(i), target=worker) workers.append(t) t.start()   # Main loop try: while 1: time.sleep(0.1) except KeyboardInterrupt: running = 0 for t in workers: t.join()
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.
#Racket
Racket
  #lang racket   (define sema (make-semaphore 4)) ; allow 4 concurrent jobs   ;; start 20 jobs and wait for all of them to end (for-each thread-wait (for/list ([i 20]) (thread (λ() (semaphore-wait sema) (printf "Job #~a acquired semaphore\n" i) (sleep 2) (printf "Job #~a done\n" i) (semaphore-post sema)))))  
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Scilab
Scilab
nmax=12, xx=3 s= blanks(xx)+" |" for j=1:nmax s=s+part(blanks(xx)+string(j),$-xx:$) end printf("%s\n",s) s=strncpy("-----",xx)+" +" for j=1:nmax s=s+" "+strncpy("-----",xx) end printf("%s\n",s) for i=1:nmax s=part(blanks(xx)+string(i),$-xx+1:$)+" |" for j = 1:nmax if j >= i then s=s+part(blanks(xx)+string(i*j),$-xx:$) else s=s+blanks(xx+1) end end printf("%s\n",s) end
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
#Sidef
Sidef
var (n, sums, ts, mc) = (100, Set([2]), [], [1]) var st = Time.micro_sec for i in (1 ..^ n) { for j in (mc[i-1]+1 .. Inf) { mc[i] = j for k in (0 .. i) { var sum = mc[k]+j if (sums.exists(sum)) { ts.clear break } ts << sum } if (ts.len > 0) { sums = (sums|Set(ts...)) break } } } var et = (Time.micro_sec - st) var s = " of the Mian-Chowla sequence are:\n" say "The first 30 terms#{s}#{mc.ft(0, 29).join(' ')}\n" say "Terms 91 to 100#{s}#{mc.ft(90, 99).join(' ')}\n" say "Computation time was #{et} seconds."
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.
#Racket
Racket
#lang racket   (define-syntax-rule (list-when test body) (if test body '()))   (let ([not-a-string 42]) (list-when (string? not-a-string) (string->list not-a-string)))
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#Raku
Raku
sub postfix:<!> { [*] 1..$^n } say 5!; # prints 120
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller 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)
#D
D
import std.random;   bool isProbablePrime(in ulong n, in uint k=10) /*nothrow*/ @safe /*@nogc*/ { static ulong modPow(ulong b, ulong e, in ulong m) pure nothrow @safe @nogc { ulong result = 1; while (e > 0) { if ((e & 1) == 1) result = (result * b) % m; b = (b ^^ 2) % m; e >>= 1; } return result; }   if (n < 2 || n % 2 == 0) return n == 2;   ulong d = n - 1; ulong s = 0; while (d % 2 == 0) { d /= 2; s++; } assert(2 ^^ s * d == n - 1);   outer: foreach (immutable _; 0 .. k) { immutable ulong a = uniform(2, n); ulong x = modPow(a, d, n); if (x == 1 || x == n - 1) continue; foreach (immutable __; 1 .. s) { x = modPow(x, 2, n); if (x == 1) return false; if (x == n - 1) continue outer; } return false; }   return true; }   void main() { // Demo code. import std.stdio, std.range, std.algorithm;   iota(2, 30).filter!isProbablePrime.writeln; }
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
#Bash
Bash
#!/bin/bash MAX=1000   m[1]=1 for n in `seq 2 $MAX` do m[n]=1 for k in `seq 2 $n` do m[n]=$((m[n]-m[n/k])) done done   echo 'The first 99 Mertens numbers are:' echo -n ' ' for n in `seq 1 99` do printf '%2d ' ${m[n]} test $((n%10)) -eq 9 && echo done   zero=0 cross=0 for n in `seq 1 $MAX` do if [ ${m[n]} -eq 0 ] then ((zero++)) test ${m[n-1]} -ne 0 && ((cross++)) fi done   echo "M(N) is zero $zero times." echo "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.
#BASIC
BASIC
FUNCTION sel$(choices$(), prompt$) IF UBOUND(choices$) - LBOUND(choices$) = 0 THEN sel$ = "" ret$ = "" DO FOR i = LBOUND(choices$) TO UBOUND(choices$) PRINT i; ": "; choices$(i) NEXT i INPUT ;prompt$, index IF index <= UBOUND(choices$) AND index >= LBOUND(choices$) THEN ret$ = choices$(index) WHILE ret$ = "" sel$ = ret$ END FUNCTION
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#C.2B.2B
C++
#include <string>   int main() { int* p;   p = new int; // allocate a single int, uninitialized delete p; // deallocate it   p = new int(2); // allocate a single int, initialized with 2 delete p; // deallocate it   std::string* p2;   p2 = new std::string; // allocate a single string, default-initialized delete p2; // deallocate it   p = new int[10]; // allocate an array of 10 ints, uninitialized delete[] p; // deallocation of arrays must use delete[]   p2 = new std::string[10]; // allocate an array of 10 strings, default-initialized delete[] p2; // deallocate it }
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#COBOL
COBOL
PROGRAM-ID. memory-allocation.   DATA DIVISION. WORKING-STORAGE SECTION. 01 based-data PIC X(20) VALUE "Hello, World!" BASED.   PROCEDURE DIVISION. *> INITIALIZED sets the data item to the VALUE. ALLOCATE based-data INITIALIZED DISPLAY based-data FREE based-data   GOBACK .
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
#jq
jq
  # objectify/1 takes an array of atomic values as inputs, and packages # these into an object with keys specified by the "headers" array and # values obtained by trimming string values, replacing empty strings # by null, and converting strings to numbers if possible. def objectify(headers): def tonumberq: tonumber? // .; def trimq: if type == "string" then sub("^ +";"") | sub(" +$";"") else . end; def tonullq: if . == "" then null else . end; . as $in | reduce range(0; headers|length) as $i ({}; .[headers[$i]] = ($in[$i] | trimq | tonumberq | tonullq) );   def csv2jsonHelper: .[0] as $headers | reduce (.[1:][] | select(length > 0) ) as $row ([]; . + [ $row|objectify($headers) ]);    
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
#Julia
Julia
using CSV, DataFrames, Statistics   # load data from csv files #df_patients = CSV.read("patients.csv", DataFrame) #df_visits = CSV.read("visits.csv", DataFrame)   # create DataFrames from text that is hard coded, so use IOBuffer(String) as input str_patients = IOBuffer("""PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz """) df_patients = CSV.read(str_patients, DataFrame) str_visits = IOBuffer("""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 """) df_visits = CSV.read(str_visits, DataFrame)   # merge on PATIENT_ID, using an :outer join or we lose Kurtz, who has no data, sort by ID df_merge = sort(join(df_patients, df_visits, on="PATIENT_ID", kind=:outer), (:PATIENT_ID,))   fnonmissing(a, f) = isempty(a) ? [] : isempty(skipmissing(a)) ? a[1] : f(skipmissing(a))   # group by patient id / last name and then aggregate to get latest visit and mean score df_result = by(df_merge, [:PATIENT_ID, :LASTNAME]) do df DataFrame(LATEST_VISIT = fnonmissing(df[:VISIT_DATE], maximum), SUM_SCORE = fnonmissing(df[:SCORE], sum), MEAN_SCORE = fnonmissing(df[:SCORE], mean)) end println(df_result)  
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 -
#Perl
Perl
use Bit::Vector::Minimal qw(); my $vec = Bit::Vector::Minimal->new(size => 24);   my %rs232 = reverse ( 1 => 'PG Protective ground', 2 => 'TD Transmitted data', 3 => 'RD Received data', 4 => 'RTS Request to send', 5 => 'CTS Clear to send', 6 => 'DSR Data set ready', 7 => 'SG Signal ground', 8 => 'CD Carrier detect', 9 => '+ voltage (testing)', 10 => '- voltage (testing)', 12 => 'SCD Secondary CD', 13 => 'SCS Secondary CTS', 14 => 'STD Secondary TD', 15 => 'TC Transmit clock', 16 => 'SRD Secondary RD', 17 => 'RC Receiver clock', 19 => 'SRS Secondary RTS', 20 => 'DTR Data terminal ready', 21 => 'SQD Signal quality detector', 22 => 'RI Ring indicator', 23 => 'DRS Data rate select', 24 => 'XTC External clock', );   $vec->set($rs232{'RD Received data'}, 1); $vec->get($rs232{'TC Transmit clock'});
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 -
#Phix
Phix
constant CD=1, RD=2, TD=3, DTR=4, ... atom addr = allocate(2) -- or wherever --read sequence bits = int_to_bits(peek2u(addr),16) integer dtr = bits[DTR] --write bits[DTR] = 1 poke2(addr,bits_to_int(bits))
http://rosettacode.org/wiki/Metallic_ratios
Metallic ratios
Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series of related ratios that are referred to as the "Metallic ratios". The Golden ratio was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The Silver ratio was was also known to 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
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP fcn lucasSeq(b){ Walker.zero().tweak('wrap(xs){ xm2,xm1 := xs; // x[n-2], x[n-1] xn:=xm1*b + xm2; xs.append(xn).del(0); xn }.fp(L(BI(1),BI(1)))).push(1,1) // xn can get big so use BigInts } fcn metallicRatio(lucasSeq,digits=32,roundup=True){ #-->(String,num iterations) bige:=BI("1e"+(digits+1)); # x[n-1]*bige*b / x[n-2] to get our digits from Ints a,b,mr := lucasSeq.next(), lucasSeq.next(), (bige*b).div(a); do(20_000){ // limit iterations c,mr2 := lucasSeq.next(), (bige*c).div(b); if(mr==mr2){ mr=mr2.add(5*roundup).div(10).toString(); return(String(mr[0],".",mr.del(0)), lucasSeq.idx); // idx ignores push(), ie first 2 terms } b,mr = c,mr2; } }
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#PicoLisp
PicoLisp
(de ppmMedianFilter (Radius Ppm) (let Len (inc (* 2 Radius)) (make (chain (head Radius Ppm)) (for (Y Ppm T (cdr Y)) (NIL (nth Y Len) (chain (tail Radius Y)) ) (link (make (chain (head Radius (get Y (inc Radius)))) (for (X (head Len Y) T) (NIL (nth X 1 Len) (chain (tail Radius (get X (inc Radius)))) ) (link (cdr (get (sort (mapcan '((Y) (mapcar '((C) (cons (+ (* (car C) 2126) # Red (* (cadr C) 7152) # Green (* (caddr C) 722) ) # Blue C ) ) (head Len Y) ) ) X ) ) (inc Radius) ) ) ) (map pop X) ) ) ) ) ) ) )
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Python
Python
import Image, ImageFilter im = Image.open('image.ppm')   median = im.filter(ImageFilter.MedianFilter(3)) median.save('image2.ppm')
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; 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.
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h>   // we return a static buffer; caller wants it, caller copies it char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; }   int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, 1234567890};   int i; char *m; for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { if (!(m = mid3(x[i]))) m = "error"; printf("%d: %s\n", x[i], m); } return 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)
#OCaml
OCaml
exception Lost exception Won   let put_mines g m n mines_number = let rec aux i = if i < mines_number then begin let x = Random.int n and y = Random.int m in if g.(y).(x) then aux i else begin g.(y).(x) <- true; aux (succ i) end end in aux 0   let print_abscissas n = print_string "\n "; for x = 1 to n do print_int (x mod 10) done; print_string "\n "; for x = 1 to n do print_char '|' done; print_newline()   let print_display d n = print_abscissas n; Array.iteri (fun y line -> Printf.printf " %2d - " (y+1); (* print ordinates *) Array.iter print_char line; print_newline() ) d; print_newline()   let reveal d g n = print_abscissas n; Array.iteri (fun y line -> Printf.printf " %2d - " (y+1); (* print ordinates *) Array.iteri (fun x c -> print_char ( match c, g.(y).(x) with | '0'..'9', _ -> c | '.', true -> 'x' | '?', true -> 'X' | '?', false -> 'N' | '.', false -> '.' | _ -> c) ) line; print_newline() ) d; print_newline()   let toggle_mark d x y = match d.(y).(x) with | '.' -> d.(y).(x) <- '?' | '?' -> d.(y).(x) <- '.' | _ -> ()   let rec feedback g d x y = if d.(y).(x) = '.' then begin let n = ref 0 in (* the number of mines around *) for i = (pred y) to (succ y) do for j = (pred x) to (succ x) do try if g.(i).(j) then incr n with _ -> () done; done; match !n with | 0 -> (* recursive feedback when no mines are around *) d.(y).(x) <- ' '; for j = (pred y) to (succ y) do for i = (pred x) to (succ x) do try feedback g d i j with _ -> () done done | _ -> d.(y).(x) <- (string_of_int !n).[0] end   let clear_cell g d x y = if g.(y).(x) then (d.(y).(x) <- '!'; raise Lost) else feedback g d x y   let rec user_input g d = try let s = read_line() in match Scanf.sscanf s "%c %d %d" (fun c x y -> c,x,y) with | 'm', x, y -> toggle_mark d (x-1) (y-1) | 'c', x, y -> clear_cell g d (x-1) (y-1) | _ -> raise Exit with Exit | Scanf.Scan_failure _ | Invalid_argument "index out of bounds" -> print_string "# wrong input, try again\n> "; user_input g d   let check_won g d = let won = ref true in Array.iteri (fun y line -> Array.iteri (fun x c -> match c, g.(y).(x) with | '.', _ -> won := false | '?', false -> won := false | _ -> () ) line ) d; if !won then raise Won   let minesweeper n m percent = let round x = int_of_float (floor (x +. 0.5)) in let mines_number = round ((float (n * m)) *. percent) in (* the ground containing the mines *) let g = Array.make_matrix m n false in put_mines g m n mines_number; Printf.printf "# You have to find %d mines\n" mines_number; (* what's displayed to the user *) let d = Array.make_matrix m n '.' in try while true do print_display d n; print_string "> "; user_input g d; check_won g d; done with | Lost -> print_endline "# You lost!"; reveal d g n | Won -> print_endline "# You won!"; reveal d g n   let () = Random.self_init(); let ios, fos = int_of_string, float_of_string in let n, m, percent = try ios Sys.argv.(1), ios Sys.argv.(2), fos Sys.argv.(3) with _ -> try ios Sys.argv.(1), ios Sys.argv.(2), 0.2 with _ -> (6, 4, 0.2) in minesweeper n m percent; ;;
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
#Sidef
Sidef
func find_B10(n, b=10) {   return 0 if (n == 0)   var P = n.of(-1) for (var m = 0; P[0] == -1; ++m) {   for r in (0..n) {   next if (P[r] == -1) next if (P[r] == m)   with ((powmod(b, m, n) + r) % n) { |t| P[t] = m if (P[t] == -1) } } }   var R = 0 var r = 0   do { R += b**P[r] r = (r - powmod(b, P[r], n))%n } while (r > 0)   return R }   printf("%5s: %28s  %s\n", 'Number', 'B10', 'Multiplier')   for n in (1..10, 95..105, 297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878) { printf("%6d: %28s  %s\n", n, var a = find_B10(n), a/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} .
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const proc: main is func begin writeln(modPow(2988348162058574136915891421498819466320163312926952423791023078876139_, 2351399303373464486466122544523690094744975233415544072992656881240319_, 10_ ** 40)); end func;
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Sidef
Sidef
say expmod( 2988348162058574136915891421498819466320163312926952423791023078876139, 2351399303373464486466122544523690094744975233415544072992656881240319, 10**40)
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an 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.
#PicoLisp
PicoLisp
(de metronome (Bpm) (if (fork) (let Pid @ (for Pendulum '(" /" . ("^H^H\\ " "^H^H /" .)) (tell Pid 'call "/usr/bin/beep" "-f" 440 "-l" 40) (prin Pendulum) (T (key (*/ 30000 Bpm)) (tell Pid 'bye)) ) (prinl) ) (wait) ) )
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an 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.
#Pure_Data
Pure Data
#N canvas 553 78 360 608 10; #X obj 20 20 cnv 15 320 140 empty empty empty 20 12 0 14 -228856 -66577 0; #X obj 20 190 cnv 15 320 36 empty empty empty 20 12 0 14 -233017 -66577 0; #X obj 67 30 vradio 20 1 0 6 empty beats empty 0 -8 0 10 -86277 -262144 -1 1; #X text 40 33 1/1; #X text 40 53 2/2; #X text 40 73 3/4; #X text 40 93 4/4; #X text 40 133 6/8; #X obj 67 167 + 1; #X floatatom 67 201 5 0 0 0 beats - -; #X obj 181 32 vsl 20 115 208 40 0 0 empty bpm empty 25 10 0 10 -86277 -262144 -1 5971 0; #X text 208 42 Larghetto 60-66; #X text 208 58 Adagio 66-76; #X text 208 74 Andante 76-108; #X text 208 90 Moderato 108-120; #X text 208 106 Allegro 120-168; #X text 208 122 Presto 168-200; #X text 208 138 Prestissimo 200-208; #X text 208 26 Largo 40-60; #X obj 181 167 int; #X floatatom 181 201 5 0 0 1 bpm - -; #X obj 149 246 expr 1000 / ($f1/60); #X obj 122 125 tgl 25 0 empty on on/off -4 -7 0 10 -261682 -86277 -86277 0 1; #X obj 122 270 metro; #X obj 122 291 int; #X obj 42 249 + 1; #X obj 52 275 mod; #X obj 122 312 moses 1; #X obj 122 347 bng 32 250 50 0 empty empty empty 17 7 0 10 -228856 -258113 -1; #X obj 161 347 bng 32 250 50 0 empty empty empty 17 7 0 10 -228856 -260097 -1; #X msg 81 399 1 2 \, 1 2 1 \, 0 3 2; #X obj 81 420 vline~; #X msg 200 399 1 2 \, 1 2 1 \, 0 3 2; #X obj 200 420 vline~; #X obj 20 420 osc~ 1400; #X obj 139 420 osc~ 1230; #X obj 65 455 *~; #X obj 184 455 *~; #X obj 116 559 dac~; #X obj 117 523 +~; #X obj 278 490 loadbang; #X msg 278 511 \; pd dsp 1 \; beats 1 \; bpm 120 \; on 1; #X connect 2 0 8 0; #X connect 8 0 9 0; #X connect 9 0 26 1; #X connect 10 0 19 0; #X connect 19 0 20 0; #X connect 20 0 21 0; #X connect 21 0 23 1; #X connect 22 0 23 0; #X connect 23 0 24 0; #X connect 24 0 25 0; #X connect 24 0 27 0; #X connect 25 0 26 0; #X connect 26 0 24 1; #X connect 27 0 28 0; #X connect 27 1 29 0; #X connect 28 0 30 0; #X connect 29 0 32 0; #X connect 30 0 31 0; #X connect 31 0 36 1; #X connect 32 0 33 0; #X connect 33 0 37 1; #X connect 34 0 36 0; #X connect 35 0 37 0; #X connect 36 0 39 0; #X connect 37 0 39 1; #X connect 39 0 38 0; #X connect 39 0 38 1; #X connect 40 0 41 0;
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active 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.
#Raku
Raku
class Semaphore { has $.tickets = Channel.new; method new ($max) { my $s = self.bless; $s.tickets.send(True) xx $max; $s; } method acquire { $.tickets.receive } method release { $.tickets.send(True) } }   sub MAIN ($units = 5, $max = 2) { my $sem = Semaphore.new($max);   my @units = do for ^$units -> $u { start { $sem.acquire; say "unit $u acquired"; sleep 2; $sem.release; say "unit $u released"; } } await @units; }
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.
#Raven
Raven
# four workers may be concurrent 4 semaphore as sem   thread worker 5 each as i sem acquire # tid is thread id tid "%d acquired semaphore\n" print 2000 ms sem release # let others acquire 100 ms   # start 10 threads group 10 each drop worker list as workers
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local const integer: n is 12; var integer: i is 0; var integer: j is 0; begin for j range 1 to n do write(j lpad 3 <& " "); end for; writeln; writeln("-" mult 4 * n); for i range 1 to n do for j range 1 to n do if j < i then write(" "); else write(i * j lpad 3 <& " "); end if; end for; writeln("|" <& i lpad 3); end for; end func;
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
#Swift
Swift
public func mianChowla(n: Int) -> [Int] { var mc = Array(repeating: 0, count: n) var ls = [2: true] var sum = 0   mc[0] = 1   for i in 1..<n { var lsx = [Int]()   jLoop: for j in (mc[i-1]+1)... { mc[i] = j   for k in 0...i { sum = mc[k] + j   if ls[sum] ?? false { lsx = [] continue jLoop }   lsx.append(sum) }   for n in lsx { ls[n] = true }   break } }   return mc }   let seq = mianChowla(n: 100)   print("First 30 terms in sequence are: \(Array(seq.prefix(30)))") print("Terms 91 to 100 are: \(Array(seq[90..<100]))")
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
#VBScript
VBScript
' Mian-Chowla sequence - VBScript - 15/03/2019 Const m = 100, mm=28000 ReDim r(mm), v(mm * 2) Dim n, t, i, j, l, s1, s2, iterate_t ReDim seq(m) t0=Timer s1 = "1": s2 = "" seq(1) = 1: n = 1: t = 1 Do While n < m t = t + 1 iterate_t = False For i = 1 to t * 2 v(i) = 0 Next i = 1 Do While i <= t And Not iterate_t If r(i) = 0 Then j = i Do While j <= t And Not iterate_t If r(j) = 0 Then l = i + j If v(l) = 1 Then r(t) = 1 iterate_t = True End If If Not iterate_t Then v(l) = 1 End If j = j + 1 Loop End If i = i + 1 Loop If Not iterate_t Then n = n + 1 seq(n) = t if n<= 30 then s1 = s1 & " " & t if n>=91 and n<=100 then s2 = s2 & " " & t End If Loop wscript.echo "t="& t wscript.echo "The Mian-Chowla sequence for elements 1 to 30:" wscript.echo s1 wscript.echo "The Mian-Chowla sequence for elements 91 to 100:" wscript.echo s2 wscript.echo "Computation time: "& Int(Timer-t0) &" sec"
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.
#Rascal
Rascal
extend ViewParseTree;   layout Whitespace = [\ \t\n]*; syntax A = "a"; syntax B = "b"; start syntax C = "c" | A C B;   layout Whitespace = [\ \t\n]*; lexical Integer = [0-9]+; start syntax E1 = Integer | E "*" E > E "+" E | "(" E ")"  ;
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#REXX
REXX
/*┌───────────────────────────────────────────────────────────────────┐ │ The REXX language doesn't allow for the changing or overriding of │ │ syntax per se, but any of the built-in-functions (BIFs) can be │ │ overridden by just specifying your own. │ │ │ │ To use the REXX's version of a built-in-function, you simply just │ │ enclose the BIF in quotation marks (and uppercase the name). │ │ │ │ The intent is two-fold: the REXX language doesn't have any │ │ reserved words, nor reserved BIFs (Built-In-Functions). │ │ │ │ So, if you don't know that VERIFY is a BIF, you can just code │ │ a subroutine (or function) with that name (or any name), and not │ │ worry about your subroutine being pre-empted. │ │ │ │ Second: if you're not satisfied how a BIF works, you can code │ │ your own. This also allows you to front-end a BIF for debugging │ │ or modifying the BIF's behavior. │ └───────────────────────────────────────────────────────────────────┘ */ yyy='123456789abcdefghi'   rrr = substr(yyy,5) /*returns efghi */ mmm = 'SUBSTR'(yyy,5) /*returns 56789abcdefgji */ sss = "SUBSTR"(yyy,5) /* (same as above) */ exit /*stick a fork in it, we're done.*/   /*──────────────────────────────────SUBSTR subroutine───────────────────*/ substr: return right(arg(1),arg(2))   /*┌───────────────────────────────────────────────────────────────────┐ │ Also, some REXX interpreters treat whitespace(s) as blanks when │ │ performing comparisons. Some of the whitespace characters are: │ │ │ │ NL (newLine) │ │ FF (formFeed) │ │ VT (vertical tab) │ │ HT (horizontal tab or TAB) │ │ LF (lineFeed) │ │ CR (carriage return) │ │ EOF (end-of-file) │ │ and/or others. │ │ │ │ Note that some of the above are ASCII or EBCDIC specific. │ │ │ │ Some REXX interpreters use the OPTIONS statement to force │ │ REXX to only treat blanks as spaces. │ │ │ │ (Both the verb and option may be in lower/upper/mixed case.) │ │ │ │ REXX interpreters which don't recognize any option won't treat │ │ the (below) statement as an error. │ └───────────────────────────────────────────────────────────────────┘ */ options strict_white_space_comparisons /*can be in lower/upper/mixed.*/
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)
#E
E
def millerRabinPrimalityTest(n :(int > 0), k :int, random) :boolean { if (n <=> 2 || n <=> 3) { return true } if (n <=> 1 || n %% 2 <=> 0) { return false } var d := n - 1 var s := 0 while (d %% 2 <=> 0) { d //= 2 s += 1 } for _ in 1..k { def nextTrial := __continue def a := random.nextInt(n - 3) + 2 # [2, n - 2] = [0, n - 4] + 2 = [0, n - 3) + 2 var x := a**d %% n # Note: Will do optimized modular exponentiation if (x <=> 1 || x <=> n - 1) { nextTrial() } for _ in 1 .. (s - 1) { x := x**2 %% n if (x <=> 1) { return false } if (x <=> n - 1) { nextTrial() } } 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
#BCPL
BCPL
get "libhdr"   manifest $( limit = 1000 $)   let mertens(v, max) be $( v!1 := 1 for n = 2 to max do $( v!n := 1 for k = 2 to n do v!n := v!n - v!(n/k) $) $)   let start() be $( let m = vec limit let eqz, crossz = 0, 0   writes("The first 99 Mertens numbers are:*N") mertens(m, limit) for y=0 to 90 by 10 do $( for x=0 to 9 do test x+y=0 then writes(" ") else writed(m!(x+y),3) wrch('*N') $)   for x=2 to limit do if m!x=0 then $( eqz := eqz + 1 unless m!(x-1)=0 do crossz := crossz + 1 $)   writef("M(N) is zero %N times.*N", eqz) writef("M(N) crosses zero %N times.*N", crossz) $)
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.
#Batch_File
Batch File
@echo off & setlocal enabledelayedexpansion   set "menuChoices="fee fie","huff and puff","mirror mirror","tick tock""   call :menu   pause>nul & exit     :menu if defined menuChoices ( set "counter=0" & for %%a in (%menuChoices%) do ( set /a "counter+=1" set "currentMenuChoice=%%a" set option[!counter!]=!currentMenuChoice:"=! ) ) :tryagain cls&echo. for /l %%a in (1,1,%counter%) do echo %%a^) !option[%%a]! echo. set /p "input=Choice 1-%counter%: " echo. for /l %%a in (1,1,%counter%) do ( if !input! equ %%a echo You chose [ %%a^) !option[%%a]! ] & goto :EOF ) echo. echo.Invalid Input. Please try again... pause goto :tryagain
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls. In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution. Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task. The following are acceptable: An original implementation from the specification, reference implementation, or pseudo-code A translation of a correct implementation from another language A library routine in the same language; however, the source must be included here. The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure. RFC 1321 hash code <== string 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890" In addition, intermediate outputs to aid in developing an implementation can be found here. The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
#11l
11l
-V rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]   constants = (0.<64).map(i -> UInt32(UInt64(abs(sin(i + 1)) * 2.0 ^ 32) [&] FFFF'FFFF))   init_values = (UInt32(6745'2301), UInt32(EFCD'AB89), UInt32(98BA'DCFE), UInt32(1032'5476))   [((UInt32, UInt32, UInt32) -> UInt32)] functions functions [+]= (b, c, d) -> (b [&] c) [|] ((-)b [&] d) functions [+]= (b, c, d) -> (d [&] b) [|] ((-)d [&] c) functions [+]= (b, c, d) -> b (+) c (+) d functions [+]= (b, c, d) -> c (+) (b [|] (-)d)   [(Int -> Int)] index_functions index_functions [+]= i -> i index_functions [+]= i -> (5 * i + 1) % 16 index_functions [+]= i -> (3 * i + 5) % 16 index_functions [+]= i -> (7 * i) % 16   F md5(=message) V orig_len_in_bits = UInt64(8) * message.len message.append(8'0) L message.len % 64 != 56 message.append(0) message.extend(bytes_from_int(orig_len_in_bits))   V hash_pieces = init_values   L(chunk_ofst) (0 .< message.len).step(64) V (a, b, c, d) = hash_pieces V chunk = message[chunk_ofst .+ 64] L(i) 64 V f = :functions[i I/ 16](b, c, d) V g = :index_functions[i I/ 16](i) V to_rotate = a + f + :constants[i] + UInt32(bytes' chunk[4 * g .+ 4]) V new_b = UInt32(b + rotl(to_rotate, :rotate_amounts[i])) (a, b, c, d) = (d, new_b, b, c) L(val) (a, b, c, d) hash_pieces[L.index] += val   [Byte] r L(x) hash_pieces r.extend([x [&] F'F, (x >> 8) [&] F'F, (x >> 16) [&] F'F, (x >> 24) [&] F'F]) R r   F md5_to_hex(digest) V s = ‘’ L(d) digest s ‘’= hex(d).lowercase().zfill(2) R s   V demo = [Bytes(‘’), Bytes(‘a’), Bytes(‘abc’), Bytes(‘message digest’), Bytes(‘abcdefghijklmnopqrstuvwxyz’), Bytes(‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’), Bytes(‘12345678901234567890123456789012345678901234567890123456789012345678901234567890’)] L(message) demo print(md5_to_hex(md5(message))‘ <= "’message.decode(‘ascii’)‘"’)
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Common_Lisp
Common Lisp
(defun show-allocation () (let ((a (cons 1 2)) (b (cons 1 2))) (declare (dynamic-extent b)) (list a b)))
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#D
D
// D is a system language so its memory management is refined. // D supports thread-local memory on default, global memory, memory // allocated on the stack, the C heap, or the D heap managed by a // garbage collector, both manually and automatically.   // This program looks scary because its purpose is to show all the // variety. But lot of this stuff is only for special situations // (like alloca), and it's not necessary in most user code.   enum int nInts = 10; // Compile-time constant.   // This is thread-local: int[nInts] data1;   // This is global: __gshared int[nInts] data2;   void main() { // Static memory, it's thread-local but its name is usable // only locally: static int[nInts] data3;   // Static memory, it's global but its name is usable only locally: __gshared static int[nInts] data4;   // ---------------------- // D supports the functions that manage memory of the C heap: import core.stdc.stdlib: malloc, calloc, realloc, free, alloca;   // Allocates space for some integers on the heap, // the memory is not initialized: auto ptr1 = cast(int*)malloc(nInts * int.sizeof); if (ptr1 == null) return;   // Increases the space for one more integer, the new space // is not initialized, but the old space is not modified: ptr1 = cast(int*)realloc(ptr1, (nInts + 1) * int.sizeof); if (ptr1 == null) return;   // calloc allocates on the heap and zeros the memory: auto ptr2 = cast(int*)calloc(nInts, int.sizeof); if (ptr2 == null) return;   // You can create a slice from a pointer: auto slice1 = ptr2[0 .. nInts];   // Frees the memory: free(ptr2); free(ptr1);   // ---------------------- import core.stdc.stdio: puts;   static struct Test { ~this() { puts("Test destructor"); } }   // Memory allocated on the stack: Test[2] array1;   { // More memory allocated on the stack: Test[2] array2; // Here array2 is removed from the stack, // and all array2 destructors get called. } puts("Block end.");   // alloca is supported in D. It's similar to malloc but the // memory is allocated on the stack: int* ptr3 = cast(int*)alloca(nInts * int.sizeof);   // You can create a slice from the pointer: auto slice2 = ptr3[0 .. nInts];   // Do not free the memory allocated with alloca: // free(ptr3);   // ---------------------- // Allocates a dynamic array on the D heap managed by // the D garbage collector: auto array3 = new int[nInts];   // Try to reserve capacity for a dynamic array on the D heap: int[] array4; array4.reserve(nInts); assert(array4.capacity >= nInts); assert(array4.length == 0);   // Appends one integer to the dynamic array: array4 ~= 100;   // Assume that it is safe to append to this array. Appends made // to this array after calling this function may append in place, // even if the array was a slice of a larger array to begin with: array4.assumeSafeAppend; array4 ~= 200; array4 ~= 300; assert(array4.length == 3); // See here for more info: // http://dlang.org/d-array-article.html     // Allocates a struct and a class on the D GC heap: static class Foo { int x; } Test* t = new Test; // This destructor will not be called. Foo f1 = new Foo; // f1 is a class reference.   // Optional. Destroys the given object and puts it in // an invalid state: f1.destroy;   import std.typecons: scoped;   // Allocates a class on the stack, unsafe: auto f3 = scoped!Foo();   // ---------------------- import core.memory: GC;   // Allocates an aligned block from the GC, initialized to zero. // Plus it doesn't scan through this block on collect. auto ptr4 = cast(int*)GC.calloc(nInts * int.sizeof, GC.BlkAttr.NO_SCAN);   // No need to test for this, because GC.calloc usually // throws OutOfMemoryError if it can't allocate. // if (ptr4 == null) // exit(1);   GC.free(ptr4); // This is optional. }
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = ImportString["PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz", "CSV"]; b = ImportString["PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3", "CSV"]; a = <|a[[1, 1]] -> #1, a[[1, 2]] -> #2|> & @@@ Rest[a]; b = <|b[[1, 1]] -> #1, b[[1, 2]] -> If[#2 != "", DateObject[#2], Missing[]], b[[1, 3]] -> If[#3 =!= "", #3, Missing[]]|> & @@@ Rest[b]; j = JoinAcross[a, b, Key["PATIENT_ID"], "Outer"]; gr = GroupBy[j, #["PATIENT_ID"] &]; <|"PATIENT_ID" -> #[[1, "PATIENT_ID"]], "LASTNAME" -> #[[1, "LASTNAME"]], "VISIT_DATE" -> If[DeleteMissing[#[[All, "VISIT_DATE"]]] =!= {}, Max@DeleteMissing[#[[All, "VISIT_DATE"]]], Missing[]], "SCORE_SUM" -> If[DeleteMissing@#[[All, "SCORE"]] =!= {}, Total@DeleteMissing@#[[All, "SCORE"]], Missing[]], "SCORE_AVG" -> If[DeleteMissing@#[[All, "SCORE"]] =!= {}, Mean@DeleteMissing@#[[All, "SCORE"]], Missing[]]|> & /@ gr // Dataset
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 -
#PicoLisp
PicoLisp
# Define bit constants (for (N . Mask) '(CD RD TD DTR SG DSR RTS CTS RI) (def Mask (>> (- 1 N) 1)) )   # Test if Clear to send (when (bit? CTS Data) ... )
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 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 -
#PL.2FI
PL/I
  declare 1 RS232_layout, 2 Carrier_Detect Bit(1), 2 Received_Data Bit(1), 2 Transmitted_Data Bit(1), 2 Data_Terminal_ready Bit(1), 2 Signal_Ground Bit(1), 2 Data_Set_Ready Bit(1), 2 Request_To_Send Bit(1), 2 Clear_To_Send Bit(1), 2 Ring_Indicator Bit(1);  
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 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 -
#Python
Python
from ctypes import Structure, c_int   rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split()   class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_9pin]     class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Racket
Racket
  #lang racket (require images/flomap math)   (define lena <<paste image of Lena here>> ) (define bm (send lena get-bitmap)) (define fm (bitmap->flomap bm))   (flomap->bitmap (build-flomap 4 (send bm get-width) (send bm get-height) (λ (k x y) (define (f x y) (flomap-ref fm k x y)) (median < (list (f (- x 1) (- y 1)) (f (- x 1) y) (f (- x 1) (+ y 1)) (f x (- y 1)) (f x y) (f x (+ y 1)) (f (+ x 1) (- y 1)) (f (+ x 1) y) (f (+ x 1) (+ y 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)
#Raku
Raku
use PDL:from<Perl5>; use PDL::Image2D:from<Perl5>;   my $image = rpic 'plasma.png'; my $smoothed = med2d($image, ones(3,3), {Boundary => 'Truncate'}); wpic $smoothed, 'plasma_median.png';
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; 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.
#C.2B.2B
C++
#include <iostream>   std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size();   if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } }   int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0};   for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }  
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)
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;   { package Local::Field;   use constant { REAL => 0, SHOW => 1, COUNT => 2, };   sub new { my ($class, $width, $height, $percent) = @_; my $field; for my $x (1 .. $width) { for my $y (1 .. $height) { $field->[$x - 1][$y - 1][REAL] = ' '; $field->[$x - 1][$y - 1][SHOW] = '.'; } } for (1 .. $percent / 100 * $width * $height) { my ($x, $y) = map int rand $_, $width, $height; redo if 'm' eq $field->[$x][$y][REAL]; $field->[$x][$y][REAL] = 'm'; for my $i ($x - 1 .. $x + 1) { for my $j ($y - 1 .. $y + 1) { $field->[$i][$j][COUNT]++ if $i >= 0 and $j >= 0 and $i <= $#$field and $j <= $#{ $field->[0] }; } } } bless $field, $class; }     sub show { my ($self) = @_; print "\n "; printf '%2d ', $_ + 1 for 0 .. $#$self; print "\n";   for my $row (0 .. $#{ $self->[0] }) { printf '%2d ', 1 + $row; for my $column (0 .. $#$self) { print $self->[$column][$row][SHOW], ' '; } print "\n"; } }     sub mark { my ($self, $x, $y) = @_; $_-- for $x, $y;   if ('.' eq $self->[$x][$y][SHOW]) { $self->[$x][$y][SHOW] = '?';   } elsif ('?' eq $self->[$x][$y][SHOW]) { $self->[$x][$y][SHOW] = '.'; } }     sub end { my $self = shift; for my $y (0 .. $#{ $self->[0] }) { for my $x (0 .. $#$self) { $self->[$x][$y][SHOW] = '!' if '.' eq $self->[$x][$y][SHOW] and 'm' eq $self->[$x][$y][REAL]; $self->[$x][$y][SHOW] = 'x' if '?' eq $self->[$x][$y][SHOW] and 'm' ne $self->[$x][$y][REAL]; } } $self->show; exit; }   sub _declassify { my ($self, $x, $y) = @_; return if '.' ne $self->[$x][$y][SHOW]; if (' ' eq $self->[$x][$y][REAL] and '.' eq $self->[$x][$y][SHOW]) { $self->[$x][$y][SHOW] = $self->[$x][$y][COUNT] || ' '; } return if ' ' ne $self->[$x][$y][SHOW];   for my $i ($x - 1 .. $x + 1) { next if $i < 0 or $i > $#$self; for my $j ($y - 1 .. $y + 1) { next if $j < 0 or $j > $#{ $self->[0] }; no warnings 'recursion'; $self->_declassify($i, $j); } } }     sub clear { my ($self, $x, $y) = @_; $_-- for $x, $y; return unless '.' eq $self->[$x][$y][SHOW];   print "You lost.\n" and $self->end if 'm' eq $self->[$x][$y][REAL];   $self->_declassify($x, $y); }     sub remain { my $self = shift; my $unclear = 0; for my $column (@$self) { for my $cell (@$column) { $unclear++ if '.' eq $cell->[SHOW]; } } return $unclear; }   }   sub help { print << '__HELP__'; Commands: h ... help q ... quit m X Y ... mark/unmark X Y c X Y ... clear X Y __HELP__ }     my ($width, $height, $percent) = @ARGV; $width ||= 6; $height ||= 4; $percent ||= 15;   my $field = 'Local::Field'->new($width, $height, $percent);   my $help = 1; while (1) { $field->show; help() if $help; $help = 0; my $remain = $field->remain; last if 0 == $remain; print "Cells remaining: $remain.\n"; my $command = <STDIN>; exit if $command =~ /^q/i;   if ($command =~ /^m.*?([0-9]+).*?([0-9]+)/i) { $field->mark($1, $2);   } elsif ($command =~ /^c.*?([0-9]+).*?([0-9]+)/i) { $field->clear($1, $2);   } elsif ($command =~ /^h/i) { $help = 1;   } else { print "Huh?\n"; } } print "You won!\n";  
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
#Tcl
Tcl
  package require Tcl 8.5   ## power of ten, modulo --> (10**expo % modval) suited for large expo proc potmod {expo modval} { if {$expo < 0} { return 0 } if {$modval < 2} { return 0 } ;# x mod 1 = 0 set r 1 set p [expr {10 % $modval}] while {$expo} { set half [expr {$expo / 2}] set odd [expr {$expo % 2}] if {$expo % 2} { set r [expr {($r * $p) % $modval}] ;# r *= p if {$r == 0} break } set expo [expr {$expo / 2}] if {$expo} { set p [expr {($p * $p) % $modval}] ;# p *= p if {$p == 1} break } } return $r }   proc sho_sol {n r} { puts "B10([format %4s $n]) = [format %28s $r] = n * [expr {$r / $n}]" }   proc do_1 {n} { if {$n < 2} { sho_sol $n 1 return } set k 0 ;# running exponent for powers of 10 set potmn 1 ;# (k-th) power of ten mod n set mvbyk($potmn) $k ;# highest k for sum with mod value set canmv [list $potmn] ;# which indices are in mvbyk(.) set solK -1 ;# highest exponent of first solution   for {incr k} {$k <= $n} {incr k} { ## By now we know what can be achieved below 10**k. ## Combine that with the new 10**k ... set potmn [expr {(10 * $potmn) % $n}] ;# new power of 10 if {$potmn == 0} { ;# found a solution set solK $k ; break } foreach mv $canmv { ## the mod value $mv can be constructed below $k set newmv [expr {($potmn + $mv) % $n}] ## ... and now we can also do $newmv. Solution? if {$newmv == 0} { set solK $k ; break } if { ! [info exists mvbyk($newmv)] } { ;# is new set mvbyk($newmv) $k ;# remember highest expo lappend canmv $newmv } } if {$solK >= 0} { break }   set newmv $potmn if { ! [info exists mvbyk($newmv)] } { set mvbyk($newmv) $k lappend canmv $newmv } } ## Reconstruct solution ... set k $solK set mv 0 ;# mod value of $k and below (it is the solution) set r "1" ;# top result, including $k while 1 { ## 10**k is the current largest power of ten in the solution ## $r includes it, already, but $mv is not yet updated set mv [expr {($mv - [potmod $k $n]) % $n}] if {$mv == 0} { append r [string repeat "0" $k] break } set subk $mvbyk($mv) append r [string repeat "0" [expr {$k - $subk - 1}]] "1" set k $subk } sho_sol $n $r }   proc do_range {lo hi} { for {set n $lo} {$n <= $hi} {incr n} { do_1 $n } }   do_range 1 10 do_range 95 105 foreach n {297 576 594 891 909 999 1998 2079 2251 2277 2439 2997 4878} { do_1 $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} .
#Swift
Swift
import BigInt   func modPow<T: BinaryInteger>(n: T, e: T, m: T) -> T { guard e != 0 else { return 1 }   var res = T(1) var base = n % m var exp = e   while true { if exp & 1 == 1 { res *= base res %= m }   if exp == 1 { return res }   exp /= 2 base *= base base %= m } }   let a = BigInt("2988348162058574136915891421498819466320163312926952423791023078876139") let b = BigInt("2351399303373464486466122544523690094744975233415544072992656881240319")   print(modPow(n: a, e: b, m: BigInt(10).power(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} .
#Tcl
Tcl
package require Tcl 8.5   # Algorithm from http://introcs.cs.princeton.edu/java/78crypto/ModExp.java.html # but Tcl has arbitrary-width integers and an exponentiation operator, which # helps simplify the code. proc tcl::mathfunc::modexp {a b n} { if {$b == 0} {return 1} set c [expr {modexp($a, $b / 2, $n)**2 % $n}] if {$b & 1} { set c [expr {($c * $a) % $n}] } return $c }
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.
#PureBasic
PureBasic
Structure METRONOMEs msPerBeat.i BeatsPerMinute.i BeatsPerCycle.i volume.i canvasGadget.i w.i h.i originX.i originY.i radius.i activityStatus.i EndStructure   Enumeration ;gadgets #TEXT_MSPB ;milliseconds per beat #STRING_MSPB ;milliseconds per beat #TEXT_BPM ;beats per minute #STRING_BPM ;beats per minute #TEXT_BPC ;beats per cycle #STRING_BPC ;beats per cycle #BUTTON_VOLM ;volume - #BUTTON_VOLP ;volume + #BUTTON_START ;start #SPIN_BPM #CANVAS_METRONOME EndEnumeration   Enumeration ;sounds #SOUND_LOW #SOUND_HIGH EndEnumeration   #WINDOW = 0 ;window   Procedure handleError(Value, text.s) If Not Value: MessageRequester("Error", text): End: EndIf EndProcedure   Procedure drawMetronome(*m.METRONOMEs, Angle.f, cycleCount = 0) Protected CircleX, CircleY, circleColor If StartDrawing(CanvasOutput(*m\canvasGadget)) Box(0, 0, *m\w, *m\h, RGB(0, 0, 0)) CircleX = Int(*m\radius * Cos(Radian(Angle))) CircleY = Int(*m\radius * Sin(Radian(Angle))) If Angle = 90 If cycleCount: circleColor = RGB(255, 0, 0): Else: circleColor = RGB(0, 255, 0): EndIf LineXY(*m\originX, *m\originY, *m\originX, *m\originY - CircleY, RGB(255, 255, 0)) Circle(*m\originX + CircleX, *m\originY - CircleY - *m\radius * 0.15, 10, circleColor) Else LineXY(*m\originX, *m\originY - *m\radius * 1.02, *m\originX, *m\originY - *m\radius, RGB(255, 255, 0)) LineXY(*m\originX, *m\originY, *m\originX + CircleX, *m\originY - CircleY, RGB(255, 255, 0)) EndIf   StopDrawing()   ProcedureReturn 1 EndIf EndProcedure   Procedure.i Metronome(*m.METRONOMEs) Protected milliseconds = Int((60 * 1000) / *m\BeatsPerMinute) Protected msPerFrame, framesPerBeat Protected i, j, cycleCount, startTime, frameEndTime, delayTime, delayError, h.f   ;calculate metronome angles for each frame of animation If *m\BeatsPerMinute < 60 framesPerBeat = Round(milliseconds / 150, #PB_Round_Nearest) Else framesPerBeat = Round((*m\BeatsPerMinute - 420) / -60, #PB_Round_Nearest) EndIf   If framesPerBeat < 1 framesPerBeat = 1 Dim metronomeFrameAngle.f(1, framesPerBeat) metronomeFrameAngle(0, 1) = 90 metronomeFrameAngle(1, 1) = 90 Else Dim metronomeFrameAngle.f(1, framesPerBeat * 2) For j = 1 To framesPerBeat h = 45 / framesPerBeat metronomeFrameAngle(0, j) = 90 - h * (j - 1) metronomeFrameAngle(0, framesPerBeat + j) = 45 + h * (j - 1) metronomeFrameAngle(1, j) = 90 + h * (j - 1) metronomeFrameAngle(1, framesPerBeat + j) = 135 - h * (j - 1) Next framesPerBeat * 2 EndIf msPerFrame = milliseconds / framesPerBeat   PlaySound(#SOUND_HIGH) startTime = ElapsedMilliseconds() Repeat For i = 0 To 1 frameEndTime = startTime + msPerFrame For j = 1 To framesPerBeat drawMetronome(*m, metronomeFrameAngle(i, j), cycleCount)   ;check for thread exit If *m\activityStatus < 0 *m\activityStatus = 0 ProcedureReturn EndIf   delayTime = frameEndTime - ElapsedMilliseconds() If (delayTime - delayError) >= 0 Delay(frameEndTime - ElapsedMilliseconds() - delayError) ;wait the remainder of frame ElseIf delayTime < 0 delayError = - delayTime EndIf frameEndTime + msPerFrame Next   ;check for thread exit If *m\activityStatus < 0 *m\activityStatus = 0 ProcedureReturn EndIf   While (ElapsedMilliseconds() - startTime) < milliseconds: Wend   SetGadgetText(*m\msPerBeat, Str(ElapsedMilliseconds() - startTime)) cycleCount + 1: cycleCount % *m\BeatsPerCycle If cycleCount = 0 PlaySound(#SOUND_HIGH) Else PlaySound(#SOUND_LOW) EndIf startTime + milliseconds Next ForEver EndProcedure   Procedure startMetronome(*m.METRONOMEs, MetronomeThread) ;start up the thread with new values *m\BeatsPerMinute = Val(GetGadgetText(#STRING_BPM)) *m\BeatsPerCycle = Val(GetGadgetText(#STRING_BPC)) *m\activityStatus = 1   If *m\BeatsPerMinute MetronomeThread = CreateThread(@Metronome(), *m) EndIf ProcedureReturn MetronomeThread EndProcedure   Procedure stopMetronome(*m.METRONOMEs, MetronomeThread) ;if the thread is running: stop it If IsThread(MetronomeThread) *m\activityStatus = -1 ;signal thread to stop EndIf drawMetronome(*m, 90) EndProcedure     Define w = 360, h = 360, ourMetronome.METRONOMEs   ;initialize the metronome With ourMetronome \msPerBeat = #STRING_MSPB \canvasGadget = #CANVAS_METRONOME \volume = 10 \w = w \h = h \originX = w / 2 \originY = h / 2 \radius = 100 EndWith   ourMetronome\canvasGadget = #CANVAS_METRONOME   ;initialize sounds handleError(InitSound(), "Sound system is Not available") handleError(CatchSound(#SOUND_LOW, ?sClick, ?eClick - ?sClick), "Could Not CatchSound") handleError(CatchSound(#SOUND_HIGH, ?sClick, ?eClick - ?sClick), "Could Not CatchSound") SetSoundFrequency(#SOUND_HIGH, 50000) SoundVolume(#SOUND_LOW, ourMetronome\volume) SoundVolume(#SOUND_HIGH, ourMetronome\volume)   ;setup window & GUI Define Style, i, wp, gh   Style = #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_MinimizeGadget handleError(OpenWindow(#WINDOW, 0, 0, w + 200 + 12, h + 4, "Metronome", Style), "Not OpenWindow") SetWindowColor(#WINDOW, $505050)   If LoadFont(0, "tahoma", 9, #PB_Font_HighQuality | #PB_Font_Bold) SetGadgetFont(#PB_Default, FontID(0)) EndIf   i = 3: wp = 10: gh = 22 TextGadget(#TEXT_MSPB, w + wp, gh * i, 100, gh, "MilliSecs/Beat ", #PB_Text_Center) StringGadget(#STRING_MSPB, w + wp + 108, gh * i, 90, gh, "0", #PB_String_ReadOnly): i + 2 TextGadget(#TEXT_BPM, w + wp, gh * i, 100, gh,"Beats/Min ", #PB_Text_Center) StringGadget(#STRING_BPM, w + wp + 108, gh * i, 90, gh, "120", #PB_String_Numeric): i + 2 GadgetToolTip(#STRING_BPM, "Valid range is 20 -> 240") TextGadget(#TEXT_BPC, w + wp, gh * i, 100, gh,"Beats/Cycle ", #PB_Text_Center) StringGadget(#STRING_BPC, w + wp + 108, gh * i, 90, gh, "4", #PB_String_Numeric): i + 2 GadgetToolTip(#STRING_BPC, "Valid range is 1 -> BPM") ButtonGadget(#BUTTON_START, w + wp, gh * i, 200, gh, "Start", #PB_Button_Toggle): i + 2 ButtonGadget(#BUTTON_VOLM, w + wp, gh * i, 100, gh, "-Volume") ButtonGadget(#BUTTON_VOLP, w + wp + 100, gh * i, 100, gh, "+Volume") CanvasGadget(ourMetronome\canvasGadget, 0, 0, ourMetronome\w, ourMetronome\h, #PB_Image_Border) drawMetronome(ourMetronome, 90)   Define msg, GID, MetronomeThread, Value Repeat ;the control loop for our application msg = WaitWindowEvent(1) GID = EventGadget() etp = EventType()   If GetAsyncKeyState_(#VK_ESCAPE): End: EndIf ;remove when app is o.k.   Select msg   Case #PB_Event_CloseWindow End   Case #PB_Event_Gadget Select GID   Case #STRING_BPM If etp = #PB_EventType_LostFocus Value = Val(GetGadgetText(#STRING_BPM)) If Value > 390 Value = 390 ElseIf Value < 20 Value = 20 EndIf SetGadgetText(#STRING_BPM, Str(Value)) EndIf   Case #STRING_BPC If etp = #PB_EventType_LostFocus Value = Val(GetGadgetText(#STRING_BPC)) If Value > Val(GetGadgetText(#STRING_BPM)) Value = Val(GetGadgetText(#STRING_BPM)) ElseIf Value < 1 Value = 1 EndIf SetGadgetText(#STRING_BPC, Str(Value)) EndIf   Case #BUTTON_VOLP, #BUTTON_VOLM ;change volume If GID = #BUTTON_VOLP And ourMetronome\volume < 100 ourMetronome\volume + 10 ElseIf GID = #BUTTON_VOLM And ourMetronome\volume > 0 ourMetronome\volume - 10 EndIf SoundVolume(#SOUND_LOW, ourMetronome\volume) SoundVolume(#SOUND_HIGH, ourMetronome\volume)   Case #BUTTON_START ;the toggle button for start/stop Select GetGadgetState(#BUTTON_START) Case 1 stopMetronome(ourMetronome, MetronomeThread) MetronomeThread = startMetronome(ourMetronome, MetronomeThread) SetGadgetText(#BUTTON_START,"Stop") Case 0 stopMetronome(ourMetronome, MetronomeThread) SetGadgetText(#BUTTON_START,"Start") EndSelect   EndSelect EndSelect ForEver End   DataSection ;a small wav file saved as raw data sClick: Data.q $0000082E46464952,$20746D6645564157,$0001000100000010,$0000AC440000AC44 Data.q $6174616400080001,$8484848300000602,$8B8A898886868585,$C0B3A9A29C95918E Data.q $31479BD3CED0CFCF,$3233323232323331,$BDAEC4C9A1423133,$D0CFCFD0CFD1CDD4 Data.q $323232333770A9CB,$2E34313332333232,$CFD0CFCACFCFAF53,$9783AAD3CED0CFD0 Data.q $3233313332448AA1,$4430333233323233,$CFD0CFAE7D7E9483,$B7B9C3B8BFD1CED0 Data.q $3233313037476898,$3E48493D32333233,$85959187775C4338,$898A8F8D807A7978 Data.q $737F898381888D8D,$3131435564717A77,$332F36413A343234,$827B7873695C4D37 Data.q $9C9B949191908F8A,$4D50515A67758694,$5451484341414245,$7B83868782756559 Data.q $565D5F616365676E,$7871675F57504B4E,$797C8083827E7C7B,$4D525E686C6D7176 Data.q $4D4B4B474343464A,$8B82796F655D5953,$7B7C83888B909392,$5153595E666F767B Data.q $5A5A5B5B59575553,$696C6E6D67615E5B,$7879777573726F6B,$71727376797C7B79 Data.q $505352505159646C,$6B6153463C3B414A,$A09B908379706D6E,$6F767A7E858C949C Data.q $4D4D4845484E5662,$80796F645B544E4C,$8487888885828283,$555A5D606369737D Data.q $6A665F58524E4E51,$878E8F8B867D736D,$54606B72797F8081,$5852504F4E4E4C4D Data.q $7E7B7A79756F675F,$6B6C6F757C7F8182,$6D6865676C6F6E6C,$6E6B6C7074777773 Data.q $615E5D60676F7372,$7069636061636463,$81817F7C7A797976,$65676B6E72797E80 Data.q $65625F5E5D5D5F62,$7D7C7B7875716E6A,$6F74777B7E7F7F7E,$454950565D63676A Data.q $605A55504B464343,$9E9F9D978E817469,$6E7D8A93989A9B9C,$444546494C505861 Data.q $7B756F665C534C46,$7E82858788888580,$5C5D61666B70757A,$6A6B6B6B6965615E Data.q $646B717676736F6B,$727272716D676261,$8285878885817A74,$5F5F636A72797D80 Data.q $645D58585A5E6060,$827D79777877746D,$7878797C80848685,$6A686664666B7075 Data.q $76726C666364686B,$807E7B7878787878,$656A6F74797B7D7F,$59585A5C5D5F6163 Data.q $84807C79746D665E,$777C81878B8C8B89,$555352555B636B72,$82776B625C595957 Data.q $989B9A979493918B,$656A6E7277818A92,$535457575656585E,$6E6E6F6D675E5753 Data.q $898C9398968D7F74,$69717E8C9697918B,$3B39414F5D656767,$695B56565A595145 Data.q $8986878A8F90897B,$7A7875757B848A8C,$747168605E636D76,$7B7365585257636F Data.q $8C8981777272777C,$70757676767A8188,$6A6D6D68625F6269,$8687847D746C6868 Data.q $8485888A89868484,$585A616B747B8083,$5B555355595C5C5A,$8C898786847D7265 Data.q $888C9096999A9892,$6163666C72797F83,$5E554E4B4C52595E,$91887C7169676663 Data.q $8E8E8A88888C9193,$656666676A737E88,$655F585352555B62,$8B88837C756F6B69 Data.q $7E858B8E8E8B898B,$62676B6D6D6C6E74,$6C6C6B6A6764605F,$7C7978787775736F Data.q $8E8C8C8C8D8D8982,$686D747C858C9091,$625C58585B5E6265,$908A837C75706C68 Data.q $848A8E9396989896,$545960676E757A7F,$65605E5D5B575352,$A19D9890877C746C Data.q $8992979A9C9FA1A2,$525355575C64707E,$736D665D56514F50,$8D8D8B8986827E79 Data.q $7777797B7F84898C,$78746F6A6A6E7376,$7B79767372747879,$6C6B69686A6F757A Data.q $7C78746F6D6C6C6D,$888B8C8B88858280,$6F75797B7D7F8184,$6F6D6B686565676A Data.q $8785817D79747270,$868B8D8D8C8A8988,$6F73777A7C7D7F82,$6F6B68656465666A Data.q $8A837D7976757472,$76787A7D82888C8D,$6562606064696F73,$8E8A847C756F6B68 Data.q $8D90939494929190,$606264686F788088,$73685D58585A5D5F,$9B96918C8987837D Data.q $71767B838C959B9D,$5B5756585D63686D,$8C86817B756F6962,$888F939597979591 Data.q $5C606366696F7780,$7A756D6259535458,$9EA2A0988D837E7C,$79858D8F8F8E9097 Data.q $656B6E6D6865666E,$797A79746C656060,$7F7F7F7F7E7C7978,$8381828384848280 Data.q $7F82888E92918D88,$59606A757C7F7F7F,$655E5A5A59585656,$A59F97918A82796E Data.q $7E848A939CA6ABAA,$48454548515E6B76,$8A7C6E6057514E4B,$A9ACABA8A4A09B94 Data.q $5A626A737F8C98A3,$60554D49484A4E54,$A9A19A928A81776B,$848C969FA7ADAFAD Data.q $4B494C525C67717B,$8A7D7167605A544F,$A2A4A5A6A6A49F96,$626970777F89949C Data.q $6B655E56504F545A,$A19F988F8379736E,$848C9296989A9C9F,$61626465676B717A Data.q $807E79736D676261,$86898B8C8A888583,$797A7E8284848484,$77777A7C7E7E7C7A Data.q $7979797B7D7E7C79,$7D7C7B7B7C7C7B7A,$7D7D7C7B7A7B7C7D,$797978777677797B Data.q $787A7A7976757678,$415380817C777576,$2C31000002005255,$30202C36202C3020 eClick: EndDataSection
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.
#Ruby
Ruby
  require 'thread'   # Simple Semaphore implementation class Semaphore def initialize(size = 1) @queue = SizedQueue.new(size) size.times { acquire } end   def acquire tap { @queue.push(nil) } end   def release tap { @queue.pop } end   # @return [Integer] def count @queue.length end   def synchronize release yield ensure acquire end end   def foo(id, sem) sem.synchronize do puts "Thread #{id} Acquired lock" sleep(2) end end   threads = [] n = 5 s = Semaphore.new(3) n.times do |i| threads << Thread.new { foo i, s } end threads.each(&:join)    
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.
#Rust
Rust
  //! Rust has a perfectly good Semaphore type already. It lacks count(), though, so we can't use it //! directly.   use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread::{self, spawn}; use std::time::Duration;   pub struct CountingSemaphore { /// Remaining resource count count: AtomicUsize,   /// How long to sleep if a resource is being contended backoff: Duration, }   pub struct CountingSemaphoreGuard<'a> { /// A reference to the owning semaphore. sem: &'a CountingSemaphore, }   impl CountingSemaphore { /// Create a semaphore with `max` available resources and a linearly increasing backoff of /// `backoff` (used during spinlock contention). pub fn new(max: usize, backoff: Duration) -> CountingSemaphore { CountingSemaphore { count: AtomicUsize::new(max), backoff, } }   /// Acquire a resource, returning a RAII CountingSemaphoreGuard. pub fn acquire(&self) -> CountingSemaphoreGuard { // Spinlock until remaining resource count is at least 1 let mut backoff = self.backoff; loop { // Probably don't need SeqCst here, but it doesn't hurt. let count = self.count.load(SeqCst); // The check for 0 is necessary to make sure we don't go negative, which is why this // must be a compare-and-swap rather than a straight decrement. if count == 0 || self .count .compare_exchange(count, count - 1, SeqCst, SeqCst) .is_err() { // Linear backoff a la Servo's spinlock contention. thread::sleep(backoff); backoff += self.backoff; } else { // We successfully acquired the resource. break; } } CountingSemaphoreGuard { sem: self } }   // Return remaining resource count pub fn count(&self) -> usize { self.count.load(SeqCst) } }   impl<'a> Drop for CountingSemaphoreGuard<'a> { /// When the guard is dropped, a resource is released back to the pool. fn drop(&mut self) { self.sem.count.fetch_add(1, SeqCst); } }   fn metered(duration: Duration) { static MAX_COUNT: usize = 4; // Total available resources static NUM_WORKERS: u8 = 10; // Number of workers contending for the resources let backoff = Duration::from_millis(1); // Linear backoff time // Create a shared reference to the semaphore let sem = Arc::new(CountingSemaphore::new(MAX_COUNT, backoff)); // Create a channel for notifying the main task that the workers are done let (tx, rx) = channel(); for i in 0..NUM_WORKERS { let sem = Arc::clone(&sem); let tx = tx.clone(); spawn(move || { // Acquire the resource let guard = sem.acquire(); let count = sem.count(); // Make sure the count is legal assert!(count < MAX_COUNT); println!("Worker {} after acquire: count = {}", i, count); // Sleep for `duration` thread::sleep(duration); // Release the resource drop(guard); // Make sure the count is legal let count = sem.count(); assert!(count <= MAX_COUNT); println!("Worker {} after release: count = {}", i, count); // Notify the main task of completion tx.send(()).unwrap(); }); } drop(tx); // Wait for all the subtasks to finish for _ in 0..NUM_WORKERS { rx.recv().unwrap(); } }   fn main() { // Hold each resource for 2 seconds per worker metered(Duration::from_secs(2)); }    
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Sidef
Sidef
var max = 12 var width = (max**2 -> len+1)   func fmt_row(*items) { items.map {|s| "%*s" % (width, s) }.join }   say fmt_row('x┃', (1..max)...) say "#{'━' * (width - 1)}╋#{'━' * (max * width)}"   { |i|  say fmt_row("#{i}┃", {|j| i <= j ? i*j : ''}.map(1..max)...) } << 1..max
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, 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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Function MianChowla(ByVal n As Integer) As Integer() Dim mc(n - 1) As Integer, sums, ts As New HashSet(Of Integer), sum As Integer : mc(0) = 1 : sums.Add(2) For i As Integer = 1 To n - 1 For j As Integer = mc(i - 1) + 1 To Integer.MaxValue mc(i) = j For k As Integer = 0 To i sum = mc(k) + j If sums.Contains(sum) Then ts.Clear() : Exit For ts.Add(sum) Next If ts.Count > 0 Then sums.UnionWith(ts) : Exit For Next Next Return mc End Function   Sub Main(ByVal args As String()) Const n As Integer = 100 Dim sw As New Stopwatch(), str As String = " of the Mian-Chowla sequence are:" & vbLf sw.Start() : Dim mc As Integer() = MianChowla(n) : sw.Stop() Console.Write("The first 30 terms{1}{2}{0}{0}Terms 91 to 100{1}{3}{0}{0}" & "Computation time was {4}ms.{0}", vbLf, str, String.Join(" ", mc.Take(30)), String.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds) End Sub End Module
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.
#Ring
Ring
  o1 = new point { x=10 y=20 z=30 } addmethod(o1,"print", func { see x + nl + y + nl + z + nl } ) o1.print() Class point x y z  
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#Ruby
Ruby
class IDVictim   # Create elements of this man, woman, or child's identification. attr_accessor :name, :birthday, :gender, :hometown   # Allows you to put in a space for anything which is not covered by the # preexisting elements. def self.new_element(element) attr_accessor element end   end
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller 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)
#EchoLisp
EchoLisp
  (lib 'bigint)   ;; output : #t if n probably prime (define (miller-rabin n (k 7) (composite #f)(x)) (define d (1- n)) (define s 0) (define a 0) (while (even? d) (set! s (1+ s)) (set! d (quotient d 2)))   (for [(i k)] (set! a (+ 2 (random (- n 3)))) (set! x (powmod a d n)) #:continue (or (= x 1) (= x (1- n))) (set! composite (for [(r (in-range 1 s))] (set! x (powmod x 2 n)) #:break (= x 1) => #t #:break (= x (1- n)) => #f #t )) #:break composite => #f ) (not composite))   ;; output (miller-rabin #101) → #t (miller-rabin #111) → #f (define big-prime (random-prime 1e+100)) 3461396142610375479080862553800503306376298093021233334170610435506057862777898396429 6627816219192601527 (miller-rabin big-prime) → #t (miller-rabin (1+ (factorial 100))) → #f (prime? (1+ (factorial 100))) ;; native → #f  
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
#C
C
#include <stdio.h> #include <stdlib.h>   int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; }   int main() { const int max = 1000; int* mertens = mertens_numbers(max); if (mertens == NULL) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 199 Mertens numbers:\n"); const int count = 200; for (int i = 0, column = 0; i < count; ++i) { if (column > 0) printf(" "); if (i == 0) printf(" "); else printf("%2d", mertens[i]); ++column; if (column == 20) { printf("\n"); column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { int m = mertens[i]; if (m == 0) { ++zero; if (previous != 0) ++cross; } previous = m; } free(mertens); printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max); printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max); return 0; }