task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Haskell
Haskell
  modPow :: Integer -> Integer -> Integer -> Integer -> Integer modPow b e 1 r = 0 modPow b 0 m r = r modPow b e m r | e `mod` 2 == 1 = modPow b' e' m (r * b `mod` m) | otherwise = modPow b' e' m r where b' = b * b `mod` m e' = e `div` 2   main = do print (modPow 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 (10 ^ 40) 1)  
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.
#AutoHotkey
AutoHotkey
bpm = 120 ; Beats per minute pattern = 4/4 ; duration = 100 ; Milliseconds beats = 0 ; internal counter   Gui -Caption   StringSplit, p, pattern, /   Start := A_TickCount   Loop { Gui Color, 0xFF0000 Gui Show, w200 h200 Na SoundBeep 750, duration beats++ Sleep 1000 * 60 / bpm - duration Loop % p1 -1 { Gui Color, 0x00FF00 Gui Show, w200 h200 Na SoundBeep, , duration beats++ Sleep 1000 * 60 / bpm - duration } }   Esc:: MsgBox % "Metronome beeped " beats " beats, over " (A_TickCount-Start)/1000 " seconds. " ExitApp
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.
#C.23
C#
using System; using System.Threading; using System.Threading.Tasks;   namespace RosettaCode { internal sealed class Program { private static void Worker(object arg, int id) { var sem = arg as SemaphoreSlim; sem.Wait(); Console.WriteLine("Thread {0} has a semaphore & is now working.", id); Thread.Sleep(2*1000); Console.WriteLine("#{0} done.", id); sem.Release(); }   private static void Main() { var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);   Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount); Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);   Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y)); } } }
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active 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.
#C.2B.2B
C++
#include <chrono> #include <iostream> #include <format> #include <semaphore> #include <thread>   using namespace std::literals;   void Worker(std::counting_semaphore<>& semaphore, int id) { semaphore.acquire(); std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); // response message std::this_thread::sleep_for(2s); std::cout << std::format("Thread {} done.\n", id); semaphore.release(); }   int main() { const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() ); std::counting_semaphore<> semaphore{numOfThreads / 2};   std::vector<std::jthread> tasks; for (int id = 0; id < numOfThreads; ++id) tasks.emplace_back(Worker, std::ref(semaphore), id);   return 0; }
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Python
Python
import operator import functools   @functools.total_ordering class Mod: __slots__ = ['val','mod']   def __init__(self, val, mod): if not isinstance(val, int): raise ValueError('Value must be integer') if not isinstance(mod, int) or mod<=0: raise ValueError('Modulo must be positive integer') self.val = val % mod self.mod = mod   def __repr__(self): return 'Mod({}, {})'.format(self.val, self.mod)   def __int__(self): return self.val   def __eq__(self, other): if isinstance(other, Mod): if self.mod == other.mod: return self.val==other.val else: return NotImplemented elif isinstance(other, int): return self.val == other else: return NotImplemented   def __lt__(self, other): if isinstance(other, Mod): if self.mod == other.mod: return self.val<other.val else: return NotImplemented elif isinstance(other, int): return self.val < other else: return NotImplemented   def _check_operand(self, other): if not isinstance(other, (int, Mod)): raise TypeError('Only integer and Mod operands are supported') if isinstance(other, Mod) and self.mod != other.mod: raise ValueError('Inconsistent modulus: {} vs. {}'.format(self.mod, other.mod))   def __pow__(self, other): self._check_operand(other) # We use the built-in modular exponentiation function, this way we can avoid working with huge numbers. return Mod(pow(self.val, int(other), self.mod), self.mod)   def __neg__(self): return Mod(self.mod - self.val, self.mod)   def __pos__(self): return self # The unary plus operator does nothing.   def __abs__(self): return self # The value is always kept non-negative, so the abs function should do nothing.   # Helper functions to build common operands based on a template. # They need to be implemented as functions for the closures to work properly. def _make_op(opname): op_fun = getattr(operator, opname) # Fetch the operator by name from the operator module def op(self, other): self._check_operand(other) return Mod(op_fun(self.val, int(other)) % self.mod, self.mod) return op   def _make_reflected_op(opname): op_fun = getattr(operator, opname) def op(self, other): self._check_operand(other) return Mod(op_fun(int(other), self.val) % self.mod, self.mod) return op   # Build the actual operator overload methods based on the template. for opname, reflected_opname in [('__add__', '__radd__'), ('__sub__', '__rsub__'), ('__mul__', '__rmul__')]: setattr(Mod, opname, _make_op(opname)) setattr(Mod, reflected_opname, _make_reflected_op(opname))   def f(x): return x**100+x+1   print(f(Mod(10,13))) # Output: Mod(1, 13)
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Yabasic
Yabasic
DOCU The N Queens Problem: DOCU Place N Queens on an NxN chess board DOCU such that they don't threaten each other.   N = 8 // try some other sizes   sub threat(q1r, q1c, q2r, q2c) // do two queens threaten each other?   if q1c = q2c then return true elsif (q1r - q1c) = (q2r - q2c) then return true elsif (q1r + q1c) = (q2r + q2c) then return true elsif q1r = q2r then return true else return false end if end sub   sub conflict(r, c, queens$) // Would square p cause a conflict with other queens on board so far? local r2, c2   for i = 1 to len(queens$) step 2 r2 = val(mid$(queens$,i,1)) c2 = val(mid$(queens$,i+1,1)) if threat(r, c, r2, c2) then return true end if next i return false end sub   sub print_board(queens$) // print a solution, showing the Queens on the board local k$   print at(1, 1); print "Solution #", soln, "\n\n "; for c = asc("a") to (asc("a") + N - 1) print chr$(c)," "; next c print for r = 1 to N print r using "##"," "; for c = 1 to N pos = instr(queens$, (str$(r)+str$(c))) if pos and mod(pos, 2) then queens$ = mid$(queens$,pos) print "Q "; else print ". "; end if next c print next r print "\nPress Enter. (q to quit) " while(true) k$ = inkey$ if lower$(k$) = "q" then exit elsif k$ = "enter" then break end if wend end sub  
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#Yabasic
Yabasic
// User defined functions sub F(n) if n = 0 return 1 return n - M(F(n-1)) end sub     sub M(n) if n = 0 return 0 return n - F(M(n-1)) end sub     for i = 0 to 20 print F(i) using "###"; next print for i = 0 to 20 print M(i) using "###"; next print
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#PowerShell
PowerShell
# For clarity $Tab = "`t"   # Create top row $Tab + ( 1..12 -join $Tab )   # For each row ForEach ( $i in 1..12 ) { $( # The number in the left column $i   # An empty slot for the bottom triangle @( "" ) * ( $i - 1 )   # Calculate the top triangle $i..12 | ForEach { $i * $_ }   # Combine them all together ) -join $Tab }
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#F.23
F#
  //Be boggled? Nigel Galloway: September 19th., 2018 let N=System.Random() let fN=List.unfold(function |(0,0)->None |(n,g)->let ng=N.Next (n+g) in Some (if ng>=n then ("Black",(n,g-1)) else ("Red",(n-1,g))))(26,26) let fG n=let (n,n')::(g,g')::_=List.countBy(fun (n::g::_)->if n=g then n else g) n in sprintf "%d %s cards and %d %s cards" n' n g' g printf "A well shuffled deck -> "; List.iter (printf "%s ") fN; printfn "" fN |> List.chunkBySize 2 |> List.groupBy List.head |> List.iter(fun(n,n')->printfn "The %s pile contains %s" n (fG n'))  
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
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq;   static class Program { static int[] MianChowla(int n) { int[] mc = new int[n - 1 + 1]; HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>(); int sum; mc[0] = 1; sums.Add(2); for (int i = 1; i <= n - 1; i++) { for (int j = mc[i - 1] + 1; ; j++) { mc[i] = j; for (int k = 0; k <= i; k++) { sum = mc[k] + j; if (sums.Contains(sum)) { ts.Clear(); break; } ts.Add(sum); } if (ts.Count > 0) { sums.UnionWith(ts); break; } } } return mc; }   static void Main(string[] args) { const int n = 100; Stopwatch sw = new Stopwatch(); string str = " of the Mian-Chowla sequence are:\n"; sw.Start(); int[] mc = 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}", '\n', str, string.Join(" ", mc.Take(30)), string.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds); } }
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.
#Arturo
Arturo
sumThemUp: function [x,y][ x+y ]   alias.infix '--> 'sumThemUp   do [ print 3 --> 4 ]
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#C
C
  // http://stackoverflow.com/questions/3385515/static-assert-in-c #define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1] // token pasting madness: #define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L) #define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L) #define COMPILE_TIME_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__)   COMPILE_TIME_ASSERT(sizeof(long)==8); int main() { COMPILE_TIME_ASSERT(sizeof(int)==4); }  
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
#C.2B.2B
C++
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream>   const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };   template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; }   template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } }   int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1);   return 0; }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; 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.
#11l
11l
F middle_three_digits(i) V s = String(abs(i)) assert(s.len >= 3 & s.len % 2 == 1, ‘Need odd and >= 3 digits’) R s[s.len I/ 2 - 1 .+ 3]   V passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] V failing = [1, 2, -1, -10, 2002, -2002, 0] L(x) passing [+] failing X.try V answer = middle_three_digits(x) print(‘middle_three_digits(#.) returned: #.’.format(x, answer)) X.catch AssertionError error print(‘middle_three_digits(#.) returned error: ’.format(x)‘’String(error))
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)
#Clojure
Clojure
(defn take-random [n coll] (->> (repeatedly #(rand-nth coll)) distinct (take n ,)))   (defn postwalk-fs "Depth first post-order traversal of form, apply successive fs at each level. (f1 (map f2 [..]))" [[f & fs] form] (f (if (and (seq fs) (coll? form)) (into (empty form) (map (partial postwalk-fs fs) form)) form)))   (defn neighbors [x y n m pred] (for [dx (range (Math/max 0 (dec x)) (Math/min n (+ 2 x))) dy (range (Math/max 0 (dec y)) (Math/min m (+ 2 y))) :when (pred dx dy)] [dx dy]))   (defn new-game [n m density] (let [mines (set (take-random (Math/floor (* n m density)) (range (* n m))))] (->> (for [y (range m) x (range n)  :let [neighbor-mines (count (neighbors x y n m #(mines (+ %1 (* %2 n)))))]] (#(if (mines (+ (* y n) x)) (assoc % :mine true) %) {:value neighbor-mines})) (partition n ,) (postwalk-fs [vec vec] ,))))   (defn display [board] (postwalk-fs [identity println #(condp % nil  :marked \?  :opened (:value %) \.)] board))   (defn boom [{board :board}] (postwalk-fs [identity println #(if (:mine %) \* (:value %))] board) true)   (defn open* [board [[x y] & rest]] (if-let [value (get-in board [y x :value])] ; if nil? value -> nil? x -> nil? queue (recur (assoc-in board [y x :opened] true) (if (pos? value) rest (concat rest (neighbors x y (count (first board)) (count board) #(not (get-in board [%2 %1 :opened])))))) board))   (defn open [board x y] (let [x (dec x), y (dec y)] (condp (get-in board [y x]) nil  :mine {:boom true :board board}  :opened board (open* board [[x y]]))))   (defn mark [board x y] (let [x (dec x), y (dec y)] (assoc-in board [y x :marked] (not (get-in board [y x :marked])))))   (defn done? [board] (if (:boom board) (boom board) (do (display board) (->> (flatten board) (remove :mine ,) (every? :opened ,)))))   (defn play [n m density] (let [board (new-game n m density)] (println [:mines (count (filter :mine (flatten board)))]) (loop [board board] (when-not (done? board) (print ">") (let [[cmd & xy] (.split #" " (read-line)) [x y] (map #(Integer. %) xy)] (recur ((if (= cmd "mark") mark open) board x y)))))))
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
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   // Title: Minimum positive multiple in base 10 using only 0 and 1   public class MinimumNumberOnlyZeroAndOne {   public static void main(String[] args) { for ( int n : getTestCases() ) { BigInteger result = getA004290(n); System.out.printf("A004290(%d) = %s = %s * %s%n", n, result, n, result.divide(BigInteger.valueOf(n))); } }   private static List<Integer> getTestCases() { List<Integer> testCases = new ArrayList<>(); for ( int i = 1 ; i <= 10 ; i++ ) { testCases.add(i); } for ( int i = 95 ; i <= 105 ; i++ ) { testCases.add(i); } for (int i : new int[] {297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878} ) { testCases.add(i); } return testCases; }   private static BigInteger getA004290(int n) { if ( n == 1 ) { return BigInteger.valueOf(1); } int[][] L = new int[n][n]; for ( int i = 2 ; i < n ; i++ ) { L[0][i] = 0; } L[0][0] = 1; L[0][1] = 1; int m = 0; BigInteger ten = BigInteger.valueOf(10); BigInteger nBi = BigInteger.valueOf(n); while ( true ) { m++; // if L[m-1, (-10^m) mod n] = 1 then break if ( L[m-1][mod(ten.pow(m).negate(), nBi).intValue()] == 1 ) { break; } L[m][0] = 1; for ( int k = 1 ; k < n ; k++ ) { //L[m][k] = Math.max(L[m-1][k], L[m-1][mod(k-pow(10,m), n)]); L[m][k] = Math.max(L[m-1][k], L[m-1][mod(BigInteger.valueOf(k).subtract(ten.pow(m)), nBi).intValue()]); }   } //int r = pow(10,m); //int k = mod(-pow(10,m), n); BigInteger r = ten.pow(m); BigInteger k = mod(r.negate(), nBi); for ( int j = m-1 ; j >= 1 ; j-- ) { if ( L[j-1][k.intValue()] == 0 ) { //r = r + pow(10, j); //k = mod(k-pow(10, j), n); r = r.add(ten.pow(j)); k = mod(k.subtract(ten.pow(j)), nBi); } } if ( k.compareTo(BigInteger.ONE) == 0 ) { r = r.add(BigInteger.ONE); } return r; }   private static BigInteger mod(BigInteger m, BigInteger n) { BigInteger result = m.mod(n); if ( result.compareTo(BigInteger.ZERO) < 0 ) { result = result.add(n); } return result; }   @SuppressWarnings("unused") private static int mod(int m, int n) { int result = m % n; if ( result < 0 ) { result += n; } return result; }   @SuppressWarnings("unused") private static int pow(int base, int exp) { return (int) Math.pow(base, exp); } }  
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} .
#Icon_and_Unicon
Icon and Unicon
procedure main() a := 2988348162058574136915891421498819466320163312926952423791023078876139 b := 2351399303373464486466122544523690094744975233415544072992656881240319 write("last 40 digits = ",mod_power(a,b,(10^40)) end   procedure mod_power(base, exponent, modulus) # fast modular exponentation if exponent < 0 then runerr(205,m) # added for this task result := 1 while exponent > 0 do { if exponent % 2 = 1 then result := (result * base) % modulus exponent /:= 2 base := base ^ 2 % modulus } return result end
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#AWK
AWK
  # syntax: GAWK -f METRONOME.AWK @load "time" BEGIN { metronome(120,6,10) metronome(72,4) exit(0) } function metronome(beats_per_min,beats_per_bar,limit, beats,delay,errors) { print("") if (beats_per_min+0 <= 0) { print("error: beats per minute is invalid") ; errors++ } if (beats_per_bar+0 <= 0) { print("error: beats per bar is invalid") ; errors++ } if (limit+0 <= 0) { limit = 999999 } if (errors > 0) { return } delay = 60 / beats_per_min printf("delay=%f",delay) while (beats < limit) { printf((beats++ % beats_per_bar == 0) ? "\nTICK" : " tick") sleep(delay) } }  
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.
#D
D
module meteredconcurrency ; import std.stdio ; import std.thread ; import std.c.time ;   class Semaphore { private int lockCnt, maxCnt ; this(int count) { maxCnt = lockCnt = count ;} void acquire() { if(lockCnt < 0 || maxCnt <= 0) throw new Exception("Negative Lock or Zero init. Lock") ; while(lockCnt == 0) Thread.getThis.yield ; // let other threads release lock synchronized lockCnt-- ; } void release() { synchronized if (lockCnt < maxCnt) lockCnt++ ; else throw new Exception("Release lock before acquire") ; } int getCnt() { synchronized return lockCnt ; } }   class Worker : Thread { private static int Id = 0 ; private Semaphore lock ; private int myId ; this (Semaphore l) { super() ; lock = l ; myId = Id++ ; } override int run() { lock.acquire ; writefln("Worker %d got a lock(%d left).", myId, lock.getCnt) ; msleep(2000) ; // wait 2.0 sec lock.release ; writefln("Worker %d released a lock(%d left).", myId, lock.getCnt) ; return 0 ; } }   void main() { Worker[10] crew ; Semaphore lock = new Semaphore(4) ;   foreach(inout c ; crew) (c = new Worker(lock)).start ; foreach(inout c ; crew) c.wait ; }
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Quackery
Quackery
[ stack ] is modulus ( --> s )   [ this ] is modular ( --> [ )   [ modulus share mod modular nested join ] is modularise ( n --> N )   [ dup nest? iff [ -1 peek modular oats ] else [ drop false ] ] is modular? ( N --> b )   [ modular? swap modular? or ] is 2modular? ( N N --> b )   [ dup modular? if [ 0 peek ] ] is demodularise ( N --> n )   [ demodularise swap demodularise swap ] is 2demodularise ( N N --> n )   [ dup $ '' = if [ $ '"modularify(2-->1)" ' $ "needs a name after it." join message put bail ] nextword $ "[ 2dup 2modular? iff [ 2demodularise " over join $ " modularise ] else " join over join $ " ] is " join swap join space join swap join ] builds modularify(2-->1) ( --> )   ( --------------------------------------------------------------- )   modularify(2-->1) + ( N N --> N )   modularify(2-->1) ** ( N N --> N )   ( --------------------------------------------------------------- )   [ dup 100 ** + 1 + ] is f ( N --> N )   13 modulus put 10 f echo cr 10 modularise f echo modulus release cr
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Racket
Racket
#lang racket (require racket/require  ;; grab all "mod*" names, but get them without the "mod", so  ;; `+' and `expt' is actually `mod+' and `modexpt' (filtered-in (λ(n) (and (regexp-match? #rx"^mod" n) (regexp-replace #rx"^mod" n ""))) math) (only-in math with-modulus)) (define (f x) (+ (expt x 100) x 1)) (with-modulus 13 (f 10)) ;; => 1
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream();   var board = [_]i8{-1} ** 8;   inline fn abs(x: var) @TypeOf(x) { return if (x < 0) -x else x; }   fn safe(c: i32, r: i32) bool { var i: i32 = 0; return while (i < c) : (i += 1) { const q = board[@intCast(u3, i)]; if (r == q or c == i + abs(q - r)) break false; } else true; }   pub fn main() !void { var i: i32 = 0; while (i >= 0) { var j = board[@intCast(u3, i)] + 1; while (j < 8) : (j += 1) { if (safe(i, j)) { board[@intCast(u3, i)] = j; i += 1; break; } } else { board[@intCast(u3, i)] = -1; i -= 1; } if (i == 8) { // found a solution for (board) |q| try stdout.print("{} ", .{q + 1}); try stdout.print("\n", .{}); i -= 1; // create a failure to try new solutions. } } }  
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#zkl
zkl
fcn f(n){ if(n==0)return(1); n-m(f(n-1,m),f) } fcn m(n){ if(n==0)return(0); n-f(m(n-1,f),m) } [0..19].apply(f).println(); // or foreach n in ([0..19]){ print(f(n)," ") } [0..19].apply(m).println(); // or foreach n in ([0..19]){ print(m(n)," ") }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Prolog
Prolog
make_table(S,E) :- print_header(S,E), make_table_rows(S,E), fail. make_table(_,_).   print_header(S,E) :- nl, write(' '), forall(between(S,E,X), print_num(X)), nl, Sp is E * 4 + 2, write(' '), forall(between(1,Sp,_), write('-')).   make_table_rows(S,E) :- between(S,E,N), nl, print_num(N), write(': '), between(S,E,N2), X is N * N2, print_row_item(N,N2,X).   print_row_item(N, N2, _) :- N2 < N, write(' '). print_row_item(N, N2, X) :- N2 >= N, print_num(X).   print_num(X) :- X < 10, format(' ~p', X). print_num(X) :- between(10,99,X), format(' ~p', X). print_num(X) :- X > 99, format(' ~p', X).
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Factor
Factor
USING: accessors combinators.extras formatting fry generalizations io kernel math math.ranges random sequences sequences.extras ; IN: rosetta-code.mind-boggling-card-trick   SYMBOLS: R B ;   TUPLE: piles deck red black discard ;   : initialize-deck ( -- seq ) [ R ] [ B ] [ '[ 26 _ V{ } replicate-as ] call ] bi@ append randomize ;   : <piles> ( -- piles ) initialize-deck [ V{ } clone ] thrice piles boa ;   : deal-step ( piles -- piles' ) dup [ deck>> pop dup ] [ discard>> push ] [ deck>> pop ] tri B = [ over black>> ] [ over red>> ] if push ;   : deal ( piles -- piles' ) 26 [ deal-step ] times ;   : choose-sample-size ( piles -- n ) [ red>> ] [ black>> ] bi shorter length [0,b] random ;   ! Partition a sequence into n random samples in one sequence and ! the leftovers in another. : sample-partition ( vec n -- leftovers sample ) [ 3 dupn ] dip sample dup [ [ swap remove-first! drop ] with each ] dip ;   : perform-swaps ( piles -- piles' ) dup dup choose-sample-size dup "Swapping %d\n" printf [ [ red>> ] dip ] [ [ black>> ] dip ] 2bi [ sample-partition ] 2bi@ [ append ] dip rot append [ >>black ] dip >>red ;   : test-assertion ( piles -- ) [ red>> ] [ black>> ] bi [ [ R = ] count ] [ [ B = ] count ] bi* 2dup = [ "Assertion correct!" ] [ "Assertion incorrect!" ] if print "R in red: %d\nB in black: %d\n" printf ;   : main ( -- ) <piles>  ! step 1 deal  ! step 2 dup "Post-deal state:\n%u\n" printf perform-swaps  ! step 3 dup "Post-swap state:\n%u\n" printf test-assertion ;  ! step 4   MAIN: main
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() { // Create pack, half red, half black and shuffle it. var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] })   // Deal from pack into 3 stacks. var red, black, discard []byte for i := 0; i < 51; i += 2 { switch pack[i] { case 'B': black = append(black, pack[i+1]) case 'R': red = append(red, pack[i+1]) } discard = append(discard, pack[i]) } lr, lb, ld := len(red), len(black), len(discard) fmt.Println("After dealing the cards the state of the stacks is:") fmt.Printf(" Red  : %2d cards -> %c\n", lr, red) fmt.Printf(" Black  : %2d cards -> %c\n", lb, black) fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard)   // Swap the same, random, number of cards between the red and black stacks. min := lr if lb < min { min = lb } n := 1 + rand.Intn(min) rp := rand.Perm(lr)[:n] bp := rand.Perm(lb)[:n] fmt.Printf("\n%d card(s) are to be swapped.\n\n", n) fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:") fmt.Printf(" Red  : %2d\n", rp) fmt.Printf(" Black  : %2d\n", bp) for i := 0; i < n; i++ { red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]] } fmt.Println("\nAfter swapping, the state of the red and black stacks is:") fmt.Printf(" Red  : %c\n", red) fmt.Printf(" Black  : %c\n", black)   // Check that the number of black cards in the black stack equals // the number of red cards in the red stack. rcount, bcount := 0, 0 for _, c := range red { if c == 'R' { rcount++ } } for _, c := range black { if c == 'B' { bcount++ } }   fmt.Println("\nThe number of red cards in the red stack =", rcount) fmt.Println("The number of black cards in the black stack =", bcount) if rcount == bcount { fmt.Println("So the asssertion is correct!") } else { fmt.Println("So the asssertion is incorrect!") } }
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#C.2B.2B
C++
using namespace std;   #include <iostream> #include <ctime>   #define n 100 #define nn ((n * (n + 1)) >> 1)   bool Contains(int lst[], int item, int size) { for (int i = 0; i < size; i++) if (item == lst[i]) return true; return false; }   int * MianChowla() { static int mc[n]; mc[0] = 1; int sums[nn]; sums[0] = 2; int sum, le, ss = 1; for (int i = 1; i < n; i++) { le = ss; for (int j = mc[i - 1] + 1; ; j++) { mc[i] = j; for (int k = 0; k <= i; k++) { sum = mc[k] + j; if (Contains(sums, sum, ss)) { ss = le; goto nxtJ; } sums[ss++] = sum; } break; nxtJ:; } } return mc; }   int main() { clock_t st = clock(); int * mc; mc = MianChowla(); double et = ((double)(clock() - st)) / CLOCKS_PER_SEC; cout << "The first 30 terms of the Mian-Chowla sequence are:\n"; for (int i = 0; i < 30; i++) { cout << mc[i] << ' '; } cout << "\n\nTerms 91 to 100 of the Mian-Chowla sequence are:\n"; for (int i = 90; i < 100; i++) { cout << mc[i] << ' '; } cout << "\n\nComputation 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.
#C.23
C#
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) (values mean spl-var spl-dev))))
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.
#Clojure
Clojure
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) (values mean spl-var spl-dev))))
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
#F.23
F#
  // Metallic Ration. Nigel Galloway: September 16th., 2020 let rec fN i g (e,l)=match i with 0->g |_->fN (i-1) (int(l/e)::g) (e,(l%e)*10I) let fI(P:int)=Seq.unfold(fun(n,g)->Some(g,((bigint P)*n+g,n)))(1I,1I) let fG fI fN=let _,(n,g)=fI|>Seq.pairwise|>Seq.mapi(fun n g->(n,fN g))|>Seq.pairwise|>Seq.find(fun((_,n),(_,g))->n=g) in (n,List.rev g) let mR n g=printf "First 15 elements when P = %d -> " n; fI n|>Seq.take 15|>Seq.iter(printf "%A "); printf "\n%d decimal places " g let Σ,n=fG(fI n)(fN (g+1) []) in printf "required %d iterations -> %d." Σ n.Head; List.iter(printf "%d")n.Tail ;printfn "" [0..9]|>Seq.iter(fun n->mR n 32; printfn ""); mR 1 256  
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.
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT" INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit   PROC MiddleThreeDigits(REAL POINTER n CHAR ARRAY res) REAL r CHAR ARRAY s(15) BYTE i   RealAbs(n,r) StrR(r,s) i=s(0) IF i<3 OR (i&1)=0 THEN res(0)=0 ELSE i==RSH 1 SCopyS(res,s,i,i+2) FI RETURN   PROC Test(CHAR ARRAY s) REAL n CHAR ARRAY res(4)   ValR(s,n) MiddleThreeDigits(n,res) IF res(0) THEN PrintF("%9S -> %S%E",s,res) ELSE PrintF("%9S -> error!%E",s) FI RETURN   PROC Main() Put(125) PutE() ;clear the screen   Test("123") Test("12345") Test("1234567") Test("987654321") Test("10001") Test("-10001") Test("-123") Test("-100") Test("100") Test("-12345") Test("1") Test("2") Test("-1") Test("-10") Test("2002") Test("-2002") Test("0") RETURN
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)
#Common_Lisp
Common Lisp
(defclass minefield () ((mines :initform (make-hash-table :test #'equal)) (width :initarg :width) (height :initarg :height) (grid :initarg :grid)))   (defun make-minefield (width height num-mines) (let ((minefield (make-instance 'minefield :width width :height height :grid (make-array (list width height) :initial-element #\.))) (mine-count 0)) (with-slots (grid mines) minefield (loop while (< mine-count num-mines) do (let ((coords (list (random width) (random height)))) (unless (gethash coords mines) (setf (gethash coords mines) T) (incf mine-count)))) minefield)))   (defun print-field (minefield) (with-slots (width height grid) minefield (dotimes (y height) (dotimes (x width) (princ (aref grid x y))) (format t "~%"))))   (defun mine-list (minefield) (loop for key being the hash-keys of (slot-value minefield 'mines) collect key))   (defun count-nearby-mines (minefield coords) (length (remove-if-not (lambda (mine-coord) (and (> 2 (abs (- (car coords) (car mine-coord)))) (> 2 (abs (- (cadr coords) (cadr mine-coord)))))) (mine-list minefield))))   (defun clear (minefield coords) (with-slots (mines grid) minefield (if (gethash coords mines) (progn (format t "MINE! You lose.~%") (dolist (mine-coords (mine-list minefield)) (setf (aref grid (car mine-coords) (cadr mine-coords)) #\x)) (setf (aref grid (car coords) (cadr coords)) #\X) nil) (setf (aref grid (car coords) (cadr coords)) (elt " 123456789"(count-nearby-mines minefield coords))))))   (defun mark (minefield coords) (with-slots (mines grid) minefield (setf (aref grid (car coords) (cadr coords)) #\?)))   (defun win-p (minefield) (with-slots (width height grid mines) minefield (let ((num-uncleared 0)) (dotimes (y height) (dotimes (x width) (let ((square (aref grid x y))) (when (member square '(#\. #\?) :test #'char=) (incf num-uncleared))))) (= num-uncleared (hash-table-count mines)))))   (defun play-game () (let ((minefield (make-minefield 6 4 5))) (format t "Greetings player, there are ~a mines.~%" (hash-table-count (slot-value minefield 'mines))) (loop (print-field minefield) (format t "Enter your command, examples: \"clear 0 1\" \"mark 1 2\" \"quit\".~%") (princ "> ") (let ((user-command (read-from-string (format nil "(~a)" (read-line))))) (format t "Your command: ~a~%" user-command) (case (car user-command) (quit (return-from play-game nil)) (clear (unless (clear minefield (cdr user-command)) (print-field minefield) (return-from play-game nil))) (mark (mark minefield (cdr user-command)))) (when (win-p minefield) (format t "Congratulations, you've won!") (return-from play-game T))))))   (play-game)
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
#jq
jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def pp(a;b;c): "\(a|lpad(4)): \(b|lpad(28)) \(c|lpad(24))";   def b10: . as $n | if . == 1 then pp(1;1;1) else ($n + 1) as $n1 | { pow: [range(0;$n)|0], val: [range(0;$n)|0], count: 0, ten: 1, x: 1 } | until (.x >= $n1; .val[.x] = .ten | reduce range(0;$n1) as $j (.; if .pow[$j] != 0 and .pow[($j+.ten)%$n] == 0 and .pow[$j] != .x then .pow[($j+.ten)%$n] = .x else . end ) | if .pow[.ten] == 0 then .pow[.ten] = .x else . end | .ten = (10*.ten) % $n | if .pow[0] != 0 then .x = $n1 # .x will soon be reset else .x += 1 end ) | .x = $n | if .pow[0] != 0 then .s = "" | until (.x == 0; .pow[.x % $n] as $p | if .count > $p then .s += ("0" * (.count-$p)) else . end | .count = $p - 1 | .s += "1" | .x = ( ($n + .x - .val[$p]) % $n ) ) | if .count > 0 then .s += ("0" * .count) else . end | pp($n; .s; .s|tonumber/$n) else "Can't do it!" end end;   def tests: [ [1, 10], [95, 105], [297], [576], [594], [891], [909], [999], [1998], [2079], [2251], [2277], [2439], [2997], [4878] ];   pp("n"; "B10"; "multiplier"), (pp("-";"-";"-") | gsub(".";"-")), ( tests[] | .[0] as $from | (if length == 2 then .[1] else $from end) as $to | range($from; $to + 1) | b10 )
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} .
#J
J
m&|@^
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Java
Java
import java.math.BigInteger;   public class PowMod { public static void main(String[] args){ BigInteger a = new BigInteger( "2988348162058574136915891421498819466320163312926952423791023078876139"); BigInteger b = new BigInteger( "2351399303373464486466122544523690094744975233415544072992656881240319"); BigInteger m = new BigInteger("10000000000000000000000000000000000000000");   System.out.println(a.modPow(b, m)); } }
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#BBC_BASIC
BBC BASIC
BeatPattern$ = "HLLL" Tempo% = 100   *font Arial,36 REPEAT FOR beat% = 1 TO LEN(BeatPattern$) IF MID$(BeatPattern$, beat%, 1) = "H" THEN SOUND 1,-15,148,1 ELSE SOUND 1,-15,100,1 ENDIF VDU 30 COLOUR 2 PRINT LEFT$(BeatPattern$,beat%-1); COLOUR 9 PRINT MID$(BeatPattern$,beat%,1); COLOUR 2 PRINT MID$(BeatPattern$,beat%+1); WAIT 6000/Tempo% NEXT UNTIL FALSE
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <signal.h> #include <time.h> #include <sys/time.h>   struct timeval start, last;   inline int64_t tv_to_u(struct timeval s) { return s.tv_sec * 1000000 + s.tv_usec; }   inline struct timeval u_to_tv(int64_t x) { struct timeval s; s.tv_sec = x / 1000000; s.tv_usec = x % 1000000; return s; }   void draw(int dir, int64_t period, int64_t cur, int64_t next) { int len = 40 * (next - cur) / period; int s, i;   if (len > 20) len = 40 - len; s = 20 + (dir ? len : -len);   printf("\033[H"); for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-'); }   void beat(int delay) { struct timeval tv = start; int dir = 0; int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay; int64_t draw_interval = 20000; printf("\033[H\033[J"); while (1) { gettimeofday(&tv, 0); slp = next - tv_to_u(tv) - corr; usleep(slp); gettimeofday(&tv, 0);   putchar(7); /* bell */ fflush(stdout);   printf("\033[5;1Hdrift: %d compensate: %d (usec) ", (int)d, (int)corr); dir = !dir;   cur = tv_to_u(tv); d = cur - next; corr = (corr + d) / 2; next += delay;   while (cur + d + draw_interval < next) { usleep(draw_interval); gettimeofday(&tv, 0); cur = tv_to_u(tv); draw(dir, delay, cur, next); fflush(stdout); } } }   int main(int c, char**v) { int bpm;   if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60; if (bpm > 600) { fprintf(stderr, "frequency %d too high\n", bpm); exit(1); }   gettimeofday(&start, 0); last = start; beat(60 * 1000000 / bpm);   return 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.
#E
E
def makeSemaphore(maximum :(int > 0)) { var current := 0 def waiters := <elib:vat.makeQueue>() def notify() { while (current < maximum && waiters.hasMoreElements()) { current += 1 waiters.optDequeue().resolve(def released) when (released) -> { current -= 1 notify() } } } def semaphore { to acquire() { waiters.enqueue(def response) notify() return response } to count() { return current } } return semaphore }   def work(label, interval, semaphore, timer, println) { when (def releaser := semaphore <- acquire()) -> { println(`$label: I have acquired the lock.`) releaser.resolve( timer.whenPast(timer.now() + interval, fn { println(`$label: I will have released the lock.`) }) ) } }   def semaphore := makeSemaphore(3) for i in 1..5 { work(i, 2000, semaphore, timer, println) }
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Raku
Raku
use Modular; sub f(\x) { x**100 + x + 1}; say f( 10 Mod 13 )
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Red
Red
Red ["Modular arithmetic"]   ; defining the modular integer class, and a constructor modulus: 13 m: function [n] [ either object? n [make n []] [context [val: n % modulus]] ] ; redefining operators +, -, *, / to include modular integers foreach [op fun][+ add - subtract * multiply / divide][ set op make op! function [a b] compose/deep [ either any [object? a object? b][ a: m a b: m b m (fun) a/val b/val ][(fun) a b] ] ] ; redefining power - ** ; second operand must be an integer **: make op! function [a n] [ either object? a [ tmp: 1 loop n [tmp: tmp * a/val % modulus] m tmp ][power a n] ] ; testing f: function [x] [x ** 100 + x + 1] print ["f definition is:" mold :f] print ["f((integer) 10) is:" f 10] print ["f((modular) 10) is: (modular)" f m 10]
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armies Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#zkl
zkl
fcn isAttacked(q, x,y) // ( (r,c), x,y ) : is queen at r,c attacked by q@(x,y)? { r,c:=q; (r==x or c==y or r+c==x+y or r-c==x-y) } fcn isSafe(r,c,qs) // queen safe at (r,c)?, qs=( (r,c),(r,c)..) solution so far { ( not qs.filter1(isAttacked,r,c) ) } fcn queensN(N=8,row=1,queens=T){ qs:=[1..N].filter(isSafe.fpM("101",row,queens)) #isSafe(row,?,( (r,c),(r,c).. ) .apply(fcn(c,r,qs){ qs.append(T(r,c)) },row,queens); if (row == N) return(qs); return(qs.apply(self.fcn.fp(N,row+1)).flatten()); }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#PureBasic
PureBasic
Procedure PrintMultiplicationTable(maxx, maxy) sp = Len(Str(maxx*maxy)) + 1 trenner$ = "+" For l1 = 1 To maxx + 1 For l2 = 1 To sp trenner$ + "-" Next trenner$ + "+" Next header$ = "|" + RSet("x", sp) + "|" For a = 1 To maxx header$ + RSet(Str(a), sp) header$ + "|" Next PrintN(trenner$) PrintN(header$) PrintN(trenner$) For y = 1 To maxy line$ = "|" + RSet(Str(y), sp) + "|" For x = 1 To maxx If x >= y line$ + RSet(Str(x*y), sp) Else line$ + Space(sp) EndIf line$ + "|" Next PrintN(line$) Next PrintN(trenner$) EndProcedure   OpenConsole() PrintMultiplicationTable(12, 12) Input()
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Haskell
Haskell
import System.Random (randomRIO) import Data.List (partition) import Data.Monoid ((<>))   main :: IO [Int] main = do   -- DEALT ns <- knuthShuffle [1 .. 52] let (rs_, bs_, discards) = threeStacks (rb <$> ns)   -- SWAPPED nSwap <- randomRIO (1, min (length rs_) (length bs_)) let (rs, bs) = exchange nSwap rs_ bs_   -- CHECKED let rrs = filter ('R' ==) rs let bbs = filter ('B' ==) bs putStrLn $ unlines [ "Discarded: " <> discards , "Swapped: " <> show nSwap , "Red pile: " <> rs , "Black pile: " <> bs , rrs <> " = Red cards in the red pile" , bbs <> " = Black cards in the black pile" , show $ length rrs == length bbs ] return ns   -- RED vs BLACK ---------------------------------------- rb :: Int -> Char rb n | even n = 'R' | otherwise = 'B'   -- THREE STACKS ---------------------------------------- threeStacks :: String -> (String, String, String) threeStacks = go ([], [], []) where go tpl [] = tpl go (rs, bs, ds) [x] = (rs, bs, x : ds) go (rs, bs, ds) (x:y:xs) | 'R' == x = go (y : rs, bs, x : ds) xs | otherwise = go (rs, y : bs, x : ds) xs   exchange :: Int -> [a] -> [a] -> ([a], [a]) exchange n xs ys = let [xs_, ys_] = splitAt n <$> [xs, ys] in (fst ys_ <> snd xs_, fst xs_ <> snd ys_)   -- SHUFFLE ----------------------------------------------- -- (See Knuth Shuffle task) knuthShuffle :: [a] -> IO [a] knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> randoms (length xs)   randoms :: Int -> IO [Int] randoms x = traverse (randomRIO . (,) 0) [1 .. (pred x)]   swapElems :: (Int, Int) -> [a] -> [a] swapElems (i, j) xs | i == j = xs | otherwise = replaceAt j (xs !! i) $ replaceAt i (xs !! j) xs   replaceAt :: Int -> a -> [a] -> [a] replaceAt i c l = let (a, b) = splitAt i l in a ++ c : drop 1 b
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#F.23
F#
  // Generate Mian-Chowla sequence. Nigel Galloway: March 23rd., 2019 let mC=let rec fN i g l=seq{ let a=(l*2)::[for i in i do yield i+l]@g let b=[l+1..l*2]|>Seq.find(fun e->Seq.forall(fun g->(Seq.contains (g-e)>>not) i) a) yield b; yield! fN (l::i) (a|>List.filter(fun n->n>b)) b} seq{yield 1; yield! fN [] [] 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.
#Common_Lisp
Common Lisp
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) (values mean spl-var spl-dev))))
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.
#D
D
enum GenStruct(string name, string fieldName) = "struct " ~ name ~ "{ int " ~ fieldName ~ "; }";   // Equivalent to: struct Foo { int bar; } mixin(GenStruct!("Foo", "bar"));   void main() { Foo f; f.bar = 10; }
http://rosettacode.org/wiki/Metallic_ratios
Metallic ratios
Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series of related ratios that are referred to as the "Metallic ratios". The Golden ratio was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The Silver ratio was was also known to 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
#Factor
Factor
USING: combinators decimals formatting generalizations io kernel math prettyprint qw sequences ; IN: rosetta-code.metallic-ratios   : lucas ( n a b -- n a' b' ) tuck reach * + ;   : lucas. ( n -- ) 1 pprint bl 1 1 14 [ lucas over pprint bl ] times 3drop nl ;   : approx ( a b -- d ) swap [ 0 <decimal> ] bi@ 32 D/ ;   : approximate ( n -- value iter ) -1 swap 1 1 0 1 [ 2dup = ] [ [ 1 + ] 5 ndip [ lucas 2dup approx ] 2dip drop ] until 4nip decimal>ratio swap ;   qw{ Platinum Golden Silver Bronze Copper Nickel Aluminum Iron Tin Lead } [ dup dup approximate { [ "Lucas sequence for %s ratio " printf ] [ "where b = %d:\n" printf ] [ "First 15 elements: " write lucas. ] [ "Approximated value: %.32f " printf ] [ "- reached after  %d iteration(s)\n\n" printf ] } spread ] each-index
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
#Go
Go
package main   import ( "fmt" "math/big" )   var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"}   func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() }   func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } }   func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
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.
#Ada
Ada
with Ada.Text_IO;   procedure Middle_Three_Digits is   Impossible: exception;   function Middle_String(I: Integer; Middle_Size: Positive) return String is S: constant String := Integer'Image(I); First: Natural := S'First; Full_Size, Border: Natural; begin while S(First) not in '0' .. '9' loop -- skip leading blanks and minus First := First + 1; end loop; Full_Size := S'Last-First+1; if (Full_Size < Middle_Size) or (Full_Size mod 2 = 0) then raise Impossible; else Border := (Full_Size - Middle_Size)/2; return S(First+Border .. First+Border+Middle_Size-1); end if; end Middle_String;   Inputs: array(Positive range <>) of Integer := (123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); Error_Message: constant String := "number of digits must be >= 3 and odd";   package IIO is new Ada.Text_IO.Integer_IO(Integer);   begin for I in Inputs'Range loop IIO.Put(Inputs(I), Width => 9); Ada.Text_IO.Put(": "); begin Ada.Text_IO.Put(Middle_String(Inputs(I), 3)); exception when Impossible => Ada.Text_IO.Put("****" & Error_Message & "****"); end; Ada.Text_IO.New_Line; end loop;   end Middle_Three_Digits;
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)
#D
D
len cell[] 56 len cnt[] 56 len flag[] 56 # subr initvars state = 0 ticks = 0 indx = -1 no_time = 0 . func getind r c . ind . ind = -1 if r >= 0 and r <= 6 and c >= 0 and c <= 7 ind = r * 8 + c . . func draw_cell ind h . . r = ind div 8 c = ind mod 8 x = c * 12 + 2.5 y = r * 12 + 14.5 move x y rect 11 11 if h > 0 # count move x + 3 y + 2 color 000 text h elif h = -3 # flag x += 4 color 000 linewidth 0.8 move x y + 3 line x y + 8 color 600 linewidth 2 move x + 0.5 y + 4 line x + 2 y + 4 elif h <> 0 # mine color 333 if h = -2 color 800 . move x + 5 y + 6 circle 3 line x + 8 y + 2 . . func open ind . . if ind <> -1 and cell[ind] = 0 cell[ind] = 2 flag[ind] = 0 color 686 call draw_cell ind cnt[ind] if cnt[ind] = 0 r0 = ind div 8 c0 = ind mod 8 for r = r0 - 1 to r0 + 1 for c = c0 - 1 to c0 + 1 if r <> r0 or c <> c0 call getind r c ind call open ind . . . . . . func show_mines m . . for ind range 56 if cell[ind] = 1 color 686 if m = -1 color 353 . call draw_cell ind m . . . func outp col s$ . . move 2.5 2 color col rect 59 11 color 000 move 5 4.5 text s$ . func upd_info . . nm = 0 nc = 0 for i range 56 nm += flag[i] if cell[i] < 2 nc += 1 . . if nc = 8 call outp 484 "Well done" call show_mines -1 state = 1 else call outp 464 8 - nm & " mines left" . . func test ind . . if cell[ind] < 2 and flag[ind] = 0 if cell[ind] = 1 call show_mines -1 color 686 call draw_cell ind -2 call outp 844 "B O O M !" state = 1 else call open ind call upd_info . . . background 676 func start . . clear color 353 for ind range 56 cnt[ind] = 0 cell[ind] = 0 flag[ind] = 0 call draw_cell ind 0 . n = 8 while n > 0 c = random 8 r = random 7 ind = r * 8 + c if cell[ind] = 0 n -= 1 cell[ind] = 1 for rx = r - 1 to r + 1 for cx = c - 1 to c + 1 call getind rx cx ind if ind > -1 cnt[ind] += 1 . . . . . call initvars call outp 464 "" textsize 4 move 5 3 text "Minesweeper - 8 mines" move 5 7.8 text "Long-press for flagging" textsize 6 timer 0 . on mouse_down if state = 0 if mouse_y < 14 and mouse_x > 60 no_time = 1 move 64.5 2 color 464 rect 33 11 . call getind (mouse_y - 14) div 12 (mouse_x - 2) div 12 indx ticks0 = ticks elif state = 3 call start . . on mouse_up if state = 0 and indx <> -1 call test indx . indx = -1 . on timer if state = 1 state = 2 timer 1 elif state = 2 state = 3 elif no_time = 0 and ticks > 3000 call outp 844 "B O O M !" call show_mines -2 state = 2 timer 1 else if indx > -1 and ticks = ticks0 + 2 if cell[indx] < 2 color 353 flag[indx] = 1 - flag[indx] opt = 0 if flag[indx] = 1 opt = -3 . call draw_cell indx opt call upd_info . indx = -1 . if no_time = 0 and ticks mod 10 = 0 move 64.5 2 color 464 if ticks >= 2500 color 844 . rect 33 11 color 000 move 66 4.5 text "Time:" & 300 - ticks / 10 . ticks += 1 timer 0.1 . . call start
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
#Julia
Julia
function B10(n) for i in Int128(1):typemax(Int128) q, b10, place = i, zero(Int128), one(Int128) while q > 0 q, r = divrem(q, 2) if r != 0 b10 += place end place *= 10 end if b10 % n == 0 return b10 end end end   for n in [1:10; 95:105; [297, 576, 891, 909, 1998, 2079, 2251, 2277, 2439, 2997, 4878]] i = B10(n) println("B10($n) = $n * $(div(i, n)) = $i") 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} .
#Julia
Julia
a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = big(10) ^ 40 @show powermod(a, b, m)
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Kotlin
Kotlin
// version 1.0.6   import java.math.BigInteger   fun main(args: Array<String>) { val a = BigInteger("2988348162058574136915891421498819466320163312926952423791023078876139") val b = BigInteger("2351399303373464486466122544523690094744975233415544072992656881240319") val m = BigInteger.TEN.pow(40) println(a.modPow(b, m)) }
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Common_Lisp
Common Lisp
(ql:quickload '(cl-openal cl-alc))   (defparameter *short-max* (- (expt 2 15) 1)) (defparameter *2-pi* (* 2 pi))   (defun make-sin (period) "Create a generator for a sine wave of the given PERIOD." (lambda (x) (sin (* *2-pi* (/ x period)))))   (defun make-tone (length frequency sampling-frequency) "Create a vector containing sound information of the given LENGTH, FREQUENCY, and SAMPLING-FREQUENCY." (let ((data (make-array (truncate (* length sampling-frequency)) :element-type '(signed-byte 16))) (generator (make-sin (/ sampling-frequency frequency)))) (dotimes (i (length data)) (setf (aref data i) (truncate (* *short-max* (funcall generator i))))) data))   (defun internal-time-ms () "Get the process's real time in ms." (* 1000 (/ (get-internal-real-time) internal-time-units-per-second)))   (defun spin-wait (next-real-time) "Wait until the process's real time has reached the given time." (loop while (< (internal-time-ms) next-real-time)))   (defun upload (buffer data sampling-frequency) "Upload the given vector DATA to a BUFFER at the given SAMPLING-FREQUENCY." (cffi:with-pointer-to-vector-data (data-ptr data) (al:buffer-data buffer :mono16 data-ptr (* 2 (length data)) sampling-frequency)))   (defun metronome (beats/minute pattern &optional (sampling-frequency 44100)) "Play a metronome until interrupted." (let ((ms/beat (/ 60000 beats/minute))) (alc:with-device (device) (alc:with-context (context device) (alc:make-context-current context) (al:with-buffer (low-buffer) (al:with-buffer (high-buffer) (al:with-source (source) (al:source source :gain 0.5) (flet ((play-it (buffer) (al:source source :buffer buffer) (al:source-play source)) (upload-it (buffer time frequency) (upload buffer (make-tone time frequency sampling-frequency) sampling-frequency))) (upload-it low-buffer 0.1 440) (upload-it high-buffer 0.15 880) (let ((next-scheduled-tone (internal-time-ms))) (loop (loop for symbol in pattern do (spin-wait next-scheduled-tone) (incf next-scheduled-tone ms/beat) (case symbol (l (play-it low-buffer)) (h (play-it high-buffer))) (princ symbol)) (terpri)))))))))))
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.
#EchoLisp
EchoLisp
  (require 'tasks) ;; tasks library   (define (task id) (wait S) ;; acquire, p-op (printf "task %d acquires semaphore @ %a" id (date->time-string (current-date))) (sleep 2000) (signal S) ;; release, v-op id)   (define S (make-semaphore 4)) ;; semaphore with init count 4   ;; run 10 // tasks (for ([i 10]) (task-run (make-task task i ) (random 500)))  
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.
#Erlang
Erlang
  -module(metered). -compile(export_all).   create_semaphore(N) -> spawn(?MODULE, sem_loop, [N,N]).   sem_loop(0,Max) -> io:format("Resources exhausted~n"), receive {release, PID} -> PID ! released, sem_loop(1,Max); {stop, _PID} -> ok end; sem_loop(N,N) -> receive {acquire, PID} -> PID ! acquired, sem_loop(N-1,N); {stop, _PID} -> ok end; sem_loop(N,Max) -> receive {release, PID} -> PID ! released, sem_loop(N+1,Max); {acquire, PID} -> PID ! acquired, sem_loop(N-1,Max); {stop, _PID} -> ok end.   release(Sem) -> Sem ! {release, self()}, receive released -> ok end. acquire(Sem) -> Sem ! {acquire, self()}, receive acquired -> ok end.   start() -> create_semaphore(10).   stop(Sem) -> Sem ! {stop, self()}.   worker(P,N,Sem) -> acquire(Sem), io:format("Worker ~b has the acquired semaphore~n",[N]), timer:sleep(500 * random:uniform(4)), release(Sem), io:format("Worker ~b has released the semaphore~n",[N]), P ! {done, self()}.   test() -> Sem = start(), Pids = lists:map(fun (N) -> spawn(?MODULE, worker, [self(),N,Sem]) end, lists:seq(1,20)), lists:foreach(fun (P) -> receive {done, P} -> ok end end, Pids), stop(Sem).  
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Ruby
Ruby
# stripped version of Andrea Fazzi's submission to Ruby Quiz #179   class Modulo include Comparable   def initialize(n = 0, m = 13) @n, @m = n % m, m end   def to_i @n end   def <=>(other_n) @n <=> other_n.to_i end   [:+, :-, :*, :**].each do |meth| define_method(meth) { |other_n| Modulo.new(@n.send(meth, other_n.to_i), @m) } end   def coerce(numeric) [numeric, @n] end   end   # Demo x, y = Modulo.new(10), Modulo.new(20)   p x > y # true p x == y # false p [x,y].sort #[#<Modulo:0x000000012ae0f8 @n=7, @m=13>, #<Modulo:0x000000012ae148 @n=10, @m=13>] p x + y ##<Modulo:0x0000000117e110 @n=4, @m=13> p 2 + y # 9 p y + 2 ##<Modulo:0x00000000ad1d30 @n=9, @m=13>   p x**100 + x +1 ##<Modulo:0x00000000ad1998 @n=1, @m=13>  
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Python
Python
>>> size = 12 >>> width = len(str(size**2)) >>> for row in range(-1,size+1): if row==0: print("─"*width + "┼"+"─"*((width+1)*size-1)) else: print("".join("%*s%1s" % ((width,) + (("x","│") if row==-1 and col==0 else (row,"│") if row>0 and col==0 else (col,"") if row==-1 else ("","") if row>col else (row*col,""))) for col in range(size+1)))     x│ 1 2 3 4 5 6 7 8 9 10 11 12 ───┼─────────────────────────────────────────────── 1│ 1 2 3 4 5 6 7 8 9 10 11 12 2│ 4 6 8 10 12 14 16 18 20 22 24 3│ 9 12 15 18 21 24 27 30 33 36 4│ 16 20 24 28 32 36 40 44 48 5│ 25 30 35 40 45 50 55 60 6│ 36 42 48 54 60 66 72 7│ 49 56 63 70 77 84 8│ 64 72 80 88 96 9│ 81 90 99 108 10│ 100 110 120 11│ 121 132 12│ 144 >>>
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#J
J
  NB. A failed assertion looks like this assert 0 |assertion failure: assert | assert 0  
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => { const // DEALT [rs_, bs_, discards] = threeStacks( map(n => even(n) ? ( 'R' ) : 'B', knuthShuffle( enumFromTo(1, 52) ) ) ),   // SWAPPED nSwap = randomRInt(1, min(rs_.length, bs_.length)), [rs, bs] = exchange(nSwap, rs_, bs_),   // CHECKED rrs = filter(c => 'R' === c, rs).join(''), bbs = filter(c => 'B' === c, bs).join(''); return unlines([ 'Discarded: ' + discards.join(''), 'Swapped: ' + nSwap, 'Red pile: ' + rs.join(''), 'Black pile: ' + bs.join(''), rrs + ' = Red cards in the red pile', bbs + ' = Black cards in the black pile', (rrs.length === bbs.length).toString() ]); };   // THREE STACKS ---------------------------------------   // threeStacks :: [Chars] -> ([Chars], [Chars], [Chars]) const threeStacks = cards => { const go = ([rs, bs, ds]) => xs => { const lng = xs.length; return 0 < lng ? ( 1 < lng ? (() => { const [x, y] = take(2, xs), ds_ = cons(x, ds); return ( 'R' === x ? ( go([cons(y, rs), bs, ds_]) ) : go([rs, cons(y, bs), ds_]) )(drop(2, xs)); })() : [rs, bs, ds_] ) : [rs, bs, ds]; }; return go([ [], [], [] ])(cards); };   // exchange :: Int -> [a] -> [a] -> ([a], [a]) const exchange = (n, xs, ys) => { const [xs_, ys_] = map(splitAt(n), [xs, ys]); return [ fst(ys_).concat(snd(xs_)), fst(xs_).concat(snd(ys_)) ]; };   // SHUFFLE --------------------------------------------   // knuthShuffle :: [a] -> [a] const knuthShuffle = xs => enumFromTo(0, xs.length - 1) .reduceRight((a, i) => { const iRand = randomRInt(0, i); return i !== iRand ? ( swapped(i, iRand, a) ) : a; }, xs);   // swapped :: Int -> Int -> [a] -> [a] const swapped = (iFrom, iTo, xs) => xs.map( (x, i) => iFrom !== i ? ( iTo !== i ? ( x ) : xs[iFrom] ) : xs[iTo] );   // GENERIC FUNCTIONS ----------------------------------   // cons :: a -> [a] -> [a] const cons = (x, xs) => Array.isArray(xs) ? ( [x].concat(xs) ) : (x + xs);   // drop :: Int -> [a] -> [a] // drop :: Int -> String -> String const drop = (n, xs) => xs.slice(n);   // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => m <= n ? iterateUntil( x => n <= x, x => 1 + x, m ) : [];   // even :: Int -> Bool const even = n => 0 === n % 2;   // filter :: (a -> Bool) -> [a] -> [a] const filter = (f, xs) => xs.filter(f);   // fst :: (a, b) -> a const fst = tpl => tpl[0];   // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] const iterateUntil = (p, f, x) => { const vs = [x]; let h = x; while (!p(h))(h = f(h), vs.push(h)); return vs; };   // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f);   // min :: Ord a => a -> a -> a const min = (a, b) => b < a ? b : a;   // randomRInt :: Int -> Int -> Int const randomRInt = (low, high) => low + Math.floor( (Math.random() * ((high - low) + 1)) );   // snd :: (a, b) -> b const snd = tpl => tpl[1];   // splitAt :: Int -> [a] -> ([a],[a]) const splitAt = n => xs => Tuple(xs.slice(0, n), xs.slice(n));   // take :: Int -> [a] -> [a] const take = (n, xs) => xs.slice(0, n);   // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // unlines :: [String] -> String const unlines = xs => xs.join('\n');   // MAIN --- return main(); })();
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
#Factor
Factor
USING: fry hash-sets io kernel math prettyprint sequences sets ;   : next ( seq sums speculative -- seq' sums' speculative' ) dup reach [ + ] with map over dup + suffix! >hash-set pick over intersect null? [ swapd union [ [ suffix! ] keep ] dip swap ] [ drop ] if 1 + ;   : mian-chowla ( n -- seq ) [ V{ 1 } HS{ 2 } [ clone ] bi@ 2 ] dip '[ pick length _ < ] [ next ] while 2drop ;   100 mian-chowla [ 30 head "First 30 terms of the Mian-Chowla sequence:" ] [ 10 tail* "Terms 91-100 of the Mian-Chowla sequence:" ] bi [ print [ pprint bl ] each nl nl ] 2bi@
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
#FreeBASIC
FreeBASIC
redim as uinteger mian(0 to 1) redim as uinteger sums(0 to 2) mian(0) = 1 : mian(1) = 2 sums(0) = 2 : sums(1) = 3 : sums(2) = 4 dim as uinteger n_mc = 2, n_sm = 3, curr = 3, tempsum while n_mc < 101 for i as uinteger = 0 to n_mc - 1 tempsum = curr + mian(i) for j as uinteger = 0 to n_sm - 1 if tempsum = sums(j) then goto loopend next j next i redim preserve as uinteger mian(0 to n_mc) mian(n_mc) = curr redim preserve as uinteger sums(0 to n_sm + n_mc) for j as uinteger = 0 to n_mc - 1 sums(n_sm + j) = mian(j) + mian(n_mc) next j n_mc += 1 n_sm += n_mc sums(n_sm-1) = 2*curr loopend: curr += 1 wend   print "Mian-Chowla numbers 1 through 30: ", for i as uinteger = 0 to 29 print mian(i), next i print print "Mian-Chowla numbers 91 through 100: ", for i as uinteger = 90 to 99 print mian(i), next i print
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.
#E
E
\ BRANCH and LOOP COMPILERS   \ branch offset computation operators : AHEAD ( -- addr) HERE 0 , ; : BACK ( addr -- ) HERE - , ; : RESOLVE ( addr -- ) HERE OVER - SWAP ! ;   \ LEAVE stack is called L0. It is initialized by QUIT. : >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; : L> ( -- x ) ( L: x -- ) LP @ @ -2 LP +! ;   \ finite loop compilers : DO ( -- ) POSTPONE <DO> HERE 0 >L 3 ; IMMEDIATE : ?DO ( -- ) POSTPONE <?DO> HERE 0 >L 3 ; IMMEDIATE : LEAVE ( -- ) ( L: -- addr ) POSTPONE UNLOOP POSTPONE BRANCH AHEAD >L ; IMMEDIATE   : RAKE ( -- ) ( L: 0 a1 a2 .. aN -- ) BEGIN L> ?DUP WHILE RESOLVE REPEAT ; IMMEDIATE   : LOOP ( -- ) 3 ?PAIRS POSTPONE <LOOP> BACK RAKE ; IMMEDIATE : +LOOP ( -- ) 3 ?PAIRS POSTPONE <+LOOP> BACK RAKE ; IMMEDIATE   \ conditional branches : IF ( ? -- ) POSTPONE ?BRANCH AHEAD 2 ; IMMEDIATE : THEN ( -- )  ?COMP 2 ?PAIRS RESOLVE ; IMMEDIATE : ELSE ( -- ) 2 ?PAIRS POSTPONE BRANCH AHEAD SWAP 2 POSTPONE THEN 2 ; IMMEDIATE   \ infinite loop compilers : BEGIN ( -- addr n) ?COMP HERE 1  ; IMMEDIATE : AGAIN ( -- ) 1 ?PAIRS POSTPONE BRANCH BACK  ; IMMEDIATE : UNTIL ( ? -- ) 1 ?PAIRS POSTPONE ?BRANCH BACK  ; IMMEDIATE : WHILE ( ? -- ) POSTPONE IF 2+  ; IMMEDIATE : REPEAT ( -- ) 2>R POSTPONE AGAIN 2R> 2- POSTPONE THEN ; IMMEDIATE
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.
#Erlang
Erlang
\ BRANCH and LOOP COMPILERS   \ branch offset computation operators : AHEAD ( -- addr) HERE 0 , ; : BACK ( addr -- ) HERE - , ; : RESOLVE ( addr -- ) HERE OVER - SWAP ! ;   \ LEAVE stack is called L0. It is initialized by QUIT. : >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; : L> ( -- x ) ( L: x -- ) LP @ @ -2 LP +! ;   \ finite loop compilers : DO ( -- ) POSTPONE <DO> HERE 0 >L 3 ; IMMEDIATE : ?DO ( -- ) POSTPONE <?DO> HERE 0 >L 3 ; IMMEDIATE : LEAVE ( -- ) ( L: -- addr ) POSTPONE UNLOOP POSTPONE BRANCH AHEAD >L ; IMMEDIATE   : RAKE ( -- ) ( L: 0 a1 a2 .. aN -- ) BEGIN L> ?DUP WHILE RESOLVE REPEAT ; IMMEDIATE   : LOOP ( -- ) 3 ?PAIRS POSTPONE <LOOP> BACK RAKE ; IMMEDIATE : +LOOP ( -- ) 3 ?PAIRS POSTPONE <+LOOP> BACK RAKE ; IMMEDIATE   \ conditional branches : IF ( ? -- ) POSTPONE ?BRANCH AHEAD 2 ; IMMEDIATE : THEN ( -- )  ?COMP 2 ?PAIRS RESOLVE ; IMMEDIATE : ELSE ( -- ) 2 ?PAIRS POSTPONE BRANCH AHEAD SWAP 2 POSTPONE THEN 2 ; IMMEDIATE   \ infinite loop compilers : BEGIN ( -- addr n) ?COMP HERE 1  ; IMMEDIATE : AGAIN ( -- ) 1 ?PAIRS POSTPONE BRANCH BACK  ; IMMEDIATE : UNTIL ( ? -- ) 1 ?PAIRS POSTPONE ?BRANCH BACK  ; IMMEDIATE : WHILE ( ? -- ) POSTPONE IF 2+  ; IMMEDIATE : REPEAT ( -- ) 2>R POSTPONE AGAIN 2R> 2- POSTPONE THEN ; IMMEDIATE
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)
#11l
11l
F isProbablePrime(n, k = 10) I n < 2 | n % 2 == 0 R n == 2   V d = n - 1 V s = 0 L d % 2 == 0 d I/= 2 s++   assert(2 ^ s * d == n - 1)   L 0 .< k V a = random:(2 .< n) V x = pow(a, d, n) I x == 1 | x == n - 1 L.continue L 0 .< s - 1 x = pow(x, 2, n) I x == 1 R 0B I x == n - 1 L.break L.was_no_break R 0B   R 1B   print((2..29).filter(x -> isProbablePrime(x)))
http://rosettacode.org/wiki/Metallic_ratios
Metallic ratios
Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series of related ratios that are referred to as the "Metallic ratios". The Golden ratio was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The Silver ratio was was also known to 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
#Groovy
Groovy
class MetallicRatios { private static List<String> names = new ArrayList<>() static { names.add("Platinum") names.add("Golden") names.add("Silver") names.add("Bronze") names.add("Copper") names.add("Nickel") names.add("Aluminum") names.add("Iron") names.add("Tin") names.add("Lead") }   private static void lucas(long b) { printf("Lucas sequence for %s ratio, where b = %d\n", names[b], b) print("First 15 elements: ") long x0 = 1 long x1 = 1 printf("%d, %d", x0, x1) for (int i = 1; i < 13; ++i) { long x2 = b * x1 + x0 printf(", %d", x2) x0 = x1 x1 = x2 } println() }   private static void metallic(long b, int dp) { BigInteger x0 = BigInteger.ONE BigInteger x1 = BigInteger.ONE BigInteger x2 BigInteger bb = BigInteger.valueOf(b) BigDecimal ratio = BigDecimal.ONE.setScale(dp) int iters = 0 String prev = ratio.toString() while (true) { iters++ x2 = bb * x1 + x0 String thiz = (x2.toBigDecimal().setScale(dp) / x1.toBigDecimal().setScale(dp)).toString() if (prev == thiz) { String plural = "s" if (iters == 1) { plural = "" } printf("Value after %d iteration%s: %s\n\n", iters, plural, thiz) return } prev = thiz x0 = x1 x1 = x2 } }   static void main(String[] args) { for (int b = 0; b < 10; ++b) { lucas(b) metallic(b, 32) } println("Golden ratio, where b = 1:") metallic(1, 256) } }
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.
#Aime
Aime
void m3(integer i) { text s;   s = itoa(i); if (s[0] == '-') { s = delete(s, 0); }   if (~s < 3) { v_integer(i); v_text(" has not enough digits\n"); } elif (~s & 1) { o_form("/w9/: ~\n", i, cut(s, ~s - 3 >> 1, 3)); } else { v_integer(i); v_text(" has an even number of digits\n"); } }   void middle_3(...) { integer i;   i = 0; while (i < count()) { m3($i); i += 1; } }   integer main(void) { middle_3(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);   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)
#EasyLang
EasyLang
len cell[] 56 len cnt[] 56 len flag[] 56 # subr initvars state = 0 ticks = 0 indx = -1 no_time = 0 . func getind r c . ind . ind = -1 if r >= 0 and r <= 6 and c >= 0 and c <= 7 ind = r * 8 + c . . func draw_cell ind h . . r = ind div 8 c = ind mod 8 x = c * 12 + 2.5 y = r * 12 + 14.5 move x y rect 11 11 if h > 0 # count move x + 3 y + 2 color 000 text h elif h = -3 # flag x += 4 color 000 linewidth 0.8 move x y + 3 line x y + 8 color 600 linewidth 2 move x + 0.5 y + 4 line x + 2 y + 4 elif h <> 0 # mine color 333 if h = -2 color 800 . move x + 5 y + 6 circle 3 line x + 8 y + 2 . . func open ind . . if ind <> -1 and cell[ind] = 0 cell[ind] = 2 flag[ind] = 0 color 686 call draw_cell ind cnt[ind] if cnt[ind] = 0 r0 = ind div 8 c0 = ind mod 8 for r = r0 - 1 to r0 + 1 for c = c0 - 1 to c0 + 1 if r <> r0 or c <> c0 call getind r c ind call open ind . . . . . . func show_mines m . . for ind range 56 if cell[ind] = 1 color 686 if m = -1 color 353 . call draw_cell ind m . . . func outp col s$ . . move 2.5 2 color col rect 59 11 color 000 move 5 4.5 text s$ . func upd_info . . nm = 0 nc = 0 for i range 56 nm += flag[i] if cell[i] < 2 nc += 1 . . if nc = 8 call outp 484 "Well done" call show_mines -1 state = 1 else call outp 464 8 - nm & " mines left" . . func test ind . . if cell[ind] < 2 and flag[ind] = 0 if cell[ind] = 1 call show_mines -1 color 686 call draw_cell ind -2 call outp 844 "B O O M !" state = 1 else call open ind call upd_info . . . background 676 func start . . clear color 353 for ind range 56 cnt[ind] = 0 cell[ind] = 0 flag[ind] = 0 call draw_cell ind 0 . n = 8 while n > 0 c = random 8 r = random 7 ind = r * 8 + c if cell[ind] = 0 n -= 1 cell[ind] = 1 for rx = r - 1 to r + 1 for cx = c - 1 to c + 1 call getind rx cx ind if ind > -1 cnt[ind] += 1 . . . . . call initvars call outp 464 "" textsize 4 move 5 3 text "Minesweeper - 8 mines" move 5 7.8 text "Long-press for flagging" textsize 6 timer 0 . on mouse_down if state = 0 if mouse_y < 14 and mouse_x > 60 no_time = 1 move 64.5 2 color 464 rect 33 11 . call getind (mouse_y - 14) div 12 (mouse_x - 2) div 12 indx ticks0 = ticks elif state = 3 call start . . on mouse_up if state = 0 and indx <> -1 call test indx . indx = -1 . on timer if state = 1 state = 2 timer 1 elif state = 2 state = 3 elif no_time = 0 and ticks > 3000 call outp 844 "B O O M !" call show_mines -2 state = 2 timer 1 else if indx > -1 and ticks = ticks0 + 2 if cell[indx] < 2 color 353 flag[indx] = 1 - flag[indx] opt = 0 if flag[indx] = 1 opt = -3 . call draw_cell indx opt call upd_info . indx = -1 . if no_time = 0 and ticks mod 10 = 0 move 64.5 2 color 464 if ticks >= 2500 color 844 . rect 33 11 color 000 move 66 4.5 text "Time:" & 300 - ticks / 10 . ticks += 1 timer 0.1 . . call start
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
#Kotlin
Kotlin
import java.math.BigInteger   fun main() { for (n in testCases) { val result = getA004290(n) println("A004290($n) = $result = $n * ${result / n.toBigInteger()}") } }   private val testCases: List<Int> get() { val testCases: MutableList<Int> = ArrayList() for (i in 1..10) { testCases.add(i) } for (i in 95..105) { testCases.add(i) } for (i in intArrayOf(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) { testCases.add(i) } return testCases }   private fun getA004290(n: Int): BigInteger { if (n == 1) { return BigInteger.ONE } val arr = Array(n) { IntArray(n) } for (i in 2 until n) { arr[0][i] = 0 } arr[0][0] = 1 arr[0][1] = 1 var m = 0 val ten = BigInteger.TEN val nBi = n.toBigInteger() while (true) { m++ if (arr[m - 1][mod(-ten.pow(m), nBi).toInt()] == 1) { break } arr[m][0] = 1 for (k in 1 until n) { arr[m][k] = arr[m - 1][k].coerceAtLeast(arr[m - 1][mod(k.toBigInteger() - ten.pow(m), nBi).toInt()]) } } var r = ten.pow(m) var k = mod(-r, nBi) for (j in m - 1 downTo 1) { if (arr[j - 1][k.toInt()] == 0) { r += ten.pow(j) k = mod(k - ten.pow(j), nBi) } } if (k.compareTo(BigInteger.ONE) == 0) { r += BigInteger.ONE } return r }   private fun mod(m: BigInteger, n: BigInteger): BigInteger { var result = m.mod(n) if (result < BigInteger.ZERO) { result += n } return 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} .
#Lambdatalk
Lambdatalk
  We will call the lib_BN library for big numbers:   {require lib_BN}   In this library {BN.compare a b} returns 1 if a > b, 0 if a = b and -1 if a < b. For a better readability we define three small functions   {def BN.= {lambda {:a :b} {= {BN.compare :a :b} 0}}} -> BN.= {def BN.even? {lambda {:n} {= {BN.compare {BN.% :n 2} 0} 0}}} -> BN.even? {def BN.square {lambda {:n} {BN.* :n :n}}} -> BN.square   {def mod-exp {lambda {:a :n :mod} {if {BN.= :n 0} then 1 else {if {BN.even? :n} then {BN.% {BN.square {mod-exp :a {BN./ :n 2} :mod}} :mod} else {BN.% {BN.* :a {mod-exp :a {BN.- :n 1} :mod}} :mod}}}}} -> mod-exp   {mod-exp 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 {BN.pow 10 40}} -> 1527229998585248450016808958343740453059 // 3300ms  
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.
#Delphi
Delphi
  program Metronome;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils;   procedure StartMetronome(bpm: double; measure: Integer); var counter: Integer; begin counter := 0; while True do begin Sleep(Trunc(1000 * (60.0 / bpm))); inc(counter); if counter mod measure = 0 then writeln('TICK') else writeln('TOCK'); end; end;   begin StartMetronome(120, 4); end.
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active 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.
#Euphoria
Euphoria
sequence sems sems = {} constant COUNTER = 1, QUEUE = 2   function semaphore(integer n) if n > 0 then sems = append(sems,{n,{}}) return length(sems) else return 0 end if end function   procedure acquire(integer id) if sems[id][COUNTER] = 0 then task_suspend(task_self()) sems[id][QUEUE] &= task_self() task_yield() end if sems[id][COUNTER] -= 1 end procedure   procedure release(integer id) sems[id][COUNTER] += 1 if length(sems[id][QUEUE])>0 then task_schedule(sems[id][QUEUE][1],1) sems[id][QUEUE] = sems[id][QUEUE][2..$] end if end procedure   function count(integer id) return sems[id][COUNTER] end function   procedure delay(atom delaytime) atom t t = time() while time() - t < delaytime do task_yield() end while end procedure   integer sem   procedure worker() acquire(sem) printf(1,"- Task %d acquired semaphore.\n",task_self()) delay(2) release(sem) printf(1,"+ Task %d released semaphore.\n",task_self()) end procedure   integer task   sem = semaphore(4)   for i = 1 to 10 do task = task_create(routine_id("worker"),{}) task_schedule(task,1) task_yield() end for   while length(task_list())>1 do task_yield() end while
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Scala
Scala
object ModularArithmetic extends App { private val x = new ModInt(10, 13) private val y = f(x)   private def f[T](x: Ring[T]) = (x ^ 100) + x + x.one   private trait Ring[T] { def +(rhs: Ring[T]): Ring[T]   def *(rhs: Ring[T]): Ring[T]   def one: Ring[T]   def ^(p: Int): Ring[T] = { require(p >= 0, "p must be zero or greater") var pp = p var pwr = this.one while ( { pp -= 1; pp } >= 0) pwr = pwr * this pwr } }   private class ModInt(var value: Int, var modulo: Int) extends Ring[ModInt] { def +(other: Ring[ModInt]): Ring[ModInt] = { require(other.isInstanceOf[ModInt], "Cannot add an unknown ring.") val rhs = other.asInstanceOf[ModInt] require(modulo == rhs.modulo, "Cannot add rings with different modulus") new ModInt((value + rhs.value) % modulo, modulo) }   def *(other: Ring[ModInt]): Ring[ModInt] = { require(other.isInstanceOf[ModInt], "Cannot multiple an unknown ring.") val rhs = other.asInstanceOf[ModInt] require(modulo == rhs.modulo, "Cannot multiply rings with different modulus") new ModInt((value * rhs.value) % modulo, modulo) }   override def one = new ModInt(1, modulo)   override def toString: String = f"ModInt($value%d, $modulo%d)" }   println("x ^ 100 + x + 1 for x = ModInt(10, 13) is " + y)   }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Quackery
Quackery
[ swap number$ tuck size - times sp echo$ ] is echo-rj ( n n --> )   say " * |" 12 times [ i^ 1+ 4 echo-rj ] cr say " ---+" char - 48 of echo$ cr [ 12 times [ i^ 1+ dup 3 echo-rj say " |" 12 times [ i^ 1+ 2dup > iff [ drop 4 times sp ] else [ dip dup * 4 echo-rj ] ] cr drop ] ]
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Julia
Julia
const rbdeck = split(repeat('R', 26) * repeat('B', 26), "") shuffledeck() = shuffle(rbdeck)   function deal!(deck, dpile, bpile, rpile) while !isempty(deck) if (topcard = pop!(deck)) == "R" push!(rpile, pop!(deck)) else push!(bpile, pop!(deck)) end push!(dpile, topcard) end end   function swap!(rpile, bpile, nswapping) rpick = sort(randperm(length(rpile))[1:nswapping]) bpick = sort(randperm(length(bpile))[1:nswapping]) rrm = rpile[rpick]; brm = bpile[bpick] deleteat!(rpile, rpick); deleteat!(bpile, bpick) append!(rpile, brm); append!(bpile, rrm) end   function mindbogglingcardtrick(verbose=true) prif(cond, txt) = (if(cond) println(txt) end) deck = shuffledeck() prif(verbose, "Shuffled deck is: $deck")   dpile, rpile, bpile = [], [], [] deal!(deck, dpile, bpile, rpile)   prif(verbose, "Before swap:") prif(verbose, "Discard pile: $dpile") prif(verbose, "Red card pile: $rpile") prif(verbose, "Black card pile: $bpile")   amount = rand(1:min(length(rpile), length(bpile))) prif(verbose, "Swapping a random number of cards: $amount will be swapped.") swap!(rpile, bpile, amount)   prif(verbose, "Red pile after swaps: $rpile") prif(verbose, "Black pile after swaps: $bpile") println("There are $(sum(map(x->x=="B", bpile))) black cards in the black card pile:") println("there are $(sum(map(x->x=="R", rpile))) red cards in the red card pile.") prif(verbose, "") end   mindbogglingcardtrick()   for _ in 1:10 mindbogglingcardtrick(false) end  
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Kotlin
Kotlin
// Version 1.2.61   import java.util.Random   fun main(args: Array<String>) { // Create pack, half red, half black and shuffle it. val pack = MutableList(52) { if (it < 26) 'R' else 'B' } pack.shuffle()   // Deal from pack into 3 stacks. val red = mutableListOf<Char>() val black = mutableListOf<Char>() val discard = mutableListOf<Char>() for (i in 0 until 52 step 2) { when (pack[i]) { 'B' -> black.add(pack[i + 1]) 'R' -> red.add(pack[i + 1]) } discard.add(pack[i]) } val sr = red.size val sb = black.size val sd = discard.size println("After dealing the cards the state of the stacks is:") System.out.printf(" Red  : %2d cards -> %s\n", sr, red) System.out.printf(" Black  : %2d cards -> %s\n", sb, black) System.out.printf(" Discard: %2d cards -> %s\n", sd, discard)   // Swap the same, random, number of cards between the red and black stacks. val rand = Random() val min = minOf(sr, sb) val n = 1 + rand.nextInt(min) var rp = MutableList(sr) { it }.shuffled().subList(0, n) var bp = MutableList(sb) { it }.shuffled().subList(0, n) println("\n$n card(s) are to be swapped\n") println("The respective zero-based indices of the cards(s) to be swapped are:") println(" Red  : $rp") println(" Black  : $bp") for (i in 0 until n) { val temp = red[rp[i]] red[rp[i]] = black[bp[i]] black[bp[i]] = temp } println("\nAfter swapping, the state of the red and black stacks is:") println(" Red  : $red") println(" Black  : $black")   // Check that the number of black cards in the black stack equals // the number of red cards in the red stack. var rcount = 0 var bcount = 0 for (c in red) if (c == 'R') rcount++ for (c in black) if (c == 'B') bcount++ println("\nThe number of red cards in the red stack = $rcount") println("The number of black cards in the black stack = $bcount") if (rcount == bcount) { println("So the asssertion is correct!") } else { println("So the asssertion is incorrect!") } }
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#Go
Go
package main   import "fmt"   func contains(is []int, s int) bool { for _, i := range is { if s == i { return true } } return false }   func mianChowla(n int) []int { mc := make([]int, n) mc[0] = 1 is := []int{2} var sum int for i := 1; i < n; i++ { le := len(is) jloop: for j := mc[i-1] + 1; ; j++ { mc[i] = j for k := 0; k <= i; k++ { sum = mc[k] + j if contains(is, sum) { is = is[0:le] continue jloop } is = append(is, sum) } break } } return mc }   func main() { mc := mianChowla(100) fmt.Println("The first 30 terms of the Mian-Chowla sequence are:") fmt.Println(mc[0:30]) fmt.Println("\nTerms 91 to 100 of the Mian-Chowla sequence are:") fmt.Println(mc[90:100]) }
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.
#Forth
Forth
\ BRANCH and LOOP COMPILERS   \ branch offset computation operators : AHEAD ( -- addr) HERE 0 , ; : BACK ( addr -- ) HERE - , ; : RESOLVE ( addr -- ) HERE OVER - SWAP ! ;   \ LEAVE stack is called L0. It is initialized by QUIT. : >L ( x -- ) ( L: -- x ) 2 LP +! LP @ ! ; : L> ( -- x ) ( L: x -- ) LP @ @ -2 LP +! ;   \ finite loop compilers : DO ( -- ) POSTPONE <DO> HERE 0 >L 3 ; IMMEDIATE : ?DO ( -- ) POSTPONE <?DO> HERE 0 >L 3 ; IMMEDIATE : LEAVE ( -- ) ( L: -- addr ) POSTPONE UNLOOP POSTPONE BRANCH AHEAD >L ; IMMEDIATE   : RAKE ( -- ) ( L: 0 a1 a2 .. aN -- ) BEGIN L> ?DUP WHILE RESOLVE REPEAT ; IMMEDIATE   : LOOP ( -- ) 3 ?PAIRS POSTPONE <LOOP> BACK RAKE ; IMMEDIATE : +LOOP ( -- ) 3 ?PAIRS POSTPONE <+LOOP> BACK RAKE ; IMMEDIATE   \ conditional branches : IF ( ? -- ) POSTPONE ?BRANCH AHEAD 2 ; IMMEDIATE : THEN ( -- )  ?COMP 2 ?PAIRS RESOLVE ; IMMEDIATE : ELSE ( -- ) 2 ?PAIRS POSTPONE BRANCH AHEAD SWAP 2 POSTPONE THEN 2 ; IMMEDIATE   \ infinite loop compilers : BEGIN ( -- addr n) ?COMP HERE 1  ; IMMEDIATE : AGAIN ( -- ) 1 ?PAIRS POSTPONE BRANCH BACK  ; IMMEDIATE : UNTIL ( ? -- ) 1 ?PAIRS POSTPONE ?BRANCH BACK  ; IMMEDIATE : WHILE ( ? -- ) POSTPONE IF 2+  ; IMMEDIATE : REPEAT ( -- ) 2>R POSTPONE AGAIN 2R> 2- POSTPONE THEN ; IMMEDIATE
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Macro ForAll(C, S) For _i as integer = 0 To Len(s) #Define C (Chr(s[_i])) #EndMacro   #Define In ,   Dim s As String = "Rosetta" ForAll(c in s) Print c; " "; Next   Print Sleep
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller 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)
#Ada
Ada
generic type Number is range <>; package Miller_Rabin is   type Result_Type is (Composite, Probably_Prime);   function Is_Prime (N : Number; K : Positive := 10) return Result_Type;   end Miller_Rabin;
http://rosettacode.org/wiki/Metallic_ratios
Metallic ratios
Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series of related ratios that are referred to as the "Metallic ratios". The Golden ratio was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The Silver ratio was was also known to 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
#J
J
  258j256":%~/+/+/ .*~^:10 x:*i.2 2 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374847540880753868917521266338622235369317931800607667263544333890865959395829056383226613199282902678806752087668925017116962070322210432162695486262963136144  
http://rosettacode.org/wiki/Metallic_ratios
Metallic ratios
Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series of related ratios that are referred to as the "Metallic ratios". The Golden ratio was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The Silver ratio was was also known to 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
#Java
Java
  import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List;   public class MetallicRatios {   private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};   public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); }   private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; }   private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; }   }  
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.
#ALGOL_68
ALGOL 68
# we define a UNION MODE so that our middle 3 digits PROC can # # return either an integer on success or a error message if # # the middle 3 digits couldn't be extracted # MODE EINT = UNION( INT # success value #, STRING # error message # ); # PROC to return the middle 3 digits of an integer. # # if this is not possible, an error message is returned # # instead # PROC middle 3 digits = ( INT number ) EINT: BEGIN # convert the absolute value of the number to a string with the # # minumum possible number characters # STRING digits = whole( ABS number, 0 ); INT len = UPB digits; IF len < 3 THEN # number has less than 3 digits # # return an error message # "number must have at least three digits" ELIF ( len MOD 2 ) = 0 THEN # the number has an even number of digits # # return an error message # "number must have an odd number of digits" ELSE # the number is suitable for extraction of the middle 3 digits # INT first digit pos = 1 + ( ( len - 3 ) OVER 2 ); # the result is the integer value of the three digits # ( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 ) + ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 ) + ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) ) ) FI END; # middle 3 digits #   main: ( # test the middle 3 digits PROC # []INT test values = ( 123, 12345, 1234567, 987654321 , 10001, -10001, -123, -100 , 100, -12345 # the following values should fail # , 1, 2, -1, -10, 2002, -2002, 0 ); FOR test number FROM LWB test values TO UPB test values DO CASE middle 3 digits( test values[ test number ] ) IN ( INT success value ): # got the middle 3 digits # printf( ( $ 11z-d, " : ", 3d $ , test values[ test number ] , success value ) ) , ( STRING error message ): # got an error message # printf( ( $ 11z-d, " : ", n( UPB error message )a $ , test values[ test number ] , error message ) ) ESAC; print( ( newline ) ) OD )
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)
#FreeBASIC
FreeBASIC
'--- Declaration of global variables --- Type mina Dim mina As Byte Dim flag As Byte Dim ok As Byte Dim numero As Byte End Type   Dim Shared As Integer size = 16, NX = 20, NY = 20 Dim Shared As Double mina = 0.10   Dim Shared tablero(NX+1,NY+1) As mina Dim Shared As Integer GameOver, ddx, ddy, kolor, nbDESCANSO Dim Shared As Double temps Dim As String tecla   '--- SUBroutines and FUNCtions --- Sub VerTodo Dim As Integer x, y For x = 1 To NX For y = 1 To NY With tablero(x,y) If .mina = 1 Or .flag > 0 Then .ok = 1 End With Next y Next x End Sub   Sub ShowGrid Dim As Integer x, y Line(ddx-1,ddy-1)-(1+ddx+size*NX,1+ddy+size*NY),&hFF0000,B For x = 1 To NX For y = 1 To NY With tablero(x,y) 'Si la casilla no se hace click If .ok = 0 Then Line(ddx+x*size,ddy+y*size)-(ddx+(x-1)*size,ddy+(y-1)*size),&h888888,BF Line(ddx+x*size,ddy+y*size)-(ddx+(x-1)*size,ddy+(y-1)*size),&h444444,B 'bandera verde If .flag = 1 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h00FF00,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h0 End If 'bandera azul If .flag = 2 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h0000FF,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h0 End If 'Si se hace clic Else If .mina = 0 Then If .numero > 0 Then Select Case .numero Case 1: kolor = &h3333FF Case 2: kolor = &h33FF33 Case 3: kolor = &hFF3333 Case 4: kolor = &hFFFF33 Case 5: kolor = &h33FFFF Case 6: kolor = &hFF33FF Case 7: kolor = &h999999 Case 8: kolor = &hFFFFFF End Select Draw String(ddx+x*size-size/1.5,ddy+y*size-size/1.5),Str(.numero),kolor End If If GameOver = 1 Then 'Si no hay Mina y una bandera verde >> rojo completo If .flag = 1 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h330000,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h555555 End If 'Si no hay Mina y una bandera azul >> azul oscuro If .flag = 2 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h000033,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h555555 End If End If Else 'Si hay una Mina sin bandera >> rojo If .flag = 0 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFF0000,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFFFF00 Else 'Si hay una Mina con bandera verde >>> verde If .flag = 1 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h00FF00,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFFFF00 End If If .flag = 2 Then 'Si hay una Mina con bandera azul >>>> verde oscuro Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h003300,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFFFF00 End If End If End If End If End With Next y Next x End Sub   Sub Calcul Dim As Integer x, y For x = 1 To NX For y = 1 To NY tablero(x,y).numero = _ Iif(tablero(x+1,y).mina=1,1,0) + Iif(tablero(x-1,y).mina=1,1,0) + _ Iif(tablero(x,y+1).mina=1,1,0) + Iif(tablero(x,y-1).mina=1,1,0) + _ Iif(tablero(x+1,y-1).mina=1,1,0) + Iif(tablero(x+1,y+1).mina=1,1,0) + _ Iif(tablero(x-1,y-1).mina=1,1,0) + Iif(tablero(x-1,y+1).mina=1,1,0) Next y Next x End Sub   Sub Inicio size = 20 If NX > 720/size Then size = 720/NX If NY > 520/size Then size = 520/NY   Redim tablero(NX+1,NY+1) As mina Dim As Integer x, y For x = 1 To NX For y = 1 To NY With tablero(x,y) .mina = Iif(Rnd > (1-mina), 1, 0) .ok = 0 .flag = 0 .numero = 0 End With Next y Next x ddx = (((800/size)-NX)/2)*size ddy = (((600/size)-NY)/2)*size Calcul End Sub   Function isGameOver As Integer Dim As Integer x, y, nbMINA, nbOK, nbAZUL, nbVERT For x = 1 To NX For y = 1 To NY If tablero(x,y).ok = 1 And tablero(X,y).mina = 1 Then Return -1 End If If tablero(x,y).ok = 0 And tablero(x,y).flag = 1 And tablero(X,y).mina = 1 Then nbOK += 1 End If If tablero(X,y).mina = 1 Then nbMINA + =1 End If If tablero(X,y).flag = 2 Then nbAZUL += 1 'End If Elseif tablero(X,y).flag = 1 Then nbVERT += 1 End If Next y Next x   If nbMINA = nbOK And nbAZUL = 0 Then Return 1 nbDESCANSO = nbMINA - nbVERT End Function   Sub ClicRecursivo(ZX As Integer, ZY As Integer) If tablero(ZX,ZY).ok = 1 Then Exit Sub If tablero(ZX,ZY).flag > 0 Then Exit Sub 'CLICK tablero(ZX,ZY).ok = 1   If tablero(ZX,ZY).mina = 1 Then Exit Sub If tablero(ZX,ZY).numero > 0 Then Exit Sub   If ZX > 0 And ZX <= NX And ZY > 0 And ZY <= NY Then ClicRecursivo(ZX+1,ZY) ClicRecursivo(ZX-1,ZY) ClicRecursivo(ZX,ZY+1) ClicRecursivo(ZX,ZY-1) ClicRecursivo(ZX+1,ZY+1) ClicRecursivo(ZX+1,ZY-1) ClicRecursivo(ZX-1,ZY+1) ClicRecursivo(ZX-1,ZY-1) End If End Sub     '--- Main Program --- Screenres 800,600,24',,1 Windowtitle"Minesweeper game" Randomize Timer Cls Dim As Integer mx, my, mb, fmb, ZX, ZY, r, tt Dim As Double t Inicio GameOver = 1 Do tecla = Inkey If GameOver = 1 Then Select Case Ucase(tecla) Case Chr(Asc("X")) NX += 5 If NX > 80 Then NX = 10 Inicio Case Chr(Asc("Y")) NY += 5 If NY > 60 Then NY = 10 Inicio Case Chr(Asc("M")) mina += 0.01 If mina > 0.26 Then mina = 0.05 Inicio Case Chr(Asc("S")) Inicio GameOver = 0 temps = Timer End Select End If   Getmouse mx,my,,mb mx -= ddx-size my -= ddy-size ZX = (MX-size/2)/size ZY = (MY-size/2)/size   If GameOver = 0 And zx > 0 And zx <= nx And zy > 0 And zy <= ny Then If MB=1 And fmb=0 Then ClicRecursivo(ZX,ZY) If MB=2 And fmb=0 Then tablero(ZX,ZY).flag += 1 If tablero(ZX,ZY).flag > 2 Then tablero(ZX,ZY).flag = 0 End If fmb = mb End If   r = isGameOver If r = -1 And GameOver = 0 Then VerTodo GameOver = 1 End If If r = 1 And GameOver = 0 Then GameOver = 1 If GameOver = 0 Then tt = Timer-temps   Screenlock Cls ShowGrid If GameOver = 0 Then Draw String (210,4), "X:" & NX & " Y:" & NY & " MINA:" & Int(mina*100) & "% TIMER : " & Int(TT) & " S REMAINING:" & nbDESCANSO,&hFFFF00 Else Draw String (260,4), "PRESS: 'S' TO START X,Y,M TO SIZE" ,&hFFFF00 Draw String (330,17), "X:" & NX & " Y:" & NY & " MINA:" & Int(mina*100) & "%" ,&hFFFF00 If r = 1 Then t += 0.01 If t > 1000 Then t = 0 Draw String (320,280+Cos(t)*100),"!! CONGRATULATION !!",&hFFFF00 End If End If Screenunlock Loop Until tecla = Chr(27) Bsave "Minesweeper.bmp",0 End
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
#Lua
Lua
function array1D(n, v) local tbl = {} for i=1,n do table.insert(tbl, v) end return tbl end   function array2D(h, w, v) local tbl = {} for i=1,h do table.insert(tbl, array1D(w, v)) end return tbl end   function mod(m, n) m = math.floor(m) local result = m % n if result < 0 then result = result + n end return result end   function getA004290(n) if n == 1 then return 1 end local arr = array2D(n, n, 0) arr[1][1] = 1 arr[1][2] = 1 local m = 0 while true do m = m + 1 if arr[m][mod(-10 ^ m, n) + 1] == 1 then break end arr[m + 1][1] = 1 for k = 1, n - 1 do arr[m + 1][k + 1] = math.max(arr[m][k + 1], arr[m][mod(k - 10 ^ m, n) + 1]) end end local r = 10 ^ m local k = mod(-r, n) for j = m - 1, 1, -1 do if arr[j][k + 1] == 0 then r = r + 10 ^ j k = mod(k - 10 ^ j, n) end end if k == 1 then r = r + 1 end return r end   function test(cases) for _,n in ipairs(cases) do local result = getA004290(n) print(string.format("A004290(%d) = %s = %d * %d", n, math.floor(result), n, math.floor(result / n))) end end   test({1, 2, 3, 4, 5, 6, 7, 8, 9}) test({95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105}) test({297, 576, 594, 891, 909, 999}) --test({1998, 2079, 2251, 2277}) --test({2439, 2997, 4878})
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} .
#Maple
Maple
a := 2988348162058574136915891421498819466320163312926952423791023078876139: b := 2351399303373464486466122544523690094744975233415544072992656881240319: a &^ b mod 10^40;
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 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} .
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = 2988348162058574136915891421498819466320163312926952423791023078876139; b = 2351399303373464486466122544523690094744975233415544072992656881240319; m = 10^40; PowerMod[a, b, m] -> 1527229998585248450016808958343740453059
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an 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.
#EchoLisp
EchoLisp
  ;; available preloaded sounds are : ok, ko, tick, tack, woosh, beep, digit . (lib 'timer)   (define (metronome) (blink) (play-sound 'tack)) (at-every 1000 'metronome) ;; every 1000 msec ;; CTRL-C to stop  
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an 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.
#F.23
F#
open System open System.Threading // You can use .wav files for your clicks. // If used, make sure they are in the same file // as this program's executable file. let high_pitch = new System.Media.SoundPlayer("Ping Hi.wav") let low_pitch = new System.Media.SoundPlayer("Ping Low.wav") let factor x y = x / y // Notice that exact bpm would not work by using // Thread.Sleep() as there are additional function calls // that would consume a miniscule amount of time. // This number may need to be adjusted based on the cpu. let cpu_error = -750.0 let print = function | 1 -> high_pitch.Play(); printf "\nTICK " | _ -> low_pitch.Play(); printf "tick " let wait (time:int) = Thread.Sleep(time) // Composition of functions let tick = float>>factor (60000.0+cpu_error)>>int>>wait let rec play beats_per_measure current_beat beats_per_minute = match current_beat, beats_per_measure with | a, b -> current_beat |> print beats_per_minute |> tick if a <> b then beats_per_minute |> play beats_per_measure (current_beat + 1) [<EntryPointAttribute>] let main (args : string[]) = let tempo, beats = int args.[0], int args.[1] Seq.initInfinite (fun i -> i + 1) |> Seq.iter (fun _ -> tempo |> play beats 1 |> ignore) 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.
#Factor
Factor
USING: calendar calendar.format concurrency.combinators concurrency.semaphores formatting kernel sequences threads ;   10 <iota> 2 <semaphore> [ [ dup now timestamp>hms "task %d acquired semaphore at %s\n" printf 2 seconds sleep ] with-semaphore "task %d released\n" printf ] curry parallel-each
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.
#FreeBASIC
FreeBASIC
#define MaxThreads 10   Dim Shared As Any Ptr ttylock   ' Teletype unfurls some text across the screen at a given location Sub teletype(Byref texto As String, Byval x As Integer, Byval y As Integer) ' This MutexLock makes simultaneously running threads wait for each other, ' so only one at a time can continue and print output. ' Otherwise, their Locates would interfere, since there is only one cursor. ' ' It's impossible to predict the order in which threads will arrive here and ' which one will be the first to acquire the lock thus causing the rest to wait.   Mutexlock ttylock   For i As Integer = 0 To (Len(texto) - 1) Locate x, y + i : Print Chr(texto[i]) Sleep 25, 1 Next i   ' MutexUnlock releases the lock and lets other threads acquire it. Mutexunlock ttylock End Sub   Sub thread(Byval userdata As Any Ptr) Dim As Integer id = Cint(userdata) teletype "Thread #" & id & " .........", 1 + id, 1 End Sub   ' Create a mutex to syncronize the threads ttylock = Mutexcreate()   ' Create child threads Dim As Any Ptr handles(0 To MaxThreads-1) For i As Integer = 0 To MaxThreads-1 handles(i) = Threadcreate(@thread, Cptr(Any Ptr, i)) If handles(i) = 0 Then Print "Error creating thread:"; i : Exit For Next i   ' This is the main thread. Now wait until all child threads have finished. For i As Integer = 0 To MaxThreads-1 If handles(i) <> 0 Then Threadwait(handles(i)) Next i   ' Clean up when finished Mutexdestroy(ttylock) Sleep
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaystyle a} and b {\displaystyle b} are said to be congruent modulo p whenever there exists an integer k {\displaystyle k} such that: a = b + k p {\displaystyle a=b+k\,p} The corresponding set of equivalence classes forms a ring denoted Z p Z {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}} . Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: f ( x ) = x 100 + x + 1 {\displaystyle f(x)=x^{100}+x+1} You will use 13 {\displaystyle 13} as the congruence modulus and you will compute f ( 10 ) {\displaystyle f(10)} . It is important that the function f {\displaystyle f} is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#Sidef
Sidef
class Modulo(n=0, m=13) {   method init { (n, m) = (n % m, m) }   method to_n { n }   < + - * ** >.each { |meth| Modulo.def_method(meth, method(n2) { Modulo(n.(meth)(n2.to_n), m) }) }   method to_s { "#{n} 「mod #{m}」" } }   func f(x) { x**100 + x + 1 } say f(Modulo(10, 13))
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#R
R
  multiplication_table <- function(n=12) { one_to_n <- 1:n x <- matrix(one_to_n) %*% t(one_to_n) x[lower.tri(x)] <- 0 rownames(x) <- colnames(x) <- one_to_n print(as.table(x), zero.print="") invisible(x) } multiplication_table()  
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
s = RandomSample@Flatten[{Table[0, 26], Table[1, 26]}] g = Take[s, {1, -1, 2}] d = Take[s, {2, -1, 2}] a = b = {}; Table[If[g[[i]] == 1, AppendTo[a, d[[i]]], AppendTo[b, d[[i]]]], {i, Length@g}]; a b dice = RandomInteger[{1, 6}] ra = Sort@RandomSample[Range@Length@a, dice] a = {Delete[a, List /@ ra], a[[ra]]} rb = Sort@RandomSample[Range@Length@b, dice] b = {Delete[b, List /@ rb], b[[rb]]} finala = Join[a[[1]], b[[2]]] finalb = Join[b[[1]], a[[2]]] Count[finala, 1] == Count[finalb, 0]
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. 1. Cards. Create a common deck of cards of 52 cards   (which are half red, half black). Give the pack a good shuffle. 2. Deal from the shuffled deck, you'll be creating three piles. Assemble the cards face down. Turn up the   top card   and hold it in your hand. if the card is   black,   then add the   next   card (unseen) to the "black" pile. If the card is     red,    then add the   next   card (unseen) to the   "red"  pile. Add the   top card   that you're holding to the discard pile.   (You might optionally show these discarded cards to get an idea of the randomness). Repeat the above for the rest of the shuffled deck. 3. Choose a random number   (call it X)   that will be used to swap cards from the "red" and "black" piles. Randomly choose   X   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch. Randomly choose   X   cards from the "black" pile (unseen), let's call this the "black" bunch. Put the     "red"    bunch into the   "black" pile. Put the   "black"   bunch into the     "red"  pile. (The above two steps complete the swap of   X   cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). 4. Order from randomness? Verify (or not) the mathematician's assertion that: The number of black cards in the "black" pile equals the number of red cards in the "red" pile. (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
#Nim
Nim
import random, sequtils, strformat, strutils   type Color {.pure.} = enum Red = "R", Black = "B"   proc `$`(s: seq[Color]): string = s.join(" ")   # Create pack, half red, half black and shuffle it. var pack = newSeq[Color](52) for i in 0..51: pack[i] = Color(i < 26) pack.shuffle()   # Deal from pack into 3 stacks. var red, black, others: seq[Color] for i in countup(0, 51, 2): case pack[i] of Red: red.add pack[i + 1] of Black: black.add pack[i + 1] others.add pack[i] echo "After dealing the cards the state of the stacks is:" echo &" Red: {red.len:>2} cards -> {red}" echo &" Black: {black.len:>2} cards -> {black}" echo &" Discard: {others.len:>2} cards -> {others}"   # Swap the same, random, number of cards between the red and black stacks. let m = min(red.len, black.len) let n = rand(1..m) var rp = toSeq(0..red.high) rp.shuffle() rp.setLen(n) var bp = toSeq(0..black.high) bp.shuffle() bp.setLen(n) echo &"\n{n} card(s) are to be swapped.\n" echo "The respective zero-based indices of the cards(s) to be swapped are:" echo " Red  : ", rp.join(" ") echo " Black  : ", bp.join(" ") for i in 0..<n: swap red[rp[i]], black[bp[i]] echo "\nAfter swapping, the state of the red and black stacks is:" echo " Red  : ", red echo " Black  : ", black   # Check that the number of black cards in the black stack equals # the number of red cards in the red stack. let rcount = red.count(Red) let bcount = black.count(Black) echo "" echo "The number of red cards in the red stack is ", rcount echo "The number of black cards in the black stack is ", bcount if rcount == bcount: echo "So the asssertion is correct." else: echo "So the asssertion is incorrect."
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#Haskell
Haskell
import Data.Set (Set, fromList, insert, member)   ------------------- MIAN-CHOWLA SEQUENCE ----------------- mianChowlas :: Int -> [Int] mianChowlas = reverse . snd . (iterate nextMC (fromList [2], [1]) !!) . subtract 1   nextMC :: (Set Int, [Int]) -> (Set Int, [Int]) nextMC (sumSet, mcs@(n:_)) = (foldr insert sumSet ((2 * m) : fmap (m +) mcs), m : mcs) where valid x = not $ any (flip member sumSet . (x +)) mcs m = until valid succ n   --------------------------- TEST ------------------------- main :: IO () main = (putStrLn . unlines) [ "First 30 terms of the Mian-Chowla series:" , show (mianChowlas 30) , [] , "Terms 91 to 100 of the Mian-Chowla series:" , show $ drop 90 (mianChowlas 100) ]
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.
#Go
Go
package main   import "fmt"   type person struct{ name string age int }   func copy(p person) person { return person{p.name, p.age} }   func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) /* is := []int{1, 2, 3} it := make([]int, 3) copy(it, is) */ }
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can 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.
#Haskell
Haskell
macro dowhile(condition, block) quote while true $(esc(block)) if !$(esc(condition)) break end end end end   macro dountil(condition, block) quote while true $(esc(block)) if $(esc(condition)) break end end end end   using Primes   arr = [7, 31]   @dowhile (!isprime(arr[1]) && !isprime(arr[2])) begin println(arr) arr .+= 1 end println("Done.")   @dountil (isprime(arr[1]) || isprime(arr[2])) begin println(arr) arr .+= 1 end println("Done.")  
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)
#ALGOL_68
ALGOL 68
MODE LINT=LONG INT; MODE LOOPINT = INT;   MODE POWMODSTRUCT = LINT; PR READ "prelude/pow_mod.a68" PR;   PROC miller rabin = (LINT n, LOOPINT k)BOOL: ( IF n<=3 THEN TRUE ELIF NOT ODD n THEN FALSE ELSE LINT d := n - 1; INT s := 0; WHILE NOT ODD d DO d := d OVER 2; s +:= 1 OD; TO k DO LINT a := 2 + ENTIER (random*(n-3)); LINT x := pow mod(a, d, n); IF x /= 1 THEN TO s DO IF x = n-1 THEN done FI; x := x*x %* n OD; else: IF x /= n-1 THEN return false FI; done: EMPTY FI OD; TRUE EXIT return false: FALSE FI );   FOR i FROM 937 TO 1000 DO IF miller rabin(i, 10) THEN print((" ",whole(i,0))) FI OD
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
#Julia
Julia
using Formatting import Base.iterate, Base.IteratorSize, Base.IteratorEltype, Base.Iterators.take   const metallicnames = ["Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"]   struct Lucas b::Int end Base.IteratorSize(s::Lucas) = Base.IsInfinite() Base.IteratorEltype(s::Lucas) = BigInt Base.iterate(s::Lucas, (x1, x2) = (big"1", big"1")) = (t = x2 * s.b + x1; (x1, (x2, t)))   printlucas(b, len=15) = (for i in take(Lucas(b), len) print(i, ", ") end; println("..."))   function lucasratios(b, len) iter = BigFloat.(collect(take(Lucas(b), len + 1))) return map(i -> iter[i + 1] / iter[i], 1:length(iter)-1) end   function metallic(b, dplaces=32) setprecision(dplaces * 5) ratios, err = lucasratios(b, dplaces * 50), BigFloat(10)^(-dplaces) errors = map(i -> abs(ratios[i + 1] - ratios[i]), 1:length(ratios)-1) iternum = findfirst(x -> x < err, errors) println("After $(iternum + 1) iterations, the value of ", format(ratios[iternum + 1], precision=dplaces), " is stable to $dplaces decimal places.\n") end   for (b, name) in enumerate(metallicnames) println("The first 15 elements of the Lucas sequence named ", metallicnames[b], " and b of $(b - 1) are:") printlucas(b - 1) metallic(b - 1) end println("Golden ratio to 256 decimal places:") metallic(1, 256)