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/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Nim
Nim
import endians, math   const SampleRate = 44100 Duration = 8 DataLength = SampleRate * Duration HdrSize = 44 FileLen = DataLength + HdrSize - 8 Bps = 8 Channels = 1   proc writeUint16(f: File; x: uint16) = var x = x var y: array[2, byte] littleEndian16(y.addr, x.addr) let n = f.writeBytes(y, 0, 2) doAssert n == 2   proc writeUint32(f: File; x: uint32) = var x = x var y: array[4, byte] littleEndian32(y.addr, x.addr) let n = f.writeBytes(y, 0, 4) doAssert n == 4     let file = open("notes.wav", fmWrite)   # Wav header. file.write "RIFF" file.writeUint32(FileLen) file.write "WAVE" file.write "fmt " file.writeUint32(16) # length of format data. file.writeUint16(1) # type of format(PCM). file.writeUint16(Channels) file.writeUint32(SampleRate) file.writeUint32(SampleRate * Bps * Channels div 8) file.writeUint16(Bps * Channels div 8) file.writeUint16(Bps) file.write "data" file.writeUint32(DataLength) # size of data section.   # Compute and write actual data. const Freqs = [261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3] for freq in Freqs: let omega = 2 * Pi * freq for i in 0..<(DataLength div Duration): let y = (32 * sin(omega * i.toFloat / SampleRate.toFloat)).toInt file.write chr(y.byte) # Signed int to byte then to char as it’s easier this way.   file.close()
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#ooRexx
ooRexx
/* REXX --------------------------------------------------------------- * 24.02.2013 Walter Pachl derived from original REXX version * Changes: sound(f,sec) --> beep(trunc(f),millisec) * $ -> sc * @. -> f. * re > ra (in sc) *--------------------------------------------------------------------*/ sc='do ra mi fa so la te do' dur=1250 /* milliseconds */ Do j=1 For words(sc) /* sound each "note" in the string*/ Call notes word(sc,j),dur /* invoke a subroutine for sounds.*/ End /* j */ Exit /* stick a fork in it, we're done.*/ notes: Procedure Arg note,dur f.=0 /* define common names for sounds.*/ f.la=220 f.si=246.94 f.te=f.si f.ta=f.te f.ti=f.te f.do=261.6256 f.ut=f.do f.ra=293.66 f.re=f.ra /* re is to be a synonym for ra */ f.mi=329.63 f.ma=f.mi f.fa=349.23 f.so=392 f.sol=f.so Say note trunc(f.note) dur If f.note\==0 Then Call beep trunc(f.note),dur /* sound the "note". */ Return
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Delphi
Delphi
  program Multisplit;   {$APPTYPE CONSOLE}   uses System.SysUtils;   begin write('['); for var s in 'a!===b=!=c'.Split(['==', '!=', '=']) do write(s.QuotedString('"'), ' '); write(']'); readln; end.
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
#360_Assembly
360 Assembly
* N-QUEENS PROBLEM 04/09/2015 MACRO &LAB XDECO &REG,&TARGET &LAB B I&SYSNDX branch around work area P&SYSNDX DS 0D,PL8 packed W&SYSNDX DS CL13 char I&SYSNDX CVD &REG,P&SYSNDX convert to decimal MVC W&SYSNDX,=X'40202020202020202020212060' nice mask EDMK W&SYSNDX,P&SYSNDX+2 edit and mark BCTR R1,0 locate the right place MVC 0(1,R1),W&SYSNDX+12 move the sign MVC &TARGET.(12),W&SYSNDX move to target MEND NQUEENS CSECT SAVE (14,12) save registers on entry BALR R12,0 establish addressability USING *,R12 set base register ST R13,SAVEA+4 link mySA->prevSA LA R11,SAVEA mySA ST R11,8(R13) link prevSA->mySA LR R13,R11 set mySA pointer LA R7,LL l LA R6,1 i=1 LOOPI LR R1,R6 do i=1 to l SLA R1,1 i*2 STH R6,A-2(R1) a(i)=i LA R6,1(R6) i=i+1 BCT R7,LOOPI loop do i OPENEM OPEN (OUTDCB,OUTPUT) open the printer file LA R9,1 n=1 start of loop LOOPN CH R9,L do n=1 to l BH ELOOPN if n>l then exit loop SR R8,R8 m=0 LA R10,1 i=1 LR R5,R9 n SLA R5,1 n*2 BCTR R5,0 r=2*n-1 E40 CR R10,R9 if i>n BH E80 then goto e80 LR R11,R10 j=i E50 LR R1,R10 i SLA R1,1 i*2 LA R6,A-2(R1) r6=@a(i) LR R1,R11 j SLA R1,1 j*2 LA R7,A-2(R1) r7=@a(j) MVC Z,0(R6) z=a(i) MVC Y,0(R7) y=a(j) LR R3,R10 i SH R3,Y -y AR R3,R9 p=i-y+n LR R4,R10 i AH R4,Y +y BCTR R4,0 q=i+y-1 MVC 0(2,R6),Y a(i)=y MVC 0(2,R7),Z a(j)=z LR R1,R3 p SLA R1,1 p*2 LH R2,U-2(R1) u(p) LTR R2,R2 if u(p)<>0 BNE E60 then goto e60 LR R1,R4 q AR R1,R5 q+r SLA R1,1 (q+r)*2 LH R2,U-2(R1) u(q+r) C R2,=F'0' if u(q+r)<>0 BNE E60 then goto e60 LR R1,R10 i SLA R1,1 i*2 STH R11,S-2(R1) s(i)=j LA R0,1 r0=1 LR R1,R3 p SLA R1,1 p*2 STH R0,U-2(R1) u(p)=1 LR R1,R4 q AR R1,R5 q+r SLA R1,1 (q+r)*2 STH R0,U-2(R1) u(q+r)=1 LA R10,1(R10) i=i+1 B E40 goto e40 E60 LA R11,1(R11) j=j+1 CR R11,R9 if j<=n BNH E50 then goto e50 E70 BCTR R11,0 j=j-1 CR R11,R10 if j=i BE E90 goto e90 LR R1,R10 i SLA R1,1 i*2 LA R6,A-2(R1) r6=@a(i) LR R1,R11 j SLA R1,1 j*2 LA R7,A-2(R1) r7=@a(j) MVC Z,0(R6) z=a(i) MVC 0(2,R6),0(R7) a(i)=a(j) MVC 0(2,R7),Z a(j)=z; B E70 goto e70 E80 LA R8,1(R8) m=m+1 E90 BCTR R10,0 i=i-1 LTR R10,R10 if i=0 BZ ZERO then goto zero LR R1,R10 i SLA R1,1 i*2 LH R2,A-2(R1) r2=a(i) LR R3,R10 i SR R3,R2 -a(i) AR R3,R9 p=i-a(i)+n LR R4,R10 i AR R4,R2 +a(i) BCTR R4,0 q=i+a(i)-1 LR R1,R10 i SLA R1,1 i*2 LH R11,S-2(R1) j=s(i) LA R0,0 r0=0 LR R1,R3 p SLA R1,1 p*2 STH R0,U-2(R1) u(p)=0 LR R1,R4 q AR R1,R5 q+r SLA R1,1 (q+r)*2 STH R0,U-2(R1) u(q+r)=0 B E60 goto e60 ZERO XDECO R9,PG+0 edit N XDECO R8,PG+12 edit M PUT OUTDCB,PG print buffer LA R9,1(R9) n=n+1 B LOOPN loop do n ELOOPN CLOSE (OUTDCB) close output L R13,SAVEA+4 previous save area addrs RETURN (14,12),RC=0 return to caller with rc=0 LTORG SAVEA DS 18F save area for chaining OUTDCB DCB DSORG=PS,MACRF=PM,DDNAME=OUTDD use OUTDD in jcl LL EQU 14 ll<=16 L DC AL2(LL) input value A DS (LL)H S DS (LL)H Z DS H Y DS H PG DS CL24 buffer U DC (4*LL-2)H'0' stack REGS make sure to include copybook jcl END NQUEENS
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Ruby
Ruby
def prime?(n) # P3 Prime Generator primality test return n | 1 == 3 if n < 5 # n: 2,3|true; 0,1,4|false return false if n.gcd(6) != 1 # this filters out 2/3 of all integers sqrtN = Integer.sqrt(n) pc = -1 # initial P3 prime candidates value until (pc += 6) > sqrtN # is resgroup 1st prime candidate > sqrtN return false if n % pc == 0 || n % (pc + 2) == 0 # if n is composite end true end   def gen_primes(a, b) (a..b).select { |pc| pc if prime? pc } end   def nsmooth(n, limit) raise "Exception(n or limit)" if n < 2 || n > 521 || limit < 1 raise "Exception(must be a prime number: n)" unless prime? n   primes = gen_primes(2, n) ns = [0] * limit ns[0] = 1 nextp = primes[0..primes.index(n)]   indices = [0] * nextp.size (1...limit).each do |m| ns[m] = nextp.min (0...indices.size).each do |i| if ns[m] == nextp[i] indices[i] += 1 nextp[i] = primes[i] * ns[indices[i]] end end end ns end   gen_primes(2, 29).each do |prime| print "The first 25 #{prime}-smooth numbers are: \n" print nsmooth(prime, 25) puts end puts gen_primes(3, 29).each do |prime| print "The 3000 to 3202 #{prime}-smooth numbers are: " print nsmooth(prime, 3002)[2999..-1] # for ruby >= 2.6: (..)[2999..] puts end puts gen_primes(503, 521).each do |prime| print "The 30,000 to 30,019 #{prime}-smooth numbers are: \n" print nsmooth(prime, 30019)[29999..-1] # for ruby >= 2.6: (..)[29999..] puts end
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Objective-C
Objective-C
@interface Demo : NSObject { // Omitted ... }   - (double) hypotenuseOfX: (double)x andY: (double)y; - (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;   @end
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#OCaml
OCaml
# let foo ~arg1 ~arg2 = arg1 + arg2;; val foo : arg1:int -> arg2:int -> int = <fun>   # let foo ~arg1:x ~arg2:y = x + y;; (* you can also use different variable names internally if you want *) val foo : arg1:int -> arg2:int -> int = <fun>   # foo ~arg2:17 ~arg1:42;; - : int = 59
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#J
J
'`N X NP' =. (0 { [)`(1 { [)`(2 { [) iter =. N %~ (NP * ]) + X % ] ^ NP nth_root =: (, , _1+[) iter^:_ f. ] 10 nth_root 7131.5^10 7131.5
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#C.2B.2B
C++
#include <string> #include <iostream>   using namespace std;   string Suffix(int num) { switch (num % 10) { case 1 : if(num % 100 != 11) return "st"; break; case 2 : if(num % 100 != 12) return "nd"; break; case 3 : if(num % 100 != 13) return "rd"; }   return "th"; }   int main() { cout << "Set [0,25]:" << endl; for (int i = 0; i < 26; i++) cout << i << Suffix(i) << " ";   cout << endl;   cout << "Set [250,265]:" << endl; for (int i = 250; i < 266; i++) cout << i << Suffix(i) << " ";   cout << endl;   cout << "Set [1000,1025]:" << endl; for (int i = 1000; i < 1026; i++) cout << i << Suffix(i) << " ";   cout << endl;   return 0; }
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Tcl
Tcl
package require Tcl 8.5   proc sortWithCollationKey {keyBuilder list} { if {![llength $list]} return foreach value $list { lappend toSort [{*}$keyBuilder $value] } foreach idx [lsort -indices $toSort] { lappend result [lindex $list $idx] } return $result } proc normalizeSpaces {str} { regsub -all {[ ]+} [string trim $str " "] " " } proc equivalentWhitespace {str} { regsub -all {\s} $str " " }   proc show {description sorter strings} { puts "Input:\n\t[join $strings \n\t]" set sorted [lsort $strings] puts "Normally sorted:\n\t[join $sorted \n\t]" set sorted [{*}$sorter $strings] puts "Naturally sorted with ${description}:\n\t[join $sorted \n\t]" }   # Two demonstrations of the space normalizer show "normalized spaces" {sortWithCollationKey normalizeSpaces} { {ignore leading spaces: 2-2} { ignore leading spaces: 2-1} { ignore leading spaces: 2+0} { ignore leading spaces: 2+1}} show "normalized spaces" {sortWithCollationKey normalizeSpaces} { {ignore m.a.s spaces: 2-2} {ignore m.a.s spaces: 2-1} {ignore m.a.s spaces: 2+0} {ignore m.a.s spaces: 2+1}}   # Use a collation key that maps all whitespace to spaces show "all whitespace equivalent" {sortWithCollationKey equivalentWhitespace} { "Equiv. spaces: 3-3" "Equiv.\rspaces: 3-2" "Equiv.\u000cspaces: 3-1" "Equiv.\u000bspaces: 3+0" "Equiv.\nspaces: 3+1" "Equiv.\tspaces: 3+2"}   # These are built-in modes show "(built-in) case insensitivity" {lsort -nocase} { {cASE INDEPENENT: 3-2} {caSE INDEPENENT: 3-1} {casE INDEPENENT: 3+0} {case INDEPENENT: 3+1}} show "digit sequences as numbers" {lsort -dictionary} { foo100bar99baz0.txt foo100bar10baz0.txt foo1000bar99baz10.txt foo1000bar99baz9.txt}
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.math.BigInteger   numeric digits 200   parse arg input -- input should be val, radix; no input results in using default test data -- test data - number pairs where 1st is value and 2nd is target radix inputs = [ - '1234, 10', '01234, 8', 'fe, 16', 'f0e, 16', - '0, 10', '00, 2', '11, 2', '070, 8', - '77, 8', 'f0e, 16', '070, 16', '0xf0e, 36', - '000999ABCXYZ, 36', 'ff, 36', 'f, 16', 'z, 37' - ] if input.length() > 0 then inputs = [input] -- replace test data with user input   loop i_ = 0 to inputs.length - 1 do in = inputs[i_] parse in val . ',' radix . valB = toDecimal(val, radix) -- NetRexx default is to store digits as Rexx strings valD = fromDecimal(valB + 0, radix) -- Add zero just to prove the result treated as a number say val.right(16)'['radix.right(2, 0)']:' valB.right(16)'[10] ==' valD.right(16)'['radix.right(2, 0)']' catch nx = NumberFormatException say 'Error -- Input:' val', radix:' radix nx.printStackTrace() end end i_   return   method toDecimal(val = String, radix = int 10) public static returns Rexx bi = BigInteger(val, radix) return bi.toString()   method fromDecimal(val = String, radix = int 10) public static returns Rexx bi = BigInteger(val.toString(), 10) return bi.toString(radix)  
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Go
Go
package main   import "fmt"   func narc(n int) []int { power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} limit := 10 result := make([]int, 0, n) for x := 0; len(result) < n; x++ { if x >= limit { for i := range power { power[i] *= i // i^m } limit *= 10 } sum := 0 for xx := x; xx > 0; xx /= 10 { sum += power[xx%10] } if sum == x { result = append(result, x) } } return result }   func main() { fmt.Println(narc(25)) }
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Kotlin
Kotlin
// version 1.1.4-3   import javax.swing.JFrame import javax.swing.JPanel import java.awt.Graphics import java.awt.Graphics2D import java.awt.Color import java.awt.Dimension import java.awt.BorderLayout import java.awt.RenderingHints import javax.swing.SwingUtilities   class XorPattern : JPanel() {   init { preferredSize = Dimension(256, 256) background = Color.white }   override fun paint(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) for (y in 0 until width) { for (x in 0 until height) { g.color = Color(0, (x xor y) % 256, 255) g.drawLine(x, y, x, y) } } } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() with (f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Munching squares" isResizable = false add(XorPattern(), BorderLayout.CENTER) pack() setLocationRelativeTo(null) isVisible = true } } }
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#BBC_BASIC
BBC BASIC
REM >munchausen FOR i% = 0 TO 5 FOR j% = 0 TO 5 FOR k% = 0 TO 5 FOR l% = 0 TO 5 m% = FNexp(i%) + FNexp(j%) + FNexp(k%) + FNexp(l%) n% = 1000 * i% + 100 * j% + 10 * k% + l% IF m% = n% AND m% > 0 THEN PRINT m% NEXT NEXT NEXT NEXT END : DEF FNexp(x%) IF x% = 0 THEN = 0 ELSE = x% ^ x%
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).
#BASIC256
BASIC256
# Rosetta Code problem: http://rosettacode.org/wiki/Mutual_recursion # by Jjuanhdez, 06/2022   n = 24 print "n : "; for i = 0 to n : print ljust(i, 3);  : next i print chr(10); ("-" * 78) print "F : "; for i = 0 to n : print ljust(F(i), 3); : next i print chr(10); "M : "; for i = 0 to n : print ljust(M(i), 3); : next i end   function F(n) if n = 0 then return 0 else return n - M(F(n-1)) end function   function M(n) if n = 0 then return 0 else return n - F(M(n-1)) end function
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Perl
Perl
use MIDI::Simple;   # setup, 1 quarter note is 0.5 seconds (500,000 microseconds) set_tempo 500_000;   # C-major scale n 60; n 62; n 64; n 65; n 67; n 69; n 71; n 72;   write_score 'scale.mid';
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Phix
Phix
-- -- demo\rosetta\Musical_scale.exw -- with javascript_semantics include pGUI.e include builtins\beep.e constant freq = {261.63,293.66,329.63,349.23,392,440,493.88,523.25}, durations = repeat(500,length(freq)-1) & 1000 function button_cb(Ihandle /*playbtn*/) beep(freq,durations,0.5) return IUP_DEFAULT end function IupOpen() Ihandle label = IupLabel("Please don't shoot the piano player, he's doing the best that he can!"), playbtn = IupButton("Play",Icallback("button_cb"),"PADDING=30x0"), hbox = IupHbox({IupFill(),playbtn,IupFill()},"MARGIN=0x20"), vbox = IupVbox({label,hbox}, "MARGIN=10x5, GAP=5"), dlg = IupDialog(vbox,`TITLE="Musical Scale"`) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Elixir
Elixir
iex(1)> Regex.split(~r/==|!=|=/, "a!====b=!=c") ["a", "", "", "b", "", "c"]
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Erlang
Erlang
20> re:split("a!===b=!=c", "==|!=|=",[{return, list}]). ["a",[],"b",[],"c"]
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
#ABAP
ABAP
  TYPES: BEGIN OF gty_matrix, 1 TYPE c, 2 TYPE c, 3 TYPE c, 4 TYPE c, 5 TYPE c, 6 TYPE c, 7 TYPE c, 8 TYPE c, 9 TYPE c, 10 TYPE c, END OF gty_matrix, gty_t_matrix TYPE STANDARD TABLE OF gty_matrix INITIAL SIZE 8.   DATA: gt_matrix TYPE gty_t_matrix, gs_matrix TYPE gty_matrix, gv_count TYPE i VALUE 0, gv_solut TYPE i VALUE 0.     SELECTION-SCREEN BEGIN OF BLOCK b01 WITH FRAME TITLE text-b01. PARAMETERS: p_number TYPE i OBLIGATORY DEFAULT 8. SELECTION-SCREEN END OF BLOCK b01.   " Filling empty table START-OF-SELECTION. DO p_number TIMES. APPEND gs_matrix TO gt_matrix. ENDDO.   " Recursive Function PERFORM fill_matrix USING gv_count 1 1 CHANGING gt_matrix. BREAK-POINT. *&---------------------------------------------------------------------* *& Form FILL_MATRIX *----------------------------------------------------------------------* FORM fill_matrix USING p_count TYPE i p_i TYPE i p_j TYPE i CHANGING p_matrix TYPE gty_t_matrix.   DATA: lv_i TYPE i, lv_j TYPE i, lv_result TYPE c LENGTH 1, lt_matrix TYPE gty_t_matrix, lv_count TYPE i, lv_value TYPE c.   lt_matrix[] = p_matrix[]. lv_count = p_count. lv_i = p_i. lv_j = p_j.   WHILE lv_i LE p_number. WHILE lv_j LE p_number. CLEAR lv_result. PERFORM check_position USING lv_i lv_j CHANGING lv_result lt_matrix. IF lv_result NE 'X'. MOVE 'X' TO lv_value. PERFORM get_position USING lv_i lv_j 'U' CHANGING lv_value lt_matrix. ADD 1 TO lv_count. IF lv_count EQ p_number. PERFORM show_matrix USING lt_matrix. ELSE. PERFORM fill_matrix USING lv_count lv_i lv_j CHANGING lt_matrix. ENDIF. lv_value = space. PERFORM get_position USING lv_i lv_j 'U' CHANGING lv_value lt_matrix. SUBTRACT 1 FROM lv_count. ENDIF. ADD 1 TO lv_j. ENDWHILE. ADD 1 TO lv_i. lv_j = 1. ENDWHILE. ENDFORM. " FILL_MATRIX   *&---------------------------------------------------------------------* *& Form CHECK_POSITION *&---------------------------------------------------------------------* FORM check_position USING value(p_i) TYPE i value(p_j) TYPE i CHANGING p_result TYPE c p_matrix TYPE gty_t_matrix.   PERFORM get_position USING p_i p_j 'R' CHANGING p_result p_matrix. CHECK p_result NE 'X'.   PERFORM check_horizontal USING p_i p_j CHANGING p_result p_matrix. CHECK p_result NE 'X'.   PERFORM check_vertical USING p_i p_j CHANGING p_result p_matrix. CHECK p_result NE 'X'.   PERFORM check_diagonals USING p_i p_j CHANGING p_result p_matrix.   ENDFORM. " CHECK_POSITION   *&---------------------------------------------------------------------* *& Form GET_POSITION *&---------------------------------------------------------------------* FORM get_position USING value(p_i) TYPE i value(p_j) TYPE i value(p_action) TYPE c CHANGING p_result TYPE c p_matrix TYPE gty_t_matrix.   FIELD-SYMBOLS: <fs_lmatrix> TYPE gty_matrix, <fs_lfield> TYPE any.   READ TABLE p_matrix ASSIGNING <fs_lmatrix> INDEX p_i. ASSIGN COMPONENT p_j OF STRUCTURE <fs_lmatrix> TO <fs_lfield>.   CASE p_action. WHEN 'U'. <fs_lfield> = p_result. WHEN 'R'. p_result = <fs_lfield>. WHEN OTHERS. ENDCASE.   ENDFORM. " GET_POSITION   *&---------------------------------------------------------------------* *& Form CHECK_HORIZONTAL *&---------------------------------------------------------------------* FORM check_horizontal USING value(p_i) TYPE i value(p_j) TYPE i CHANGING p_result TYPE c p_matrix TYPE gty_t_matrix. DATA: lv_j TYPE i, ls_matrix TYPE gty_matrix.   FIELD-SYMBOLS <fs> TYPE c.   lv_j = 1. READ TABLE p_matrix INTO ls_matrix INDEX p_i. WHILE lv_j LE p_number. ASSIGN COMPONENT lv_j OF STRUCTURE ls_matrix TO <fs>. IF <fs> EQ 'X'. p_result = 'X'. RETURN. ENDIF. ADD 1 TO lv_j. ENDWHILE. ENDFORM. " CHECK_HORIZONTAL   *&---------------------------------------------------------------------* *& Form CHECK_VERTICAL *&---------------------------------------------------------------------* FORM check_vertical USING value(p_i) TYPE i value(p_j) TYPE i CHANGING p_result TYPE c p_matrix TYPE gty_t_matrix. DATA: lv_i TYPE i, ls_matrix TYPE gty_matrix.   FIELD-SYMBOLS <fs> TYPE c.   lv_i = 1. WHILE lv_i LE p_number. READ TABLE p_matrix INTO ls_matrix INDEX lv_i. ASSIGN COMPONENT p_j OF STRUCTURE ls_matrix TO <fs>. IF <fs> EQ 'X'. p_result = 'X'. RETURN. ENDIF. ADD 1 TO lv_i. ENDWHILE. ENDFORM. " CHECK_VERTICAL   *&---------------------------------------------------------------------* *& Form CHECK_DIAGONALS *&---------------------------------------------------------------------* FORM check_diagonals USING value(p_i) TYPE i value(p_j) TYPE i CHANGING p_result TYPE c p_matrix TYPE gty_t_matrix. DATA: lv_dx TYPE i, lv_dy TYPE i.   * I++ J++ (Up Right) lv_dx = 1. lv_dy = 1. PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. CHECK p_result NE 'X'.   * I-- J-- (Left Down) lv_dx = -1. lv_dy = -1. PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. CHECK p_result NE 'X'.   * I++ J-- (Right Down) lv_dx = 1. lv_dy = -1. PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. CHECK p_result NE 'X'.   * I-- J++ (Left Up) lv_dx = -1. lv_dy = 1. PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. CHECK p_result NE 'X'. ENDFORM. " CHECK_DIAGONALS   *&---------------------------------------------------------------------* *& Form CHECK_DIAGONAL *&---------------------------------------------------------------------* FORM check_diagonal USING value(p_i) TYPE i value(p_j) TYPE i value(p_dx) TYPE i value(p_dy) TYPE i CHANGING p_result TYPE c p_matrix TYPE gty_t_matrix. DATA: lv_i TYPE i, lv_j TYPE i, ls_matrix TYPE gty_matrix.   FIELD-SYMBOLS <fs> TYPE c.   lv_i = p_i. lv_j = p_j. WHILE 1 EQ 1. ADD: p_dx TO lv_i, p_dy TO lv_j.   IF p_dx EQ 1. IF lv_i GT p_number. EXIT. ENDIF. ELSE. IF lv_i LT 1. EXIT. ENDIF. ENDIF.   IF p_dy EQ 1. IF lv_j GT p_number. EXIT. ENDIF. ELSE. IF lv_j LT 1. EXIT. ENDIF. ENDIF.   READ TABLE p_matrix INTO ls_matrix INDEX lv_i. ASSIGN COMPONENT lv_j OF STRUCTURE ls_matrix TO <fs>. IF <fs> EQ 'X'. p_result = 'X'. RETURN. ENDIF. ENDWHILE. ENDFORM. " CHECK_DIAGONAL *&---------------------------------------------------------------------* *& Form SHOW_MATRIX *----------------------------------------------------------------------* FORM show_matrix USING p_matrix TYPE gty_t_matrix. DATA: lt_matrix TYPE gty_t_matrix, lv_j TYPE i VALUE 1, lv_colum TYPE string VALUE '-'.   FIELD-SYMBOLS: <fs_matrix> TYPE gty_matrix, <fs_field> TYPE c.   ADD 1 TO gv_solut.   WRITE:/ 'Solution: ', gv_solut.   DO p_number TIMES. CONCATENATE lv_colum '----' INTO lv_colum. ENDDO.   LOOP AT p_matrix ASSIGNING <fs_matrix>. IF sy-tabix EQ 1. WRITE:/ lv_colum. ENDIF. WRITE:/ '|'. DO p_number TIMES. ASSIGN COMPONENT lv_j OF STRUCTURE <fs_matrix> TO <fs_field>. IF <fs_field> EQ space. WRITE: <fs_field> ,'|'. ELSE. WRITE: <fs_field> COLOR 2 HOTSPOT ON,'|'. ENDIF. ADD 1 TO lv_j. ENDDO. lv_j = 1. WRITE: / lv_colum. ENDLOOP.   SKIP 1. ENDFORM. " SHOW_MATRIX  
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Rust
Rust
fn is_prime(n: u32) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 0 { return false; } p += 4; } true }   fn find_primes(from: u32, to: u32) -> Vec<u32> { let mut primes: Vec<u32> = Vec::new(); for p in from..=to { if is_prime(p) { primes.push(p); } } primes }   fn find_nsmooth_numbers(n: u32, count: usize) -> Vec<u128> { let primes = find_primes(2, n); let num_primes = primes.len(); let mut result = Vec::with_capacity(count); let mut queue = Vec::with_capacity(num_primes); let mut index = Vec::with_capacity(num_primes); for i in 0..num_primes { index.push(0); queue.push(primes[i] as u128); } result.push(1); for i in 1..count { for p in 0..num_primes { if queue[p] == result[i - 1] { index[p] += 1; queue[p] = result[index[p]] * primes[p] as u128; } } let mut min_index: usize = 0; for p in 1..num_primes { if queue[min_index] > queue[p] { min_index = p; } } result.push(queue[min_index]); } result }   fn print_nsmooth_numbers(n: u32, begin: usize, count: usize) { let numbers = find_nsmooth_numbers(n, begin + count); print!("{}: {}", n, &numbers[begin]); for i in 1..count { print!(", {}", &numbers[begin + i]); } println!(); }   fn main() { println!("First 25 n-smooth numbers for n = 2 -> 29:"); for n in 2..=29 { if is_prime(n) { print_nsmooth_numbers(n, 0, 25); } } println!(); println!("3 n-smooth numbers starting from 3000th for n = 3 -> 29:"); for n in 3..=29 { if is_prime(n) { print_nsmooth_numbers(n, 2999, 3); } } println!(); println!("20 n-smooth numbers starting from 30,000th for n = 503 -> 521:"); for n in 503..=521 { if is_prime(n) { print_nsmooth_numbers(n, 29999, 20); } } }
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Sidef
Sidef
func smooth_generator(primes) { var s = primes.len.of { [1] } { var n = s.map { .first }.min { |i| s[i].shift if (s[i][0] == n) s[i] << (n * primes[i]) } * primes.len n } }   for p in (primes(2,29)) { var g = smooth_generator(p.primes) say ("First 25 #{'%2d'%p}-smooth numbers: ", 25.of { g.run }.join(' ')) }   say ''   for p in (primes(3,29)) { var g = smooth_generator(p.primes) say ("3,000th through 3,002nd #{'%2d'%p}-smooth numbers: ", 3002.of { g.run }.last(3).join(' ')) }
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Oz
Oz
declare class Foo meth init skip end meth bar(PP %% positional parameter named1:N1 named2:N2 namedWithDefault:NWD <= 42) {System.showInfo "PP: "#PP#", N1: "#N1#", N2: "#N2#", NWD: "#NWD} end end   O = {New Foo init} {O bar(1 named1:2 named2:3 namedWithDefault:4)} %% ok {O bar(1 named2:2 named1:3)} %% ok {O bar(1 named1:2)} %% not ok, "missing message feature in object application"
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Perl
Perl
sub funkshun { my %h = @_; # Print every argument and its value. print qq(Argument "$_" has value "$h{$_}".\n) foreach sort keys %h; # If a 'verbosity' argument was passed in, print its value # whatever that value may be. print "Verbosity specified as $h{verbosity}.\n" if exists $h{verbosity}; # Say that safe mode is on if 'safe' is set to a true value. # Otherwise, say that it's off. print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n"; }
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Java
Java
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0");// we handle only real positive numbers return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; // starting "guessed" value... while(Math.abs(x - x_prev) > p) { x_prev = x; x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n; } return x; }
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Clojure
Clojure
  (defn n-th [n] (str n (let [rem (mod n 100)] (if (and (>= rem 11) (<= rem 13)) "th" (condp = (mod n 10) 1 "st" 2 "nd" 3 "rd" "th")))))   (apply str (interpose " " (map n-th (range 0 26)))) (apply str (interpose " " (map n-th (range 250 266)))) (apply str (interpose " " (map n-th (range 1000 1026))))  
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Wren
Wren
import "/pattern" for Pattern import "/str" for Str import "/fmt" for Fmt import "/sort" for Cmp, Sort   var p2 = Pattern.new("+2 ") var p3 = Pattern.new("/s") // any whitespace character var p5 = Pattern.new("+1/d")   /** Only covers ISO-8859-1 accented characters plus (for consistency) Ÿ */ var ucAccented = ["ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ"] var lcAccented = ["àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ"] var ucNormal = "ACEINOUY" var lcNormal = "aceinouy"   /** Only the commoner ligatures */ var ucLigatures = "ÆIJŒ" var lcLigatures = "æijœ" var ucSeparated = ["AE", "IJ", "OE"] var lcSeparated = ["ae", "ij", "oe"]   /** Miscellaneous replacements */ var miscLetters = "ßſʒ" var miscReplacements = ["ss", "s", "s"]   /** Displays strings including whitespace as if the latter were literal characters */ var toDisplayString = Fn.new { |s| var whitespace = ["\t", "\n", "\v", "\f", "\r"] var whitespace2 = ["\\t", "\\n", "\\v", "\\f", "\\r"] for (i in 0..4) s = s.replace(whitespace[i], whitespace2[i]) return s }   /** Ignoring leading space(s) */ var selector1 = Fn.new { |s| s.trimStart(" ") }   /** Ignoring multiple adjacent spaces i.e. condensing to a single space */ var selector2 = Fn.new { |s| p2.replaceAll(s, " ") }   /** Equivalent whitespace characters (equivalent to a space say) */ var selector3 = Fn.new { |s| p3.replaceAll(s, " ") }   /** Case independent sort */ var selector4 = Fn.new { |s| Str.lower(s) }   /** Numeric fields as numerics (deals with up to 20 digits) */ var selector5 = Fn.new { |s| for (m in p5.findAll(s)) { var ix = m.index var repl = Fmt.swrite("$020d", Num.fromString(m.text)) s = s[0...ix] + repl + s[ix + m.length..-1] } return s }   /** Title sort */ var selector6 = Fn.new { |s| var t = Str.lower(s) if (t.startsWith("the ")) return s.skip(4).join() if (t.startsWith("an ")) return s.skip(3).join() if (t.startsWith("a ")) return s.skip(2).join() return s }   /** Equivalent accented characters (and case) */ var selector7 = Fn.new { |s| var sb = "" for (c in s) { var outer = false var i = 0 for (ucs in ucAccented) { if (ucs.contains(c)) { sb = sb + ucNormal[i] outer = true break } i = i + 1 } if (outer) continue i = 0 for (lcs in lcAccented) { if (lcs.contains(c)) { sb = sb + lcNormal[i] outer = true break } i = i + 1 } if (outer) continue sb = sb + c } return Str.lower(sb) }   /** Separated ligatures */ var selector8 = Fn.new { |s| var i = 0 for (c in ucLigatures) { s = s.replace(c, ucSeparated[i]) i = i + 1 } i = 0 for (c in lcLigatures) { s = s.replace(c, lcSeparated[i]) i = i + 1 } return s }   /** Character replacements */ var selector9 = Fn.new { |s| var i = 0 for (c in miscLetters) { s = s.replace(c, miscReplacements[i]) i = i + 1 } return s }   System.print("The 9 string lists, sorted 'naturally':\n") var selectors = [selector1, selector2, selector3, selector4, selector5, selector6, selector7, selector8, selector9] var ss = [ [ "ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1" ], [ "ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1" ], [ "Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\vspaces: 3-1", "Equiv.\fspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2" ], [ "cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1" ], [ "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt" ], [ "The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda" ], [ "Equiv. ý accents: 2-2", "Equiv. Ý accents: 2-1", "Equiv. y accents: 2+0", "Equiv. Y accents: 2+1" ], [ "IJ ligatured ij", "no ligature" ], [ "Start with an ʒ: 2-2", "Start with an ſ: 2-1", "Start with an ß: 2+0", "Start with an s: 2+1" ] ] for (i in 0..8) { var sel = selectors[i] var cmp = Fn.new { |s1, s2| Cmp.string.call(sel.call(s1), sel.call(s2)) } Sort.insertion(ss[i], cmp) System.print(ss[i].map { |s| "'%(s)'" }.join("\n")) if (i < 8) System.print() }
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Nim
Nim
import strutils   proc reverse(a: string): string = result = newString(a.len) for i, c in a: result[a.high - i] = c   const digits = "0123456789abcdefghijklmnopqrstuvwxyz"   proc toBase[T](num: T, base: range[2..36]): string = if num == 0: return "0" result = "" if num < 0: result.add '-' var tmp = abs(num) var s = "" while tmp > 0: s.add digits[int(tmp mod base)] tmp = tmp div base result.add s.reverse   proc fromBase(str: string, base: range[2..36]): BiggestInt = var str = str let first = if str[0] == '-': 1 else: 0   for i in first .. str.high: let c = str[i].toLowerAscii assert c in digits[0 ..< base] result = result * base + digits.find c   if first == 1: result *= -1   echo 26.toBase 16 echo "1a".fromBase 16
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#OCaml
OCaml
let int_of_basen n str = match n with | 16 -> int_of_string("0x" ^ str) | 2 -> int_of_string("0b" ^ str) | 8 -> int_of_string("0o" ^ str) | _ -> failwith "unhandled"   let basen_of_int n d = match n with | 16 -> Printf.sprintf "%x" d | 8 -> Printf.sprintf "%o" d | _ -> failwith "unhandled"
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#GW-BASIC
GW-BASIC
1 DEFINT A-W : DEFDBL X-Z : DIM D(9) : DIM X2(9) : KEY OFF : CLS 2 FOR A = 0 TO 9 : X2(A) = A : NEXT A 3 FOR N = 1 TO 7 4 FOR N9 = N TO 0 STEP -1 5 FOR N8 = N-N9 TO 0 STEP -1 6 FOR N7 = N-N9-N8 TO 0 STEP -1 7 FOR N6 = N-N9-N8-N7 TO 0 STEP -1 8 FOR N5 = N-N9-N8-N7-N6 TO 0 STEP -1 9 FOR N4 = N-N9-N8-N7-N6-N5 TO 0 STEP -1 10 FOR N3 = N-N9-N8-N7-N6-N5-N4 TO 0 STEP -1 11 FOR N2 = N-N9-N8-N7-N6-N5-N4-N3 TO 0 STEP -1 12 FOR N1 = N-N9-N8-N7-N6-N5-N4-N3-N2 TO 0 STEP -1 13 N0 = N-N9-N8-N7-N6-N5-N4-N3-N2-N1 14 X = N1 + N2*X2(2) + N3*X2(3) + N4*X2(4) + N5*X2(5) + N6*X2(6) + N7*X2(7) + N8*X2(8) + N9*X2(9) 15 S$ = MID$(STR$(X),2) 16 IF LEN(S$) < N THEN GOTO 25 17 IF LEN(S$) <> N THEN GOTO 24 18 FOR A = 0 TO 9 : D(A) = 0 : NEXT A 19 FOR A = 0 TO N-1 20 B = ASC(MID$(S$,A+1,1))-48 21 D(B) = D(B) + 1 22 NEXT A 23 IF N0 = D(0) AND N1 = D(1) AND N2 = D(2) AND N3 = D(3) AND N4 = D(4) AND N5 = D(5) AND N6 = D(6) AND N7 = D(7) AND N8 = D(8) AND N9 = D(9) THEN PRINT X, 24 NEXT N1 : NEXT N2 : NEXT N3 : NEXT N4 : NEXT N5 : NEXT N6 : NEXT N7 : NEXT N8 : NEXT N9 25 FOR A = 2 TO 9 26 X2(A) = X2(A) * A 27 NEXT A 28 NEXT N 29 PRINT 30 PRINT "done" 31 END
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Liberty_BASIC
Liberty BASIC
  nomainwin   w =512 ' allow for title bar and window border WindowWidth =w +2 WindowHeight =w +34   open "XOR Pattern" for graphics_nsb_nf as #w   #w "trapclose quit"   #w "down"   for x =0 to w -1 for y =0 to w -1 b =( x xor y) and 255 print b #w "color "; 255 -b; " "; b /2; " "; b #w "set "; x; " "; w -y -1 scan next y next x   #w "flush"   wait   sub quit j$ close #w end end sub  
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#BQN
BQN
Dgts ← •Fmt-'0'˙ IsMnch ← ⊢=+´∘(⋆˜ Dgts) IsMnch¨⊸/ 1+↕5000
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).
#Bc
Bc
cat mutual_recursion.bc: define f(n) { if ( n == 0 ) return(1); return(n - m(f(n-1))); }   define m(n) { if ( n == 0 ) return(0); return(n - f(m(n-1))); }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#PowerShell
PowerShell
$frequencies = 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 foreach($tone in $frequencies){ [Console]::beep($tone, 500) }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Pure_Data
Pure Data
#N canvas 898 363 360 460 10; #X obj 63 21 bng 15 250 50 0 empty start start 17 7 0 10 -262144 -1 -1; #X floatatom 135 21 5 0 0 1 bpm bpm -; #X obj 135 40 expr 1000 / ($f1/60); #X obj 135 62 int; #X obj 117 123 + 1; #X obj 117 145 mod 9; #X obj 63 123 int 1; #X obj 63 176 hradio 15 1 0 9 empty empty empty 0 -8 0 10 -262144 -1 -1 0; #X obj 63 196 route 0 1 2 3 4 5 6 7; #X msg 15 248 0; #X msg 93 248 62; #X msg 123 248 64; #X msg 63 248 60; #X msg 153 248 65; #X msg 183 248 67; #X msg 213 248 69; #X msg 243 248 71; #X msg 273 248 72; #X obj 111 313 mtof; #X obj 84 357 osc~; #X obj 84 384 dac~; #X obj 237 323 loadbang; #X obj 63 101 metro; #X msg 237 345 \; pd dsp 1 \; bpm 136 \; start 1; #X connect 0 0 22 0; #X connect 1 0 2 0; #X connect 2 0 3 0; #X connect 3 0 22 1; #X connect 4 0 5 0; #X connect 5 0 6 1; #X connect 6 0 4 0; #X connect 6 0 7 0; #X connect 7 0 8 0; #X connect 8 0 9 0; #X connect 8 1 12 0; #X connect 8 2 10 0; #X connect 8 3 11 0; #X connect 8 4 13 0; #X connect 8 5 14 0; #X connect 8 6 15 0; #X connect 8 7 16 0; #X connect 8 8 17 0; #X connect 9 0 19 0; #X connect 9 0 22 0; #X connect 10 0 18 0; #X connect 11 0 18 0; #X connect 12 0 18 0; #X connect 13 0 18 0; #X connect 14 0 18 0; #X connect 15 0 18 0; #X connect 16 0 18 0; #X connect 17 0 18 0; #X connect 18 0 19 0; #X connect 19 0 20 0; #X connect 19 0 20 1; #X connect 21 0 23 0; #X connect 22 0 6 0;
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#F.23
F#
> "a!===b=!=c".Split([|"=="; "!="; "="|], System.StringSplitOptions.None);; val it : string [] = [|"a"; ""; "b"; ""; "c"|]   > "a!===b=!=c".Split([|"="; "!="; "=="|], System.StringSplitOptions.None);; val it : string [] = [|"a"; ""; ""; "b"; ""; "c"|]
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Queens is Board : array (1..8, 1..8) of Boolean := (others => (others => False)); function Test (Row, Column : Integer) return Boolean is begin for J in 1..Column - 1 loop if ( Board (Row, J) or else (Row > J and then Board (Row - J, Column - J)) or else (Row + J <= 8 and then Board (Row + J, Column - J)) ) then return False; end if; end loop; return True; end Test; function Fill (Column : Integer) return Boolean is begin for Row in Board'Range (1) loop if Test (Row, Column) then Board (Row, Column) := True; if Column = 8 or else Fill (Column + 1) then return True; end if; Board (Row, Column) := False; end if; end loop; return False; end Fill; begin if not Fill (1) then raise Program_Error; end if; for I in Board'Range (1) loop Put (Integer'Image (9 - I)); for J in Board'Range (2) loop if Board (I, J) then Put ("|Q"); elsif (I + J) mod 2 = 1 then Put ("|/"); else Put ("| "); end if; end loop; Put_Line ("|"); end loop; Put_Line (" A B C D E F G H"); end Queens;
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Swift
Swift
import BigInt import Foundation   extension BinaryInteger { @inlinable public var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true }   let max = Self(ceil((Double(self).squareRoot())))   for i in stride(from: 2, through: max, by: 1) { if self % i == 0 { return false } }   return true } }   @inlinable public func smoothN<T: BinaryInteger>(n: T, count: Int) -> [T] { let primes = stride(from: 2, to: n + 1, by: 1).filter({ $0.isPrime }) var next = primes var indices = [Int](repeating: 0, count: primes.count) var res = [T](repeating: 0, count: count)   res[0] = 1   guard count > 1 else { return res }   for m in 1..<count { res[m] = next.min()!   for i in 0..<indices.count where res[m] == next[i] { indices[i] += 1 next[i] = primes[i] * res[indices[i]] } }   return res }   for n in 2...29 where n.isPrime { print("The first 25 \(n)-smooth numbers are: \(smoothN(n: n, count: 25))") }   print()   for n in 3...29 where n.isPrime { print("The 3000...3002 \(n)-smooth numbers are: \(smoothN(n: BigInt(n), count: 3002).dropFirst(2999).prefix(3))") }   print()   for n in 503...521 where n.isPrime { print("The 30,000...30,019 \(n)-smooth numbers are: \(smoothN(n: BigInt(n), count: 30_019).dropFirst(29999).prefix(20))") }
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Wren
Wren
import "/math" for Int import "/big" for BigInt, BigInts   // cache all primes up to 521 var smallPrimes = Int.primeSieve(521) var primes = smallPrimes.map { |p| BigInt.new(p) }.toList   var nSmooth = Fn.new { |n, size| if (n < 2 || n > 521) Fiber.abort("n must be between 2 and 521") if (size < 1) Fiber.abort("size must be at least 1") var bn = BigInt.new(n) var ok = false for (prime in primes) { if (bn == prime) { ok = true break } } if (!ok) Fiber.abort("n must be a prime number") var ns = List.filled(size, null) ns[0] = BigInt.one var next = [] for (i in 0...primes.count) { if (primes[i] > bn) break next.add(primes[i]) } var indices = List.filled(next.count, 0) for (m in 1...size) { ns[m] = BigInts.min(next) for (i in 0...indices.count) { if (ns[m] == next[i]) { indices[i] = indices[i] + 1 next[i] = primes[i] * ns[indices[i]] } } } return ns }   smallPrimes = smallPrimes.where { |p| p <= 29 } for (i in smallPrimes) { System.print("The first 25 %(i)-smooth numbers are:") System.print(nSmooth.call(i, 25)) System.print() } for (i in smallPrimes.skip(1)) { System.print("The 3,000th to 3,202nd %(i)-smooth numbers are:") System.print(nSmooth.call(i, 3002)[2999..-1]) System.print() } for (i in [503, 509, 521]) { System.print("The 30,000th to 30,019th %(i)-smooth numbers are:") System.print(nSmooth.call(i, 30019)[29999..-1]) System.print() }
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Phix
Phix
global function timedelta(atom weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0)
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#PHP
PHP
function named($args) { $args += ["gbv" => 2, "motor" => "away", "teenage" => "fbi"]; echo $args["gbv"] . " men running " . $args['motor'] . " from the " . $args['teenage']; }   named(["teenage" => "cia", "gbv" => 10]);
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#JavaScript
JavaScript
function nthRoot(num, nArg, precArg) { var n = nArg || 2; var prec = precArg || 12;   var x = 1; // Initial guess. for (var i=0; i<prec; i++) { x = 1/n * ((n-1)*x + (num / Math.pow(x, n-1))); }   return x; }
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#CLU
CLU
nth = proc (n: int) returns (string) num: string := int$unparse(n) sfx: array[string] := array[string]$[0: "th", "st", "nd", "rd"]   if n / 10 // 10 = 1 cor n // 10 > 3 then return(num || sfx[0]) else return(num || sfx[n // 10]) end end nth   do_range = proc (from, to: int) po: stream := stream$primary_output() col: int := 0   for i: int in int$from_to(from,to) do stream$putleft(po, nth(i), 7) col := col + 1 if col = 10 then stream$putc(po, '\n') col := 0 end end stream$putl(po, "\n") end do_range   start_up = proc () do_range(0,25) do_range(250,265) do_range(1000,1025) end start_up
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#zkl
zkl
fcn dsuSort(x,orig){ // decorate-sort-undecorate sort x.enumerate().sort(fcn([(_,a)],[(_,b)]){a<b}) .apply('wrap([(n,_)]){orig[n]}); }
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#PARI.2FGP
PARI/GP
toBase(n,b)={ my(s="",t); while(n, t=n%b; n\=b; s=Str(if(t<=9,t,Strchr(Vecsmall([87+t]))),s) ); if(#s,s,"0") }; fromBase(s,b)={ my(t=0); s=Vecsmall(s); for(i=1,#s,1, t=b*t+s[i]-if(s[i]<58,48,87) ); t };
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Haskell
Haskell
import Data.Char (digitToInt)   isNarcissistic :: Int -> Bool isNarcissistic n = (sum ((^ digitCount) <$> digits) ==) n where digits = digitToInt <$> show n digitCount = length digits   main :: IO () main = mapM_ print $ take 25 (filter isNarcissistic [0 ..])
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Lua
Lua
local clr = {} function drawMSquares() local points = {} for y = 0, hei-1 do for x = 0, wid-1 do local idx = bit.bxor(x, y)%256 local r, g, b = clr[idx][1], clr[idx][2], clr[idx][3] local point = {x+1, y+1, r/255, g/255, b/255, 1} table.insert (points, point) end end love.graphics.points(points) end   function createPalette() for i = 0, 255 do clr[i] = {i*2.8%256, i*3.2%256, i*1.5%256} end end   function love.load() wid, hei = 256, 256 love.window.setMode(wid, hei) canvas = love.graphics.newCanvas() love.graphics.setCanvas(canvas) createPalette() drawMSquares() love.graphics.setCanvas() end   function love.draw() love.graphics.setColor(1,1,1) love.graphics.draw(canvas) end
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#C
C
#include <stdio.h> #include <math.h>   int main() { for (int i = 1; i < 5000; i++) { // loop through each digit in i // e.g. for 1000 we get 0, 0, 0, 1. int sum = 0; for (int number = i; number > 0; number /= 10) { int digit = number % 10; // find the sum of the digits // raised to themselves sum += pow(digit, digit); } if (sum == i) { // the sum is equal to the number // itself; thus it is a // munchausen number printf("%i\n", i); } } return 0; }
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).
#BCPL
BCPL
get "libhdr"   // Mutually recursive functions let f(n) = n=0 -> 1, n - m(f(n-1)) and m(n) = n=0 -> 0, n - f(m(n-1))   // Print f(0..15) and m(0..15) let start() be $( writes("F:") for i=0 to 15 do $( writes(" ") writen(f(i)) $) writes("*NM:") for i=0 to 15 do $( writes(" ") writen(m(i)) $) writes("*N") $)
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Python
Python
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#R
R
  install.packages("audio") library(audio) hz=c(1635,1835,2060,2183,2450,2750,3087,3270) for (i in 1:8){ play(audioSample(sin(1:1000), hz[i])) Sys.sleep(.7) }  
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Factor
Factor
USING: arrays fry kernel make sequences ;   IN: rosetta-code.multisplit   : ?pair ( ? x -- {?,x}/f ) over [ 2array ] [ 2drop f ] if ;   : best-separator ( seq -- pos index ) dup [ first ] map infimum '[ first _ = ] find nip first2 ;   : first-subseq ( separators seq -- n separator ) dupd [ swap [ subseq-start ] dip ?pair ] curry map-index sift [ drop f f ] [ best-separator rot nth ] if-empty ;   : multisplit ( string separators -- seq ) '[ [ _ over first-subseq dup ] [ length -rot cut-slice swap , swap tail-slice ] while 2drop , ] { } make ;
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub Split(s As String, sepList() As String, result() As String, removeEmpty As Boolean = False, showSepInfo As Boolean = False) If s = "" OrElse UBound(sepList) = -1 Then Redim result(0) result(0) = s Return End If Dim As Integer i = 0, j, count = 0, empty = 0, length Dim As Integer position(len(s) + 1) Dim As Integer sepIndex(1 To len(s)) Dim As Integer sepLength(len(s)) position(0) = 0 : sepLength(0) = 1   While i < Len(s) For j = lbound(sepList) To ubound(sepList) length = len(sepList(j)) If length = 0 Then Continue For '' ignore blank separators If mid(s, i + 1, length) = sepList(j) Then count += 1 position(count) = i + 1 sepIndex(count) = j sepLength(count) = length i += length - 1 Exit For End If Next j i += 1 Wend   Redim result(count) If count = 0 Then If showSepInfo Then Print "No delimiters were found" : Print End If result(0) = s Return End If position(count + 1) = len(s) + 1   For i = 1 To count + 1 length = position(i) - position(i - 1) - sepLength(i - 1) result(i - 1 - empty) = Mid(s, position(i - 1) + sepLength(i - 1), length) If removeEmpty AndAlso cbool(length = 0) Then empty += 1 Next   If empty > 0 Then Redim Preserve result(count - empty)   If showSepInfo Then Print "The 1-based indices of the delimiters found are : " Print For x As Integer = 1 To count Print "At index"; position(x), sepList(sepIndex(x)) Next Print End If End Sub     Dim s As String = "a!===b=!=c" Print "The string to be split is : "; s Print Dim a() As String '' to hold results Dim b(1 To 3) As String = {"==", "!=", "="} '' separators to be used in order of priority (highest first) split s, b(), a(), False, True '' show separator info Print "The sub-strings are : " Print For i As integer = 0 To ubound(a) Print Using "##"; i + 1; Print " : "; a(i) Next Print Print "Press any key to quit" Sleep
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
#ALGOL_68
ALGOL 68
INT ofs = 1, # Algol68 normally uses array offset of 1 # dim = 8; # dim X dim chess board # [ofs:dim+ofs-1]INT b;   PROC unsafe = (INT y)BOOL:( INT i, t, x; x := b[y]; FOR i TO y - LWB b DO t := b[y - i]; IF t = x THEN break true ELIF t = x - i THEN break true ELIF t = x + i THEN break true FI OD; FALSE EXIT break true: TRUE );   INT s := 0;   PROC print board = VOID:( INT x, y; print((new line, "Solution # ", s+:=1, new line)); FOR y FROM LWB b TO UPB b DO FOR x FROM LWB b TO UPB b DO print("|"+(b[y]=x|"Q"|: ODD(x+y)|"/"|" ")) OD; print(("|", new line)) OD );   main: ( INT y := LWB b; b[LWB b] := LWB b - 1; FOR i WHILE y >= LWB b DO WHILE b[y]+:=1; # BREAK # IF b[y] <= UPB b THEN unsafe(y) ELSE FALSE FI DO SKIP OD; IF b[y] <= UPB b THEN IF y < UPB b THEN b[y+:=1] := LWB b - 1 ELSE print board FI ELSE y-:=1 FI OD )
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP   fcn nSmooth(n,sz){ // --> List of big ints if(sz<1) throw(Exception.ValueError("size must be at least 1")); bn,primes,ns := BI(n), List(), List.createLong(sz); if(not bn.probablyPrime()) throw(Exception.ValueError("n must be prime")); p:=BI(1); while(p<n){ primes.append(p.nextPrime().copy()) } // includes n ns.append(BI(1)); next:=primes.copy(); if(Void!=( z:=primes.find(bn)) ) next.del(z+1,*);   indices:=List.createLong(next.len(),0); do(sz-1){ ns.append( nm:=BI( next.reduce(fcn(a,b){ a.min(b) }) )); foreach i in (indices.len()){ if(nm==next[i]){ indices[i]+=1; next[i]=primes[i]*ns[indices[i]]; } } } ns }
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#PicoLisp
PicoLisp
(de foo @ (bind (rest) # Bind symbols in CARs to values in CDRs (println 'Bar 'is Bar) (println 'Mumble 'is Mumble) ) )   (foo '(Bar . 123) '(Mumble . "def"))
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#PowerShell
PowerShell
function Test { Write-Host Argument 1 is $args[0] }
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Prolog
Prolog
:- initialization(main).   main :- sum(b=2,output=Output,a=1), writeln(Output).   sum(A1,B1,C1) :- named_args([A1,B1,C1],[a=A,b=B,output=Output]), Output is A + B.   named_args([],_). named_args([A|B],C) :- member(A,C), named_args(B,C).  
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#jq
jq
# An iterative algorithm for finding: self ^ (1/n) to the given # absolute precision if "precision" > 0, or to within the precision # allowed by IEEE 754 64-bit numbers.   # The following implementation handles underflow caused by poor estimates. def iterative_nth_root(n; precision): def abs: if . < 0 then -. else . end; def sq: .*.; def pow(p): . as $in | reduce range(0;p) as $i (1; . * $in); def _iterate: # state: [A, x1, x2, prevdelta] .[0] as $A | .[1] as $x1 | .[2] as $x2 | .[3] as $prevdelta | ( $x2 | pow(n-1)) as $power | if $power <= 2.155094094640383e-309 then [$A, $x1, ($x1 + $x2)/2, n] | _iterate else (((n-1)*$x2 + ($A/$power))/n) as $x1 | (($x1 - $x2)|abs) as $delta | if (precision == 0 and $delta == $prevdelta and $delta < 1e-15) or (precision > 0 and $delta <= precision) or $delta == 0 then $x1 else [$A, $x2, $x1, $delta] | _iterate end end  ; if n == 1 then . elif . == 0 then 0 elif . < 0 then error("iterative_nth_root: input \(.) < 0") elif n != (n|floor) then error("iterative_nth_root: argument \(n) is not an integer") elif n == 0 then error("iterative_nth_root(0): domain error") elif n < 0 then 1/iterative_nth_root(-n; precision) else [., ., (./n), n, 0] | _iterate end ;
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. NTH-PROGRAM. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUMBER. 05 N PIC 9(8). 05 LAST-TWO-DIGITS PIC 99. 05 LAST-DIGIT PIC 9. 05 N-TO-OUTPUT PIC Z(7)9. 05 SUFFIX PIC AA. PROCEDURE DIVISION. TEST-PARAGRAPH. PERFORM NTH-PARAGRAPH VARYING N FROM 0 BY 1 UNTIL N IS GREATER THAN 25. PERFORM NTH-PARAGRAPH VARYING N FROM 250 BY 1 UNTIL N IS GREATER THAN 265. PERFORM NTH-PARAGRAPH VARYING N FROM 1000 BY 1 UNTIL N IS GREATER THAN 1025. STOP RUN. NTH-PARAGRAPH. MOVE 'TH' TO SUFFIX. MOVE N (7:2) TO LAST-TWO-DIGITS. IF LAST-TWO-DIGITS IS LESS THAN 4, OR LAST-TWO-DIGITS IS GREATER THAN 20, THEN PERFORM DECISION-PARAGRAPH. MOVE N TO N-TO-OUTPUT. DISPLAY N-TO-OUTPUT WITH NO ADVANCING. DISPLAY SUFFIX WITH NO ADVANCING. DISPLAY SPACE WITH NO ADVANCING. DECISION-PARAGRAPH. MOVE N (8:1) TO LAST-DIGIT. IF LAST-DIGIT IS EQUAL TO 1 THEN MOVE 'ST' TO SUFFIX. IF LAST-DIGIT IS EQUAL TO 2 THEN MOVE 'ND' TO SUFFIX. IF LAST-DIGIT IS EQUAL TO 3 THEN MOVE 'RD' TO SUFFIX.
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Pascal
Pascal
Program ConvertDemo(output);   uses Math, SysUtils;   const alphanum = '0123456789abcdefghijklmnopqrstuvwxyz';   function ToDecimal(base: integer; instring: string): integer; var inlength, i, n: integer; begin ToDecimal := 0; inlength := length(instring); for i := 1 to inlength do begin n := pos(instring[i], alphanum) - 1; n := n * base**(inlength-i); Todecimal := ToDecimal + n; end; end;   function ToBase(base, number: integer): string; var i, rem: integer; begin ToBase :=' '; for i := 31 downto 1 do begin if (number < base) then begin ToBase[i] := alphanum[number+1]; break; end; rem := number mod base; ToBase[i] := alphanum[rem+1]; number := number div base; end; ToBase := trimLeft(ToBase); end;   begin writeln ('1A: ', ToDecimal(16, '1a')); writeln ('26: ', ToBase(16, 26)); end.  
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) limit := integer(A[1]) | 25 every write(isNarcissitic(seq(0))\limit) end   procedure isNarcissitic(n) sn := string(n) m := *sn every (sum := 0) +:= (!sn)^m return sum = n end
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ListDensityPlot[ Table[Table[ FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]], 2], {x, 0, 255}], {y, 0, 255}]]
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#MATLAB
MATLAB
size = 256; [x,y] = meshgrid([0:size-1]);   c = bitxor(x,y);   colormap bone(size); image(c); axis equal;
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#C.23
C#
Func<char, int> toInt = c => c-'0';   foreach (var i in Enumerable.Range(1,5000) .Where(n => n == n.ToString() .Sum(x => Math.Pow(toInt(x), toInt(x))))) Console.WriteLine(i);
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , 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).
#BQN
BQN
F ← {0:1; 𝕩-M F𝕩-1} M ← {0:0; 𝕩-F M𝕩-1} ⍉"FM"∾>(F∾M)¨↕15
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Racket
Racket
  #lang racket (require ffi/unsafe ffi/unsafe/define) (define-ffi-definer defmm (ffi-lib "Winmm")) (defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] [_pointer = #f] [_int32 = 0] -> _void -> h)) (defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) (define M (midiOutOpen)) (define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z))))   (for ([i '(60 62 64 65 67 69 71 72)]) (midi #x90 i 127) (sleep 0.5)) (sleep 2)  
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Raku
Raku
for 0,2,4,5,7,9,11,12 { shell "play -n -c1 synth 0.2 sin %{$_ - 9}" }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#REXX
REXX
/*REXX program sounds eight notes of the C major natural diatonic music scale.*/ parse arg ! /*obtain optional arguments from the CL*/ /* [↓] invoke boilerplate REXX code. */ if !all( arg() ) then exit /*determine which REXX is running, if */ /* any form of help requested, exit.*/ if \!regina & \!pcrexx then do say "***error*** this program can't execute under:"  !ver exit 13 end   $ = 'do ra me fa so la te do' /*the words for music scale sounding. */ dur = 1/4 /*define duration as a quarter second. */ do j=1 for words($) /*sound each "note" in the string. */ call notes word($, j), dur /*invoke a subroutine for the sounds. */ end /*j*/ /* [↑] sound each of the words. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ notes: procedure expose !regina !pcrexx; arg note,dur /*obtain the arguments from list. */ @.= 0 /*define common names for sounds. */ @.la= 220; @.si= 246.94; @.te= @.si; @.ta= @.te; @.ti= @.te @.do= 261.6256; @.ut= @.do; @.re= 293.66; @.ra= @.re; @.mi= 329.63 @.ma= @.mi; @.fa= 349.23; @.so= 392; @.sol= @.so if @.note==0 then return /*if frequency is zero, skip it. */ if !pcrexx then call sound @.note,dur /*sound the note using SOUND bif. */ if !regina then do /* [↓] reformat some numbers. */ ms= format(dur*1000, , 0) /*Regina requires DUR in millisec.*/ intN= format(@.note, , 0) /* " " NOTE is integer.*/ call beep intN, ms /*sound the note using BEEP BIF.*/ end return /*─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ !all: !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1 !cal: if symbol('!CALL')\=="VAR" then !call=; return !call !env: !env= 'ENVIRONMENT'; if !sys=="MSDOS" |  !brexx |  !r4 |  !roo then !env= 'SYSTEM'; if !os2 then !env= "OS2"!env;  !ebcdic= 3=='f3'x; if !crx then !env="DOS"; return !fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _= lastpos('\',!fn);  !fm= left(!fn,_);  !fn= substr(!fn,_+1); parse var !fn !fn "." !ft; end; return word(0 !fn !ft !fm, 1 + ('0'arg(1) ) ) !rex: parse upper version !ver !vernum !verdate .;  !brexx= 'BY'==!vernum; !kexx= "KEXX"==!ver; !pcrexx= 'REXX/PERSONAL'==!ver | "REXX/PC"==!ver; !r4= 'REXX-R4'==!ver; !regina= "REXX-REGINA"==left(!ver, 11); !roo= 'REXX-ROO'==!ver; call !env; return !sys: !cms= !sys=='CMS';  !os2= !sys=="OS2";  !tso= !sys=='TSO' |  !sys=="MVS";  !vse= !sys=='VSE';  !dos= pos("DOS", !sys)\==0 | pos('WIN', !sys)\==0 |  !sys=="CMD";  !crx= left(!sys, 6)=='DOSCRX'; call !rex; return !var: call !fid; if !kexx then return space( dosenv( arg(1) ) ); return space( value( arg(1), , !env) )
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Go
Go
package main   import ( "fmt" "strings" )   func ms(txt string, sep []string) (ans []string) { for txt > "" { sepMatch := "" posMatch := len(txt) for _, s := range sep { if p := strings.Index(txt, s); p >= 0 && p < posMatch { sepMatch = s posMatch = p } } ans = append(ans, txt[:posMatch]) txt = txt[posMatch+len(sepMatch):] } return }   func main() { fmt.Printf("%q\n", ms("a!===b=!=c", []string{"==", "!=", "="})) }
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
#APL
APL
  ⍝Solution accm←{⍺,((⍴⍵)=⍴⊃⍺)↑⊂⍵} atk←{∪∊(⊂⍵)+¯1 0 1×⊂⌽⍳⍴⍵} dfs←{⊃∇⍨/⌽(⊂⍺ ⍺⍺ ⍵),⍺ ⍵⍵ ⍵} qfmt←{⍵∘.=⍳⍴⍵} subs←{(⊂⍵),¨(⍳⍴⊃⍺)~atk ⍵} queens←{qfmt¨(↓0 ⍵⍴0)accm dfs subs ⍬} printqueens←{i←1⋄{⎕←'answer'i⋄⎕←⍵⋄i+←1}¨queens ⍵}   ⍝Example printqueens 6  
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Python
Python
def subtract(x, y): return x - y   subtract(5, 3) # used as positional parameters; evaluates to 2 subtract(y = 3, x = 5) # used as named parameters; evaluates to 2
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#R
R
divide <- function(numerator, denominator) { numerator / denominator }   divide(3, 2) # 1.5 divide(numerator=3, denominator=2) # 1.5 divide(n=3, d=2) # 1.5 divide(den=3, num=2) # 0.66 divide(den=3, 2) # 0.66 divide(3, num=2) # 0.66
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Julia
Julia
function nthroot(n::Integer, r::Real) r < 0 || n == 0 && throw(DomainError()) n < 0 && return 1 / nthroot(-n, r) r > 0 || return 0 x = r / n prevdx = r while true y = x ^ (n - 1) dx = (r - y * x) / (n * y) abs(dx) ≥ abs(prevdx) && return x x += dx prevdx = dx end end   @show nthroot.(-5:2:5, 5.0) @show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Kotlin
Kotlin
// version 1.0.6   fun nthRoot(x: Double, n: Int): Double { if (n < 2) throw IllegalArgumentException("n must be more than 1") if (x <= 0.0) throw IllegalArgumentException("x must be positive") val np = n - 1 fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n var g1 = x var g2 = iter(g1) while (g1 != g2) { g1 = iter(g1) g2 = iter(iter(g2)) } return g1 }   fun main(args: Array<String>) { val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) for (number in numbers) println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") }
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Common_Lisp
Common Lisp
(defun add-suffix (number) (let* ((suffixes #10("th" "st" "nd" "rd" "th")) (last2 (mod number 100)) (last-digit (mod number 10)) (suffix (if (< 10 last2 20) "th" (svref suffixes last-digit)))) (format nil "~a~a" number suffix)))  
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Perl
Perl
sub to2 { sprintf "%b", shift; } sub to16 { sprintf "%x", shift; } sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } sub from16 { hex(shift); }
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#J
J
getDigits=: "."0@": NB. get digits from number isNarc=: (= +/@(] ^ #)@getDigits)"0 NB. test numbers for Narcissism
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#Java
Java
public class Narc{ public static boolean isNarc(long x){ if(x < 0) return false;   String xStr = Long.toString(x); int m = xStr.length(); long sum = 0;   for(char c : xStr.toCharArray()){ sum += Math.pow(Character.digit(c, 10), m); } return sum == x; }   public static void main(String[] args){ for(long x = 0, count = 0; count < 25; x++){ if(isNarc(x)){ System.out.print(x + " "); count++; } } } }
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Microsoft_Small_Basic
Microsoft Small Basic
' Munching squares - smallbasic - 27/07/2018 size=256 GraphicsWindow.Width=size GraphicsWindow.Height=size For i=0 To size-1 For j=0 To size-1 BitXor() 'color=i Xor j GraphicsWindow.SetPixel(i,j,GraphicsWindow.GetColorFromRGB(0,color,color)) EndFor EndFor   Sub BitXor '(i,j)->color n=i Int2Bit() ib=ret n=j Int2Bit() jb=ret color=0 For k=1 to 8 ki=Text.GetSubText(ib,k,1) kj=Text.GetSubText(jb,k,1) If ki="1" Or kj="1" Then kk="1" Else kk="0" EndIf If ki="1" And kj="1" Then kk="0" EndIf color=2*color+kk EndFor EndSub   Sub Int2Bit 'n->ret x=n ret="" For k=1 to 8 t=Math.Floor(x/2) r=Math.Remainder(x,2) ret=Text.Append(r,ret) x=t EndFor EndSub
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#MiniScript
MiniScript
xor = function(a, b) result = 0 bit = 1 while a > 0 or b > 0 if (a%2 == 0) != (b%2 == 0) then result = result + bit bit = bit * 2 a = floor(a/2) b = floor(b/2) end while return result end function   for x in range(0,255) for y in range(0,255) gfx.setPixel x, y, color.rgb(0, xor(x,y), 0) end for end for
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#C.2B.2B
C++
  #include <math.h> #include <iostream>   unsigned pwr[10];   unsigned munch( unsigned i ) { unsigned sum = 0; while( i ) { sum += pwr[(i % 10)]; i /= 10; } return sum; }   int main( int argc, char* argv[] ) { for( int i = 0; i < 10; i++ ) pwr[i] = (unsigned)pow( (float)i, (float)i ); std::cout << "Munchausen Numbers\n==================\n"; for( unsigned i = 1; i < 5000; i++ ) if( i == munch( i ) ) std::cout << i << "\n"; return 0; }  
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).
#Bracmat
Bracmat
(F=.!arg:0&1|!arg+-1*M$(F$(!arg+-1))); (M=.!arg:0&0|!arg+-1*F$(M$(!arg+-1)));   -1:?n&whl'(!n+1:~>20:?n&put$(F$!n " "))&put$\n 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13   -1:?n&whl'(!n+1:~>20:?n&put$(M$!n " "))&put$\n 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Ring
Ring
  # Project : Musical scale   loadlib("C:\Ring\extensions\ringbeep\ringbeep.dll") freqs = [[262,"Do"], [294,"Ra"], [330,"Me"], [349,"Fa"], [392,"So"], [440,"La"], [494,"Te"], [523,"do"]] for f = 1 to len(freqs) see freqs[f][2] + nl beep(freqs[f][1],300) next  
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Scala
Scala
import net.java.dev.sna.SNA   object PlayMusicScale extends App with SNA {   snaLibrary = "Kernel32" val Beep = SNA[Int, Int, Unit]   println("Please don't shoot the piano player, he's doing the best that he can!") List(0, 2, 4, 5, 7, 9, 11, 12). foreach(f => Beep((261.63 * math.pow(2, f / 12.0)).toInt, if (f == 12) 1000 else 500)) println("That's all") }
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#Haskell
Haskell
import Data.List (isPrefixOf, stripPrefix, genericLength, intercalate)   trysplit :: String -> [String] -> Maybe (String, String) trysplit s delims = case filter (`isPrefixOf` s) delims of [] -> Nothing (d:_) -> Just (d, (\(Just x) -> x) $ stripPrefix d s)   multisplit :: String -> [String] -> [(String, String, Int)] multisplit list delims = let ms [] acc pos = [(acc, [], pos)] ms l@(s:sx) acc pos = case trysplit l delims of Nothing -> ms sx (s : acc) (pos + 1) Just (d, sxx) -> (acc, d, pos) : ms sxx [] (pos + genericLength d) in ms list [] 0   main :: IO () main = do let parsed = multisplit "a!===b=!=c" ["==", "!=", "="] mapM_ putStrLn [ "split string:" , intercalate "," $ map (\(a, _, _) -> a) parsed , "with [(string, delimiter, offset)]:" , show parsed ]
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
#AppleScript
AppleScript
-- Finds all possible solutions and the unique patterns.   property Grid_Size : 8   property Patterns : {} property Solutions : {} property Test_Count : 0   property Rotated : {}   on run local diff local endTime local msg local rows local startTime   set Patterns to {} set Solutions to {} set Rotated to {}   set Test_Count to 0   set rows to Make_Empty_List(Grid_Size)   set startTime to current date Solve(1, rows) set endTime to current date set diff to endTime - startTime   set msg to ("Found " & (count Solutions) & " solutions with " & (count Patterns) & " patterns in " & diff & " seconds.") as text display alert msg   return Solutions end run   on Solve(row as integer, rows as list) if row is greater than (count rows) then Append_Solution(rows) return end if   repeat with column from 1 to Grid_Size set Test_Count to Test_Count + 1 if Place_Queen(column, row, rows) then Solve(row + 1, rows) end if end repeat end Solve   on abs(n) if n < 0 then -n else n end if end abs   on Place_Queen(column as integer, row as integer, rows as list) local colDiff local previousRow local rowDiff local testColumn   repeat with previousRow from 1 to (row - 1) set testColumn to item previousRow of rows   if testColumn is equal to column then return false end if   set colDiff to abs(testColumn - column) as integer set rowDiff to row - previousRow if colDiff is equal to rowDiff then return false end if end repeat   set item row of rows to column return true end Place_Queen   on Append_Solution(rows as list) local column local rowsCopy local testReflection local testReflectionText local testRotation local testRotationText local testRotations   copy rows to rowsCopy set end of Solutions to rowsCopy local rowsCopy   copy rows to testRotation set testRotations to {} repeat 3 times set testRotation to Rotate(testRotation) set testRotationText to testRotation as text if Rotated contains testRotationText then return end if set end of testRotations to testRotationText   set testReflection to Reflect(testRotation) set testReflectionText to testReflection as text if Rotated contains testReflectionText then return end if set end of testRotations to testReflectionText end repeat   repeat with testRotationText in testRotations set end of Rotated to (contents of testRotationText) end repeat set end of Rotated to (rowsCopy as text) set end of Rotated to (Reflect(rowsCopy) as text)   set end of Patterns to rowsCopy end Append_Solution   on Make_Empty_List(depth as integer) local i local emptyList   set emptyList to {} repeat with i from 1 to depth set end of emptyList to missing value end repeat return emptyList end Make_Empty_List   on Rotate(rows as list) local column local newColumn local newRow local newRows local row local rowCount   set rowCount to (count rows) set newRows to Make_Empty_List(rowCount) repeat with row from 1 to rowCount set column to (contents of item row of rows) set newRow to column set newColumn to rowCount - row + 1 set item newRow of newRows to newColumn end repeat   return newRows end Rotate   on Reflect(rows as list) local column local newRows   set newRows to {} repeat with column in rows set end of newRows to (count rows) - column + 1 end repeat   return newRows end Reflect
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Racket
Racket
  #lang racket   (define (pizza sauce  ;; mandatory keyword argument #:topping topping  ;; optional keyword argument with default #:type [type "deep dish"]) (printf "~a pizza with ~a sauce topped with ~a~n" type sauce topping))   (pizza "tomato" #:topping "onion") (pizza #:topping "onion" "garlic" #:type "pan")  
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Raku
Raku
sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) { ... }
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#REXX
REXX
/*REXX pgm shows named parameters when called as a subroutine/function*/ /*┌────────────────────────────────────────────────────────────────────┐ │ The syntax of: xxx = func1(parmName2=arg2, parmName1=arg1) │ │ │ │ in the REXX language is interpreted specifically as: │ │ │ │ xxx = func1( yyy , zzz ) │ │ │ │ where yyy is the logical result of comparing (the REXX variables)│ │ │ │ parmName2 with arg2 and │ │ │ │ where zzz is the logical result of comparing (the REXX variables)│ │ │ │ parmName1 with arg1 │ │ │ │ (either as two strings, or arithmetically if both "parmName2" and │ │ "arg2" are both valid REXX numbers. In the REXX language, there │ │ is no way to declare (define) what a variable is [or its type], as │ │ each literal that can be a variable is assumed to be one. If it's │ │ not defined, then its uppercase name is used for the value. │ │ │ │ Consider the one-line REXX program: say Where are you? │ │ causes REXX to consider that four-word expression as a "SAY" │ │ statement, followed by three REXX variables, each of which aren't │ │ defined (that is, have a value), so REXX uses a value which is the │ │ uppercased value of the REXX variable name, namely three values in │ │ this case, so the following is displayed: WHERE ARE YOU? │ │ │ │ [There is a mechanism in REXX to catch this behavior and raise the │ │ NOVALUE condition.] │ │ │ │ To allow a solution to be used for this task's requirement, and │ │ and not get tangled up with the legal REXX syntactical expressions │ │ shown, this REXX programming example uses a variation of the │ │ task's illustration to allow a method in REXX of using named │ │ parameters: xxx = func1('parmName2=' arg2, "parmName1=" arg1) │ │ │ │ Also, REXX allows the omitting of arguments by just specifying a │ │ comma (or nothing at all, in the case of a single argument): │ │ │ │ xxx = func1(,zzz) │ │ │ │ would indicate that the 1st argument has been omitted. │ │ │ │ xxx = func1(yyy) │ │ │ │ would indicate that the 2nd argument (and all other subsequent │ │ arguments) has/have been omitted. │ └────────────────────────────────────────────────────────────────────┘*/   parse arg count,itemX /*assume 2 values have been used,*/ /*or whatever ... just to show...*/ do j=1 for arg(); _=arg(1) /*now, lets examine each argument*/ if arg(j,'Omitted') then iterate /*skip examining if argJ omitted.*/ /*(above) This is superfluous, */ /* but it demonstrates a method. */ if \arg(j,"Exists") then iterate /*exactly the same as previous. */ /*Only 1st char (2nd arg) is used*/ first=strip(word(_,1)) /*extract the 1st word in arg(j).*/ if right(first,1)\=='=' then iterate /*skip if 1st word isn't: xxx= */ parse var _ varname '= ' value /*parse the named variable &value*/ if varname=='' then iterate /*not the correct format, so skip*/ /*(above) fix this for real pgm. */ call value varname,value /*use BIF to set REXX variable. */ end /*j*/   /* ∙∙∙ perform some REXX magic here with specified parameters and stuff:*/ /* do this, do that, perform dis & dat, compute, gears whiz, cogs */ /* turn, wheels spin, belts move, things get assigned, stuff gets */ /* computed, wheels spin, belts move, things get assigned, motors*/ /* humm, engines roar, coal gets burned, water turns to steam, real */ /* work (some of it useful) gets done, and something is produced. */   return 'the final meaning of life, or 42 --- whichever is appropriate.' /*stick a fork in it, we're done.*/
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Lambdatalk
Lambdatalk
  {def root {def good-enough? {lambda {next guess tol} {< {abs {- next guess}} tol} }} {def improve {lambda {guess num deg} {/ {+ {* {- deg 1} guess} {/ num {pow guess {- deg 1}}}} deg} }} {def *root {lambda {guess num deg tol} {let { {guess guess} {num num} {deg deg} {tol tol} {next {improve guess num deg}} } {if {good-enough? next guess tol} then guess else {*root next num deg tol}} }}} {lambda {num deg tol} {*root 1.0 num deg tol} }} -> root   {root {pow 2 10} 10 0.1} -> 2.0473293223683866 {root {pow 2 10} 10 0.01} -> 2.004632048354822 {root {pow 2 10} 10 0.001} -> 2.000047868581671  
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh";   # Given an int32, return decimal string and add an ordinal suffix sub ordsfx(n: int32, buf: [uint8]): (out: [uint8]) is var sfx: [uint8][] := {"th", "st", "nd", "rd"}; out := buf; buf := IToA(n, 10, buf); # IToA is included in standard library   # Since we now already have the digits, we can make the decision # without doing any more work. if (n > 10 and [@prev @prev buf] == '1') or ([@prev buf] > '3') then CopyString(sfx[0], buf); else CopyString(sfx[[@prev buf]-'0'], buf); end if; end sub;   # Print suffixed numerals from start to end inclusive sub test(start: int32, end_: int32) is var buf: uint8[16]; # buffer   var n: uint8 := 10; while start <= end_ loop print(ordsfx(start, &buf[0])); print_char(' '); start := start + 1; n := n - 1; if n == 0 then print_nl(); n := 10; end if; end loop; print_nl(); end sub;   test(0, 25); test(250,265); test(1000,1025);
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Phix
Phix
with javascript_semantics ?{26,0b11010,0o32,0x1A,0X1a,#1A,0(16)1A} -- displays {26,26,26,26,26,26,26} printf(1,"%d == 0b%b == 0x%x\n",26) -- displays 26 == 0b11010 == 0x1A printf(1,"%d == o(62)%A\n",{26,{62,26}}) -- displays 26 == 0(62)Q ?to_number("1a",{},16) -- displays 26 include mpfr.e mpfr f = mpfr_init() mpfr_set_str(f,"110.01",2) printf(1,"0b%s == %s\n",{mpfr_get_fixed(f,0,2),mpfr_get_fixed(f)}) -- 0b110.01 == 6.25
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in the decimal representation of   n {\displaystyle n} . Narcissistic (decimal) numbers are sometimes called   Armstrong   numbers, named after Michael F. Armstrong. They are also known as   Plus Perfect   numbers. An example   if   n {\displaystyle n}   is   153   then   m {\displaystyle m} ,   (the number of decimal digits)   is   3   we have   13 + 53 + 33   =   1 + 125 + 27   =   153   and so   153   is a narcissistic decimal number Task Generate and show here the first   25   narcissistic decimal numbers. Note:   0 1 = 0 {\displaystyle 0^{1}=0} ,   the first in the series. See also   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.   MathWorld entry:   Narcissistic Number.   Wikipedia entry:     Narcissistic number.
#JavaScript
JavaScript
function isNarc(x) { var str = x.toString(), i, sum = 0, l = str.length; if (x < 0) { return false; } else { for (i = 0; i < l; i++) { sum += Math.pow(str.charAt(i), l); } } return sum == x; } function main(){ var n = []; for (var x = 0, count = 0; count < 25; x++){ if (isNarc(x)){ n.push(x); count++; } } return n.join(' '); }
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Nim
Nim
import random import imageman   randomize()   # Build a color table. var colors: array[256, ColorRGBU] for color in colors.mitems: color = ColorRGBU [byte rand(255), byte rand(255), byte rand(255)]     var image = initImage[ColorRGBU](256, 256)   for i in 0..255: for j in 0..255: image[i, j] = colors[i xor j]   image.savePNG("munching_squares.png")
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#OCaml
OCaml
open Graphics   let () = open_graph ""; resize_window 256 256; for y = 0 to pred (size_y()) do for x = 0 to pred (size_x()) do let v = (x lxor y) land 0xFF in set_color (rgb v (255 - v) 0); plot x y done; done; ignore(read_key())
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#Clojure
Clojure
(ns async-example.core (:require [clojure.math.numeric-tower :as math]) (:use [criterium.core]) (:gen-class))   (defn get-digits [n] " Convert number of a list of digits (e.g. 545 -> ((5), (4), (5)) " (map #(Integer/valueOf (str %)) (String/valueOf n)))   (defn sum-power [digits] " Convert digits such as abc... to a^a + b^b + c^c ..." (let [digits-pwr (fn [n] (apply + (map #(math/expt % %) digits)))] (digits-pwr digits)))   (defn find-numbers [max-range] " Filters for Munchausen numbers " (->> (range 1 (inc max-range)) (filter #(= (sum-power (get-digits %)) %))))     (println (find-numbers 5000))  
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).
#Brat
Brat
female = null #yes, this is necessary   male = { n | true? n == 0 { 0 } { n - female male(n - 1) } }   female = { n | true? n == 0 { 1 } { n - male female(n - 1 ) } }   p 0.to(20).map! { n | female n } p 0.to(20).map! { n | male n }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Sparkling
Sparkling
var sampleRate = 44100.0; var duration = 8.0; var dataLength = round(sampleRate * duration); var dataLength_b0 = dataLength >> 0 & 0xff; var dataLength_b1 = dataLength >> 8 & 0xff; var dataLength_b2 = dataLength >> 16 & 0xff; var dataLength_b3 = dataLength >> 24 & 0xff;   const adjustedHdrSize = 36;   var len = dataLength - adjustedHdrSize; var len_b0 = len >> 0 & 0xff; var len_b1 = len >> 8 & 0xff; var len_b2 = len >> 16 & 0xff; var len_b3 = len >> 24 & 0xff;   // WAV header var wavhdr = "RIFF"; wavhdr ..= fmtstr("%c%c%c%c", len_b0, len_b1, len_b2, len_b3); wavhdr ..= "WAVE"; wavhdr ..= "fmt "; wavhdr ..= "\x10\x00\x00\x00"; wavhdr ..= "\x01\x00"; wavhdr ..= "\x01\x00"; wavhdr ..= "\x44\xac\x00\x00"; wavhdr ..= "\x44\xac\x00\x00"; wavhdr ..= "\x01\x00"; wavhdr ..= "\x08\x00"; wavhdr ..= "data"; wavhdr ..= fmtstr("%c%c%c%c", dataLength_b0, dataLength_b1, dataLength_b2, dataLength_b3);   // write wav header var f = fopen("notes.wav", "w"); fwrite(f, wavhdr);     // compute and write actual data var frequs = { 261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3 };   for var j = 0; j < duration; j++ { var frequ = frequs[j]; var omega = 2 * M_PI * frequ; for var i = 0; i < dataLength / 8; i++ { var y = 32 * sin(omega * i / sampleRate); var byte = fmtstr("%c", round(y)); fwrite(f, byte); } }   fclose(f);
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Tcl
Tcl
package require sound   # Encapsulate the tone generation set filter [snack::filter generator 1 20000 0.5 sine -1] set sound [snack::sound -rate 22050] proc play {frequency length} { global filter sound   $filter configure $frequency $sound play -filter $filter   # Need to run event loop; Snack uses it internally after $length {set donePlay 1} vwait donePlay   $sound stop }   # Major scale up, then down; extra delay at ends of scale set tonicFrequency 261.63; # C4 foreach i {0 2 4 5 7 9 11 12 11 9 7 5 4 2 0} { play [expr {$tonicFrequency*2**($i/12.0)}] [expr {$i%12?250:500}] }