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/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Phix
Phix
with javascript_semantics function Moebius(integer n) if n=1 then return 1 end if sequence f = prime_factors(n,true) for i=2 to length(f) do if f[i] = f[i-1] then return 0 end if end for return iff(odd(length(f))?-1:+1) end function sequence s = {" ."} for i=1 to 199 do s = append(s,sprintf("%3d",Moebius(i))) end for puts(1,join_by(s,1,20," "))
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Racket
Racket
  #lang racket (define (natural-sort l) (define (list<? l1 l2) (cond [(null? l2) #f] [(null? l1) #t] [(number? (car l1)) (cond [(< (car l1) (car l2)) #t] [(< (car l2) (car l1)) #f] [else (list<? (cdr l1) (cdr l2))])] [(string? (car l1)) (cond [(string<? (car l1) (car l2)) #t] [(string<? (car l2) (car l1)) #f] [else (list<? (cdr l1) (cdr l2))])])) (define (->keys s) (define s* (string-normalize-spaces (string-foldcase s))) (for/list ([x (regexp-match* #px"\\d+" s* #:gap-select? #t)] [i (in-naturals)]) (if (odd? i) (string->number x) x))) (sort l list<? #:key ->keys #:cache-keys? #t))   (natural-sort (shuffle '("foo9.txt" "foo10.txt" "x9y99" "x9y100" "x10y0" "x z" "x y"))) ;; => '("foo9.txt" "foo10.txt" "x9y99" "x9y100" "x10y0" "x y" "x z")  
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "/fmt" for Fmt   var ncs = Fn.new { |a| var f = "$d " if (a[0] is String) { for (i in 0...a.count) a[i] = a[i].bytes[0] f = "$c " } var generate // recursive generate = Fn.new { |m, k, c| if (k == m) { if (c[m - 1] != c[0] + m - 1) { for (i in 0...m) Fmt.write(f, a[c[i]]) System.print() } } else { for (j in 0...a.count) { if (k == 0 || j > c[k - 1]) { c[k] = j generate.call(m, k + 1, c) } } } }   for (m in 2...a.count) { var c = List.filled(m, 0) generate.call(m, 0, c) } }   var a = [1, 2, 3, 4] ncs.call(a) System.print() var ca = ["a", "b", "c", "d", "e"] ncs.call(ca)
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.
#Lua
Lua
function dec2base (base, n) local result, digit = "" while n > 0 do digit = n % base if digit > 9 then digit = string.char(digit + 87) end n = math.floor(n / base) result = digit .. result end return result end   local x = dec2base(16, 26) print(x) --> 1a print(tonumber(x, 16)) --> 26
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.
#Elixir
Elixir
defmodule RC do def narcissistic(m) do Enum.reduce(1..10, [0], fn digits,acc -> digitPowers = List.to_tuple(for i <- 0..9, do: power(i, digits)) Enum.reduce(power(10, digits-1) .. power(10, digits)-1, acc, fn n,result -> sum = divsum(n, digitPowers, 0) if n == sum do if length(result) == m-1, do: throw Enum.reverse(result, [n]) [n | result] else result end end) end) end   defp divsum(0, _, sum), do: sum defp divsum(n, digitPowers, sum) do divsum(div(n,10), digitPowers, sum+elem(digitPowers,rem(n,10))) end   defp power(n, m), do: power(n, m, 1)   defp power(_, 0, pow), do: pow defp power(n, m, pow), do: power(n, m-1, pow*n) end   try do RC.narcissistic(25) catch x -> IO.inspect x 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.
#ERRE
ERRE
PROGRAM NARCISISTIC   !$DOUBLE   BEGIN N=0 LOOP C$=MID$(STR$(N),2) LENG=LEN(C$) SUM=0 FOR I=1 TO LENG DO C=VAL(MID$(C$,I,1)) SUM+=C^LENG END FOR IF N=SUM THEN PRINT(N;) COUNT=COUNT+1 EXIT IF COUNT=25 END IF N=N+1 END LOOP END PROGRAM
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
vec3 color; float c,p; vec2 b;   void main(void) { vec2 uv = gl_FragCoord.xy / iResolution.xy; float scale = iResolution.x / iResolution.y; uv = uv-0.5; uv.y/=scale;   b = uv*256.0+256.0; c = 0.0;     for(float i=16.0;i>=1.0;i-=1.0) { p = pow(2.0,i);   if((p < b.x) ^^ (p < b.y)) { c += p; }   if(p < b.x) { b.x -= p; }   if(p < b.y) { b.y -= p; }   }   c=mod(c/128.0,1.0);   color = vec3(sin(c+uv.x*cos(uv.y*1.2)), tan(c+uv.y-0.3)*1.1, cos(c-uv.y+0.9));   gl_FragColor = vec4(color,1.0); }
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
#APL
APL
(⊢(/⍨)⊢=+/∘(*⍨∘⍎¨⍕)¨)⍳ 5000
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#ARM_Assembly
ARM Assembly
.text .global _start @@@ Implementation of F(n), n in R0. n is considered unsigned. F: tst r0,r0 @ n = 0? moveq r0,#1 @ In that case, the result is 1 bxeq lr @ And we can return to the caller push {r0,lr} @ Save link register and argument to stack sub r0,r0,#1 @ r0 -= 1 = n-1 bl F @ r0 = F(r0) = F(n-1) bl M @ r0 = M(r0) = M(F(n-1)) pop {r1,lr} @ Restore link register and argument in r1 sub r0,r1,r0 @ Result is n-F(M(n-1)) bx lr @ Return to caller.   @@@ Implementation of M(n), n in R0. n is considered unsigned. M: tst r0,r0 @ n = 0? bxeq lr @ In that case the result is also 0; return. push {r0,lr} @ Save link register and argument to stack sub r0,r0,#1 @ r0 -= 1 = n-1 bl M @ r0 = M(r0) = M(n-1) bl F @ r0 = M(r0) = F(M(n-1)) pop {r1,lr} @ Restore link register and argument in r1 sub r0,r1,r0 @ Result is n-M(F(n-1)) bx lr @ Return to caller   @@@ Print F(0..15) and M(0..15) _start: ldr r1,=fmsg @ Print values for F ldr r4,=F bl prfn ldr r1,=mmsg @ Print values for M ldr r4,=M bl prfn mov r7,#1 @ Exit process swi #0   @@@ Helper function for output: print [r1], then [r4](0..15) @@@ This assumes [r4] preserves r3 and r4; M and F do. prfn: push {lr} @ Keep link register bl pstr @ Print the string mov r3,#0 @ Start at 0 1: mov r0,r3 @ Call the function in r4 with current number blx r4 add r0,r0,#'0 @ Make ASCII digit ldr r1,=dgt @ Store in digit string strb r0,[r1] ldr r1,=dstr @ Print result bl pstr add r3,r3,#1 @ Next number cmp r3,#15 @ Keep going up to and including 15 bls 1b ldr r1,=nl @ Print newline afterwards bl pstr pop {pc} @ Return to address on stack @@@ Print length-prefixed string r1 to stdout pstr: push {lr} @ Keep link register mov r0,#1 @ stdout = 1 ldrb r2,[r1],#1 @ r2 = length prefix mov r7,#4 @ 4 = write syscall swi #0 pop {pc} @ Return to address on stack .data fmsg: .ascii "\3F: " mmsg: .ascii "\3M: " dstr: .ascii "\2" dgt: .ascii "* " nl: .ascii "\1\n"
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#J
J
require'media/wav' 0.25 wavnote 0 2 4 5 7 9 11 12
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#JavaScript
JavaScript
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Sample Page</title> </head> <body> Upon loading the page you should hear the scale. <script type="text/javascript"> function musicalScale(freqArr){ // create web audio api context var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext();   // create oscillator and gain node var oscillator = audioCtx.createOscillator(); var gainNode = audioCtx.createGain();   // connect oscillator to gain node to speakers oscillator.connect(gainNode); gainNode.connect(audioCtx.destination);   // set frequencies to play duration = 0.5 // seconds freqArr.forEach(function (freq, i){ oscillator.frequency.setValueAtTime(freq, audioCtx.currentTime + i * duration); });   // start playing! oscillator.start(); // stop playing! oscillator.stop(audioCtx.currentTime + freqArr.length * duration); }   musicalScale([261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]); </script> </body> </html>
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.
#C
C
#include <stdio.h> #include <string.h>   void parse_sep(const char *str, const char *const *pat, int len) { int i, slen; while (*str != '\0') { for (i = 0; i < len || !putchar(*(str++)); i++) { slen = strlen(pat[i]); if (strncmp(str, pat[i], slen)) continue; printf("{%.*s}", slen, str); str += slen; break; } } }   int main() { const char *seps[] = { "==", "!=", "=" }; parse_sep("a!===b=!=c", seps, 3);   return 0; }
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory qw<primes>; use List::Util qw<min>;   #use bigint # works, but slow use Math::GMPz; # this module gives roughly 16x speed-up   sub smooth_numbers { # my(@m) = @_; # use with 'bigint' my @m = map { Math::GMPz->new($_) } @_; # comment out to NOT use Math::GMPz my @s; push @s, [1] for 0..$#m;   return sub { my $n = $s[0][0]; $n = min $n, $s[$_][0] for 1..$#m; for (0..$#m) { shift @{$s[$_]} if $s[$_][0] == $n; push @{$s[$_]}, $n * $m[$_] } return $n } }   sub abbrev { my($n) = @_; return $n if length($n) <= 50; substr($n,0,10) . "...(@{[length($n) - 2*10]} digits omitted)..." . substr($n, -10, 10) }   my @primes = @{primes(10_000)};   my $start = 3000; my $cnt = 3; for my $n_smooth (0..9) { say "\nFirst 25, and ${start}th through @{[$start+2]}nd $primes[$n_smooth]-smooth numbers:"; my $s = smooth_numbers(@primes[0..$n_smooth]); my @S25; push @S25, $s->() for 1..25; say join ' ', @S25;   my @Sm; my $c = 25; do { my $sn = $s->(); push @Sm, abbrev($sn) if ++$c >= $start; } until @Sm == $cnt; say join ' ', @Sm; }   $start = 30000; $cnt = 20; for my $n_smooth (95..97) { # (503, 509, 521) { say "\n${start}th through @{[$start+$cnt-1]}th $primes[$n_smooth]-smooth numbers:"; my $s = smooth_numbers(@primes[0..$n_smooth]); my(@Sm,$c); do { my $sn = $s->(); push @Sm, $sn if ++$c >= $start; } until @Sm == $cnt; say join ' ', @Sm; }
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
#LabVIEW
LabVIEW
define mymethod( -first::integer, // with no default value the param is required -second::integer, -delimiter::string = ':' // when given a default value the param becomes optional ) => #first + #delimiter + #second   mymethod( -first = 54, -second = 45 ) '<br />' mymethod( -second = 45, // named params can be given in any order -first = 54, -delimiter = '#' )
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
#Lasso
Lasso
define mymethod( -first::integer, // with no default value the param is required -second::integer, -delimiter::string = ':' // when given a default value the param becomes optional ) => #first + #delimiter + #second   mymethod( -first = 54, -second = 45 ) '<br />' mymethod( -second = 45, // named params can be given in any order -first = 54, -delimiter = '#' )
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.
#Go
Go
func root(a float64, n int) float64 { n1 := n - 1 n1f, rn := float64(n1), 1/float64(n) x, x0 := 1., 0. for { potx, t2 := 1/x, a for b := n1; b > 0; b >>= 1 { if b&1 == 1 { t2 *= potx } potx *= potx } x0, x = x, rn*(n1f*x+t2) if math.Abs(x-x0)*1e15 < x { break } } return x }
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#BCPL
BCPL
get "libhdr"   // Generate ASCII string of number n with ordinal suffix // The string is stored at v. let nth(n, v) = valof $( let sfx = "thstndrd" let c, s = 0, ? // Generate digits $( c := c + 1 v%c := n rem 10 + '0' n := n / 10 $) repeatuntil n = 0   // Put digits in correct order for i = 1 to c/2 do $( let d = v%i v%i := v%(c+1-i) v%(c+1-i) := d $)   // The length of the string is the amount of digits + 2 v%0 := c+2;   // Figure out the proper suffix from the last two digits test v%(c-1)='1' | v%c>'3' then s := 0 else s := 2*(v%c - '0')   v%(c+1) := sfx%(s+1) v%(c+2) := sfx%(s+2)   resultis v $)   let start() be $( let buf = vec 10 for i = 0 to 25 do writef("%S*N", nth(i, buf)) for i = 250 to 265 do writef("%S*N", nth(i, buf)) for i = 1000 to 1025 do writef("%S*N", nth(i, buf)) $)
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Python
Python
  # Python Program to evaluate # Mobius def M(N) = 1 if N = 1 # M(N) = 0 if any prime factor # of N is contained twice # M(N) = (-1)^(no of distinct # prime factors) # Python Program to # evaluate Mobius def # M(N) = 1 if N = 1 # M(N) = 0 if any # prime factor of # N is contained twice # M(N) = (-1)^(no of # distinct prime factors)   # def to check if # n is prime or not def isPrime(n) :   if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True   def mobius(N) :   # Base Case if (N == 1) : return 1   # For a prime factor i # check if i^2 is also # a factor. p = 0 for i in range(1, N + 1) : if (N % i == 0 and isPrime(i)) :   # Check if N is # divisible by i^2 if (N % (i * i) == 0) : return 0 else :   # i occurs only once, # increase f p = p + 1   # All prime factors are # contained only once # Return 1 if p is even # else -1 if(p % 2 != 0) : return -1 else : return 1   # Driver Code print("Mobius numbers from 1..99:")   for i in range(1, 100): print(f"{mobius(i):>4}", end = '')   if i % 20 == 0: print() # This code is contributed by # Manish Shaw(manishshaw1)
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Raku
Raku
# Sort groups of digits in number order. Sort by order of magnitude then lexically. sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~$0.chars.chr~$0},:g) ~"\x0"~$a }   # Collapse multiple ws characters to a single. sub collapse ($a) { $a.subst( / ( \s ) $0+ /, -> $/ { $0 }, :g ) }   # Convert all ws characters to a space. sub normalize ($a) { $a.subst( / ( \s ) /, ' ', :g ) }   # Ignore common leading articles for title sorts sub title ($a) { $a.subst( / :i ^ ( a | an | the ) >> \s* /, '' ) }   # Decompose ISO-Latin1 glyphs to their base character. sub latin1_decompose ($a) { $a.trans: < Æ AE æ ae Þ TH þ th Ð TH ð th ß ss À A Á A Â A Ã A Ä A Å A à a á a â a ã a ä a å a Ç C ç c È E É E Ê E Ë E è e é e ê e ë e Ì I Í I Î I Ï I ì i í i î i ï i Ò O Ó O Ô O Õ O Ö O Ø O ò o ó o ô o õ o ö o ø o Ñ N ñ n Ù U Ú U Û U Ü U ù u ú u û u ü u Ý Y ÿ y ý y >.hash; }   # Used as:   my @tests = ( [ "Task 1a\nSort while ignoring leading spaces.", [ 'ignore leading spaces: 1', ' ignore leading spaces: 4', ' ignore leading spaces: 3', ' ignore leading spaces: 2' ], {.trim} # builtin method. ], [ "Task 1b\nSort while ignoring multiple adjacent spaces.", [ 'ignore m.a.s spaces: 3', 'ignore m.a.s spaces: 1', 'ignore m.a.s spaces: 4', 'ignore m.a.s spaces: 2' ], {.&collapse} ], [ "Task 2\nSort with all white space normalized to regular spaces.", [ "Normalized\tspaces: 4", "Normalized\xa0spaces: 1", "Normalized\x20spaces: 2", "Normalized\nspaces: 3" ], {.&normalize} ], [ "Task 3\nSort case independently.", [ 'caSE INDEPENDENT: 3', 'casE INDEPENDENT: 2', 'cASE INDEPENDENT: 4', 'case INDEPENDENT: 1' ], {.lc} # builtin method ], [ "Task 4\nSort groups of digits in natural number order.", [ <Foo100bar99baz0.txt foo100bar10baz0.txt foo1000bar99baz10.txt foo1000bar99baz9.txt 201st 32nd 3rd 144th 17th 2 95> ], {.&naturally} ], [ "Task 5 ( mixed with 1, 2, 3 & 4 )\n" ~ "Sort titles, normalize white space, collapse multiple spaces to\n" ~ "single, trim leading white space, ignore common leading articles\n" ~ 'and sort digit groups in natural order.', [ 'The Wind in the Willows 8', ' The 39 Steps 3', 'The 7th Seal 1', 'Wanda 6', 'A Fish Called Wanda 5', ' The Wind and the Lion 7', 'Any Which Way But Loose 4', '12 Monkeys 2' ], {.&normalize.&collapse.trim.&title.&naturally} ], [ "Task 6, 7, 8\nMap letters in Latin1 that have accents or decompose to two\n" ~ 'characters to their base characters for sorting.', [ <apple Ball bald car Card above Æon æon aether niño nina e-mail Évian evoke außen autumn> ], {.&latin1_decompose.&naturally} ] );     for @tests -> $case { my $code_ref = $case.pop; my @array = $case.pop.list; say $case.pop, "\n";   say "Standard Sort:\n"; .say for @array.sort;   say "\nNatural Sort:\n"; .say for @array.sort: {.$code_ref};   say "\n" ~ '*' x 40 ~ "\n"; }
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
fcn non_continuous_subsequences(ary){ pwerSet(ary).filter(fcn(list){(not isContinuous(list)) }) } fcn isContinuous(ary){ if(ary.len()<2) return(True); foreach n in (ary.len()-1){ if(1+ary[n]!=ary[n+1]) return(False); } return(True); } non_continuous_subsequences(T(1,2,3,4)).println();
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.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { k$=lambda$ (m, b as integer=16) -> { if b<2 or b>16 then error "base out of range" if m=0 then ="0" : exit z$="0123456789ABCDEF" =lambda$ z$, b (m) ->{ =if$(m=0->"", lambda$(m div b)+mid$(z$, m mod b + 1, 1)) }(m) } k=lambda (m$, b as integer=16) -> { if b<2 or b>16 then error "base out of range" m$=trim$(m$) if m$="0" then =0 : exit z$="0123456789ABCDEF" =lambda z$, b (m$) ->{ =if(Len(m$)=0->0, lambda(mid$(m$,2))+(instr(z$, left$(m$,1))-1)*b**(len(m$)-1)) }(m$) } Print k$(0)="0", k("0")=0 Print k$(65535)="FFFF", k("FFFF", 16)=65535 Print k$(0xF00F)="F00F", k("F00F", 16)=0xF00F Print k$(0xFFFFFFFF)="FFFFFFFF", k("FFFFFFFF", 16)=0xFFFFFFFF Print k$(100, 8)="144", k("144", 8)=100 Print k$(100, 2)="1100100", k("1100100", 2)=100 } Checkit  
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.
#F.23
F#
  //Naïve solution of Narcissitic number: Nigel Galloway - Febryary 18th., 2015 open System let rec _Digits (n,g) = if n < 10 then n::g else _Digits(n/10,n%10::g)   seq{0 .. Int32.MaxValue} |> Seq.filter (fun n -> let d = _Digits (n, []) d |> List.fold (fun a l -> a + int ((float l) ** (float (List.length d)))) 0 = n) |> Seq.take(25) |> Seq.iter (printfn "%A")  
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.
#GLSL
GLSL
vec3 color; float c,p; vec2 b;   void main(void) { vec2 uv = gl_FragCoord.xy / iResolution.xy; float scale = iResolution.x / iResolution.y; uv = uv-0.5; uv.y/=scale;   b = uv*256.0+256.0; c = 0.0;     for(float i=16.0;i>=1.0;i-=1.0) { p = pow(2.0,i);   if((p < b.x) ^^ (p < b.y)) { c += p; }   if(p < b.x) { b.x -= p; }   if(p < b.y) { b.y -= p; }   }   c=mod(c/128.0,1.0);   color = vec3(sin(c+uv.x*cos(uv.y*1.2)), tan(c+uv.y-0.3)*1.1, cos(c-uv.y+0.9));   gl_FragColor = vec4(color,1.0); }
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
#AppleScript
AppleScript
------------------- MUNCHAUSEN NUMBER ? --------------------   -- isMunchausen :: Int -> Bool on isMunchausen(n)   -- digitPowerSum :: Int -> Character -> Int script digitPowerSum on |λ|(a, c) set d to c as integer a + (d ^ d) end |λ| end script   (class of n is integer) and ¬ n = foldl(digitPowerSum, 0, characters of (n as string))   end isMunchausen     --------------------------- TEST --------------------------- on run   filter(isMunchausen, enumFromTo(1, 5000))   --> {1, 3435}   end run     -------------------- GENERIC FUNCTIONS ---------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo   -- filter :: (a -> Bool) -> [a] -> [a] on filter(p, xs) tell mReturn(p) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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).
#Arturo
Arturo
f: $[n][ if? n=0 -> 1 else -> n-m f n-1 ] m: $[n][ if? n=0 -> 0 else -> n-f m n-1 ]   loop 0..20 'i [ print ["f(" i ")=" f i] print ["m(" i ")=" m i] print "" ]
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.
#Julia
Julia
using PortAudio   function paudio() devs = PortAudio.devices() devnum = findfirst(x -> x.maxoutchans > 0, devs) (devnum == nothing) && error("No output device for audio found") return PortAudioStream(devs[devnum].name, 0, 2) end   function play(ostream, pitch, durationseconds) sinewave(t) = 0.6sin(t) + 0.2sin(2t) + .05sin(8t) timesamples = 0:(1 / 44100):(durationseconds * 0.98) v = Float64[sinewave(2π * pitch * t) for t in timesamples] write(ostream, v) sleep(durationseconds * 0.9) end   # C major scale starting with middle C # pitches from //pages.mtu.edu/~suits/notefreqs.html const scale = [261.6, 293.7, 329.6, 349.2, 392, 440, 493.9, 523.3] const ostream = paudio() for pitch in scale play(ostream, pitch, 0.5) sleep(0.4) end  
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.
#Kotlin
Kotlin
// Kotlin Native v0.3   import kotlinx.cinterop.* import win32.*   fun main(args: Array<String>) { val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523) // CDEFGABc val dur = 500 repeat(5) { for (freq in freqs) Beep(freq, dur) } }
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Multisplit { internal static class Program { private static void Main(string[] args) { foreach (var s in "a!===b=!=c".Multisplit(true, "==", "!=", "=")) // Split the string and return the separators. { Console.Write(s); // Write the returned substrings and separators to the console. } Console.WriteLine(); }   private static IEnumerable<string> Multisplit(this string s, bool returnSeparators = false, params string[] delimiters) { var currentString = new StringBuilder(); /* Initiate the StringBuilder. This will hold the current string to return * once we find a separator. */   int index = 0; // Initiate the index counter at 0. This tells us our current position in the string to read.   while (index < s.Length) // Loop through the string. { // This will get the highest priority separator found at the current index, or null if there are none. string foundDelimiter = (from delimiter in delimiters where s.Length >= index + delimiter.Length && s.Substring(index, delimiter.Length) == delimiter select delimiter).FirstOrDefault();   if (foundDelimiter != null) { yield return currentString.ToString(); // Return the current string. if (returnSeparators) // Return the separator, if the user specified to do so. yield return string.Format("{{\"{0}\", ({1}, {2})}}", foundDelimiter, index, index + foundDelimiter.Length); currentString.Clear(); // Clear the current string. index += foundDelimiter.Length; // Move the index past the current separator. } else { currentString.Append(s[index++]); // Add the character at this index to the current string. } }   if (currentString.Length > 0) yield return currentString.ToString(); // If we have anything left over, return it. } } }
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Phix
Phix
with javascript_semantics include mpfr.e function nsmooth(integer n, integer needed) -- note that n is a prime index, ie 1,2,3,4... for 2,3,5,7... sequence smooth = {mpz_init(1)}, nexts = get_primes(-n), indices = repeat(1,n) for i=1 to n do nexts[i] = mpz_init(nexts[i]) end for for i=2 to needed do mpz x = mpz_init_set(mpz_min(nexts)) smooth = append(smooth,x) for j=1 to n do if mpz_cmp(nexts[j],x)<=0 then indices[j] += 1 mpz_mul_si(nexts[j],smooth[indices[j]],get_prime(j)) end if end for end for return smooth end function function flat_str(sequence s) for i=1 to length(s) do s[i] = shorten(mpz_get_str(s[i]),ml:=10) end for return join(s," ") end function for n=1 to 10 do printf(1,"%d-smooth[1..25]: %s\n",{get_prime(n),flat_str(nsmooth(n, 25))}) end for for n=1 to 10 do printf(1,"%d-smooth[3000..3002]: %s\n",{get_prime(n),flat_str(nsmooth(n, 3002)[3000..3002])}) end for for n=96 to 98 do -- primes 503, 509, and 521 printf(1,"%d-smooth[30000..30019]: %s\n",{get_prime(n),flat_str(nsmooth(n, 30019)[30000..30019])}) end for
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
#Lingo
Lingo
-- accepts either 3 integers or a single property list on foo (arg1, arg2, arg3) if ilk(arg1)=#propList then args = arg1 arg1 = args[#arg1] arg2 = args[#arg2] arg3 = args[#arg3] end if put "arg1="&arg1 put "arg2="&arg2 put "arg3="&arg3 end   foo(1,2) -- 3rd argument omitted -- "arg1=1" -- "arg2=2" -- "arg3="   foo([#arg3:3]) -- only 3rd argument specified -- "arg1=" -- "arg2=" -- "arg3=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
#Lua
Lua
  function CreatePet(options) local name=options.name local species=options.species local breed=options.breed print('Created a '..breed..' '..species..' named '..name) end CreatePet{name='Rex',species='Dog',breed='Irish Setter'} --position does not matter here.  
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.
#Groovy
Groovy
import static Constants.tolerance import static java.math.RoundingMode.HALF_UP   def root(double base, double n) { double xOld = 1 double xNew = 0 while (true) { xNew = ((n - 1) * xOld + base/(xOld)**(n - 1))/n if ((xNew - xOld).abs() < tolerance) { break } xOld = xNew } (xNew as BigDecimal).setScale(7, HALF_UP) }  
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.
#Befunge
Befunge
0>55*:>1-\:0\`!v #v$#$<^:\+*8"}"_ >35*:>1-\:0\`!v #v$#$<^:\+*2"}"_ 5< v$_v#!::-<0*5 @v <,*>#81#4^# _   >>:0\>:55+%68*v: tsnr |:/+ 55\+<, htdd >$>:#,_$:vg v"d"\*!`3:%+55<9 >%55+/1-!!*:8g,^
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Raku
Raku
use Prime::Factor;   sub μ (Int \n) { return 0 if n %% 4 or n %% 9 or n %% 25 or n %% 49 or n %% 121; my @p = prime-factors(n); +@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0 }   my @möbius = lazy flat '', 1, (2..*).hyper.map: -> \n { μ(n) };   # The Task put "Möbius sequence - First 199 terms:\n", @möbius[^200]».fmt('%3s').batch(20).join: "\n";
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#REXX
REXX
/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/ parse arg LO HI grp . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 199 /* " " " " " " */ if grp=='' | grp=="," then grp= 20 /* " " " " " " */ /* ______ */ call genP HI /*generate primes up to the √ HI */ say center(' The Möbius sequence from ' LO " ──► " HI" ", max(50, grp*3), '═') /*title*/ $= /*variable holds output grid of GRP #s.*/ do j=LO to HI; $= $ right( mobius(j), 2) /*process some numbers from LO ──► HI.*/ if words($)==grp then do; say substr($, 2); $= /*show grid if fully populated,*/ end /* and nullify it for more #s.*/ end /*j*/ /*for small grids, using wordCnt is OK.*/   if $\=='' then say substr($, 2) /*handle any residual numbers not shown*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ mobius: procedure expose @.; parse arg x /*obtain a integer to be tested for mu.*/ if x<1 then return '∙' /*special? Then return symbol for null.*/ #= 0 /*start with a value of zero. */ do k=1; p= @.k /*get the Kth (pre─generated) prime.*/ if p>x then leave /*prime (P) > X? Then we're done. */ if p*p>x then do; #= #+1; leave /*prime (P**2 > X? Bump # and leave.*/ end if x//p==0 then do; #= #+1 /*X divisible by P? Bump mu number. */ x= x % p /* Divide by prime. */ if x//p==0 then return 0 /*X÷by P? Then return zero*/ end end /*k*/ /*# (below) is almost always small, <9*/ if #//2==0 then return 1 /*Is # even? Then return postive 1 */ return -1 /* " " odd? " " negative 1. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6= 13; nP=6 /*assign low primes; # primes.*/ do lim=nP until lim*lim>=HI /*only keep primes up to the sqrt(HI).*/ end /*lim*/ do j=@.nP+4 by 2 to HI /*only find odd primes from here on. */ parse var j '' -1 _;if _==5 then iterate /*Is last digit a "5"? Then not prime*/ if j// 3==0 then iterate /*is J divisible by 3? " " " */ if j// 7==0 then iterate /* " " " " 7? " " " */ if j//11==0 then iterate /* " " " " 11? " " " */ if j//13==0 then iterate /* " " " " 13? " " " */ do k=7 while k*k<=j /*divide by some generated odd primes. */ if j // @.k==0 then iterate j /*Is J divisible by P? Then not prime*/ end /*k*/ /* [↓] a prime (J) has been found. */ nP= nP+1; if nP<=HI then @.nP= j /*bump prime count; assign prime to @.*/ end /*j*/; return
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Ruby
Ruby
ar.sort_by{|str| str.downcase.gsub(/\Athe |\Aa |\Aan /, "").lstrip.gsub(/\s+/, " ")}
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.
#M4
M4
eval(26,16) define(`frombase',`eval(0r$2:$1)') frombase(1a,16)
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.
#Factor
Factor
USING: io kernel lists lists.lazy math math.functions math.text.utils prettyprint sequences ; IN: rosetta-code.narcissistic-decimal-number   : digit-count ( n -- count ) log10 floor >integer 1 + ;   : narcissist? ( n -- ? ) dup [ 1 digit-groups ] [ digit-count [ ^ ] curry ] bi map-sum = ;   : first25 ( -- seq ) 25 0 lfrom [ narcissist? ] lfilter ltake list>array ;   : main ( -- ) first25 [ pprint bl ] each ;   MAIN: main
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.
#Gnuplot
Gnuplot
set pm3d map set size square set isosamples 255,255 splot [0:255][0:255]-(floor(x)^floor(y))
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.
#Go
Go
package main   import ( "image" "image/png" "os" )   func main() { g := image.NewGray(image.Rect(0, 0, 256, 256)) for i := range g.Pix { g.Pix[i] = uint8(i>>8 ^ i) } f, _ := os.Create("xor.png") png.Encode(f, g) f.Close() }
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
#Arturo
Arturo
munchausen?: function [n][ n = sum map split to :string n 'digit [ d: to :integer digit d^d ] ]   loop 1..5000 'x [ if munchausen? x -> print 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).
#AutoHotkey
AutoHotkey
Loop 20 i := A_Index-1, t .= "`n" i "`t " M(i) "`t " F(i) MsgBox x`tmale`tfemale`n%t%   F(n) { Return n ? n - M(F(n-1)) : 1 }   M(n) { Return n ? n - F(M(n-1)) : 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.
#Lilypond
Lilypond
% Start at middle C \relative c' { c d e f g a b c }
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.
#Locomotive_Basic
Locomotive Basic
10 mode 1 20 print "Note","Freq. (Hz)","Period" 30 ' program loop: 40 if sq(1)<128 then gosub 70 ' play next note if channel is inactive 50 goto 40 60 ' play next note 70 read n 80 if n<0 then end 90 note=note+1 100 ' calculation from chapter 7, page 26 of the CPC manual: 110 f=440*(2^((n-10)/12)) 120 p=round(62500/f) 130 print mid$("cdefgabc",note,1),round(f,2),p 140 sound 1,p,100 150 return 160 data 1,3,5,6,8,10,12,13,-1
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.
#C.2B.2B
C++
#include <iostream> #include <boost/tokenizer.hpp> #include <string>   int main( ) { std::string str( "a!===b=!=c" ) , output ; typedef boost::tokenizer<boost::char_separator<char> > tokenizer ; boost::char_separator<char> separator ( "==" , "!=" ) , sep ( "!" ) ; tokenizer mytok( str , separator ) ; tokenizer::iterator tok_iter = mytok.begin( ) ; for ( ; tok_iter != mytok.end( ) ; ++tok_iter ) output.append( *tok_iter ) ; tokenizer nexttok ( output , sep ) ; for ( tok_iter = nexttok.begin( ) ; tok_iter != nexttok.end( ) ; ++tok_iter ) std::cout << *tok_iter << " " ; std::cout << '\n' ; return 0 ; }
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Python
Python
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]   def isPrime(n): if n < 2: return False   for i in primes: if n == i: return True if n % i == 0: return False if i * i > n: return True print "Oops,", n, " is too large"   def init(): s = 24 while s < 600: if isPrime(s - 1) and s - 1 > primes[-1]: primes.append(s - 1) if isPrime(s + 1) and s + 1 > primes[-1]: primes.append(s + 1) s += 6   def nsmooth(n, size): if n < 2 or n > 521: raise Exception("n") if size < 1: raise Exception("n")   bn = n ok = False for prime in primes: if bn == prime: ok = True break if not ok: raise Exception("must be a prime number: n")   ns = [0] * size ns[0] = 1   next = [] for prime in primes: if prime > bn: break next.append(prime)   indicies = [0] * len(next) for m in xrange(1, size): ns[m] = min(next) for i in xrange(0, len(indicies)): if ns[m] == next[i]: indicies[i] += 1 next[i] = primes[i] * ns[indicies[i]]   return ns   def main(): init()   for p in primes: if p >= 30: break print "The first", p, "-smooth numbers are:" print nsmooth(p, 25) print   for p in primes[1:]: if p >= 30: break print "The 3000 to 3202", p, "-smooth numbers are:" print nsmooth(p, 3002)[2999:] print   for p in [503, 509, 521]: print "The 30000 to 3019", p, "-smooth numbers are:" print nsmooth(p, 30019)[29999:] print   main()
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
#M2000_Interpreter
M2000 Interpreter
  module namedparam (x as decimal=10, y as integer=50) { Print type$(x), x Print type$(y), y } namedparam 10, 20 namedparam  ?, ? Push 1, 2 : namedparam Stack New { \\ it is empty namedparam namedparam  %y=500 namedparam  %x=20 } namedparam %x=1, %y=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
#Maple
Maple
f := proc(a, {b:= 1, c:= 1}) print (a*(c+b)); end proc: #a is a mandatory positional parameter, b and c are optional named parameters f(1);#you must have a value for a for the procedure to work 2 f(1, c = 1, b = 2); 3 f(2, b = 5, c = 3);#b and c can be put in any order 16
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.
#Haskell
Haskell
n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n)
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.
#BQN
BQN
Nth ← { sfx ← ⟨"th","st","nd","rd"⟩ (•Fmt 𝕩)∾sfx⊑˜ (1≠10|⌊𝕩÷10)×(3≥10|𝕩)×10|𝕩 }   ∘‿4⥊ Nth¨ (↕26) ∾ (250+↕16) ∾ (1000+↕26)
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Ring
Ring
  mobStr = " . "   for i = 1 to 200 if mobius(i) >= 0 mobStr + = " " ok temp = string(mobius(i)) if left(temp,2) = "-0" temp = right(temp,len(temp)-1) ok mobStr += temp + " " if i % 10 = 9 see mobStr + nl mobStr = " " ok next   func mobius(n) if n = 1 return 1 ok for d = 2 to ceil(sqrt(n)) if n % d = 0 if n % (d*d) = 0 return 0 ok return -mobius(n/d) ok next return -1  
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Ruby
Ruby
require 'prime'   def μ(n) pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end   ([" "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }    
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Scala
Scala
object NaturalSorting { implicit object ArrayOrdering extends Ordering[Array[String]] { // 4 val INT = "([0-9]+)".r def compare(a: Array[String], b: Array[String]) = { val l = Math.min(a.length, b.length) (0 until l).prefixLength(i => a(i) equals b(i)) match { case i if i == l => Math.signum(b.length - a.length).toInt case i => (a(i), b(i)) match { case (INT(c), INT(d)) => Math.signum(c.toInt - d.toInt).toInt case (c, d) => c compareTo d } } } }   def natural(s: String) = { val replacements = Map('\u00df' -> "ss", '\u017f' -> "s", '\u0292' -> "s").withDefault(s => s.toString) // 8 import java.text.Normalizer Normalizer.normalize(Normalizer.normalize( s.trim.toLowerCase, // 1.1, 1.2, 3 Normalizer.Form.NFKC), // 7 Normalizer.Form.NFD).replaceAll("[\\p{InCombiningDiacriticalMarks}]", "") // 6 .replaceAll("^(the|a|an) ", "") // 5 .flatMap(replacements.apply) // 8 .split(s"\\s+|(?=[0-9])(?<=[^0-9])|(?=[^0-9])(?<=[0-9])") // 1.3, 2 and 4 } }   object NaturalSortingTest extends App { import NaturalSorting._   val tests = List( ("1 Ignoring leading spaces", List("ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"), List(" ignore leading spaces: 2+0", " ignore leading spaces: 2+1", " ignore leading spaces: 2-1", "ignore leading spaces: 2-2")), ("1 Ignoring multiple adjacent spaces (m.a.s)", List("ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"), List("ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2-2")), ("2 Equivalent whitespace characters", List("Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\u000cspaces: 3-1", "Equiv.\u000bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"), List("Equiv.\u000bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2", "Equiv.\u000cspaces: 3-1", "Equiv.\rspaces: 3-2", "Equiv. spaces: 3-3")), ("3 Case Independent sort", List("cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"), List("casE INDEPENENT: 3+0", "case INDEPENENT: 3+1", "caSE INDEPENENT: 3-1", "cASE INDEPENENT: 3-2")), ("4 Numeric fields as numerics", List("foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"), List("foo100bar10baz0.txt", "foo100bar99baz0.txt", "foo1000bar99baz9.txt", "foo1000bar99baz10.txt")), ("5 Title sorts", List("The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"), List("The 39 steps", "The 40th step more", "Wanda", "The Wind in the Willows")), ("6 Equivalent accented characters (and case)", List("Equiv. \u00fd accents: 2-2", "Equiv. \u00dd accents: 2-1", "Equiv. y accents: 2+0", "Equiv. Y accents: 2+1"), List("Equiv. y accents: 2+0", "Equiv. Y accents: 2+1", "Equiv. \u00dd accents: 2-1", "Equiv. \u00fd accents: 2-2")), ("7 Separated ligatures", List("\u0132 ligatured ij", "no ligature"), List("\u0132 ligatured ij", "no ligature")), ("8 Character replacements", List("Start with an \u0292: 2-2", "Start with an \u017f: 2-1", "Start with an \u00df: 2+0", "Start with an s: 2+1"), List("Start with an s: 2+1", "Start with an \u017f: 2-1", "Start with an \u0292: 2-2", "Start with an \u00df: 2+0")) )   val width = tests.flatMap(_._2).map(_.length).max assert(tests.forall{case (title, input, expected) => val result = input.sortBy(natural) val okay = result == expected val label = if (okay) "pass" else "fail" println(s"$label: $title".toUpperCase) input.zip(result).foreach{case (a, b) => println(s" ${a.padTo(width, ' ')} | ${b.padTo(width, ' ')}")} okay }) }
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.
#Maple
Maple
#converts a number to a given based represented by a string to_base := proc(num, based) local i; local chart := "0123456789abcdefghijklmnopqrstuvwxyz"; local conversion := ListTools:-Reverse((convert(num,base,based))); local str := StringTools:-StringBuffer(); for i in conversion do str:-append(chart[i+1]); end do; return str; end proc:   #find the location of char in chart find_digit := proc(char) if (StringTools:-HasAlpha(char)) then return (StringTools:-Ord(char) - 87); else return (StringTools:-Ord(char) - 48); end if; end proc:   #converts a string with given base to a number from_base := proc(str, base) local char; local result := 0; for char in str do result *= base; result += find_digit(char); end do; return result; end proc:
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
IntegerString[26,16] FromDigits["1a", 16])
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.
#Forth
Forth
   : dig.num \ returns input number and the number of its digits ( n -- n n1 ) dup 0 swap begin swap 1 + swap dup 10 >= while 10 / repeat drop ;    : zero.divmod \ /mod that returns zero if number is zero dup 0 = if drop 0 else /mod then ;    : zero.div \ division that returns zero if divisor is zero dup 0 = if drop else / then ;    : next.last depth 2 - roll ; \ gets next-to-last number from the stack    : ten.to \ ( n -- 10^n ) returns 1 for zero and negative dup 0 <= if drop 1 else dup 1 = if drop 10 else 10 swap 1 do 10 * loop then then ;    : split.div \ returns input number and its digits ( n -- n n1 n2 n3....) dup 10 < if dup else \ duplicates single digit numbers dig.num \ provides number of digits swap dup rot dup 1 - ten.to swap \ stack juggling, ten raised to number of digits - 1... 1 do \ ... is the needed divisor, counter on top and ... dup rot swap zero.divmod swap rot 10 / \ ...division loop loop drop then ;    : to.pow \ nth power of positive numbers ( n m -- n^m ) swap dup rot dup 0 <= if 2drop drop 1 else 0 do swap dup rot * loop swap zero.div then ;    : num.pow \ raises each digit to the power of (number of digits) depth 1 - 0 do next.last depth 1 - to.pow loop ;    : add.num depth 2 > if begin + depth 2 = until then ;    : narc.check split.div num.pow add.num ;    : narc.num 0 { a b } \ ( m -- n1 n2 n3 ... nm ) page \ displays m narcissistic decimal numbers... 999999999 0 do \ ...beginning with 0 a b = if leave then i narc.check = if i . cr b 1 + to b then loop  ;   25 narc.num  
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.
#FreeBASIC
FreeBASIC
' normal version: 14-03-2017 ' compile with: fbc -s console ' can go up to 18 digits (ulongint is 64bit), above 18 overflow will occur   Dim As Integer n, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, a, b Dim As Integer d() Dim As ULongInt d2pow(0 To 9) = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} Dim As ULongInt x Dim As String str_x   For n = 1 To 7 For n9 = n To 0 Step -1 For n8 = n-n9 To 0 Step -1 For n7 = n-n9-n8 To 0 Step -1 For n6 = n-n9-n8-n7 To 0 Step -1 For n5 = n-n9-n8-n7-n6 To 0 Step -1 For n4 = n-n9-n8-n7-n6-n5 To 0 Step -1 For n3 = n-n9-n8-n7-n6-n5-n4 To 0 Step -1 For n2 = n-n9-n8-n7-n6-n5-n4-n3 To 0 Step -1 For n1 = n-n9-n8-n7-n6-n5-n4-n3-n2 To 0 Step -1 n0 = n-n9-n8-n7-n6-n5-n4-n3-n2-n1   x = n1 + n2*d2pow(2) + n3*d2pow(3) + n4*d2pow(4) + n5*d2pow(5)_ + n6*d2pow(6) + n7*d2pow(7) + n8*d2pow(8) + n9*d2pow(9)   str_x = Str(x) If Len(str_x) = n Then   ReDim d(10) For a = 0 To n-1 d(Str_x[a]- Asc("0")) += 1 Next a   If n0 = d(0) AndAlso n1 = d(1) AndAlso n2 = d(2) AndAlso n3 = d(3)_ AndAlso n4 = d(4) AndAlso n5 = d(5) AndAlso n6 = d(6)_ AndAlso n7 = d(7) AndAlso n8 = d(8) AndAlso n9 = d(9) Then Print x End If End If   Next n1 Next n2 Next n3 Next n4 Next n5 Next n6 Next n7 Next n8 Next n9   For a As Integer = 2 To 9 d2pow(a) = d2pow(a) * a Next a   Next n   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep 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.
#Haskell
Haskell
import qualified Data.ByteString as BY (writeFile, pack)   import Data.Bits (xor)   main :: IO () main = BY.writeFile "out.pgm" (BY.pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [ x `xor` y | x <- [0 .. 255] , y <- [0 .. 255] ]))
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main(A) #: XOR graphic wsize := 512 cmax := 32768 wparms := ["Xmas Xor Graphic","g",sprintf("size=%d,%d",wsize),"bg=black"] &window := open!wparms | stop("Unable to open window")   every y := 0 to wsize - 1 do every x := 0 to wsize - 1 do { c := cmax/wsize * iand(wsize-1,ixor(x,y)) Fg(sprintf("%d,%d,%d",c,cmax-c,0)) DrawPoint(x,y) }   until Event() == &lpress # wait for left button to quit close(&window) end
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#AutoHotkey
AutoHotkey
Loop, 5000 { Loop, Parse, A_Index var += A_LoopField**A_LoopField if (var = A_Index) num .= var "`n" var := 0 } Msgbox, %num%
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).
#AWK
AWK
cat mutual_recursion.awk: #!/usr/local/bin/gawk -f   # User defined functions function F(n) { return n == 0 ? 1 : n - M(F(n-1)) }   function M(n) { return n == 0 ? 0 : n - F(M(n-1)) }   BEGIN { for(i=0; i <= 20; i++) { printf "%3d ", F(i) } print "" for(i=0; i <= 20; i++) { printf "%3d ", M(i) } print "" }
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.
#Lua
Lua
c = string.char midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) -- header midi = midi .. "MTrk" .. c(0,0,0,8*8+4) -- track for _,note in ipairs{60,62,64,65,67,69,71,72} do midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0) -- notes end midi = midi .. c(0, 0xFF, 0x2F, 0) -- end   file = io.open("scale.mid", "wb") file:write(midi) file:close()   -- (optional: hex dump to screen) midi:gsub(".", function(c) io.write(string.format("%02X ", string.byte(c))) end)
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.
#CoffeeScript
CoffeeScript
  multi_split = (text, separators) -> # Split text up, using separators to break up text and discarding # separators. # # Returns an array of strings, which can include empty strings when # separators are found either adjacent to each other or at the # beginning/end of the text. # # Separators have precedence, according to their order in the array, # and each separator should be at least one character long. result = [] i = 0 s = '' while i < text.length found = false for separator in separators if text.substring(i, i + separator.length) == separator found = true i += separator.length result.push s s = '' break if !found s += text[i] i += 1 result.push s result   console.log multi_split 'a!===b=!=c', ['==', '!=', '='] # [ 'a', '', 'b', '', 'c' ] console.log multi_split '', ['whatever'] # [ '' ]  
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Quackery
Quackery
  [ behead 0 swap rot witheach [ 2dup < iff drop done nip nip i^ 1+ swap ] ] is smallest ( [ --> n n )   [ stack ] is end.test ( --> s )   [ ]'[ end.test put dup temp put ' [ 1 ] 0 rot size of [ over end.test share do if done [] unrot dup dip [ witheach [ dip dup peek temp share i^ peek * rot swap join swap ] ] rot smallest dip [ 2dup peek 1+ unrot poke ] rot swap over -1 peek over = iff drop else join swap again ] drop end.test release temp release ] is smoothwith ( [ --> [ )   [ ' [ 2 3 5 7 11 13 17 19 23 29 ] swap split drop ] is primes ( n --> [ )   10 times [ i^ 1+ primes smoothwith [ size 25 = ] echo cr ] cr 9 times [ i^ 2 + primes smoothwith [ size 3002 = ] -3 split nip echo cr ]
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Raku
Raku
sub smooth-numbers (*@list) { cache my \Smooth := gather { my %i = (flat @list) Z=> (Smooth.iterator for ^@list); my %n = (flat @list) Z=> 1 xx *;   loop { take my $n := %n{*}.min;   for @list -> \k { %n{k} = %i{k}.pull-one * k if %n{k} == $n; } } } }   sub abbrev ($n) { $n.chars > 50 ?? $n.substr(0,10) ~ "...({$n.chars - 20} digits omitted)..." ~ $n.substr(* - 10) !! $n }   my @primes = (2..*).grep: *.is-prime;   my $start = 3000;   for ^@primes.first( * > 29, :k ) -> $p { put join "\n", "\nFirst 25, and {$start}th through {$start+2}nd {@primes[$p]}-smooth numbers:", $(smooth-numbers(|@primes[0..$p])[^25]), $(smooth-numbers(|@primes[0..$p])[$start - 1 .. $start + 1]».&abbrev); }   $start = 30000;   for 503, 509, 521 -> $p { my $i = @primes.first( * == $p, :k ); put "\n{$start}th through {$start+19}th {@primes[$i]}-smooth numbers:\n" ~ smooth-numbers(|@primes[0..$i])[$start - 1 .. $start + 18]; }
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Options[fn]={Add->False,Offset-> 0}; fn[x_,y_,OptionsPattern[]]:=If[OptionValue[Add]==True,x+y+OptionValue[Offset],{x,y,OptionValue[Offset]}] fn[3,4,{Add->True,Offset->2}] fn[3,4,{Offset->2,Add->True}]
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
#MATLAB_.2F_Octave
MATLAB / Octave
function foo(varargin) for k= 1:2:length(varargin); switch (varargin{k}) case {'param1'} param1 = varargin{k+1}; case {'param2'} param2 = varargin{k+1}; end; end; printf('param1: %s\n',param1); printf('param2: %s\n',param2); end;   foo('param1','a1','param2','b2'); foo('param2','b2','param1','a1');
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.
#HicEst
HicEst
WRITE(Messagebox) NthRoot(5, 34) WRITE(Messagebox) NthRoot(10, 7131.5^10)   FUNCTION NthRoot(n, A) REAL :: prec = 0.001   IF( (n > 0) * (A > 0) ) THEN NthRoot = A / n DO i = 1, 1/prec x = ((n-1)*NthRoot + A/(NthRoot^(n-1))) / n IF( ABS(x - NthRoot) <= prec ) THEN RETURN ENDIF NthRoot = x ENDDO ENDIF   WRITE(Messagebox, Name) 'Cannot solve problem for:', prec, n, A 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.
#C
C
#include <stdio.h>   char* addSuffix(int num, char* buf, size_t len) { char *suffixes[4] = { "th", "st", "nd", "rd" }; int i;   switch (num % 10) { case 1 : i = (num % 100 == 11) ? 0 : 1; break; case 2 : i = (num % 100 == 12) ? 0 : 2; break; case 3 : i = (num % 100 == 13) ? 0 : 3; break; default: i = 0; };   snprintf(buf, len, "%d%s", num, suffixes[i]); return buf; }   int main(void) { int i;   printf("Set [0,25]:\n"); for (i = 0; i < 26; i++) { char s[5]; printf("%s ", addSuffix(i, s, 5)); } putchar('\n');   printf("Set [250,265]:\n"); for (i = 250; i < 266; i++) { char s[6]; printf("%s ", addSuffix(i, s, 6)); } putchar('\n');   printf("Set [1000,1025]:\n"); for (i = 1000; i < 1026; i++) { char s[7]; printf("%s ", addSuffix(i, s, 7)); } putchar('\n');   return 0; }
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Sidef
Sidef
say moebius(53) #=> -1 say moebius(54) #=> 0 say moebius(55) #=> 1
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Tiny_BASIC
Tiny BASIC
PRINT "Enter an integer" INPUT N IF N < 0 THEN LET N = -N IF N < 2 THEN GOTO 100 + N LET C = 1 LET F = 2 10 IF ((N/F)/F)*F*F = N THEN GOTO 100 IF (N/F)*F = N THEN GOTO 30 20 LET F = F + 1 IF F<=N THEN GOTO 10 GOTO 100 + C 30 LET N = N / F LET C = -C GOTO 20 99 PRINT "-1" END 100 PRINT "0" END 101 PRINT "1" END
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int   var isSquareFree = Fn.new { |n| var i = 2 while (i * i <= n) { if (n%(i*i) == 0) return false i = (i > 2) ? i + 2 : i + 1 } return true }   var mu = Fn.new { |n| if (n < 1) Fiber.abort("Argument must be a positive integer") if (n == 1) return 1 var sqFree = isSquareFree.call(n) var factors = Int.primeFactors(n) if (sqFree && factors.count % 2 == 0) return 1 if (sqFree) return -1 return 0 }   System.print("The first 199 Möbius numbers are:") for (i in 0..9) { for (j in 0..19) { if (i == 0 && j == 0) { System.write(" ") } else { System.write("%(Fmt.dm(3, mu.call(i*20 + j))) ") } } System.print() }
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme write) (only (srfi 1) drop take-while) (only (srfi 13) string-drop string-join string-prefix-ci? string-tokenize) (srfi 132))     ;; Natural sort function (define (natural-sort lst) ; <1><2> ignores leading, trailing and multiple adjacent spaces ; by tokenizing on whitespace (all whitespace characters), ; and joining with a single space (define (ignore-spaces str) (string-join (string-tokenize str) " ")) ; <5> Remove articles from string (define (drop-articles str) (define (do-drop articles str) (cond ((null? articles) str) ((string-prefix-ci? (car articles) str) (string-drop str (string-length (car articles)))) (else (do-drop (cdr articles) str)))) (do-drop '("a " "an " "the ") str)) ; <4> split string into number/non-number groups (define (group-digits str) (let loop ((chars (string->list str)) (doing-num? (char-numeric? (string-ref str 0))) (groups '())) (if (null? chars) (map (lambda (s) ; convert numbers to actual numbers (if (char-numeric? (string-ref s 0)) (string->number s) s)) (map list->string groups)) ; leave groups in reverse, as right-most significant (let ((next-group (take-while (if doing-num? char-numeric? (lambda (c) (not (char-numeric? c)))) chars))) (loop (drop chars (length next-group)) (not doing-num?) (cons next-group groups)))))) ; (list-sort (lambda (a b) ; implements the numeric fields comparison <4> (let loop ((lft (group-digits (drop-articles (ignore-spaces a)))) (rgt (group-digits (drop-articles (ignore-spaces b))))) (cond ((null? lft) ; a is shorter #t) ((null? rgt) ; b is shorter #f) ((equal? (car lft) (car rgt)) ; if equal, look at next pair (loop (cdr lft) (cdr rgt))) ((and (number? (car lft)) ; compare as numbers (number? (car rgt))) (< (car lft) (car rgt))) ((and (string? (car lft)) ; compare as strings (string? (car rgt))) (string-ci<? (car lft) (car rgt))) ; <3> ignoring case ((and (number? (car lft)) ; strings before numbers (string? (car rgt))) #f) ((and (string? (car lft)) ; strings before numbers (number? (car rgt))) #t)))) lst))   ;; run string examples (define (display-list title lst) (display title) (newline) (display "[\n") (for-each (lambda (i) (display i)(newline)) lst) (display "]\n"))   (for-each (lambda (title example) (display title) (newline) (display-list "Text strings:" example) (display-list "Normally sorted:" (list-sort string<? example)) (display-list "Naturally sorted:" (natural-sort example)) (newline)) '("# Ignoring leading spaces" "# Ignoring multiple adjacent spaces (m.a.s.)" "# Equivalent whitespace characters" "# Case Independent sort" "# Numeric fields as numerics" "# Numeric fields as numerics - shows sorting from right" "# Title sorts") '(("ignore leading spaces: 2-2" " ignore leading spaces: 2-1" " ignore leading spaces: 2+0" " ignore leading spaces: 2+1") ("ignore m.a.s spaces: 2-2" "ignore m.a.s spaces: 2-1" "ignore m.a.s spaces: 2+0" "ignore m.a.s spaces: 2+1") ("Equiv. spaces: 3-3" "Equiv.\rspaces: 3-2" "Equiv.\x0c;spaces: 3-1" "Equiv.\x0b;spaces: 3+0" "Equiv.\nspaces: 3+1" "Equiv.\tspaces: 3+2") ("cASE INDEPENDENT: 3-2" "caSE INDEPENDENT: 3-1" "casE INDEPENDENT: 3+0" "case INDEPENDENT: 3+1") ("foo100bar99baz0.txt" "foo100bar10baz0.txt" "foo1000bar99baz10.txt" "foo1000bar99baz9.txt") ("foo1bar99baz4.txt" "foo2bar99baz3.txt" "foo4bar99baz1.txt" "foo3bar99baz2.txt") ("The Wind in the Willows" "The 40th step more" "The 39 steps" "Wanda")))  
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.
#MATLAB_.2F_Octave
MATLAB / Octave
dec2base(26,16) base2dec('1a', 16)
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.
#FunL
FunL
def narcissistic( start ) = power = 1 powers = array( 0..9 )   def narc( n ) = num = n.toString() m = num.length()   if power != m power = m powers( 0..9 ) = [i^m | i <- 0..9]   if n == sum( powers(int(d)) | d <- num ) n # narc( n + 1 ) else narc( n + 1 )   narc( start )   println( narcissistic(0).take(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.
#J
J
require 'viewmat' viewmat ~:"1/&.#: ~ i.256
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.
#Java
Java
import java.awt.Color; import java.awt.Graphics;   import javax.swing.JFrame; import javax.swing.JPanel;   public class XorPattern extends JFrame{ private JPanel xorPanel;   public XorPattern(){ xorPanel = new JPanel(){ @Override public void paint(Graphics g) { for(int y = 0; y < getHeight();y++){ for(int x = 0; x < getWidth();x++){ g.setColor(new Color(0, (x ^ y) % 256, 0)); g.drawLine(x, y, x, y); } } } }; add(xorPanel); setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }   public static void main(String[] args){ new XorPattern(); } }
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
#AWK
AWK
  # syntax: GAWK -f MUNCHAUSEN_NUMBERS.AWK BEGIN { for (i=1; i<=5000; i++) { sum = 0 for (j=1; j<=length(i); j++) { digit = substr(i,j,1) sum += digit ^ digit } if (i == sum) { printf("%d\n",i) } } exit(0) }  
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#BaCon
BaCon
' Mutually recursive FUNCTION F(int n) TYPE int RETURN IIF(n = 0, 1, n - M(F(n -1))) END FUNCTION   FUNCTION M(int n) TYPE int RETURN IIF(n = 0, 0, n - F(M(n - 1))) END FUNCTION   ' Get iteration limit, default 20 SPLIT ARGUMENT$ BY " " TO arg$ SIZE args limit = IIF(args > 1, VAL(arg$[1]), 20)   FOR i = 0 TO limit PRINT F(i) FORMAT "%2d " NEXT PRINT FOR i = 0 TO limit PRINT M(i) FORMAT "%2d " NEXT PRINT
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.
#M2000_Interpreter
M2000 Interpreter
  Module checkit { \\ using internal speaker TUNE 300, "C3DEFGABC4" TUNE 300, "C3C#DD#EFF#GG#AA#BC4" Thread { score 10, 100, "CAC" Play 10, 1 } as drums interval 1000 \\ Play in background (16 scores - no 10 for drum machine) SCORE 1, 300, "C3DEFGABC4" PLAY 1, 19 ' use score 1 with organ 19 Wait 2400 } checkit  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
EmitSound@Sound[SoundNote /@ {0, 2, 4, 5, 7, 9, 11, 12}]
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.
#D
D
import std.stdio, std.array, std.algorithm;   string[] multiSplit(in string s, in string[] divisors) pure nothrow { string[] result; auto rest = s.idup;   while (true) { bool done = true; string delim; { string best; foreach (const div; divisors) { const maybe = rest.find(div); if (maybe.length > best.length) { best = maybe; delim = div; done = false; } } } result.length++; if (done) { result.back = rest.idup; return result; } else { const t = rest.findSplit(delim); result.back = t[0].idup; rest = t[2]; } } }   void main() { "a!===b=!=c" .multiSplit(["==", "!=", "="]) .join(" {} ") .writeln; }
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
#11l
11l
-V BoardSize = 8   F underAttack(col, queens) I col C queens R 1B L(x) queens I abs(col - x) == queens.len - L.index R 1B R 0B   F solve(n) V result = [[Int]()] [[Int]] newSolutions L(row) 1 .. n L(solution) result L(i) 1 .. BoardSize I !underAttack(i, solution) newSolutions.append(solution [+] [i]) swap(&result, &newSolutions) newSolutions.clear() R result   print(‘Solutions for a chessboard of size ’String(BoardSize)‘x’String(BoardSize)) print()   L(answer) solve(BoardSize) L(col) answer V row = L.index I row > 0 print(‘ ’, end' ‘’) print(Char(code' ‘a’.code + row)‘’col, end' ‘’) print(end' I L.index % 4 == 3 {"\n"} E ‘ ’)
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#REXX
REXX
/*REXX pgm computes&displays X n-smooth numbers; both X and N can be specified as ranges*/ numeric digits 200 /*be able to handle some big numbers. */ parse arg LOx HIx LOn HIn . /*obtain optional arguments from the CL*/ if LOx=='' | LOx=="," then LOx= 1 /*Not specified? Then use the default.*/ if HIx=='' | HIx=="," then HIx= LOx + 24 /* " " " " " " */ if LOn=='' | LOn=="," then LOn= 2 /* " " " " " " */ if HIn=='' | HIn=="," then HIn= LOn + 27 /* " " " " " " */ call genP HIn /*generate enough primes to satisfy HIn*/ @aList= ' a list of the '; @thru= ' through ' /*literals used with a SAY.*/   do j=LOn to HIn; if !.j==0 then iterate /*if not prime, then skip this number. */ call smooth HIx,j; $= /*invoke SMOOTH; initialize $ (list). */ do k=LOx to HIx; $= $ #.k /*append a smooth number to " " " */ end /*k*/ say center(@aList th(LOx) @thru th(HIx) ' numbers for' j"-smooth ", 130, "═") say strip($); say end /*j*/ /* [↑] the $ list has a leading blank.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: procedure expose @. !. #; parse arg x /*#≡num of primes; @. ≡array of primes.*/ @.=; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23; #=9  !.=0;  !.2=1; !.3=2; !.5=3; !.7=4; !.11=5; !.13=6; !.17=7; !.19=8; !.23=9 do k=@.#+6 by 2 until #>=x ; if k//3==0 then iterate parse var k '' -1 _; if _==5 then iterate do d=4 until @.d**2>k; if k//@.d==0 then iterate k end /*d*/ #= # + 1;  !.k= #; @.#= k /*found a prime, bump counter; assign @*/ end /*k*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ smooth: procedure expose @. !. #.; parse arg y,p /*obtain the arguments from the invoker*/ if p=='' then p= 3 /*Not specified? Then assume Hamming #s*/ n= !.p /*the number of primes being used. */ nn= n - 1; #.= 0; #.1= 1 /*an array of n-smooth numbers (so far)*/ f.= 1 /*the indices of factors of a number. */ do j=2 for y-1; _= f.1 z= @.1 * #._ do k=2 for nn; _= f.k; v= @.k * #._; if v<z then z= v end /*k*/ #.j= z do d=1 for n; _= f.d; if @.d * #._==z then f.d= f.d + 1 end /*d*/ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ th: parse arg th; return th || word('th st nd rd', 1+(th//10)*(th//100%10\==1)*(th//10<4))
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
#Modula-3
Modula-3
PROCEDURE Foo(Arg1: INTEGER; Arg2: REAL := 0.0);
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Nemerle
Nemerle
Foo(number : int, word = "Default", option = true) : void // note type inference with default values   Foo(word = "Bird", number = 3) // an argument with a default value can be omitted from function call Foo(3, option = false, word = "Bird") // unnamed arguments must be in same order as function definition and precede named arguments  
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
#Nim
Nim
proc subtract(x, y): auto = x - y   echo subtract(5, 3) # used as positional parameters echo subtract(y = 3, x = 5) # used as named parameters
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() showroot(125,3) showroot(27,3) showroot(1024,10) showroot(39.0625,4) showroot(7131.5^10,10) end   procedure showroot(a,n) printf("%i-th root of %i = %i\n",n,a,root(a,n)) end   procedure root(a,n,p) #: finds the n-th root of the number a to precision p if n < 0 | type(n) !== "integer" then runerr(101,n) if a < 0 then runerr(205,a) /p := 1e-14 # precision xn := a / real(n) # initial guess while abs(a - xn^n) > p do xn := ((n - 1) * (xi := xn) + a / (xi ^ (n-1))) / real(n) return xn end   link printf
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#C.23
C#
using System; using System.Linq;   class Program { private static string Ordinalize(int i) { i = Math.Abs(i);   if (new[] {11, 12, 13}.Contains(i%100)) return i + "th";   switch (i%10) { case 1: return i + "st"; case 2: return i + "nd"; case 3: return i + "rd"; default: return i + "th"; } }   static void Main() { Console.WriteLine(string.Join(" ", Enumerable.Range(0, 26).Select(Ordinalize))); Console.WriteLine(string.Join(" ", Enumerable.Range(250, 16).Select(Ordinalize))); Console.WriteLine(string.Join(" ", Enumerable.Range(1000, 26).Select(Ordinalize))); } }
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#XPL0
XPL0
func Mobius(N); int N, Cnt, F, K; [Cnt:= 0; F:= 2; K:= 0; repeat if rem(N/F) = 0 then [Cnt:= Cnt+1; N:= N/F; K:= K+1; if K >= 2 then return 0; ] else [F:= F+1; K:= 0]; until F > N; return if Cnt&1 then -1 else 1; ];   int N; [Format(3, 0); Text(0, " "); for N:= 1 to 199 do [RlOut(0, float(Mobius(N))); if rem(N/20) = 19 then CrLf(0); ]; ]
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#Yabasic
Yabasic
outstr$ = " . " for i = 1 to 200 if mobius(i) >= 0 then outstr$ = outstr$ + " " : fi outstr$ = outstr$ + str$(mobius(i)) + " " if mod(i, 10) = 9 then print outstr$ outstr$ = "" end if next i end   sub mobius(n) if n = 1 then return 1 : fi for d = 2 to int(sqr(n)) if mod(n, d) = 0 then if mod(n, (d*d)) = 0 then return 0 : fi return -mobius(n/d) end if next d return -1 end sub
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n: μ(1) is defined to be 1. μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. μ(n) = 0 if n has a squared prime factor. Task Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) See also Wikipedia: Möbius function Related Tasks Mertens function
#zkl
zkl
fcn mobius(n){ pf:=primeFactors(n); sq:=pf.filter1('wrap(f){ (n % (f*f))==0 }); // False if square free if(sq==False){ if(pf.len().isEven) 1 else -1 } else 0 } fcn primeFactors(n){ // Return a list of prime factors of n acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum if(n==1 or k>maxD) acc.close(); else{ q,r:=n.divr(k); // divr-->(quotient,remainder) if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt())); return(self.fcn(n,k+1+k.isOdd,acc,maxD)) # both are tail recursion } }(n,2,Sink(List),n.toFloat().sqrt()); m:=acc.reduce('*,1); // mulitply factors if(n!=m) acc.append(n/m); // opps, missed last factor else acc; }
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Sidef
Sidef
class String { # Sort groups of digits in number order. Sort by order of magnitude then lexically. -> naturally { self.lc.gsub(/(\d+)/, {|s1| "0" + s1.len.chr + s1 }) + "\x0" + self };   # Collapse multiple ws characters to a single. -> collapse { self.gsub(/(\s)\1+/, {|s1| s1 }) };   # Convert all ws characters to a space. -> normalize { self.gsub(/(\s)/, ' ') };   # Ignore common leading articles for title sorts -> title { self.sub(/^(?:a|an|the)\b\s*/i, '') };   # Decompose ISO-Latin1 glyphs to their base character. -> latin1_decompose { static tr = Hash.new(%w( Æ AE æ ae Þ TH þ th Ð TH ð th ß ss À A Á A Â A Ã A Ä A Å A à a á a â a ã a ä a å a Ç C ç c È E É E Ê E Ë E è e é e ê e ë e Ì I Í I Î I Ï I ì i í i î i ï i Ò O Ó O Ô O Õ O Ö O Ø O ò o ó o ô o õ o ö o ø o Ñ N ñ n Ù U Ú U Û U Ü U ù u ú u û u ü u Ý Y ÿ y ý y )...);   var re = Regex.new('(' + tr.keys.join('|') + ')'); self.gsub(re, {|s1| tr{s1} }); } }
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.
#.D0.9C.D0.9A-61.2F52
МК-61/52
П8 -> 1 0 П0 ПП 13 ИП7 П0 ИП8 ПП 13 С/П П7 -> П6 -> 1 П4 П5 Сx <-> ^ ПП 68 П3 - ИП7 * П2 ПП 68 ИП4 ИП6 * П4 / + ИП2 ИП1 - x#0 45 L0 27 -> ИП3 ^ ИП7 / ПП 68 ИП7 * - ИП5 * + ИП5 ИП6 * П5 -> ИП1 x=0 47 -> В/О 1 + П1 КИП1 -> -> ИП1 В/О
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func narc(n int) []int { power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} limit := 10 result := make([]int, 0, n) for x := 0; len(result) < n; x++ { if x >= limit { for i := range power { power[i] *= i // i^m } limit *= 10 } sum := 0 for xx := x; xx > 0; xx /= 10 { sum += power[xx%10] } if sum == x { result = append(result, x) } } return result }   func main() { fmt.Println(narc(25)) }
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#jq
jq
jq -n -r -f Munching_squares.jq > Munching_squares.svg
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.
#Julia
Julia
using Gtk, Cairo   const can = @GtkCanvas() const win = GtkWindow(can, "Munching Squares", 512, 512)   @guarded draw(can) do widget ctx = getgc(can) for x in 0:255, y in 0:255 set_source_rgb(ctx, abs(255 - x - y) / 255, ((255 - x) ⊻ y) / 255, (x ⊻ (255 - y)) / 255) circle(ctx, 2x, 2y, 2) fill(ctx) end end   show(can) const cond = Condition() endit(w) = notify(cond) signal_connect(endit, win, :destroy) wait(cond)  
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
#BASIC
BASIC
10 DEF FN P(X)=INT(X^X*SGN(X)) 20 FOR I=0 TO 5 30 FOR J=0 TO 5 40 FOR K=0 TO 5 50 FOR L=0 TO 5 60 M=FN P(I)+FN P(J)+FN P(K)+FN P(L) 70 N=1000*I+100*J+10*K+L 80 IF M=N AND M>0 THEN PRINT M 90 NEXT L 100 NEXT K 110 NEXT J 120 NEXT 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).
#BASIC
BASIC
DECLARE FUNCTION f! (n!) DECLARE FUNCTION m! (n!)   FUNCTION f! (n!) IF n = 0 THEN f = 1 ELSE f = m(f(n - 1)) END IF END FUNCTION   FUNCTION m! (n!) IF n = 0 THEN m = 0 ELSE m = f(m(n - 1)) END IF END FUNCTION
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Nanoquery
Nanoquery
import tonegen   note_freqs = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}   tg = new(tonegen) for freq in note_freqs tg.beep(freq) end