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/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.
#Icon_and_Unicon
Icon and Unicon
procedure main() s := "a!===b=!=c" # just list the tokens every writes(multisplit(s,["==", "!=", "="])," ") | write()   # list tokens and indices every ((p := "") ||:= t := multisplit(s,sep := ["==", "!=", "="])) | break write() do if t == !sep then writes(t," (",*p+1-*t,") ") else writes(t," ")   end   procedure multisplit(s,L) s ? while not pos(0) do { t := =!L | 1( arb(), match(!L)|pos(0) ) suspend t } end   procedure arb() suspend .&subject[.&pos:&pos <- &pos to *&subject + 1] 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
#Arc
Arc
(def nqueens (n (o queens)) (if (< len.queens n) (let row (if queens (+ 1 queens.0.0) 0) (each col (range 0 (- n 1)) (let new-queens (cons (list row col) queens) (if (no conflicts.new-queens) (nqueens n new-queens))))) (prn queens)))   ; check if the first queen in 'queens' lies on the same column or diagonal as ; any of the others (def conflicts (queens) (let (curr . rest) queens (or (let curr-column curr.1 (some curr-column (map [_ 1] rest))) ; columns (some [diagonal-match curr _] rest))))   (def diagonal-match (curr other) (is (abs (- curr.0 other.0)) (abs (- curr.1 other.1))))
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
#Ruby
Ruby
def example(foo: 0, bar: 1, grill: "pork chops") puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}" end   # Note that :foo is omitted and :grill precedes :bar example(grill: "lamb kebab", bar: 3.14)
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
#Scala
Scala
  def add(x: Int, y: Int = 1) = x + y  
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
#Scheme
Scheme
  (define (keyarg-parser argdefs args kont) (apply kont (map (lambda (argdef) (let loop ((args args)) (cond ((null? args) (cadr argdef)) ((eq? (car argdef) (car args)) (cadr args)) (else (loop (cdr args)))))) argdefs)))   (define (print-name . args) (keyarg-parser '((first #f)(last "?")) args (lambda (first last) (display last) (cond (first (display ", ") (display first))) (newline))))  
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.
#langur
langur
writeln "operator" writeln( (7131.5 ^ 10) ^/ 10 ) writeln 64 ^/ 6 writeln()   # To make the example from the D language work, we set a low maximum for the number of digits after a decimal point in division. mode divMaxScale = 7   val .nthroot = f(.n, .A, .p) { var .x = [.A, .A / .n] while abs(.x[2]-.x[1]) > .p { .x = [.x[2], ((.n-1) x .x[2] + .A / (.x[2] ^ (.n-1))) / .n] } simplify .x[2] }   writeln "calculation" writeln .nthroot(10, 7131.5 ^ 10, 0.001) writeln .nthroot(6, 64, 0.001)
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.
#Crystal
Crystal
struct Int def ordinalize num = self.abs ordinal = if (11..13).includes?(num % 100) "th" else case num % 10 when 1; "st" when 2; "nd" when 3; "rd" else "th" end end "#{self}#{ordinal}" end end   [(0..25),(250..265),(1000..1025)].each{|r| puts r.map{ |n| n.ordinalize }.join(", "); puts}  
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.
#PHP
PHP
base_convert("26", 10, 16); // returns "1a"
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.
#PicoLisp
PicoLisp
(de numToString (N Base) (default Base 10) (let L NIL (loop (let C (% N Base) (and (> C 9) (inc 'C 39)) (push 'L (char (+ C `(char "0")))) ) (T (=0 (setq N (/ N Base)))) ) (pack L) ) )   (de stringToNum (S Base) (default Base 10) (let N 0 (for C (chop S) (when (> (setq C (- (char C) `(char "0"))) 9) (dec 'C 39) ) (setq N (+ C (* N Base))) ) N ) )   (prinl (numToString 26 16)) (prinl (stringToNum "1a" 16)) (prinl (numToString 123456789012345678901234567890 36))
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.
#jq
jq
def is_narcissistic: def digits: tostring | explode[] | [.] | implode | tonumber; def pow(n): . as $x | reduce range(0;n) as $i (1; . * $x);   (tostring | length) as $len | . == reduce digits as $d (0; . + ($d | pow($len)) ) 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.
#Julia
Julia
using Printf # for Julia version 1.0+   function isnarcissist(n, b=10) -1 < n || return false d = digits(n, base=b) m = length(d) n == mapreduce((x)->x^m, +, d) end   function findnarcissist(verbose=false) goal = 25 ncnt = 0 verbose && println("Finding the first ", goal, " Narcissistic numbers:") for i in 0:typemax(1) isnarcissist(i) || continue ncnt += 1 verbose && println(@sprintf "  %2d %7d" ncnt i) ncnt < goal || break end end   findnarcissist() @time findnarcissist(true)  
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.
#Octave
Octave
size = 256; [x,y] = meshgrid([0:size-1]);   c = bitxor(x,y);   colormap(jet(size)); image(c); axis equal;
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.
#Perl
Perl
use GD;   my $img = new GD::Image(256, 256, 1);   for my $y(0..255) { for my $x(0..255) { my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y)); $img->setPixel($x, $y, $color); } }   print $img->png
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
#CLU
CLU
digits = iter (n: int) yields (int) while n>0 do yield(n//10) n := n/10 end end digits   munchausen = proc (n: int) returns (bool) k: int := 0 for d: int in digits(n) do  % Note: 0^0 is to be regarded as 0 if d~=0 then k := k + d ** d end end return(n = k) end munchausen   start_up = proc () po: stream := stream$primary_output() for i: int in int$from_to(1,5000) do if munchausen(i) then stream$putl(po, int$unparse(i)) end end end start_up
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).
#C
C
#include <stdio.h> #include <stdlib.h>   /* let us declare our functions; indeed here we need really only M declaration, so that F can "see" it and the compiler won't complain with a warning */ int F(const int n); int M(const int n);   int F(const int n) { return (n == 0) ? 1 : n - M(F(n - 1)); }   int M(const int n) { return (n == 0) ? 0 : n - F(M(n - 1)); }   int main(void) { int i; for (i = 0; i < 20; i++) printf("%2d ", F(i)); printf("\n"); for (i = 0; i < 20; i++) printf("%2d ", M(i)); printf("\n"); return EXIT_SUCCESS; }
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.
#Ursa
Ursa
decl double<> notes append 261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25 notes   for (decl int i) (< i (size notes)) (inc i) ursa.util.sound.beep notes<i> 0.5 end for
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.
#VBA
VBA
Option Explicit   Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long   Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
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.
#J
J
multisplit=: 4 :0 'sep begin'=. |: t=. y /:~&.:(|."1)@;@(i.@#@[ ,.L:0"0 I.@E.L:0) x end=. begin + sep { #@>y last=. next=. 0 r=. 2 0$0 while. next<#begin do. r=. r,.(last}.x{.~next{begin);next{t last=. next{end next=. 1 i.~(begin>next{begin)*.begin>:last end. r=. r,.'';~last}.x )
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
#Arturo
Arturo
result: new []   queens: function [n, i, a, b, c][ if? i < n [ loop 1..n 'j [ if all? @[ not? contains? a j not? contains? b i+j not? contains? c i-j ] -> queens n, i+1, a ++ @[j], b ++ @[i+j], c ++ @[i-j]   ] ] else [ if n = size a -> 'result ++ @[a] ] ]   BoardSize: 6   queens BoardSize, 0, [], [], [] loop result 'solution [ loop solution 'col [   line: new repeat "-" BoardSize line\[col-1]: `Q` print line ] 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
#SenseTalk
SenseTalk
introduce "Mary" introduce "Pablo", "Hola" introduce greeting:"Bonjour", name:"Brigitte" by name   to introduce name, greeting:"Hello" put greeting && name end introduce  
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
#Sidef
Sidef
func example(foo: 0, bar: 1, grill: "pork chops") { say "foo is #{foo}, bar is #{bar}, and grill is #{grill}"; }   # Note that :foo is omitted and :grill precedes :bar example(grill: "lamb kebab", bar: 3.14);
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
#Smalltalk
Smalltalk
Object subclass: AnotherClass [ "..." initWithArray: anArray [ "single argument" ] initWithArray: anArray andString: aString [ "two args; these two methods in usage resemble a named argument, with optional andString argument" ] "..." ]
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.
#Liberty_BASIC
Liberty BASIC
  print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 )); print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001)) print "125'th root of 5642 by LB's exponentiation operator is "; using( "#.###############", 5642^(1 /125))   print "27^(1 / 3)", using( "#.###############", NthRoot( 3, 27, 0.00001)) print "2^(1 / 2)", using( "#.###############", NthRoot( 2, 2, 0.00001)) print "1024^(1 /10)", using( "#.###############", NthRoot( 10, 1024, 0.00001))   wait   function NthRoot( n, A, p) x( 0) =A x( 1) =A /n while abs( x( 1) -x( 0)) >p x( 0) =x( 1) x( 1) =( ( n -1.0) *x( 1) +A /x( 1)^( n -1.0)) /n wend NthRoot =x( 1) end function   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.
#D
D
import std.stdio, std.string, std.range, std.algorithm;   string nth(in uint n) pure { static immutable suffix = "th st nd rd th th th th th th".split; return "%d'%s".format(n, (n % 100 <= 10 || n % 100 > 20) ? suffix[n % 10] : "th"); }   void main() { foreach (r; [iota(26), iota(250, 266), iota(1000, 1026)]) writefln("%-(%s %)", r.map!nth); }
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.
#PL.2FI
PL/I
  convert: procedure (N, base) returns (character (64) varying) recursive; declare N fixed binary (31), base fixed binary; declare table (0:15) character ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); declare s character (64) varying;   if N = 0 then return ('');   s = convert(N/base, base); return (s || table(mod(N, base)) ); end convert;  
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.
#PL.2FM
PL/M
100H:   /* CONVERT A NUMBER TO A GIVEN BASE */ TO$BASE: PROCEDURE (N, BASE, BUF) ADDRESS; DECLARE (N, BUF, I, J, K) ADDRESS; DECLARE (D, BASE, STR BASED BUF) BYTE;   /* GENERATE DIGITS */ I = 0; DIGIT: D = N MOD BASE; N = N / BASE; IF D < 10 THEN STR(I) = D + '0'; ELSE STR(I) = (D - 10) + 'A'; I = I + 1; IF N > 0 THEN GO TO DIGIT;   /* PUT DIGITS IN HIGH-ENDIAN ORDER */ J = 0; K = I-1; DO WHILE (J < K); D = STR(K); STR(K) = STR(J); STR(J) = D; K = K-1; J = J+1; END;   STR(I) = '$'; RETURN BUF; END TO$BASE;     /* READ A NUMBER IN A GIVEN BASE */ FROM$BASE: PROCEDURE (BUF, BASE) ADDRESS; DECLARE (BUF, RESULT) ADDRESS; DECLARE (D, BASE, CHAR BASED BUF) BYTE;   RESULT = 0; DO WHILE CHAR <> '$'; D = CHAR - '0'; IF D >= 10 THEN D = D - ('A' - '0') + 10; RESULT = (RESULT * BASE) + D; BUF = BUF + 1; END; RETURN RESULT; END FROM$BASE;   /* CP/M BDOS ROUTINES */ BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT; CRLF: PROCEDURE; CALL PRINT(.(13,10,'$')); END CRLF;   /* EXAMPLES */ DECLARE I BYTE, N ADDRESS;   CALL PRINT(.'1234 IN BASES 2-36: $'); CALL CRLF; DO I=2 TO 36; CALL PRINT(.'BASE $'); CALL PRINT(TO$BASE(I, 10, .MEMORY)); CALL PRINT(.(': ',9,'$')); CALL PRINT(TO$BASE(1234, I, .MEMORY)); CALL CRLF; END;   CALL PRINT(.'''25'' IN BASES 10-36: $'); CALL CRLF; DO I=10 TO 36; CALL PRINT(.'BASE $'); CALL PRINT(TO$BASE(I, 10, .MEMORY)); CALL PRINT(.(':',9,'$')); N = FROM$BASE(.'25$', I); CALL PRINT(TO$BASE(N, 10, .MEMORY)); CALL CRLF; END;   CALL EXIT; EOF
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.
#Kotlin
Kotlin
// version 1.1.0   fun isNarcissistic(n: Int): Boolean { if (n < 0) throw IllegalArgumentException("Argument must be non-negative") var nn = n val digits = mutableListOf<Int>() val powers = IntArray(10) { 1 } while (nn > 0) { digits.add(nn % 10) for (i in 1..9) powers[i] *= i // no need to calculate powers[0] nn /= 10 } val sum = digits.filter { it > 0 }.map { powers[it] }.sum() return n == sum }   fun main(args: Array<String>) { println("The first 25 narcissistic (or Armstrong) numbers are:") var i = 0 var count = 0 do { if (isNarcissistic(i)) { print("$i ") count++ } i++ } while (count < 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.
#Phix
Phix
-- -- demo\rosetta\Munching_squares.exw -- ================================= -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) for y=0 to height-1 do for x=0 to width-1 do cdCanvasPixel(cddbuffer, x, y, xor_bits(x,y)) end for end for cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_RED) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=250x250") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas, `TITLE="Munching squares",RESIZE=NO`) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#Common_Lisp
Common Lisp
  ;;; check4munch maximum &optional b ;;; Return a list with all Munchausen numbers less then or equal to maximum. ;;; Checks are done in base b (<=10, dpower is the limiting factor here). (defun check4munch (maximum &optional (base 10)) (do ((n 1 (1+ n)) (result NIL (if (munchp n base) (cons n result) result))) ((> n maximum) (nreverse result))))   ;;; ;;; munchp n &optional b ;;; Return T if n is a Munchausen number in base b. (defun munchp (n &optional (base 10)) (if (= n (apply #'+ (mapcar #'dpower (n2base n base)))) T NIL))   ;;; dpower d ;;; Returns d^d. I.e. the digit to the power of itself. ;;; 0^0 is set to 0. For discussion see e.g. the wikipedia entry. ;;; This function is mainly performance optimization. (defun dpower (d) (aref #(0 1 4 27 256 3125 45556 823543 16777216 387420489) d))   ;;; divmod a b ;;; Return (q,k) such that a = b*q + k and k>=0. (defun divmod (a b) (let ((foo (mod a b))) (list (/ (- a foo) b) foo)))   ;;; n2base n &optional b ;;; Return a list with the digits of n in base b representation. (defun n2base (n &optional (base 10) (digits NIL)) (if (zerop n) digits (let ((dm (divmod n base))) (n2base (car dm) base (cons (cadr dm) digits)))))  
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).
#C.23
C#
namespace RosettaCode { class Hofstadter { static public int F(int n) { int result = 1; if (n > 0) { result = n - M(F(n-1)); }   return result; }   static public int M(int n) { int result = 0; if (n > 0) { result = n - F(M(n - 1)); }   return result; } } }
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.
#Vlang
Vlang
import strings import os import encoding.binary import math   const ( sample_rate = 44100 duration = 8 data_length = sample_rate * duration hdr_size = 44 file_len = data_length + hdr_size - 8 ) fn main() {   // buffers mut buf1 := []byte{len:1} mut buf2 := []byte{len:2} mut buf4 := []byte{len:4}   // WAV header mut sb := strings.new_builder(128) sb.write_string("RIFF") binary.little_endian_put_u32(mut &buf4, file_len) sb.write(buf4)? // file size - 8 sb.write_string("WAVE") sb.write_string("fmt ") binary.little_endian_put_u32(mut &buf4, 16) sb.write(buf4)? // length of format data (= 16) binary.little_endian_put_u16(mut &buf2, 1) sb.write(buf2)? // type of format (= 1 (PCM)) sb.write(buf2)? // number of channels (= 1) binary.little_endian_put_u32(mut &buf4, sample_rate) sb.write(buf4)? // sample rate sb.write(buf4)? // sample rate * bps(8) * channels(1) / 8 (= sample rate) sb.write(buf2)? // bps(8) * channels(1) / 8 (= 1) binary.little_endian_put_u16(mut &buf2, 8) sb.write(buf2)? // bits per sample (bps) (= 8) sb.write_string("data") binary.little_endian_put_u32(mut &buf4, data_length) sb.write(buf4)? // size of data section wavhdr := sb.str().bytes()   // write WAV header mut f := os.create("notes.wav")? defer { f.close() } f.write(wavhdr)?   // compute and write actual data freqs := [261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3]! for j in 0..duration { freq := freqs[j] omega := 2 * math.pi * freq for i in 0..data_length/duration { y := 32 * math.sin(omega*f64(i)/f64(sample_rate)) buf1[0] = u8(math.round(y)) f.write(buf1)? } } }
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.
#Wren
Wren
import "/sound" for Wav   var sampleRate = 44100 var duration = 8 var data = List.filled(sampleRate * duration, 0) var freqs = [261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3] for (j in 0...duration) { var freq = freqs[j] var omega = 2 * Num.pi * freq for (i in 0...sampleRate) { var y = (32 * (omega * i / sampleRate).sin).round & 255 data[i + j * sampleRate] = y } } Wav.create("musical_scale.wav", data, sampleRate)
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.
#Java
Java
import java.util.*;   public class MultiSplit {   public static void main(String[] args) { System.out.println("Regex split:"); System.out.println(Arrays.toString("a!===b=!=c".split("==|!=|=")));   System.out.println("\nManual split:"); for (String s : multiSplit("a!===b=!=c", new String[]{"==", "!=", "="})) System.out.printf("\"%s\" ", s); }   static List<String> multiSplit(String txt, String[] separators) { List<String> result = new ArrayList<>(); int txtLen = txt.length(), from = 0;   for (int to = 0; to < txtLen; to++) { for (String sep : separators) { int sepLen = sep.length(); if (txt.regionMatches(to, sep, 0, sepLen)) { result.add(txt.substring(from, to)); from = to + sepLen; to = from - 1; // compensate for the increment break; } } } if (from < txtLen) result.add(txt.substring(from)); return result; } }
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
#AWK
AWK
  #!/usr/bin/gawk -f # Solve the Eight Queens Puzzle # Inspired by Raymond Hettinger [https://code.activestate.com/recipes/576647/] # Just the vector of row positions per column is kept, # and filled with all possibilities from left to right recursively, # then checked against the columns left from the current one: # - is a queen in the same row # - is a queen in the digonal # - is a queen in the reverse diagonal BEGIN { dim = ARGC < 2 ? 8 : ARGV[1] # make vec an array vec[1] = 0 # scan for a solution if (tryqueen(1, vec, dim)) result(vec, dim) else print "No solution with " dim " queens." }   # try if a queen can be set in column (col) function tryqueen(col, vec, dim, new) { for (new = 1; new <= dim; ++new) { # check all previous columns if (noconflict(new, col, vec, dim)) { vec[col] = new if (col == dim) return 1 # must try next column(s) if (tryqueen(col+1, vec, dim)) return 1 } } # all tested, failed return 0 }   # check if setting the queen (new) in column (col) is ok # by checking the previous colums conflicts function noconflict(new, col, vec, dim, j) { for (j = 1; j < col; j++) { if (vec[j] == new) return 0 # same row if (vec[j] == new - col + j) return 0 # diagonal conflict if (vec[j] == new + col - j) return 0 # reverse diagonal conflict } # no test failed, no conflict return 1 }   # print matrix function result(vec, dim, row, col, sep, lne) { # print the solution vector for (row = 1; row <= dim; ++row) printf " %d", vec[row] print   # print a board matrix for (row = 1; row <= dim; ++row) { lne = "|" for (col = 1; col <= dim; ++col) { if (row == vec[col]) lne = lne "Q|" else lne = lne "_|" } print lne } }      
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
#Standard_ML
Standard ML
fun dosomething (a, b, c) = print ("a = " ^ a ^ "\nb = " ^ Real.toString b ^ "\nc = " ^ Int.toString c ^ "\n")   fun example {a, b, c} = dosomething (a, b, c)
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
#Suneido
Suneido
  test = function (one, two, three = '', four = '', five = '') { Print('one: ' $ one $ ', two: ' $ two $ ', three: ' $ three $ ', four: ' $ four $ ', five: ' $ five) } test('1', '2', five: '5', three: '3')  
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
#Swift
Swift
func greet(person: String, hometown: String) -> String { return "Hello \(person)! Glad you could visit from \(hometown)." } print(greet(person: "Bill", hometown: "Cupertino"))
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.
#Lingo
Lingo
on nthRoot (x, root) return power(x, 1.0/root) end
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.
#Logo
Logo
to about :a :b output and [:a - :b < 1e-5] [:a - :b > -1e-5] end   to root :n :a [:guess :a] localmake "next ((:n-1) * :guess + :a / power :guess (:n-1)) / n if about :guess :next [output :next] output (root :n :a :next) end   show root 5 34  ; 2.02439745849989
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.
#Delphi
Delphi
proc nonrec nth(word n; *char buf) *char: channel output text ch; open(ch, buf); write(ch; n, if (n/10)%10=1 then "th" elif n%10=1 then "st" elif n%10=2 then "nd" elif n%10=3 then "rd" else "th" fi ); close(ch); buf corp;   proc nonrec print_range(word start, stop) void: [8] char buf; word col, n; col := 0; for n from start upto stop do write(nth(n, &buf[0])); col := col + 1; if col%10=0 then writeln() else write('\t') fi od; writeln() corp   proc nonrec main() void: print_range(0, 25); print_range(250, 265); print_range(1000, 1025) corp
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.
#Pop11
Pop11
define number_to_base(n, base); radix_apply(n, '%p', sprintf, base); enddefine;
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.
#Ksh
Ksh
  #!/bin/ksh   # Narcissistic decimal number   # # Variables: #   # # Functions: #   # # Function _isnarcissist(n) - return 1 if n is a narcissistic decimal number # function _isnarcissist { typeset _n ; integer _n=$1   (( ${_n} == $(_sumpowdigits ${_n}) )) && return 1 return 0 }   # # Function _sumpowdigits(n) - return sum of the digits raised to #digit power # function _sumpowdigits { typeset _n ; integer _n=$1 typeset _i ; typeset -si _i typeset _sum ; integer _sum=0   for ((_i=0; _i<${#_n}; _i++)); do (( _sum+=(${_n:_i:1}**${#_n}) )) done echo ${_sum} }   ###### # main # ######   integer i cnt=0 for ((i=0; cnt<25; i++)); do _isnarcissist ${i} ; (( $? )) && printf "%3d. %d\n" $(( ++cnt )) ${i} done  
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.
#PHP
PHP
header("Content-Type: image/png");   $w = 256; $h = 256;   $im = imagecreate($w, $h) or die("Cannot Initialize new GD image stream");   $color = array(); for($i=0;$i<256;$i++) { array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i)); }   for($i=0;$i<$w;$i++) { for($j=0;$j<$h;$j++) { imagesetpixel($im,$i,$j,$color[$i^$j]); } }   imagepng($im); imagedestroy($im);
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. MUNCHAUSEN.   DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 CANDIDATE PIC 9(4). 03 DIGITS PIC 9 OCCURS 4 TIMES, REDEFINES CANDIDATE. 03 DIGIT PIC 9. 03 POWER-SUM PIC 9(5).   01 OUTPUT-LINE. 03 OUT-NUM PIC ZZZ9.   PROCEDURE DIVISION. BEGIN. PERFORM MUNCHAUSEN-TEST VARYING CANDIDATE FROM 1 BY 1 UNTIL CANDIDATE IS GREATER THAN 6000. STOP RUN.   MUNCHAUSEN-TEST. MOVE ZERO TO POWER-SUM. MOVE 1 TO DIGIT. INSPECT CANDIDATE TALLYING DIGIT FOR LEADING '0'. PERFORM ADD-DIGIT-POWER VARYING DIGIT FROM DIGIT BY 1 UNTIL DIGIT IS GREATER THAN 4. IF POWER-SUM IS EQUAL TO CANDIDATE, MOVE CANDIDATE TO OUT-NUM, DISPLAY OUTPUT-LINE.   ADD-DIGIT-POWER. COMPUTE POWER-SUM = POWER-SUM + DIGITS(DIGIT) ** DIGITS(DIGIT)
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).
#C.2B.2B
C++
#include <iostream> #include <vector> #include <iterator>   class Hofstadter { public: static int F(int n) { if ( n == 0 ) return 1; return n - M(F(n-1)); } static int M(int n) { if ( n == 0 ) return 0; return n - F(M(n-1)); } };   using namespace std;   int main() { int i; vector<int> ra, rb;   for(i=0; i < 20; i++) { ra.push_back(Hofstadter::F(i)); rb.push_back(Hofstadter::M(i)); } copy(ra.begin(), ra.end(), ostream_iterator<int>(cout, " ")); cout << endl; copy(rb.begin(), rb.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
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.
#XPL0
XPL0
\Square waves on the beeper speaker: code Sound=39; real Period; int I; [Period:= 1190000.0/261.625565; \middle C for I:= 2 to 9 do [Sound(1, 4, fix(Period)); \times 2^(-1/6) else 2^(-1/12) Period:= Period * (if I&3 then 0.890898719 else 0.943874313); ]; ]   \MIDI grand piano (requires 32-bit Windows or Sound Blaster 16): code Sound=39; int Note, I; [port($331):= $3F; \set MPU-401 into UART mode Note:= 60; \start at middle C for I:= 2 to 9+1 do \(last note is not played) [port($330):= $90; port($330):= Note; port($330):= $7F; Sound(0, 4, 1); \This "Sound" is off, but convenient 0.22 sec delay Note:= Note + (if I&3 then 2 else 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.
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Musical_scale // by Galileo, 03/2022   sample_rate = 44100 duration = 8 dataLength = sample_rate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 data 261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3   sub int_to_bytes(dato, long) local dato$, esp, esp$, i   esp$ = "00000000" dato$ = hex$(dato) esp = long * 2 dato$ = right$(esp$ + dato$, esp) for i = esp - 1 to 1 step -2 poke #fn, dec(mid$(dato$, i, 2)) next end sub   fn = open("notesyab.wav", "wb")   print #fn, "RIFF"; int_to_bytes(fileLen, 4) print #fn, "WAVEfmt "; int_to_bytes(16, 4) // length of format data (= 16) int_to_bytes(1, 2) // type of format (= 1 (PCM)) int_to_bytes(1, 2) // number of channels (= 1) int_to_bytes(sample_rate, 4) // sample rate int_to_bytes(sample_rate, 4) // sample rate * bps(8) * channels(1) / 8 (= sample rate) int_to_bytes(1,2) // bps(8) * channels(1) / 8 (= 1) int_to_bytes(8,2) // bits per sample (bps) (= 8) print #fn, "data"; int_to_bytes(dataLength, 4) // size of data section   for j = 1 to duration read f omega = 2 * PI * f for i = 0 to dataLength/duration-1 y = 32 * sin(omega * i / sample_rate) byte = and(y, 255) poke #fn, byte next next   close(fn)   if peek$("os") = "windows" then system("notesyab.wav") else // Linux system("aplay notesyab.wav") endif
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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM Musical scale 20 LET n=0: REM Start at middle C 30 LET d=0.2: REM Make each note 0.2 seconds in duration 40 FOR l=1 TO 8 50 BEEP d,n 60 READ i: REM Number of semitones to increment 70 LET n=n+i 80 NEXT l 90 STOP 9000 DATA 2,2,1,2,2,2,1,2:REM WWHWWWH
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.
#JavaScript
JavaScript
RegExp.escape = function(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }   multisplit = function(string, seps) { var sep_regex = RegExp(_.map(seps, function(sep) { return RegExp.escape(sep); }).join('|')); return string.split(sep_regex); }
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.
#jq
jq
# peeloff(delims) either peels off a delimiter or # a single character from the input string. # The input should be a nonempty string, and delims should be # a non-empty array of delimiters; # return [peeledoff, remainder] # where "peeledoff" is either [delim] or the peeled off character: def peeloff(delims): delims[0] as $delim | if startswith($delim) then [ [$delim], .[ ($delim|length):]] elif (delims|length)>1 then peeloff(delims[1:]) else [ .[0:1], .[1:]] end ;   # multisplit_parse(delims) produces an intermediate parse. # Input must be of the parse form: [ string, [ delim ], ... ] # Output is of the same form. def multisplit_parse(delims): if (delims|length) == 0 or length == 0 then . else .[length-1] as $last | .[0:length-1] as $butlast | if ($last|type) == "array" then . # all done elif $last == "" then . else ($last | peeloff(delims)) as $p # [ peeledoff, next ] | $p[0] as $peeledoff | $p[1] as $next | if ($next|length) > 0 then $butlast + [$peeledoff] + ([$next]|multisplit_parse(delims)) else $butlast + $p end end end ;   def multisplit(delims): [.] | multisplit_parse(delims) # insert "" between delimiters, compress strings, remove trailing "" if any | reduce .[] as $x ([]; if length == 0 then [ $x ] elif ($x|type) == "array" then if (.[length-1]|type) == "array" then . + ["", $x] else . + [$x] end elif .[length-1]|type == "string" then .[0:length-1] + [ .[length-1] + $x ] else . + [$x] 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
#ATS
ATS
  (* ****** ****** *) // // Solving N-queen puzzle // (* ****** ****** *) // // How to test: // ./queens // How to compile: // patscc -DATS_MEMALLOC_LIBC -o queens queens.dats // (* ****** ****** *) // #include "share/atspre_staload.hats" // #include "share/HATS/atspre_staload_libats_ML.hats" // (* ****** ****** *)   fun solutions(N:int) = let // fun show ( board: list0(int) ) : void = ( list0_foreach<int> ( list0_reverse(board) , lam(n) => ((N).foreach()(lam(i) => print_string(if i = n then " Q" else " _")); print_newline()) ) ; print_newline() ) // fun safe ( i: int, j: int, k: int, xs: list0(int) ) : bool = ( case+ xs of | nil0() => true | cons0(x, xs) => x != i && x != j && x != k && safe(i, j+1, k-1, xs) ) // fun loop ( col: int, xs: list0(int) ) : void = (N).foreach() ( lam(i) => if safe(i, i+1, i-1, xs) then let val xs = cons0(i, xs) in if col = N then show(xs) else loop(col+1, xs) end // end of [then] ) // in loop(1, nil0()) end // end of [solutions]   (* ****** ****** *)   val () = solutions(8)   (* ****** ****** *)   implement main0() = ()   (* ****** ****** *)   (* end of [queens.dats] *)  
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
#Tcl
Tcl
proc example args { # Set the defaults array set opts {-foo 0 -bar 1 -grill "hamburger"} # Merge in the values from the caller array set opts $args # Use the arguments return "foo is $opts(-foo), bar is $opts(-bar), and grill is $opts(-grill)" } # Note that -foo is omitted and -grill precedes -bar example -grill "lamb kebab" -bar 3.14 # => ‘foo is 0, bar is 3.14, and grill is lamb kebab’
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
#VBA
VBA
  Public Function timedelta(Optional weeks As Integer = 0, Optional days As Integer = 0, _ Optional hours As Integer = 0, Optional minutes As Integer = 0, Optional seconds As Integer = 0, _ Optional milliseconds As Integer = 0, Optional microseconds As Integer = 0) As Variant End Function Public Sub main() '-- can be invoked as: fourdays = timedelta(days:=4) '-- fourdays = timedelta(0,4) '-- equivalent '-- **NB** a plain '=' is a very different thing oneday = timedelta(days = 1) '-- equivalent to timedelta([weeks:=]IIf((days=1,-1:0)) '-- with NO error if no local variable days exists. 'VBA will assume local variable days=0 Dim hours As Integer shift = timedelta(hours:=hours) '-- perfectly valid (param hours:=local hours) '-- timedelta(0,hours:=15,3) '-- illegal (it is not clear whether you meant days:=3 or minutes:=3) 'VBA expects a named parameter for 3 End Sub
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
#Visual_Basic
Visual Basic
'the function Sub whatever(foo As Long, bar As Integer, baz As Byte, qux As String) '... End Sub 'calling the function -- note the Pascal-style assignment operator Sub crap() whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?" End Sub
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.
#Lua
Lua
  function nroot(root, num) return num^(1/root) end  
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.
#M2000_Interpreter
M2000 Interpreter
Flush empty stack Over 2 copy 2nd as new top (so 2nd now is 3rd) Over 2,2 repeat Over 2 two times. Shift 2 send top to 2nd, and 2nd to top (1st) (there is a SHFITBACK to revesre action) Drop drop top Number get top if is number, else raise error Read, read a variable form top. Functions parameters works with a read too Function Root { Read a, n%, d as double=1.e-4 ...... } because we can send any type and number if function, interpreter can make conversions if we declare that, or if it not possible (no conversion done to a numeric variable if a string is in top of stack) we get an error. Also if we send less values, and we didn't initialize variable before, we get error too. Here we need to flush stack for other parameters if from an error anyone put more arguments. (interpreter never count before call a user function, except for calling events by using event object, so there there is a signature to follow) n% is double inside.
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.
#Draco
Draco
proc nonrec nth(word n; *char buf) *char: channel output text ch; open(ch, buf); write(ch; n, if (n/10)%10=1 then "th" elif n%10=1 then "st" elif n%10=2 then "nd" elif n%10=3 then "rd" else "th" fi ); close(ch); buf corp;   proc nonrec print_range(word start, stop) void: [8] char buf; word col, n; col := 0; for n from start upto stop do write(nth(n, &buf[0])); col := col + 1; if col%10=0 then writeln() else write('\t') fi od; writeln() corp   proc nonrec main() void: print_range(0, 25); print_range(250, 265); print_range(1000, 1025) corp
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.
#PureBasic
PureBasic
Global alphanum$ = "0123456789abcdefghijklmnopqrstuvwxyz" ;36 digits #maxIntegerBitSize = SizeOf(Integer) * 8   Procedure toDecimal(base, s.s) Protected length, i, toDecimal   length = Len(s) If length: toDecimal = FindString(alphanum$, Left(s, 1), 1) - 1: EndIf   For i = 2 To length toDecimal * base + FindString(alphanum$, Mid(s, i, 1), 1) - 1 Next ProcedureReturn toDecimal EndProcedure   Procedure.s toBase(base, number) Protected i, rem, toBase.s{#maxIntegerBitSize} = Space(#maxIntegerBitSize)   For i = #maxIntegerBitSize To 1 Step -1 rem = number % base PokeC(@toBase + i - 1, PeekC(@alphanum$ + rem)) If number < base: Break: EndIf number / base Next ProcedureReturn LTrim(toBase) EndProcedure   If OpenConsole() PrintN( Str(toDecimal(16, "1a")) )   PrintN( toBase(16, 26) )   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
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.
#Lua
Lua
function isNarc (n) local m, sum, digit = string.len(n), 0 for pos = 1, m do digit = tonumber(string.sub(n, pos, pos)) sum = sum + digit^m end return sum == n end   local n, count = 0, 0 repeat if isNarc(n) then io.write(n .. " ") count = count + 1 end n = n + 1 until count == 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.
#PL.2FI
PL/I
munch: procedure options (main); /* 21 May 2014 */   declare screen (0:255, 0:255) bit(24) aligned; declare b bit(8) aligned; declare (x, y) unsigned fixed binary (8);   do x = 0 upthru hbound(screen,2); do y = 0 upthru hbound(screen,1); b = unspec(x) ^ unspec(y); screen(x,y) = b; end; end; call writeppm(screen); end munch;
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.
#Processing
Processing
  //Aamrun, 26th June 2022   size(1200,720);   loadPixels();   for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ pixels[j + i*width] = color(i^j); } }   updatePixels();  
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
#Cowgol
Cowgol
include "cowgol.coh";   sub digitPowerSum(n: uint16): (sum: uint32) is var powers: uint32[10] := {1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489};   sum := 0; loop sum := sum + powers[(n % 10) as uint8]; n := n / 10; if n == 0 then break; end if; end loop; end sub;   var n: uint16 := 1; while n < 5000 loop if n as uint32 == digitPowerSum(n) then print_i16(n); print_nl(); end if; n := n + 1; end loop;
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).
#Ceylon
Ceylon
Integer f(Integer n) => if (n > 0) then n - m(f(n-1)) else 1;   Integer m(Integer n) => if (n > 0) then n - f(m(n-1)) else 0;   shared void run() { printAll((0:20).map(f)); printAll((0:20).map(m)); }
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.
#Julia
Julia
  julia> split(s, r"==|!=|=") 5-element Array{SubString{String},1}: "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.
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { val input = "a!===b=!=c" val delimiters = arrayOf("==", "!=", "=") val output = input.split(*delimiters).toMutableList() for (i in 0 until output.size) { if (output[i].isEmpty()) output[i] = "empty string" else output[i] = "\"" + output[i] + "\"" } println("The splits are:") println(output)   // now find positions of matched delimiters val matches = mutableListOf<Pair<String, Int>>() var index = 0 while (index < input.length) { var matched = false for (d in delimiters) { if (input.drop(index).take(d.length) == d) { matches.add(d to index) index += d.length matched = true break } } if (!matched) index++ } println("\nThe delimiters matched and the indices at which they occur are:") println(matches) }
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
#AutoHotkey
AutoHotkey
; ; Post: http://www.autohotkey.com/forum/viewtopic.php?p=353059#353059 ; Timestamp: 05/may/2010 ;   MsgBox % funcNQP(5) MsgBox % funcNQP(8)   Return   ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ; ; ** USED VARIABLES ** ; ; Global: All variables named Array[???] ; ; Function funcNPQ: nQueens , OutText , qIndex ; ; Function Unsafe: nIndex , Idx , Tmp , Aux ; ; Function PutBoard: Output , QueensN , Stc , xxx , yyy ; ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   funcNQP(nQueens) { Global Array[0] := -1 Local OutText , qIndex := 0 While ( qIndex >= 0 ) { Array[%qIndex%]++ While ( (Array[%qIndex%] < nQueens) && Unsafe(qIndex) ) Array[%qIndex%]++ If ( Array[%qIndex%] < nQueens ) { If ( qIndex < nQueens-1 ) qIndex++ , Array[%qIndex%] := -1 Else PutBoard(OutText,nQueens) } Else qIndex-- } Return OutText }   ;------------------------------------------   Unsafe(nIndex) { Global Local Idx := 1 , Tmp := 0 , Aux := Array[%nIndex%] While ( Idx <= nIndex ) { Tmp := "Array[" nIndex - Idx "]" Tmp := % %Tmp% If ( ( Tmp = Aux ) || ( Tmp = Aux-Idx ) || ( Tmp = Aux+Idx ) ) Return 1 Idx++ } Return 0 }   ;------------------------------------------   PutBoard(ByRef Output,QueensN) { Global Static Stc = 0 Local xxx := 0 , yyy := 0 Output .= "`n`nSolution #" (++Stc) "`n" While ( yyy < QueensN ) { xxx := 0 While ( xxx < QueensN ) Output .= ( "|" ( ( Array[%yyy%] = xxx ) ? "Q" : "_" ) ) , xxx++ Output .= "|`n" , yyy++ } }
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
#Wren
Wren
var printName = Fn.new { |name| if (!(name is Map && name["first"] != null && name["last"] != null)) { Fiber.abort("Argument must be a map with keys \"first\" and \"last\"") } System.print("%(name["first"]) %(name["last"])") }   printName.call({"first": "Abraham", "last": "Lincoln"}) // normal order printName.call({"last": "Trump", "first": "Donald"}) // reverse order printName.call({"forename": "Boris", "lastname": "Johnson"}) // wrong parameter names
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
#XSLT
XSLT
<xsl:template name="table-header"> <xsl:param name="title"/> ... </xsl:template>
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.
#Maple
Maple
  root(1728, 3);   root(1024, 10);   root(2.0, 2);  
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.
#Elena
Elena
import extensions; import system'math; import system'routines;   extension op { ordinalize() { int i := self.Absolute; if (new int[]{11,12,13}.ifExists(i.mod:100)) { ^ i.toPrintable() + "th" };   (i.mod(10)) => 1 { ^ i.toPrintable() + "st" } 2 { ^ i.toPrintable() + "nd" } 3 { ^ i.toPrintable() + "rd" };   ^ i.toPrintable() + "th" } }   public program() { console.printLine(new Range(0,26).selectBy(mssgconst ordinalize<op>[1])); console.printLine(new Range(250,26).selectBy(mssgconst ordinalize<op>[1])); console.printLine(new Range(1000,26).selectBy(mssgconst ordinalize<op>[1])) }
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.
#Python
Python
i = int('1a',16) # returns the integer 26
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.
#Quackery
Quackery
( [ $ '' over abs [ base share /mod digit rot join swap dup 0 = until ] drop swap 0 < if [ $ '-' swap join ] ] is number$ ( n --> $ )   [ base put number$ base release $ '' swap witheach [ lower join ] ] is >base$ ( n b --> $ )   say "The number 2970609818455516403037 in hexatrigesimal is " 2970609818455516403037 36 >base$ echo$ say "."
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.
#Maple
Maple
    Narc:=proc(i) local num,len,j,sums: sums:=0: num := parse~(StringTools:-Explode((convert(i,string)))): len:=numelems(num): for j from 1 to len do sums:=sums+(num[j]^(len)): end do; if sums = i then return i; else return NULL; end if; end proc:   i:=0: NDN:=[]: while numelems(NDN)<25 do NDN:=[op(NDN),(Narc(i))]: i:=i+1: end do: NDN;  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
narc[1] = 0; narc[n_] := narc[n] = NestWhile[# + 1 &, narc[n - 1] + 1, Plus @@ (IntegerDigits[#]^IntegerLength[#]) != # &]; narc /@ Range[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.
#Prolog
Prolog
xor_pattern :- new(D, window('XOR Pattern')), send(D, size, size(512,512)), new(Img, image(@nil, width := 512, height := 512 , kind := pixmap)),   forall(between(0,511, I), ( forall(between(0,511, J), ( V is I xor J, R is (V * 1024) mod 65536, G is (65536 - V * 1024) mod 65536, ( V mod 2 =:= 0 -> B is (V * 4096) mod 65536 ; B is (65536 - (V * 4096)) mod 65536), send(Img, pixel(I, J, colour(@default, R, G, B))))))),   new(Bmp, bitmap(Img)), send(D, display, Bmp, point(0,0)), send(D, open).  
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
#D
D
import std.stdio;   void 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 += digit ^^ digit; } if (sum == i) { // the sum is equal to the number // itself; thus it is a // munchausen number writeln(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).
#Clojure
Clojure
(declare F) ; forward reference   (defn M [n] (if (zero? n) 0 (- n (F (M (dec n))))))   (defn F [n] (if (zero? n) 1 (- n (M (F (dec n))))))
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.
#Lua
Lua
--[[ Returns a table of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified as a single- or multi-character string or a table of such strings. If chars is omitted, it defaults to the set of all space characters, and keep is taken to be false. The limit and keep arguments are optional: they are a maximum size for the result and a flag determining whether empty fields should be kept in the result. ]] function split (str, chars, limit, keep) local limit, splitTable, entry, pos, match = limit or 0, {}, "", 1 if keep == nil then keep = true end if not chars then for e in string.gmatch(str, "%S+") do table.insert(splitTable, e) end return splitTable end while pos <= str:len() do match = nil if type(chars) == "table" then for _, delim in pairs(chars) do if str:sub(pos, pos + delim:len() - 1) == delim then match = string.len(delim) - 1 break end end elseif str:sub(pos, pos + chars:len() - 1) == chars then match = string.len(chars) - 1 end if match then if not (keep == false and entry == "") then table.insert(splitTable, entry) if #splitTable == limit then return splitTable end entry = "" end else entry = entry .. str:sub(pos, pos) end pos = pos + 1 + (match or 0) end if entry ~= "" then table.insert(splitTable, entry) end return splitTable end   local multisplit = split("a!===b=!=c", {"==", "!=", "="})   -- Returned result is a table (key/value pairs) - display all entries print("Key\tValue") print("---\t-----") for k, v in pairs(multisplit) do print(k, v) 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
#BBC_BASIC
BBC BASIC
Size% = 8 Cell% = 32 VDU 23,22,Size%*Cell%;Size%*Cell%;Cell%,Cell%,16,128+8,5 *font Arial Unicode MS,16 GCOL 3,11 FOR i% = 0 TO Size%-1 STEP 2 RECTANGLE FILL i%*Cell%*2,0,Cell%*2,Size%*Cell%*2 RECTANGLE FILL 0,i%*Cell%*2,Size%*Cell%*2,Cell%*2 NEXT num% = FNqueens(Size%, Cell%) SYS "SetWindowText", @hwnd%, "Total " + STR$(num%) + " solutions" REPEAT : WAIT 1 : UNTIL FALSE END   DEF FNqueens(n%, s%) LOCAL i%, j%, m%, p%, q%, r%, a%(), b%(), c%() DIM a%(n%), b%(n%), c%(4*n%-2) FOR i% = 1 TO DIM(a%(),1) : a%(i%) = i% : NEXT m% = 0 i% = 1 j% = 0 r% = 2*n%-1 REPEAT i% -= 1 j% += 1 p% = 0 q% = -r% REPEAT i% += 1 c%(p%) = 1 c%(q%+r%) = 1 SWAP a%(i%),a%(j%) p% = i% - a%(i%) + n% q% = i% + a%(i%) - 1 b%(i%) = j% j% = i% + 1 UNTIL j% > n% OR c%(p%) OR c%(q%+r%) IF c%(p%)=0 IF c%(q%+r%)=0 THEN IF m% = 0 THEN FOR p% = 1 TO n% MOVE 2*s%*(a%(p%)-1)+6, 2*s%*p%+6 PRINT "♛"; NEXT ENDIF m% += 1 ENDIF j% = b%(i%) WHILE j% >= n% AND i% <> 0 REPEAT SWAP a%(i%), a%(j%) j% = j%-1 UNTIL j% < i% i% -= 1 p% = i% - a%(i%) + n% q% = i% + a%(i%) - 1 j% = b%(i%) c%(p%) = 0 c%(q%+r%) = 0 ENDWHILE UNTIL i% = 0 = m%
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Root[A,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.
#MATLAB
MATLAB
function answer = nthRoot(number,root)   format long   answer = number / root; guess = number;   while not(guess == answer) guess = answer; answer = (1/root)*( ((root - 1)*guess) + ( number/(guess^(root - 1)) ) ); end   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.
#Elixir
Elixir
defmodule RC do def ordinalize(n) do num = abs(n) ordinal = if rem(num, 100) in 4..20 do "th" else case rem(num, 10) do 1 -> "st" 2 -> "nd" 3 -> "rd" _ -> "th" end end "#{n}#{ordinal}" end end   Enum.each([0..25, 250..265, 1000..1025], fn range -> Enum.map(range, fn n -> RC.ordinalize(n) end) |> Enum.join(" ") |> IO.puts end)
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.
#R
R
      int2str <- function(x, b) { if(x==0) return("0") if(x<0) return(paste0("-", base(-x,b)))   map <- c(as.character(0:9), letters) res <- "" while (x>0) { res <- c(map[x %% b + 1], res) x <- x %/% b } return(paste(res, collapse="")) }   str2int <- function(s, b) { map <- c(as.character(0:9), letters) s <- strsplit(s,"")[[1]] res <- sapply(s, function(x) which(map==x)) res <- as.vector((res-1) %*% b^((length(res)-1):0)) return(res) }   ## example: convert 255 to hex (ff): int2str(255, 16)   ## example: convert "1a" in base 16 to integer (26): str2int("1a", 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.
#Racket
Racket
  #lang racket   ;; Both assume valid inputs (define (num->str N r) (let loop ([N N] [digits '()]) (define-values [N1 d] (quotient/remainder N r)) (define digits1 (cons (integer->char (+ d (if (< d 10) 48 55))) digits)) (if (zero? N) (list->string digits1) (loop N1 digits1)))) (define (str->num S r) (for/fold ([N 0]) ([B (string->bytes/utf-8 (string-upcase S))]) (+ (* N r) (- B (if (< 64 B) 55 48)))))   ;; To try it out: (define (random-test) (define N (random 1000000)) (define r (+ 2 (random 35))) (define S (num->str N r)) (define M (str->num S r)) (printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD))) ;; (random-test)  
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.
#MATLAB
MATLAB
function testNarcissism x = 0; c = 0; while c < 25 if isNarcissistic(x) fprintf('%d ', x) c = c+1; end x = x+1; end fprintf('\n') end   function tf = isNarcissistic(n) dig = sprintf('%d', n) - '0'; tf = n == sum(dig.^length(dig)); 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.
#PureBasic
PureBasic
#palletteSize = 128 Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values Protected result = x ! y ProcedureReturn Mod(result, #palletteSize) / #palletteSize EndProcedure   Procedure drawPattern() StartDrawing(ImageOutput(0)) DrawingMode(#PB_2DDrawing_Gradient) CustomGradient(@XorPattern()) ;specify a gradient pallette from which only specific indexes will be used For i = 1 To #palletteSize GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD Next Box(0, 0, ImageWidth(0), ImageHeight(0)) StopDrawing() EndProcedure   If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu) CreateImage(0, WindowWidth(0), WindowHeight(0)) drawPattern() ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0)) Repeat event = WaitWindowEvent(20) Until event = #PB_Event_CloseWindow EndIf
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
#Dc
Dc
[ O ~ S! d 0!=M L! d ^ + ] sM [p] sp [z d d lM x =p z 5001>L ] sL lL 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).
#CLU
CLU
% At the top level, definitions can only see the definitions above. % But if we put F and M in a cluster, they can see each other. mutrec = cluster is F, M rep = null   F = proc (n: int) returns (int) if n=0 then return(1) else return(n - M(F(n-1))) end end F   M = proc (n: int) returns (int) if n=0 then return(0) else return(n - F(M(n-1))) end end M end mutrec   % If we absolutely _must_ have them defined at the top level, % we can then just take them out of the cluster. F = mutrec$F M = mutrec$M   % Print the first few values for F and M print_first_16 = proc (name: string, fn: proctype (int) returns (int)) po: stream := stream$primary_output() stream$puts(po, name || ":") for i: int in int$from_to(0,15) do stream$puts(po, " " || int$unparse(fn(i))) end stream$putl(po, "") end print_first_16   start_up = proc () print_first_16("F", F) print_first_16("M", M) end start_up
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.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { DIM sep$() sep$() = ("==", "!=", "=") PRINT "String splits into:" FNmultisplit("a!===b=!=c", sep$(), FALSE) PRINT "For extra credit:" FNmultisplit("a!===b=!=c", sep$(), TRUE) END   SUB FNmultisplit(s$, d$(), info%) LOCAL d%, i%, j%, m%, p%, o$ p% = 1 REPEAT { m% = LEN(s$) FOR i% = 0 TO DIMENSION(d$(),1)-1 d% = INSTR(s$, d$(i%), p%) IF d% THEN IF d% < m% THEN m% = d% : j% = i% NEXT I% IF m% < LEN(s$) THEN { o$ += """" + MID$(s$, p%, m%-p%) + """" IF info% THEN {o$ += " (" + d$(j%) + ") "} ELSE o$ += ", " p% = m% + LEN(d$(j%)) }   } UNTIL m% = LEN(s$) PRINT o$ + """" + MID$(s$, p%) + """" END SUB } CheckIt  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringSplit["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
#BCPL
BCPL
// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10.   GET "libhdr.h"   GLOBAL { count:ug; all }   LET try(ld, row, rd) BE TEST row=all   THEN count := count + 1   ELSE { LET poss = all & ~(ld | row | rd) WHILE poss DO { LET p = poss & -poss poss := poss - p try(ld+p << 1, row+p, rd+p >> 1) } }   LET start() = VALOF { all := 1   FOR i = 1 TO 16 DO { count := 0 try(0, 0, 0) writef("Number of solutions to %i2-queens is %i7*n", i, count) all := 2*all + 1 }   RESULTIS 0 }  
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.
#Maxima
Maxima
nth_root(a, n) := block( [x, y, d, p: fpprec], fpprec: p + 10, x: bfloat(a), eps: 10.0b0^-p, y: do ( d: bfloat((a / x^(n - 1) - x) / n), if abs(d) < eps * x then return(x), x: x + d ), fpprec: p, bfloat(y) )$
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.
#Metafont
Metafont
vardef mnthroot(expr n, A) = x0 := A / n; m := n - 1; forever: x1 := (m*x0 + A/(x0 ** m)) / n; exitif abs(x1 - x0) < abs(x0 * 0.0001); x0 := x1; endfor; x1 enddef;   primarydef n nthroot A = mnthroot(n, A) enddef;   show 5 nthroot 34;  % 2.0244 show 0.5 nthroot 7; % 49.00528   bye
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.
#ERRE
ERRE
  PROGRAM NTH_SOLVE   ! ! for rosettacode.org !   PROCEDURE NTH(S%,E%) LOCAL I%,SUFF$ FOR I%=S% TO E% DO SUFF$="th" IF I% MOD 10=1 AND I% MOD 100<>11 THEN SUFF$="st" END IF IF I% MOD 10=2 AND I% MOD 100<>12 THEN SUFF$="nd" END IF IF I% MOD 10=3 AND I% MOD 100<>13 THEN SUFF$="rd" END IF PRINT(STR$(I%)+SUFF$+" ";) END FOR PRINT END PROCEDURE   BEGIN NTH(0,25) NTH(250,265) NTH(1000,1025) END PROGRAM  
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.
#Raku
Raku
sub from-base(Str $str, Int $base) { +":$base\<$str>"; }   sub to-base(Real $num, Int $base) { $num.base($base); }
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.
#Nanoquery
Nanoquery
def is_narcissist(num) digits = {} for digit in str(num) digits.append(int(digit)) end   sum = 0 for digit in digits sum += digit ^ len(num) end   return sum = num end   def narcissist(n) results = {}   i = 0 while len(results) < n if is_narcissist(i) results.append(i) end i += 1 end   return results end   // get 25 narcissist numbers for num in narcissist(25) print num + " " end println
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.
#Nim
Nim
import sequtils, strutils   func digits(n: Natural): seq[int] = result.add n mod 10 var n = n div 10 while n != 0: result.add n mod 10 n = n div 10   proc findNarcissistic(count: Natural): seq[int] = var n = 0 m = 10 powers = toseq(0..9) while true: while n < m: var s = 0 for d in n.digits: inc s, powers[d] if s == n: result.add n if result.len == count: return inc n for i in 0..9: powers[i] *= i m *= 10   echo findNarcissistic(25).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.
#Python
Python
import Image, ImageDraw   image = Image.new("RGB", (256, 256)) drawingTool = ImageDraw.Draw(image)   for x in range(256): for y in range(256): drawingTool.point((x, y), (0, x^y, 0))   del drawingTool image.save("xorpic.png", "PNG")
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
#Delphi
Delphi
defmodule Munchausen do @pow for i <- 0..9, into: %{}, do: {i, :math.pow(i,i) |> round}   def number?(n) do n == Integer.digits(n) |> Enum.reduce(0, fn d,acc -> @pow[d] + acc end) end end   Enum.each(1..5000, fn i -> if Munchausen.number?(i), do: IO.puts i end)
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).
#CoffeeScript
CoffeeScript
  F = (n) -> if n is 0 then 1 else n - M F n - 1   M = (n) -> if n is 0 then 0 else n - F M n - 1   console.log [0...20].map F console.log [0...20].map M