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/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
#FreeBASIC
FreeBASIC
Dim Shared foo As Long, bar As Integer, baz As Byte, qux As String 'la función Sub LoqueSea(foo As Long, bar As Integer, baz As Byte, qux As String) '... End Sub   'llamando a la función Sub Algo() LoqueSea(bar = 1, baz = 2, foo = -1, qux = "Probando") End Sub
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Erlang
Erlang
fixed_point(F, Guess, Tolerance) -> fixed_point(F, Guess, Tolerance, F(Guess)). fixed_point(_, Guess, Tolerance, Next) when abs(Guess - Next) < Tolerance -> Next; fixed_point(F, _, Tolerance, Next) -> fixed_point(F, Next, Tolerance, F(Next)).
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.
#AWK
AWK
  # syntax: GAWK -f NTH.AWK BEGIN { prn(0,25) prn(250,265) prn(1000,1025) exit(0) } function prn(start,stop, i) { printf("%d-%d: ",start,stop) for (i=start; i<=stop; i++) { printf("%d%s ",i,nth(i)) } printf("\n") } function nth(yearday, nthday) { if (yearday ~ /1[1-3]$/) { # 11th,12th,13th nthday = "th" } else if (yearday ~ /1$/) { # 1st,21st,31st,etc. nthday = "st" } else if (yearday ~ /2$/) { # 2nd,22nd,32nd,etc. nthday = "nd" } else if (yearday ~ /3$/) { # 3rd,23rd,33rd,etc. nthday = "rd" } else if (yearday ~ /[0456789]$/) { # 4th-10th,20th,24th-30th,etc. nthday = "th" } return(nthday) }  
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
#J
J
mu=: ({{*/1-y>1}} * _1 ^ 2|+/)@q:~&_
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
#Java
Java
  public class MöbiusFunction {   public static void main(String[] args) { System.out.printf("First 199 terms of the möbius function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", möbiusFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } }   private static int MU_MAX = 1_000_000; private static int[] MU = null;   // Compute mobius function via sieve private static int möbiusFunction(int n) { if ( MU != null ) { return MU[n]; }   // Populate array MU = new int[MU_MAX+1]; int sqrt = (int) Math.sqrt(MU_MAX); for ( int i = 0 ; i < MU_MAX ; i++ ) { MU[i] = 1; }   for ( int i = 2 ; i <= sqrt ; i++ ) { if ( MU[i] == 1 ) { // for each factor found, swap + and - for ( int j = i ; j <= MU_MAX ; j += i ) { MU[j] *= -i; } // square factor = 0 for ( int j = i*i ; j <= MU_MAX ; j += i*i ) { MU[j] = 0; } } }   for ( int i = 2 ; i <= MU_MAX ; i++ ) { if ( MU[i] == i ) { MU[i] = 1; } else if ( MU[i] == -i ) { MU[i] = -1; } else if ( MU[i] < 0 ) { MU[i] = 1; } else if ( MU[i] > 0 ) { MU[i] = -1; } } return MU[n]; }   }  
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']
#Perl
Perl
  use feature 'fc'; use Unicode::Normalize;   sub natural_sort { my @items = map { my $str = fc(NFKD($_)); $str =~ s/\s+/ /; $str =~ s/|^(?:the|a|an) \b|\p{Nonspacing_Mark}| $//g; my @fields = $str =~ /(?!\z) ([^0-9]*+) ([0-9]*+)/gx; [$_, \@fields] } @_; return map { $_->[0] } sort { my @x = @{$a->[1]}; my @y = @{$b->[1]}; my $numeric; while (@x && @y) { my ($x, $y) = (shift @x, shift @y); return (($numeric = !$numeric) ? $x cmp $y : $x <=> $y or next); } return @x <=> @y; } @items; }  
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
#Scheme
Scheme
(define (ncsubseq lst) (let recurse ((s 0) (lst lst)) (if (null? lst) (if (>= s 3) '(()) '()) (let ((x (car lst)) (xs (cdr lst))) (if (even? s) (append (map (lambda (ys) (cons x ys)) (recurse (+ s 1) xs)) (recurse s xs)) (append (map (lambda (ys) (cons x ys)) (recurse s xs)) (recurse (+ s 1) xs)))))))
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.
#jq
jq
# Convert the input integer to a string in the specified base (2 to 36 inclusive) def convert(base): def stream: recurse(if . > 0 then ./base|floor else empty end) | . % base ; if . == 0 then "0" else [stream] | reverse | .[1:] | if base < 10 then map(tostring) | join("") elif base <= 36 then map(if . < 10 then 48 + . else . + 87 end) | implode else error("base too large") end end;   # input string is converted from "base" to an integer, within limits # of the underlying arithmetic operations, and without error-checking: def to_i(base): explode | reverse | map(if . > 96 then . - 87 else . - 48 end) # "a" ~ 97 => 10 ~ 87 | reduce .[] as $c # state: [power, ans] ([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)]) | .[1];
http://rosettacode.org/wiki/Negative_base_numbers
Negative base numbers
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the decimal number 146 as negaternary (expect 21102) Encode the decimal number 15 as negadecimal (expect 195) In each of the above cases, convert the encoded number back to decimal. extra credit supply an integer, that when encoded to base   -62   (or something "higher"),   expresses the name of the language being used   (with correct capitalization).   If the computer language has non-alphanumeric characters,   try to encode them into the negatory numerals,   or use other characters instead.
#Wren
Wren
import "/fmt" for Fmt   var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"   var encodeNegBase = Fn.new { |n, b| if (b < -62 || b > -1) Fiber.abort("Base must be between -1 and -62") if (n == 0) return "0" var out = "" while (n != 0) { var rem = n % b n = (n/b).truncate if (rem < 0) { n = n + 1 rem = rem -b } out = out + digits[rem] } return out[-1..0] }   var decodeNegBase = Fn.new { |ns, b| if (b < -62 || b > -1) Fiber.abort("Base must be between -1 and -62") if (ns == "0") return 0 var total = 0 var bb = 1 for (c in ns[-1..0]) { total = total + digits.indexOf(c)*bb bb = bb * b } return total }   var nbl = [ [10, -2], [146, -3], [15, -10], [-7425195, -62] ] for (p in nbl) { var ns = encodeNegBase.call(p[0], p[1]) Fmt.print("$8d encoded in base $-3d = $s", p[0], p[1], ns) var n = decodeNegBase.call(ns, p[1]) Fmt.print("$8s decoded in base $-3d = $d\n", ns, p[1], n) }
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To win every time,   the second player simply takes 4 minus the number the first player took.   So if the first player takes 1,   the second takes 3 ─── if the first player takes 2,   the second should take 2 ─── and if the first player takes 3,   the second player will take 1. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#Wren
Wren
import "io" for Stdin, Stdout   var showTokens = Fn.new { |tokens| System.print("Tokens remaining %(tokens)\n") }   var tokens = 12 while (true) { showTokens.call(tokens) System.write(" How many tokens 1, 2 or 3? ") Stdout.flush() var t = Num.fromString(Stdin.readLine()) if (t.type != Num || !t.isInteger || t < 1 || t > 3) { System.print("\nMust be an integer between 1 and 3, try again.\n") } else { var ct = 4 - t var s = (ct != 1) ? "s" : "" System.write(" Computer takes %(ct) token%(s)\n\n") tokens = tokens - 4 } if (tokens == 0) { showTokens.call(0) System.print(" Computer wins!") break } }
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.
#C.2B.2B
C++
  #include <iostream> #include <vector> using namespace std; typedef unsigned int uint;   class NarcissisticDecs { public: void makeList( int mx ) { uint st = 0, tl; int pwr = 0, len; while( narc.size() < mx ) { len = getDigs( st ); if( pwr != len ) { pwr = len; fillPower( pwr ); } tl = 0; for( int i = 1; i < 10; i++ ) tl += static_cast<uint>( powr[i] * digs[i] );   if( tl == st ) narc.push_back( st ); st++; } }   void display() { for( vector<uint>::iterator i = narc.begin(); i != narc.end(); i++ ) cout << *i << " "; cout << "\n\n"; }   private: int getDigs( uint st ) { memset( digs, 0, 10 * sizeof( int ) ); int r = 0; while( st ) { digs[st % 10]++; st /= 10; r++; } return r; }   void fillPower( int z ) { for( int i = 1; i < 10; i++ ) powr[i] = pow( static_cast<float>( i ), z ); }   vector<uint> narc; uint powr[10]; int digs[10]; };   int main( int argc, char* argv[] ) { NarcissisticDecs n; n.makeList( 25 ); n.display(); return system( "pause" ); }  
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.
#C.23
C#
using System.Drawing; using System.Drawing.Imaging; using System.Linq;   class XORPattern { static void Main() { var size = 0x100; var black = Color.Black.ToArgb(); var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray(); using (var image = new Bitmap(size, size)) { for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { image.SetPixel(x, y, palette[x ^ y]); } } image.Save("XORPatternCSharp.png", ImageFormat.Png); } } }
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
#8080_Assembly
8080 Assembly
putch: equ 2 ; CP/M syscall to print character puts: equ 9 ; CP/M syscall to print string org 100h lxi b,0500h ; B C D E hold 4 digits of number lxi d,0000h ; we work backwards from 5000 lxi h,-5000 ; HL holds negative binary representation of number test: push h ; Keep current number push d ; Keep last two digits (to use DE as scratch register) push h ; Keep current number (to test against) lxi h,0 ; Digit power sum = 0 mov a,b call addap mov a,c call addap mov a,d call addap mov a,e call addap xra a ; Correct for leading zeroes ora b jnz calc dcx h ora c jnz calc dcx h ora d jnz calc dcx h calc: pop d ; Load current number (as negative) into DE dad d ; Add to sum of digits (if equal, should be 0) mov a,h ; See if they are equal ora l pop d ; Restore last two digits pop h ; Restore current number jnz next ; If not equal, this is not a Munchhausen number mov a,b ; Otherwise, print the number call pdgt mov a,c call pdgt mov a,d call pdgt mov a,e call pdgt call pnl next: inx h ; Increment negative binary representation mvi a,5 dcr e ; Decrement last digit jp test ; If not negative, try next number mov e,a ; Otherwise, set to 5, inx h ; Add 4 extra to HL, inx h inx h inx h dcr d jp test mov d,a push d ; Add 40 extra to HL, lxi d,40 dad d pop d dcr c jp test mov c,a push d ; Add 400 extra to HL, lxi d,400 dad d pop d dcr b jp test ret ; When B<0, we're done ;;; Print A as digit pdgt: adi '0' push b ; Save all registers (CP/M tramples them) push d push h mov e,a ; Print character mvi c,putch call 5 restor: pop h ; Restore registers pop d pop b ret ;;; Print newline pnl: push b ; Save all registers push d push h lxi d,nl ; Print newline mvi c,puts call 5 jmp restor ; Restore registers nl: db 13,10,'$' ;;; Add A^A to HL addap: push d ; Keep DE push h ; Keep HL add a ; A *= 2 (entries are 2 bytes wide) mvi d,0 ; DE = lookup table index mov e,a lxi h,dpow ; Calculate table address dad d mov e,m ; Load low byte into E inx h mov d,m ; Load high byte into D pop h ; Retrieve old HL dad d ; Add power pop d ; Restore DE ret dpow: dw 1,1,4,27,256,3125 ; 0^0 to 5^5 lookup table
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).
#Aime
Aime
integer F(integer n); integer M(integer n);   integer F(integer n) { integer r; if (n) { r = n - M(F(n - 1)); } else { r = 1; } return r; }   integer M(integer n) { integer r; if (n) { r = n - F(M(n - 1)); } else { r = 0; } return r; }   integer main(void) { integer i; i = 0; while (i < 20) { o_winteger(3, F(i)); i += 1; } o_byte('\n'); i = 0; while (i < 20) { o_winteger(3, M(i)); i += 1; } o_byte('\n'); return 0; }
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Clojure
Clojure
(use 'overtone.live)   ; Define your desired instrument ; Using saw-wave from: https://github.com/overtone/overtone/wiki/Chords-and-scales (definst saw-wave [freq 440 attack 0.01 sustain 0.4 release 0.1 vol 0.4] (* (env-gen (env-lin attack sustain release) 1 1 0 1 FREE) (saw freq) vol))   (defn play [note ms] (saw-wave (midi->hz note)) (Thread/sleep ms))   (doseq [note (scale :c4 :major)] (play note 500))
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#Commodore_BASIC
Commodore BASIC
10 rem musical scale 15 rem rosetta code 20 print chr$(147) 25 s=54272 30 for l=s to s+23:poke l,0:next 35 poke s+5,9:poke s+6,0 40 poke s+24,15 45 for i=1 to 8 50 read fq 60 ff=int(fq/.06097) 65 fh=int(ff/256):fl=ff-(256*fh) 70 poke s+1,fh:poke s,fl 75 poke s+4,17 80 for d=1 to 350:next 85 poke s+4,16 90 for d=1 to 25:next 95 next i 500 data 261.63,293.66,329.63,349.23,392,440,493.88,523.25
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.
#Ada
Ada
with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Text_IO;   procedure Multisplit is package String_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (Element_Type => String); use type String_Lists.Cursor;   function Split (Source  : String; Separators : String_Lists.List) return String_Lists.List is Result  : String_Lists.List; Next_Position  : Natural := Source'First; Prev_Position  : Natural := Source'First; Separator_Position : String_Lists.Cursor; Separator_Length  : Natural; Changed  : Boolean; begin loop Changed  := False; Separator_Position := Separators.First; while Separator_Position /= String_Lists.No_Element loop Separator_Length := String_Lists.Element (Separator_Position)'Length; if Next_Position + Separator_Length - 1 <= Source'Last and then Source (Next_Position .. Next_Position + Separator_Length - 1) = String_Lists.Element (Separator_Position) then if Next_Position > Prev_Position then Result.Append (Source (Prev_Position .. Next_Position - 1)); end if; Result.Append (String_Lists.Element (Separator_Position)); Next_Position := Next_Position + Separator_Length; Prev_Position := Next_Position; Changed  := True; exit; end if; Separator_Position := String_Lists.Next (Separator_Position); end loop; if not Changed then Next_Position := Next_Position + 1; end if; if Next_Position > Source'Last then Result.Append (Source (Prev_Position .. Source'Last)); exit; end if; end loop; return Result; end Split;   Test_Input  : constant String := "a!===b=!=c"; Test_Separators : String_Lists.List; Test_Result  : String_Lists.List; Pos  : String_Lists.Cursor; begin Test_Separators.Append ("=="); Test_Separators.Append ("!="); Test_Separators.Append ("="); Test_Result := Split (Test_Input, Test_Separators); Pos  := Test_Result.First; while Pos /= String_Lists.No_Element loop Ada.Text_IO.Put (" " & String_Lists.Element (Pos)); Pos := String_Lists.Next (Pos); end loop; Ada.Text_IO.New_Line; -- other order of separators Test_Separators.Clear; Test_Separators.Append ("="); Test_Separators.Append ("!="); Test_Separators.Append ("=="); Test_Result := Split (Test_Input, Test_Separators); Pos  := Test_Result.First; while Pos /= String_Lists.No_Element loop Ada.Text_IO.Put (" " & String_Lists.Element (Pos)); Pos := String_Lists.Next (Pos); end loop; end Multisplit;
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
#J
J
  nsmooth=: dyad define NB. TALLY nsmooth N factors=. x: i.@:>:&.:(p:inv) y smoothies=. , 1x result=. , i. 0x while. x > # result do. mn =. {. smoothies smoothies =. ({.~ (x <. #)) ~. /:~ (}. smoothies) , mn * factors result=. result , mn end. )  
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
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.List;   public class NSmoothNumbers {   public static void main(String[] args) { System.out.printf("show the first 25 n-smooth numbers for n = 2 through n = 29%n"); int max = 25; List<BigInteger> primes = new ArrayList<>(); for ( int n = 2 ; n <= 29 ; n++ ) { if ( isPrime(n) ) { primes.add(BigInteger.valueOf(n)); System.out.printf("The first %d %d-smooth numbers:%n", max, n); BigInteger[] humble = nSmooth(max, primes.toArray(new BigInteger[0])); for ( int i = 0 ; i < max ; i++ ) { System.out.printf("%s ", humble[i]); } System.out.printf("%n%n"); } }   System.out.printf("show three numbers starting with 3,000 for n-smooth numbers for n = 3 through n = 29%n"); int count = 3; max = 3000 + count - 1; primes = new ArrayList<>(); primes.add(BigInteger.valueOf(2)); for ( int n = 3 ; n <= 29 ; n++ ) { if ( isPrime(n) ) { primes.add(BigInteger.valueOf(n)); System.out.printf("The %d through %d %d-smooth numbers:%n", max-count+1, max, n); BigInteger[] nSmooth = nSmooth(max, primes.toArray(new BigInteger[0])); for ( int i = max-count ; i < max ; i++ ) { System.out.printf("%s ", nSmooth[i]); } System.out.printf("%n%n"); } }   System.out.printf("Show twenty numbers starting with 30,000 n-smooth numbers for n=503 through n=521%n"); count = 20; max = 30000 + count - 1; primes = new ArrayList<>(); for ( int n = 2 ; n <= 521 ; n++ ) { if ( isPrime(n) ) { primes.add(BigInteger.valueOf(n)); if ( n >= 503 && n <= 521 ) { System.out.printf("The %d through %d %d-smooth numbers:%n", max-count+1, max, n); BigInteger[] nSmooth = nSmooth(max, primes.toArray(new BigInteger[0])); for ( int i = max-count ; i < max ; i++ ) { System.out.printf("%s ", nSmooth[i]); } System.out.printf("%n%n"); } } }   }   private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; }   private static BigInteger[] nSmooth(int n, BigInteger[] primes) { int size = primes.length; BigInteger[] test = new BigInteger[size]; for ( int i = 0 ; i < size ; i++ ) { test[i] = primes[i]; } BigInteger[] results = new BigInteger[n]; results[0] = BigInteger.ONE;   int[] indexes = new int[size]; for ( int i = 0 ; i < size ; i++ ) { indexes[i] = 0; }   for ( int index = 1 ; index < n ; index++ ) { BigInteger min = test[0]; for ( int i = 1 ; i < size ; i++ ) { min = min.min(test[i]); } results[index] = min;   for ( int i = 0 ; i < size ; i++ ) { if ( results[index].compareTo(test[i]) == 0 ) { indexes[i] = indexes[i] + 1; test[i] = primes[i].multiply(results[indexes[i]]); } } } return results; }   }  
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
#Go
Go
package main   import ( "fmt" )   type params struct {x, y, z int}   func myFunc(p params) int { return p.x + p.y + p.z }   func main() { r := myFunc(params{x: 1, y: 2, z: 3}) // all fields, same order fmt.Println("r =", r) s := myFunc(params{z: 3, y: 2, x: 1}) // all fields, different order fmt.Println("s =", s) t := myFunc(params{y: 2}) // only one field, others set to zero fmt.Println("t =", t) }
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.
#Excel
Excel
=A1^(1/B1)
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.
#F.23
F#
  let nthroot n A = let rec f x = let m = n - 1. let x' = (m * x + A/x**m) / n match abs(x' - x) with | t when t < abs(x * 1e-9) -> x' | _ -> f x' f (A / double n)   [<EntryPoint>] let main args = if args.Length <> 2 then eprintfn "usage: nthroot n A" exit 1 let (b, n) = System.Double.TryParse(args.[0]) let (b', A) = System.Double.TryParse(args.[1]) if (not b) || (not b') then eprintfn "error: parameter must be a number" exit 1 printf "%A" (nthroot n A) 0  
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.
#Babel
Babel
((irregular ("st" "nd" "rd"))   (main {(0 250 1000) { test ! "\n" << } each})   (test { <- {iter 1 - -> dup <- + ordinalify ! << {iter 10 %} {" "} {"\n"} ifte << } 26 times})   (ordinalify { <- {{ -> dup <- 100 % 10 cugt } ! { -> dup <- 100 % 14 cult } ! and not { -> dup <- 10  % 0 cugt } ! { -> dup <- 10  % 4 cult } ! and and} { -> dup <- %d "'" irregular -> 10 % 1 - ith . . } { -> %d "'th" . } ifte }))
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
#jq
jq
# Input: a non-negative integer, $n # Output: an array of size $n + 1 such that the nth-mobius number is .[$n] # i.e. $n|mobius_array[-1] # For example, the first mobius number could be evaluated by 1|mobius_array[-1]. def mobius_array: . as $n | ($n|sqrt) as $sqrt | reduce range(2; 1 + $sqrt) as $i ([range(0; $n + 1) | 1]; if .[$i] == 1 then # for each factor found, swap + and - reduce range($i; $n + 1; $i) as $j (.; .[$j] *= -$i) | ($i*$i) as $isq # square factor = 0 | reduce range($isq; $n + 1; $isq) as $j (.; .[$j] = 0 ) else . end ) | reduce range(2; 1 + $n) as $i (.; if .[$i] == $i then .[$i] = 1 elif .[$i] == -$i then .[$i] = -1 elif .[$i] < 0 then .[$i] = 1 elif .[$i] > 0 then .[$i] = -1 else .[$i] = 0 # avoid "-0" end);   # For one-off computations: def mu($n): $n | mobius_array[-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
#Julia
Julia
using Primes   # modified from reinermartin's PR at https://github.com/JuliaMath/Primes.jl/pull/70/files function moebius(n::Integer) @assert n > 0 m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0 reduce(*, m(p, e) for (p, e) in factor(n) if p ≥ 0; init=1) end μ(n) = moebius(n)   print("First 199 terms of the Möbius sequence:\n ") for n in 1:199 print(lpad(μ(n), 3), n % 20 == 19 ? "\n" : "") 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
#Kotlin
Kotlin
import kotlin.math.sqrt   fun main() { println("First 199 terms of the möbius function are as follows:") print(" ") for (n in 1..199) { print("%2d ".format(mobiusFunction(n))) if ((n + 1) % 20 == 0) { println() } } }   private const val MU_MAX = 1000000 private var MU: IntArray? = null   // Compute mobius function via sieve private fun mobiusFunction(n: Int): Int { if (MU != null) { return MU!![n] }   // Populate array MU = IntArray(MU_MAX + 1) val sqrt = sqrt(MU_MAX.toDouble()).toInt() for (i in 0 until MU_MAX) { MU!![i] = 1 } for (i in 2..sqrt) { if (MU!![i] == 1) { // for each factor found, swap + and - for (j in i..MU_MAX step i) { MU!![j] *= -i } // square factor = 0 for (j in i * i..MU_MAX step i * i) { MU!![j] = 0 } } } for (i in 2..MU_MAX) { when { MU!![i] == i -> { MU!![i] = 1 } MU!![i] == -i -> { MU!![i] = -1 } MU!![i] < 0 -> { MU!![i] = 1 } MU!![i] > 0 -> { MU!![i] = -1 } } } return MU!![n] }
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']
#Phix
Phix
-- -- demo/rosetta/Natural_sorting2.exw -- function utf32ch(sequence s) for i=1 to length(s) do s[i] = utf8_to_utf32(s[i])[1] end for return s end function constant common = {"the","it","to","a","of","is"}, {al,ac_replacements} = columnize({ {"Æ","AE"},{"æ","ae"},{"Þ","TH"},{"þ","th"}, {"Ð","TH"},{"ð","th"},{"ß","ss"},{"�","fi"}, {"�","fl"},{"�",'s'},{"’",'z'}, {"À",'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'}}), accents_and_ligatures = utf32ch(al) function normalise(string s) sequence utf32 = utf8_to_utf32(s) sequence res = {} integer i = 1, ch, prev for i=1 to length(utf32) do ch = utf32[i] if find(ch," \t\r\n\x0b\x0c") then if length(res)>0 and prev!=' ' then res &= -1 end if prev = ' ' elsif find(ch,"0123456789") then if length(res)=0 or prev!='0' then res &= ch-'0' else res[$] = res[$]*10+ch-'0' end if prev = '0' else object rep = find(ch,accents_and_ligatures) if rep then rep = lower(ac_replacements[rep]) else rep = lower(ch) end if if length(res) and sequence(res[$]) then res[$] &= rep else res = append(res,""&rep) end if prev = ch end if end for for i=1 to length(common) do while 1 do integer k = find(common[i],res) if k=0 then exit end if res[k..k] = {} if length(res) and res[1]=-1 then res = res[2..$] end if end while end for if length(res) and prev=' ' then res = res[1..$-1] end if return res end function sequence tests = { {" leading spaces: 4", " leading spaces: 3", "leading spaces: 2", " leading spaces: 1"}, {"adjacent spaces: 3", "adjacent spaces: 4", "adjacent spaces: 1", "adjacent spaces: 2"}, {"white space: 3-2", "white\r space: 3-3", "white\x0cspace: 3-1", "white\x0bspace: 3+0", "white\n space: 3+1", "white\t space: 3+2"}, {"caSE independent: 3-1", "cASE independent: 3-2", "casE independent: 3+0", "case independent: 3+1"}, {"foo1000bar99baz9.txt", "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt"}, {"foo1bar", "foo100bar", "foo bar", "foo1000bar"}, {"The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"}, {"ignore ý accents: 2-2", "ignore Ý accents: 2-1", "ignore y accents: 2+0", "ignore Y accents: 2+1"}, {"Ball","Card","above","aether", "apple","autumn","außen","bald", "car","e-mail","evoke","nina", "niño","Æon","Évian","æon"}, } sequence s, n, t, tags function natural(integer i, integer j) return compare(t[i],t[j]) end function for i=1 to length(tests) do s = tests[i] n = sort(s) t = repeat(0,length(s)) for j=1 to length(s) do t[j] = normalise(s[j]) end for tags = custom_sort(routine_id("natural"),tagset(length(s))) if i=3 then -- clean up the whitespace mess for j=1 to length(s) do s[j] = substitute_all(s[j],{"\r","\x0c","\x0b","\n","\t"},{"\\r","\\x0c","\\x0b","\\n","\\t"}) n[j] = substitute_all(n[j],{"\r","\x0c","\x0b","\n","\t"},{"\\r","\\x0c","\\x0b","\\n","\\t"}) end for end if printf(1,"%-30s %-30s %-30s\n",{"original","normal","natural"}) printf(1,"%-30s %-30s %-30s\n",{"========","======","======="}) for k=1 to length(tags) do printf(1,"%-30s|%-30s|%-30s\n",{s[k],n[k],s[tags[k]]}) end for puts(1,"\n") end for
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const func array bitset: ncsub (in bitset: seq, in integer: s) is func result var array bitset: subseq is 0 times {}; local var bitset: x is {}; var bitset: xs is {}; var bitset: ys is {}; begin if seq <> {} then x := {min(seq)}; xs := seq - x; for ys range ncsub(xs, s + 1 - s rem 2) do subseq &:= x | ys; end for; subseq &:= ncsub(xs, s + s rem 2); elsif s >= 3 then subseq &:= {}; end if; end func;   const proc: main is func local var bitset: seq is {}; begin for seq range ncsub({1, 2, 3, 4}, 0) do writeln(seq); end for; end func;
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.
#Julia
Julia
  @show string(185, base=2) @show string(185, base=3) @show string(185, base=4) @show string(185, base=5) @show string(185, base=6) @show string(185, base=7) @show string(185, base=8) @show string(185, base=9) @show string(185, base=10) @show string(185, base=11) @show string(185, base=12) @show string(185, base=13) @show string(185, base=14) @show string(185, base=15) @show string(185, base=16)  
http://rosettacode.org/wiki/Negative_base_numbers
Negative base numbers
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the decimal number 146 as negaternary (expect 21102) Encode the decimal number 15 as negadecimal (expect 195) In each of the above cases, convert the encoded number back to decimal. extra credit supply an integer, that when encoded to base   -62   (or something "higher"),   expresses the name of the language being used   (with correct capitalization).   If the computer language has non-alphanumeric characters,   try to encode them into the negatory numerals,   or use other characters instead.
#zkl
zkl
fcn toNBase(n,radix){ var [const] cs=[0..9].chain(["a".."z"]).pump(String); //"0123456789abcd..z" _assert_(-37 < radix < -1,"invalid radix"); digits:=List(); while(n){ reg r; n,r=n.divr(radix); // C compiler semantics if(r<0){ n+=1; r-=radix; } digits.append(r); } digits.reverse().pump(String,cs.get); }   fcn toInt(str,radix){ // the toInt(radix) method radix is 2..36 str.reduce('wrap(s,d,rdx){ s*radix + d.toInt(rdx); },0,radix.abs()); }
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.
#Clojure
Clojure
  (ns narcissistic.core (:require [clojure.math.numeric-tower :as math]))   (defn digits [n] ;; digits of a number. (->> n str (map (comp read-string str))))   (defn narcissistic? [n] ;; True if the number is a Narcissistic one. (let [d (digits n) s (count d)] (= n (reduce + (map #(math/expt % s) d)))))   (defn firstNnarc [n] ;;list of the first "n" Narcissistic numbers. (take n (filter narcissistic? (range))))  
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.
#C.2B.2B
C++
  #include <windows.h> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 512;   //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h; return true; }   void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); }   void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); }   void setPenColor( DWORD c ) { clr = c; createPen(); }   void setPenWidth( int w ) { wid = w; createPen(); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];   ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); }   HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; //-------------------------------------------------------------------------------------------------- class mSquares { public: mSquares() { bmp.create( BMP_SIZE, BMP_SIZE ); createPallete(); }   void draw() { HDC dc = bmp.getDC(); for( int y = 0; y < BMP_SIZE; y++ ) for( int x = 0; x < BMP_SIZE; x++ ) { int c = ( x ^ y ) % 256; SetPixel( dc, x, y, clrs[c] ); }   BitBlt( GetDC( GetConsoleWindow() ), 30, 30, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); //bmp.saveBitmap( "f:\\rc\\msquares_cpp.bmp" ); }   private: void createPallete() { for( int x = 0; x < 256; x++ ) clrs[x] = RGB( x<<1, x, x<<2 );//rand() % 180 + 50, rand() % 200 + 50, rand() % 180 + 50 ); }   unsigned int clrs[256]; myBitmap bmp; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() ); mSquares s; s.draw(); return system( "pause" ); } //--------------------------------------------------------------------------------------------------  
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
#Action.21
Action!
;there are considered digits 0-5 because 6^6>5000 DEFINE MAXDIGIT="5" INT ARRAY powers(MAXDIGIT+1)   INT FUNC Power(BYTE x) INT res BYTE i   IF x=0 THEN RETURN (0) FI res=1 FOR i=0 TO x-1 DO res==*x OD RETURN (res)   BYTE FUNC IsMunchausen(INT x) INT sum,tmp BYTE d   tmp=x sum=0 WHILE tmp#0 DO d=tmp MOD 10 IF d>MAXDIGIT THEN RETURN (0) FI sum==+powers(d) tmp==/10 OD IF sum=x THEN RETURN (1) FI RETURN (0)   PROC Main() INT i   FOR i=0 TO MAXDIGIT DO powers(i)=Power(i) OD FOR i=1 TO 5000 DO IF IsMunchausen(i) THEN PrintIE(i) FI OD RETURN
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).
#ALGOL_68
ALGOL 68
PROC (INT)INT m; # ONLY required for ELLA ALGOL 68RS - an official subset OF full ALGOL 68 #   PROC f = (INT n)INT: IF n = 0 THEN 1 ELSE n - m(f(n-1)) FI;   m := (INT n)INT: IF n = 0 THEN 0 ELSE n - f(m(n-1)) FI;   main: ( FOR i FROM 0 TO 19 DO print(whole(f(i),-3)) OD; new line(stand out); FOR i FROM 0 TO 19 DO print(whole(m(i),-3)) OD; new line(stand out) )
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.
#Delphi
Delphi
  program Musical_scale;   {$APPTYPE CONSOLE}   uses Winapi.Windows;   var notes: TArray<Double> = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25];   begin for var note in notes do Beep(Round(note), 500); readln; 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.
#EasyLang
EasyLang
n[] = [ 262 294 330 349 392 440 494 523 ] for i range len n[] sound [ n[i] 0.5 ] sleep 0.6 .
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.
#ALGOL_68
ALGOL 68
# split a string based on a number of separators #   # MODE to hold the split results # MODE SPLITINFO = STRUCT( STRING text # delimited string, may be empty # , INT position # starting position of the token # , STRING delimiter # the delimiter that terminated the token # ); # calculates the length of string s # OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s; # returns TRUE if s starts with p, FALSE otherwise # PRIO STARTSWITH = 5; OP STARTSWITH = ( STRING s, p )BOOL: IF LENGTH p > LENGTH s THEN FALSE ELSE s[ LWB s : ( LWB s + LENGTH p ) - 1 ] = p FI; # returns an array of SPLITINFO describing the tokens in str based on the delimiters # # zero-length delimiters are ignored # PRIO SPLIT = 5; OP SPLIT = ( STRING str, []STRING delimiters )[]SPLITINFO: BEGIN # count the number of tokens # # allow there to be as many tokens as characters in the string + 2 # # that would cater for a string composed of delimiters only # [ 1 : ( UPB str + 3 ) - LWB str ]SPLITINFO tokens; INT token count := 0; INT str pos := LWB str; INT str max = UPB str; BOOL token pending := FALSE; # construct the tokens # str pos := LWB str; INT prev pos := LWB str; token count := 0; token pending := FALSE; WHILE str pos <= str max DO BOOL found delimiter := FALSE; FOR d FROM LWB delimiters TO UPB delimiters WHILE NOT found delimiter DO IF LENGTH delimiters[ d ] > 0 THEN IF found delimiter := str[ str pos : ] STARTSWITH delimiters[ d ] THEN token count +:= 1; tokens[ token count ] := ( str[ prev pos : str pos - 1 ], prev pos, delimiters[ d ] ); str pos +:= LENGTH delimiters[ d ]; prev pos := str pos; token pending := FALSE FI FI OD; IF NOT found delimiter THEN # the current character is part of s token # token pending := TRUE; str pos +:= 1 FI OD; IF token pending THEN # there is an additional token after the final delimiter # token count +:= 1; tokens[ token count ] := ( str[ prev pos : ], prev pos, "" ) FI; # return an array of the actual tokens # tokens[ 1 : token count ] END # SPLIT # ;     # test the SPLIT operator # []SPLITINFO test tokens = "a!===b=!=c" SPLIT []STRING( "==", "!=", "=" ); FOR t FROM LWB test tokens TO UPB test tokens DO SPLITINFO token = test tokens[ t ]; print( ( "token: [", text OF token, "] at: ", whole( position OF token, 0 ), " delimiter: (", delimiter OF token, ")", newline ) ) OD
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#JavaScript
JavaScript
  function isPrime(n){ var x = Math.floor(Math.sqrt(n)), i = 2   while ((i <= x) && (n % i != 0)) i++   return (x < i) }   function smooth(n, s, k){ var p = [] for (let i = 2; i <= n; i++){ if (isPrime(i)){ p.push([BigInt(i), [1n], 0]) } }   var res = [] for (let i = 0; i < s + k; i++){ var m = p[0][1][p[0][2]]   for (let j = 1; j < p.length; j++){ if (p[j][1][p[j][2]] < m) m = p[j][1][p[j][2]] }   for (let j = 0; j < p.length; j++){ p[j][1].push(p[j][0]*m) if (p[j][1][p[j][2]] == m) p[j][2]++ }   res.push(m) }   return res.slice(s-1, s-1+k); }   // main   var sOut = ""   for (let x of [[2, 29, 1, 25], [3, 29, 3000, 3], [503, 521, 30000, 20]]){ for (let n = x[0]; n <= x[1]; n++){ if (isPrime(n)){ sOut += x[2] + " to " + (x[2] - 1 + x[3]) + " " + n + "-smooth numbers: " + smooth(n, x[2], x[3]) + "\n" } } }   console.log(sOut)  
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
#Haskell
Haskell
data X = X data Y = Y data Point = Point Int Int deriving Show   createPointAt :: X -> Int -> Y -> Int -> Point createPointAt X x Y y = Point x y   main = print $ createPointAt X 5 Y 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
#Icon_and_Unicon
Icon and Unicon
procedure main() testproc("x:=",1,"y:=",2,"z:=",3) testproc("x:=",3,"y:=",1,"z:=",2) testproc("z:=",4,"x:=",2,"y:=",3) testproc("i:=",1,"y:=",2,"z:=",3) end   procedure testproc(A[]) #: demo to test named parameters write("Calling testproc")   while a := get(A) do # implement named parameters here (( a ? (v := =!["x","y","z"], =":=") | # valid parameter name? stop("No parameter ",a)) & # . . no ((variable(a[1:-2]) := get(A)) | # assign runerr(205,a))) # . . problem   write(" x:=",x) write(" y:=",y) write(" z:=",z) end
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Factor
Factor
USING: kernel locals math math.functions prettyprint ;   :: th-root ( a n -- a^1/n ) a [ a over n 1 - ^ /f over n 1 - * + n /f swap over 1e-5 ~ not ] loop ;   34 5 th-root .  ! 2.024397458499888 34 5 recip ^ .  ! 2.024397458499888
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.
#Forth
Forth
: th-root { F: a F: n -- a^1/n } a begin a fover n 1e f- f** f/ fover n 1e f- f* f+ n f/ fswap fover 1e-5 f~ until ;   34e 5e th-root f. \ 2.02439745849989 34e 5e 1/f f** f. \ 2.02439745849989
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs: 0..25, 250..265, 1000..1025 Note: apostrophes are now optional to allow correct apostrophe-less English.
#BaCon
BaCon
' Nth (sans apostrophes) FUNCTION nth$(NUMBER n) TYPE STRING LOCAL suffix IF n < 0 THEN RETURN STR$(n) IF MOD(n, 100) >= 11 AND MOD(n, 100) <= 13 THEN suffix = "th" ELSE suffix = MID$("thstndrdthththththth", MOD(n, 10) * 2 + 1, 2) ENDIF RETURN CONCAT$(STR$(n), suffix) END FUNCTION   ' Test a few ranges FOR i = 1 TO 4 READ first, last per = 1 FOR n = first TO last PRINT nth$(n) FORMAT "%s " ' limit to 10 entries per line IF per = 10 OR n = last THEN per = 1 PRINT ELSE INCR per ENDIF NEXT NEXT DATA 0, 25, 250, 265, 1000, 1025, -20, -11
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
#Lua
Lua
function buildArray(size, value) local tbl = {} for i=1, size do table.insert(tbl, value) end return tbl end   MU_MAX = 1000000 sqroot = math.sqrt(MU_MAX) mu = buildArray(MU_MAX, 1)   for i=2, sqroot do if mu[i] == 1 then -- for each factor found, swap + and - for j=i, MU_MAX, i do mu[j] = mu[j] * -i end -- square factor = 0 for j=i*i, MU_MAX, i*i do mu[j] = 0 end end end   for i=2, MU_MAX do if mu[i] == i then mu[i] = 1 elseif mu[i] == -i then mu[i] = -1 elseif mu[i] < 0 then mu[i] = 1 elseif mu[i] > 0 then mu[i] = -1 end end   print("First 199 terms of the mobius function are as follows:") io.write(" ") for i=1, 199 do io.write(string.format("%2d ", mu[i])) if (i + 1) % 20 == 0 then print() end end
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']
#PicoLisp
PicoLisp
(de parseNatural (Str) (clip (make (for (L (chop Str) L) (cond ((sp? (car L)) (link " ") (while (and L (sp? (car L))) (pop 'L) ) ) ((>= "9" (car L) "0") (link (format (make (loop (link (pop 'L)) (NIL (>= "9" (car L) "0")) ) ) ) ) ) (T (let Word (pack (replace (make (loop (link (lowc (pop 'L))) (NIL L) (T (sp? (car L))) (T (>= "9" (car L) "0")) ) ) "ß" "ss" "ſ" "s" "ʒ" "s" ) ) (unless (member Word '(the it to)) (link Word) ) ) ) ) ) ) ) )
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
#Sidef
Sidef
func non_continuous(min, max, subseq=[], has_gap=false) {   static current = [];   range(min, max).each { |i| current.push(i); has_gap && subseq.append([current...]); i < max && non_continuous(i.inc, max, subseq, has_gap); current.pop; has_gap = current.len; }   subseq; }   say non_continuous(1, 3); say non_continuous(1, 4); say non_continuous("a", "d");
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
#Standard_ML
Standard ML
fun fence s [] = if s >= 3 then [[]] else []   | fence s (x :: xs) = if s mod 2 = 0 then map (fn ys => x :: ys) (fence (s + 1) xs) @ fence s xs else map (fn ys => x :: ys) (fence s xs) @ fence (s + 1) xs   fun ncsubseq xs = fence 0 xs
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.
#Kotlin
Kotlin
// version 1.0.6   fun min(x: Int, y: Int) = if (x < y) x else y   fun convertToBase(n: Int, b: Int): String { if (n < 2 || b < 2 || b == 10 || b > 36) return n.toString() // leave as decimal val sb = StringBuilder() var digit: Int var nn = n while (nn > 0) { digit = nn % b if (digit < 10) sb.append(digit) else sb.append((digit + 87).toChar()) nn /= b } return sb.reverse().toString() }   fun convertToDecimal(s: String, b: Int): Int { if (b !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36") if (b == 10) return s.toInt() val t = s.toLowerCase() var result = 0 var digit: Int var multiplier = 1 for (i in t.length - 1 downTo 0) { digit = -1 if (t[i] >= '0' && t[i] <= min(57, 47 + b).toChar()) digit = t[i].toInt() - 48 else if (b > 10 && t[i] >= 'a' && t[i] <= min(122, 87 + b).toChar()) digit = t[i].toInt() - 87 if (digit == -1) throw IllegalArgumentException("Invalid digit present") if (digit > 0) result += multiplier * digit multiplier *= b } return result }   fun main(args: Array<String>) { for (b in 2..36) { val s = convertToBase(36, b) val f = "%2d".format(b) println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}") } }
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.
#COBOL
COBOL
  PROGRAM-ID. NARCISSIST-NUMS. DATA DIVISION. WORKING-STORAGE SECTION.   01 num-length PIC 9(2) value 0. 01 in-sum PIC 9(9) value 0. 01 counter PIC 9(9) value 0. 01 current-number PIC 9(9) value 0. 01 narcissist PIC Z(9). 01 temp PIC 9(9) value 0. 01 modulo PIC 9(9) value 0. 01 answer PIC 9 .   PROCEDURE DIVISION. MAIN-PROCEDURE. DISPLAY "the first 20 narcissist numbers:" .   MOVE 20 TO counter. PERFORM UNTIL counter=0   PERFORM 000-NARCISSIST-PARA   IF answer = 1 SUBTRACT 1 from counter GIVING counter MOVE current-number TO narcissist DISPLAY narcissist END-IF   ADD 1 TO current-number   END-PERFORM   STOP RUN.   000-NARCISSIST-PARA.   MOVE ZERO TO in-sum. MOVE current-number TO temp. COMPUTE num-length =1+ FUNCTION Log10(temp)   PERFORM UNTIL temp=0   DIVIDE temp BY 10 GIVING temp REMAINDER modulo   COMPUTE modulo=modulo**num-length ADD modulo to in-sum GIVING in-sum   END-PERFORM.   IF current-number=in-sum MOVE 1 TO answer ELSE MOVE 0 TO answer END-IF.   END PROGRAM NARCISSIST-NUMS.    
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.
#Commodore_BASIC
Commodore BASIC
100 FOR I=0 TO 24 110 : Y=INT(I*127/24) 120 : FOR J=0 TO 39 130 : X=INT(J*127/39) 140 : HL = (X OR Y) AND NOT (X AND Y) 150 : H = INT(HL / 8) 160 : L = HL - 8 * H 170 : POKE 2048+I*40+J,L*16+H 180 : POKE 3072+I*40+J,160 190 : NEXT J 210 NEXT I 220 GETKEY K$
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.
#D
D
void main() { import std.stdio;   enum width = 512, height = 512;   auto f = File("xor_pattern.ppm", "wb"); f.writefln("P6\n%d %d\n255", width, height); foreach (immutable y; 0 .. height) foreach (immutable x; 0 .. width) { immutable c = (x ^ y) & ubyte.max; immutable ubyte[3] u3 = [255 - c, c / 2, c]; f.rawWrite(u3); } }
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
#Ada
Ada
with Ada.Text_IO;   procedure Munchausen is   function Is_Munchausen (M : in Natural) return Boolean is Table : constant array (Character range '0' .. '9') of Natural := (0**0, 1**1, 2**2, 3**3, 4**4, 5**5, 6**6, 7**7, 8**8, 9**9); Image : constant String := M'Image; Sum  : Natural := 0; begin for I in Image'First + 1 .. Image'Last loop Sum := Sum + Table (Image (I)); end loop; return Image = Sum'Image; end Is_Munchausen;   begin for M in 1 .. 5_000 loop if Is_Munchausen (M) then Ada.Text_IO.Put (M'Image); end if; end loop; Ada.Text_IO.New_Line; end Munchausen;
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).
#ALGOL_W
ALGOL W
begin  % define mutually recursive funtions F and M that compute the elements  %  % of the Hofstadter Female and Male sequences  %   integer procedure F ( integer value n ) ; if n = 0 then 1 else n - M( F( n - 1 ) );   integer procedure M ( integer value n ) ; if n = 0 then 0 else n - F( M( n - 1 ) );    % print the first few elements of the sequences  % i_w := 2; s_w := 1; % set I/O formatting  % write( "F: " ); for i := 0 until 20 do writeon( F( i ) ); write( "M: " ); for i := 0 until 20 do writeon( M( i ) );   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.
#Emacs_Lisp
Emacs Lisp
(defun play-scale (freq-list dur) "Play a list of frequencies." (setq header (unibyte-string ; AU header: 46 115 110 100 ; ".snd" magic number 0 0 0 24 ; start of data bytes 255 255 255 255 ; file size is unknown 0 0 0 3 ; 16 bit PCM samples 0 0 172 68 ; 44,100 samples/s 0 0 0 1)) ; mono (setq s nil) (dolist (freq freq-list) (setq v (mapcar (lambda (x) (mod (round (* 32000 (sin (* 2 pi freq x (/ 44100.0))))) 65536)) (number-sequence 0 (* dur 44100)))) (setq s (apply #'concat s (flatten-list (mapcar (lambda (x) (list (unibyte-string (ash x -8)) (unibyte-string (mod x 256)))) v))))) (setq s (concat header s)) (play-sound `(sound :data ,s)))   (play-scale '(261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25) .5)
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.
#Arturo
Arturo
print split.by:["==" "!=" "="] "a!===b=!=c"
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#AutoHotkey
AutoHotkey
Str := "a!===b=!=c" Sep := ["==","!=", "="] Res := StrSplit(Str, Sep) for k, v in Res Out .= (Out?",":"") v MsgBox % Out for k, v in Sep N .= (N?"|":"") "\Q" v "\E" MsgBox % RegExReplace(str, "(.*?)(" N ")", "$1 {$2}")
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
#Julia
Julia
using Primes   function nsmooth(N, needed) nexts, smooths = [BigInt(i) for i in 2:N if isprime(i)], [BigInt(1)] prim, count = deepcopy(nexts), 1 indices = ones(Int, length(nexts)) while count < needed x = minimum(nexts) push!(smooths, x) count += 1 for j in 1:length(nexts) (nexts[j] <= x) && (nexts[j] = prim[j] * smooths[(indices[j] += 1)]) end end return (smooths[end] > typemax(Int)) ? smooths : Int.(smooths) end   function testnsmoothfilters() for i in filter(isprime, 1:29) println("The first 25 n-smooth numbers for n = $i are: ", nsmooth(i, 25)) end for i in filter(isprime, 3:29) println("The 3000th through 3002nd ($i)-smooth numbers are: ", nsmooth(i, 3002)[3000:3002]) end for i in filter(isprime, 503:521) println("The 30000th through 30019th ($i)-smooth numbers >= 30000 are: ", nsmooth(i, 30019)[30000:30019]) end end   testnsmoothfilters()  
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
#Kotlin
Kotlin
import java.math.BigInteger   var primes = mutableListOf<BigInteger>() var smallPrimes = mutableListOf<Int>()   // cache all primes up to 521 fun init() { val two = BigInteger.valueOf(2) val three = BigInteger.valueOf(3) val p521 = BigInteger.valueOf(521) val p29 = BigInteger.valueOf(29) primes.add(two) smallPrimes.add(2) var i = three while (i <= p521) { if (i.isProbablePrime(1)) { primes.add(i) if (i <= p29) { smallPrimes.add(i.toInt()) } } i += two } }   fun min(bs: List<BigInteger>): BigInteger { require(bs.isNotEmpty()) { "slice must have at lease one element" } val it = bs.iterator() var res = it.next() while (it.hasNext()) { val t = it.next() if (t < res) { res = t } } return res }   fun nSmooth(n: Int, size: Int): List<BigInteger> { require(n in 2..521) { "n must be between 2 and 521" } require(size >= 1) { "size must be at least 1" }   val bn = BigInteger.valueOf(n.toLong()) var ok = false for (prime in primes) { if (bn == prime) { ok = true break } } require(ok) { "n must be a prime number" }   val ns = Array<BigInteger>(size) { BigInteger.ZERO } ns[0] = BigInteger.ONE val next = mutableListOf<BigInteger>() for (i in 0 until primes.size) { if (primes[i] > bn) { break } next.add(primes[i]) } val indices = Array(next.size) { 0 } for (m in 1 until size) { ns[m] = min(next) for (i in indices.indices) { if (ns[m] == next[i]) { indices[i]++ next[i] = primes[i] * ns[indices[i]] } } }   return ns.toList() }   fun main() { init() for (i in smallPrimes) { println("The first 25 $i-smooth numbers are:") println(nSmooth(i, 25)) println() } for (i in smallPrimes.drop(1)) { println("The 3,000th to 3,202 $i-smooth numbers are:") println(nSmooth(i, 3_002).drop(2_999)) println() } for (i in listOf(503, 509, 521)) { println("The 30,000th to 30,019 $i-smooth numbers are:") println(nSmooth(i, 30_019).drop(29_999)) println() } }
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
#J
J
NB. Strand notation myFunc['c:\file.txt' 906 'blue' fs]   NB. Commas, like other langs myFunc['c:\file.txt', 906, 'blue' fs]   NB. Unspecified args are defaulted ("optional") myFunc['c:\file.txt' fs]   NB. Can use named arguments, like eg VB myFunc[color='blue' fs]   NB. Often values needn't be quoted myFunc[color= blue fs]   NB. Combination of comma syntax and name=value myFunc[max=906, color=blue fs]   NB. Spelling of names is flexible myFunc[MAX=906, COLOR=blue fs]   NB. Order of names is flexible myFunc[COLOR=blue, MAX=906 fs]   NB. Even the delimiters are flexible... myFunc<MAX=906, COLOR=blue fs>
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
#Java
Java
processNutritionFacts(new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build());
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.
#Fortran
Fortran
program NthRootTest implicit none   print *, nthroot(10, 7131.5**10) print *, nthroot(5, 34.0)   contains   function nthroot(n, A, p) real :: nthroot integer, intent(in) :: n real, intent(in) :: A real, intent(in), optional :: p   real :: rp, x(2)   if ( A < 0 ) then stop "A < 0" ! we handle only real positive numbers elseif ( A == 0 ) then nthroot = 0 return end if   if ( present(p) ) then rp = p else rp = 0.001 end if   x(1) = A x(2) = A/n ! starting "guessed" value...   do while ( abs(x(2) - x(1)) > rp ) x(1) = x(2) x(2) = ((n-1.0)*x(2) + A/(x(2) ** (n-1.0)))/real(n) end do   nthroot = x(2)   end function nthroot   end program NthRootTest
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.
#BASIC
BASIC
  function ordinal(n) ns$ = string(n) begin case case right(ns$, 1) = "1" if right(ns$, 2) = "11" then return ns$ + "th" return ns$ + "st" case right(ns$, 1) = "2" if right(ns$, 2) = "12" then return ns$ + "th" return ns$ + "nd" case right(ns$, 1) = "3" if right(ns$, 2) = "13" then return ns$ + "th" return ns$ + "rd" else return ns$ + "th" end case end function   subroutine imprimeOrdinal(a, b) for i = a to b print ordinal(i); " "; next i print end subroutine   call imprimeOrdinal (0, 25) call imprimeOrdinal (250, 265) call imprimeOrdinal (1000, 1025) 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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Grid[Partition[MoebiusMu[Range[99]], UpTo[10]]]
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
#Nim
Nim
import std/[math, sequtils, strformat]   func getStep(n: int): int {.inline.} = result = 1 + n shl 2 - n shr 1 shl 1   func primeFac(n: int): seq[int] = var maxq = int(sqrt(float(n))) d = 1 q: int = 2 + (n and 1) # Start with 2 or 3 according to oddity.   while q <= maxq and n %% q != 0: q = getStep(d) inc d if q <= maxq: let q1 = primeFac(n /% q) let q2 = primeFac(q) result = concat(q2, q1, result) else: result.add(n)   func squareFree(num: int): bool = let fact = primeFac num   for i in fact: if fact.count(i) > 1: return false   return true   func mobius(num: int): int = if num == 1: return num   let fact = primeFac num   for i in fact: ## check if it has a squared prime factor if fact.count(i) == 2: return 0   if num.squareFree: if fact.len mod 2 == 0: return 1 else: return -1   when isMainModule: echo "The first 199 möbius numbers are:"   for i in 1..199: stdout.write fmt"{mobius(i):4}" if i mod 20 == 0: echo "" # print newline  
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
#Pascal
Pascal
See Mertens_function#Pascal
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']
#PowerShell
PowerShell
  # six sorting $Discard = '^a ', '^an ', '^the ' $List = '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.`fspaces: 3-1<==", "Equiv.`vspaces: 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<==', 'Lâmpada accented characters<==', 'Lúdico accented characters<==', ' Lula Free  !!! accented characters<==', 'Amanda accented characters<==', 'Ágata accented characters<==', 'Ångström accented characters<==', 'Ângela accented characters<==', 'À toa accented characters<==', 'ânsia accented characters<==', 'álibi accented characters<==', 'foo100bar99baz0.txt<==', 'foo100bar10baz0.txt<==', 'foo1000bar99baz10.txt<==', 'foo1000bar99baz9.txt<==', 'The Wind in the Willows<==', 'The 40th step more<==', 'The 39 steps<==', 'Wanda<=='   'List index sorting' $List ' ' 'Lexicographically sorting' $List | Sort-Object ' ' 'Natural sorting' $List | Sort-Object -Property { [Regex]::Replace( ( ( & { If ($_.Trim() -match ($Discard -join '|')) { $_ -replace '^\s*[^\s]+\s*' } Else { $_.Trim() } } ) -replace '\s+' ), '\d+', { $args[0].Value.PadLeft(20) } ) }  
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
#Tcl
Tcl
proc subsets l { set res [list [list]] foreach e $l { foreach subset $res {lappend res [lappend subset $e]} } return $res } proc is_not_continuous seq { set last [lindex $seq 0] foreach e [lrange $seq 1 end] { if {$e-1 != $last} {return 1} set last $e } return 0 } proc lfilter {f list} { set res {} foreach i $list {if [$f $i] {lappend res $i}} return $res }   % lfilter is_not_continuous [subsets {1 2 3 4}] {1 3} {1 4} {2 4} {1 2 4} {1 3 4}
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.
#LFE
LFE
  > (: erlang list_to_integer '"1a" 16) 26 > #x1a 26 > (: erlang integer_to_list 26 16) "1A" > (: erlang list_to_integer '"101110111000" 2) 3000 > #b101110111000 3000 > (: erlang integer_to_list 3000 2) "101110111000"  
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.
#Common_Lisp
Common Lisp
  (defun integer-to-list (n) (map 'list #'digit-char-p (prin1-to-string n)))   (defun narcissisticp (n) (let* ((lst (integer-to-list n)) (e (length lst))) (= n (reduce #'+ (mapcar (lambda (x) (expt x e)) lst)))))   (defun start () (loop for c from 0 while (< narcissistic 25) counting (narcissisticp c) into narcissistic do (if (narcissisticp c) (print c))))  
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.
#EchoLisp
EchoLisp
  (lib 'types) (lib 'plot) (plot-size 512 512) ;; for example   ;; use m = 16, 32, 44, .. to change the definition (number of losanges) (define (plot-munch (m 256)) (define PIX (pixels->int32-vector)) ;; get canvas image (define (pcolor x y) ;; color at (x,y) (hsv->rgb (// (bitwise-xor (modulo x m) (modulo y m)) m) 0.9 0.9)) (pixels-map pcolor PIX) (vector->pixels PIX)) ;; draw canvas image   (plot-much) ;; ESC to see tge drawing  
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
#ALGOL_68
ALGOL 68
# Find Munchausen Numbers between 1 and 5000 # # note that 6^6 is 46 656 so we only need to consider numbers consisting of 0 to 5 #   # table of Nth powers - note 0^0 is 0 for Munchausen numbers, not 1 # []INT nth power = ([]INT( 0, 1, 2 * 2, 3 * 3 * 3, 4 * 4 * 4 * 4, 5 * 5 * 5 * 5 * 5 ))[ AT 0 ];   INT d1 := 0; INT d1 part := 0; INT d2 := 0; INT d2 part := 0; INT d3 := 0; INT d3 part := 0; INT d4 := 1; WHILE d1 < 6 DO INT number = d1 part + d2 part + d3 part + d4; INT digit power sum := nth power[ d1 ] + nth power[ d2 ] + nth power[ d3 ] + nth power[ d4 ]; IF digit power sum = number THEN print( ( whole( number, 0 ), newline ) ) FI; d4 +:= 1; IF d4 > 5 THEN d4 := 0; d3 +:= 1; d3 part +:= 10; IF d3 > 5 THEN d3 := 0; d3 part := 0; d2 +:= 1; d2 part +:= 100; IF d2 > 5 THEN d2 := 0; d2 part := 0; d1 +:= 1; d1 part +:= 1000; FI FI FI OD  
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).
#APL
APL
f ← {⍵=0:1 ⋄ ⍵-m∇⍵-1} m ← {⍵=0:0 ⋄ ⍵-f∇⍵-1} ⍉'nFM'⍪↑(⊢,f,m)¨0,⍳20
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.
#Forth
Forth
HEX \ PC speaker hardware control (requires giveio or DOSBOX for windows operation) 042 constant fctrl 061 constant sctrl 0FC constant smask 043 constant tctrl 0B6 constant spkr   : sing ( -- ) sctrl pc@ 03 or sctrl pc! ; : silence ( -- ) sctrl pc@ smask and 01 or sctrl pc! ;   : tone ( divisor -- )  ?dup \ check for non-zero input if spkr tctrl pc! \ enable PC speaker dup fctrl pc! \ load low byte 8 rshift fctrl pc! \ load high byte sing else silence then ;   DECIMAL 1193181. 2constant clock \ internal oscillator freq. MHz x 10   : Hz ( freq -- divisor) clock rot um/mod nip  ; \ convert Freq to osc. divisor   \ duration control variables and values variable on_time variable off_time variable feel \ controls the on/off time ratio   60 value tempo   4000 tempo um* 2constant timebase \ 1 whole note=4000 ms @ 60 Beats/min   : bpm>ms ( bpm -- ms) timebase rot um/mod nip ; \ convert beats per minute to milliseconds : wholenote ( -- ms ) tempo bpm>ms ; \ using tempo set the BPM   : play ( divisor -- ) tone on_time @ ms silence off_time @ ms ;   : expression ( ms n --) \ adjust the on:off ratio using n over swap - tuck - ( -- on-mS off-mS ) off_time ! on_time ! ; \ store times in variables   : note ( -- ms ) on_time @ off_time @ + ; \ returns duration of current note   : duration! ( ms -- ) feel @ expression ;   : 50% ( n -- n/2) 2/ ; : % ( n n2 -- n%) 100 */ ; \ calculate n2% of n : 50%+ ( n -- n+50%) dup 50% + ; \ dotted notes have 50% more time   VOCABULARY MUSIC   MUSIC DEFINITIONS : BPM ( bpm -- ) \ set tempo in beats per minute to tempo wholenote duration! ;   : legato 0 feel ! ; : staccatto note 8 % feel ! ; : Marcato note 3 % feel ! ;   : 1/1 wholenote duration! ; : 1/2 wholenote 50% duration! ; : 1/2. 1/2 note 50%+ duration! ; : 1/4 1/2 note 50% duration! ; : 1/4. 1/4 note 50%+ duration! ; : 1/8 1/4 note 50% duration! ; : 1/8. 1/8 note 50%+ duration! ; : 1/16 1/8 note 50% duration! ; : 1/32 1/16 note 50% duration! ; : rest note ms ;   \ note object creator : note: create hz , \ compile time: compile divisor into the note does> @ play ; \ run time: fetch the value and play the tone   \ freq Natural Freq Accidental En-harmonic \ ------------- ---------------- ---------------- 131 note: C3 139 note: C#3 synonym Db3 C#3 147 note: D3 156 note: D#3 synonym Eb3 D#3 165 note: E3 175 note: F3 185 note: F#3 synonym Gb3 F#3 196 note: G3 208 note: G#3 synonym Ab3 G#3 220 note: A3 233 note: A#3 synonym Bb3 A#3 247 note: B3 262 note: C4 277 note: C#4 synonym Db4 C#4   : Cmajor 1/8 C3 D3 E3 F3 G3 A3 B3 C4 ; : Chromatic 1/8 C3 C#3 D3 D#3 E3 F3 F#3 G3 G#3 A3 A#3 B3 C4 ;  
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.
#FreeBASIC
FreeBASIC
REM FreeBASIC no tiene la capacidad de emitir sonido de forma nativa. REM La función Sound no es mía, incluyo los créditos correspondientes. ' Sound Function v0.3 For DOS/Linux/Win by yetifoot ' Credits: ' http://www.frontiernet.net/~fys/snd.htm ' http://delphi.about.com/cs/adptips2003/a/bltip0303_3.htm #ifdef __FB_WIN32__ #include Once "windows.bi" #endif Sub Sound_DOS_LIN(Byval freq As Uinteger, dur As Uinteger) Dim t As Double Dim As Ushort fixed_freq = 1193181 \ freq   Asm mov dx, &H61 ' turn speaker on in al, dx or al, &H03 out dx, al mov dx, &H43 ' get the timer ready mov al, &HB6 out dx, al mov ax, word Ptr [fixed_freq] ' move freq to ax mov dx, &H42 ' port to out out dx, al ' out low order xchg ah, al out dx, al ' out high order End Asm   t = Timer While ((Timer - t) * 1000) < dur ' wait for out specified duration Sleep(1) Wend   Asm mov dx, &H61 ' turn speaker off in al, dx and al, &HFC out dx, al End Asm End Sub   Sub Sound(Byval freq As Uinteger, dur As Uinteger) #ifndef __fb_win32__ ' If not windows Then call the asm version. Sound_DOS_LIN(freq, dur) #Else ' If Windows Dim osv As OSVERSIONINFO   osv.dwOSVersionInfoSize = Sizeof(OSVERSIONINFO) GetVersionEx(@osv)   Select Case osv.dwPlatformId Case VER_PLATFORM_WIN32_NT ' If NT then use Beep from API Beep_(freq, dur) Case Else ' If not on NT then use the same as DOS/Linux Sound_DOS_LIN(freq, dur) End Select #endif End Sub   '---------- Sound(262, 250) 'C4 Sound(294, 250) 'D4 Sound(330, 250) 'E4 Sound(349, 250) 'F4 Sound(392, 250) 'G4 Sound(440, 250) 'A4 Sound(494, 250) 'B4 Sound(523, 250) 'C5 Sleep
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.
#AWK
AWK
  # syntax: GAWK -f MULTISPLIT.AWK BEGIN { str = "a!===b=!=c" sep = "(==|!=|=)" printf("str: %s\n",str) printf("sep: %s\n\n",sep) n = split(str,str_arr,sep,sep_arr) printf("parsed: ") for (i=1; i<=n; i++) { printf("'%s'",str_arr[i]) if (i<n) { printf(" '%s' ",sep_arr[i]) } } printf("\n\nstrings: ") for (i=1; i<=n; i++) { printf("'%s' ",str_arr[i]) } printf("\n\nseparators: ") for (i=1; i<n; i++) { printf("'%s' ",sep_arr[i]) } printf("\n") exit(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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[GenerateSmoothNumbers] GenerateSmoothNumbers[max_?Positive] := GenerateSmoothNumbers[max, 7] GenerateSmoothNumbers[max_?Positive, maxprime_?Positive] := Module[{primes, len, vars, body, endspecs, its, data}, primes = Prime[Range[PrimePi[maxprime]]]; len = Length[primes]; If[max < Min[primes], {} , vars = Table[Unique[], len]; body = Times @@ (primes^vars); endspecs = Prepend[Most[primes^vars], 1]; endspecs = FoldList[Times, endspecs]; its = Transpose[{vars, ConstantArray[0, len], MapThread[N@Log[#1, max/#2] &, {primes, endspecs}]}]; With[{b = body, is = its}, data = Table[b, Evaluate[Sequence @@ is]]; ]; data = Sort[Flatten[data]]; data ] ] Take[GenerateSmoothNumbers[10^8, 2], 25] Take[GenerateSmoothNumbers[200, 3], 25] Take[GenerateSmoothNumbers[200, 5], 25] Take[GenerateSmoothNumbers[200, 7], 25] Take[GenerateSmoothNumbers[200, 11], 25] Take[GenerateSmoothNumbers[200, 13], 25] Take[GenerateSmoothNumbers[200, 17], 25] Take[GenerateSmoothNumbers[200, 19], 25] Take[GenerateSmoothNumbers[200, 23], 25] Take[GenerateSmoothNumbers[200, 29], 25] Take[GenerateSmoothNumbers[10^40, 3], {3000, 3002}] Take[GenerateSmoothNumbers[10^15, 5], {3000, 3002}] Take[GenerateSmoothNumbers[10^10, 7], {3000, 3002}] Take[GenerateSmoothNumbers[10^7, 11], {3000, 3002}] Take[GenerateSmoothNumbers[10^7, 13], {3000, 3002}] Take[GenerateSmoothNumbers[10^6, 17], {3000, 3002}] Take[GenerateSmoothNumbers[10^5, 19], {3000, 3002}] Take[GenerateSmoothNumbers[10^5, 23], {3000, 3002}] Take[GenerateSmoothNumbers[10^5, 29], {3000, 3002}]   s = Select[Range[10^5], FactorInteger /* Last /* First /* LessEqualThan[503]]; s[[30000 ;; 30019]] s = Select[Range[10^5], FactorInteger /* Last /* First /* LessEqualThan[509]]; s[[30000 ;; 30019]] s = Select[Range[10^5], FactorInteger /* Last /* First /* LessEqualThan[521]]; s[[30000 ;; 30019]]
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
#Nim
Nim
import sequtils, strutils import bignum   const N = 521     func initPrimes(): tuple[primes: seq[Int]; smallPrimes: seq[int]] =   var sieve: array[2..N, bool] for n in 2..N: if not sieve[n]: for k in countup(n * n, N, n): sieve[k] = true   for n, isComposite in sieve: if not isComposite: result.primes.add newInt(n) if n <= 29: result.smallPrimes.add n   # Cache all primes up to N. let (Primes, SmallPrimes) = initPrimes()       proc nSmooth(n, size: Positive): seq[Int] = assert n in 2..N, "'n' must be between 2 and " & $N   let bn = newInt(n) assert bn in Primes, "'n' must be a prime number"   result.setLen(size) result[0] = newInt(1)   var next: seq[Int] for prime in Primes: if prime > bn: break next.add prime   var indices = newSeq[int](next.len) for m in 1..<size: result[m] = next[next.minIndex()] for i in 0..indices.high: if result[m] == next[i]: inc indices[i] next[i] = Primes[i] * result[indices[i]]     when isMainModule:   for n in SmallPrimes: echo "The first ", n, "-smooth numbers are:" echo nSmooth(n, 25).join(" ") echo ""   for n in SmallPrimes[1..^1]: echo "The 3000th to 3202th ", n, "-smooth numbers are:" echo nSmooth(n, 3002)[2999..^1].join(" ") echo ""   for n in [503, 509, 521]: echo "The 30000th to 30019th ", n, "-smooth numbers are:" echo nSmooth(n, 30_019)[29_999..^1].join(" ") echo ""
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
#JavaScript
JavaScript
function example(options) { // assign some defaults where the user's has not provided a value opts = {} opts.foo = options.foo || 0; opts.bar = options.bar || 1; opts.grill = options.grill || 'pork chops'   alert("foo is " + opts.foo + ", bar is " + opts.bar + ", and grill is " + opts.grill); }   example({grill: "lamb kebab", bar: 3.14}); // => "foo is 0, bar is 3.14, and grill is lamb kebab"
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#jq
jq
  def formatName(obj): ({ "name": "?"} + obj) as $obj # the default default value is null | ($obj|.name) as $name | ($obj|.first) as $first | if ($first == null) then $name else $name + ", " + $first end;  
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#FreeBASIC
FreeBASIC
' version 14-01-2019 ' compile with: fbc -s console   Function nth_root(n As Integer, number As Double) As Double   Dim As Double a1 = number / n, a2 , a3   Do a3 = Abs(a2 - a1) a2 = ((n -1) * a1 + number / a1 ^ (n -1)) / n Swap a1, a2 Loop Until Abs(a2 - a1) = a3   Return a1   End Function   ' ------=< MAIN >=------   Dim As UInteger n Dim As Double tmp   Print Print " n 5643 ^ 1 / n nth_root ^ n" Print " ------------------------------------" For n = 3 To 11 Step 2 tmp = nth_root(n, 5643) Print Using " ### ###.######## ####.########"; n; tmp; tmp ^ n Next   Print For n = 25 To 125 Step 25 tmp = nth_root(n, 5643) Print Using " ### ###.######## ####.########"; n; tmp; tmp ^ n Next   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep 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.
#Batch_File
Batch File
@echo off ::Main thing... call :Nth 0 25 call :Nth 250 265 call :Nth 1000 1025 pause exit /b ::The subroutine :Nth <lbound> <ubound> setlocal enabledelayedexpansion for /l %%n in (%~1,1,%~2) do ( set curr_num=%%n set "out=%%nth" if !curr_num:~-1!==1 (set "out=%%nst") if !curr_num:~-1!==2 (set "out=%%nnd") if !curr_num:~-1!==3 (set "out=%%nrd") set "range_output=!range_output! !out!" ) echo."!range_output:~1!" goto :EOF
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
#Perl
Perl
use utf8; use strict; use warnings; use feature 'say'; use List::Util 'uniq';   sub prime_factors { my ($n, $d, @factors) = (shift, 1); while ($n > 1 and $d++) { $n /= $d, push @factors, $d until $n % $d; } @factors }   sub μ { my @p = prime_factors(shift); @p == uniq(@p) ? 0 == @p%2 ? 1 : -1 : 0; }   my @möebius; push @möebius, μ($_) for 1 .. (my $upto = 199);   say "Möbius sequence - First $upto terms:\n" . (' 'x4 . sprintf "@{['%4d' x $upto]}", @möebius) =~ s/((.){80})/$1\n/gr;
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']
#Python
Python
# -*- coding: utf-8 -*- # Not Python 3.x (Can't compare str and int)     from itertools import groupby from unicodedata import decomposition, name from pprint import pprint as pp   commonleaders = ['the'] # lowercase leading words to ignore replacements = {u'ß': 'ss', # Map single char to replacement string u'ſ': 's', u'ʒ': 's', }   hexdigits = set('0123456789abcdef') decdigits = set('0123456789') # Don't use str.isnumeric   def splitchar(c): ' De-ligature. De-accent a char' de = decomposition(c) if de: # Just the words that are also hex numbers de = [d for d in de.split() if all(c.lower() in hexdigits for c in d)] n = name(c, c).upper() # (Gosh it's onerous) if len(de)> 1 and 'PRECEDE' in n: # E.g. ʼn LATIN SMALL LETTER N PRECEDED BY APOSTROPHE de[1], de[0] = de[0], de[1] tmp = [ unichr(int(k, 16)) for k in de] base, others = tmp[0], tmp[1:] if 'LIGATURE' in n: # Assume two character ligature base += others.pop(0) else: base = c return base     def sortkeygen(s): '''Generate 'natural' sort key for s   Doctests: >>> sortkeygen(' some extra spaces ') [u'some extra spaces'] >>> sortkeygen('CasE InseNsItIve') [u'case insensitive'] >>> sortkeygen('The Wind in the Willows') [u'wind in the willows'] >>> sortkeygen(u'\462 ligature') [u'ij ligature'] >>> sortkeygen(u'\335\375 upper/lower case Y with acute accent') [u'yy upper/lower case y with acute accent'] >>> sortkeygen('foo9.txt') [u'foo', 9, u'.txt'] >>> sortkeygen('x9y99') [u'x', 9, u'y', 99] ''' # Ignore leading and trailing spaces s = unicode(s).strip() # All space types are equivalent s = ' '.join(s.split()) # case insentsitive s = s.lower() # Title words = s.split() if len(words) > 1 and words[0] in commonleaders: s = ' '.join( words[1:]) # accent and ligatures s = ''.join(splitchar(c) for c in s) # Replacements (single char replaced by one or more) s = ''.join( replacements.get(ch, ch) for ch in s ) # Numeric sections as numerics s = [ int("".join(g)) if isinteger else "".join(g) for isinteger,g in groupby(s, lambda x: x in decdigits)]   return s   def naturalsort(items): ''' Naturally sort a series of strings   Doctests: >>> naturalsort(['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda']) ['The 39 steps', 'The 40th step more', 'Wanda', 'The Wind in the Willows']   ''' return sorted(items, key=sortkeygen)   if __name__ == '__main__': import string   ns = naturalsort   print '\n# Ignoring leading spaces' txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Ignoring multiple adjacent spaces (m.a.s)' txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Equivalent whitespace characters' txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3) for i,ch in enumerate(reversed(string.whitespace))] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Case Indepenent sort' s = 'CASE INDEPENENT' txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Numeric fields as numerics' txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Title sorts' txt = ['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Equivalent accented characters (and case)' txt = ['Equiv. %s accents: 2%+i' % (ch, i-2) for i,ch in enumerate(u'\xfd\xddyY')] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Separated ligatures' txt = [u'\462 ligatured ij', 'no ligature',] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt))   print '\n# Character replacements' s = u'ʒſßs' # u'\u0292\u017f\xdfs' txt = ['Start with an %s: 2%+i' % (ch, i-2) for i,ch in enumerate(s)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; print '\n'.join(sorted(txt)) print 'Naturally sorted:'; print '\n'.join(ns(txt))
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
#Ursala
Ursala
#import std   noncontinuous = num; ^rlK3ZK17rSS/~& powerset   #show+   examples = noncontinuous 'abcde'
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
#VBScript
VBScript
'Non-continuous subsequences - VBScript - 03/02/2021 Function noncontsubseq(l) Dim i, j, g, n, r, s, w, m Dim a, b, c n = Ubound(l) For s = 0 To n-2 For g = s+1 To n-1 a = "[" For i = s To g-1 a = a & l(i) & ", " Next 'i For w = 1 To n-g r = n+1-g-w For i = 1 To 2^r-1 Step 2 b = a For j = 0 To r-1 If i And 2^j Then b=b & l(g+w+j) & ", " Next 'j c = (Left(b, Len(b)-1)) WScript.Echo Left(c, Len(c)-1) & "]" m = m+1 Next 'i Next 'w Next 'g Next 's noncontsubseq = m End Function 'noncontsubseq list = Array("1", "2", "3", "4") WScript.Echo "List: [" & Join(list, ", ") & "]" nn = noncontsubseq(list) WScript.Echo nn & " non-continuous subsequences"
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.
#Liberty_BASIC
Liberty BASIC
' Base Converter v6   global alphanum$ alphanum$ ="0123456789abcdefghijklmnopqrstuvwxyz"   for i =1 to 20 RandNum = int( 100 *rnd( 1)) base =2 +int( 35 *rnd( 1))   print "Decimal "; using( "###", RandNum); " to base "; using( "###", base);_ " is "; toBase$( base, RandNum),_ " back to dec. "; toDecimal( base, toBase$( base, RandNum)) next i   end ' ___________________________________________________________   function toBase$( base, number) ' Convert decimal variable to number string. toBase$ ="" for i =10 to 1 step -1 remainder =number mod base toBase$ =mid$( alphanum$, remainder +1, 1) +toBase$ number =int( number /base) if number <1 then exit for next i end function   function toDecimal( base, s$) ' Convert number string to decimal variable. toDecimal =0 for i =1 to len( s$) toDecimal =toDecimal *base +instr( alphanum$, mid$( s$, i, 1), 1) -1 next i end function  
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.
#D
D
void main() { import std.stdio, std.algorithm, std.conv, std.range;   immutable isNarcissistic = (in uint n) pure @safe => n.text.map!(d => (d - '0') ^^ n.text.length).sum == n; writefln("%(%(%d %)\n%)", uint.max.iota.filter!isNarcissistic.take(25).chunks(5)); }
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.
#Factor
Factor
USING: accessors images images.loader kernel math sequences ; IN: rosetta-code.munching-squares   : img-data ( -- seq ) 256 sq [ B{ 0 0 0 255 } ] replicate ;   : (munching) ( elt index -- elt' ) 256 /mod bitxor [ rest ] dip prefix ;   : munching ( -- seq ) img-data [ (munching) ] map-index B{ } concat-as ;   : <munching-img> ( -- img ) <image> { 256 256 } >>dim BGRA >>component-order ubyte-components >>component-type munching >>bitmap ;   : main ( -- ) <munching-img> "munching.png" save-graphic-image ;   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.
#FreeBASIC
FreeBASIC
' version 03-11-2016 ' compile with: fbc -s gui   Dim As ULong x, y, r, w = 256   ScreenRes w, w, 32   For x = 0 To w -1 For y = 0 To w -1 r =(x Xor y) And 255 PSet(x, y), RGB(r, r , r) ' gray scale ' PSet(x, y), RGB(r, 255 - r, 0) ' red + green ' PSet(x, y), RGB(r, 0, 0) ' red Next Next   ' empty keyboard buffer While Inkey <> "" : Wend WindowTitle "Close window or hit any key to end program" Sleep 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
#ALGOL_W
ALGOL W
% Find Munchausen Numbers between 1 and 5000  % % note that 6^6 is 46 656 so we only need to consider numbers consisting of 0 to 5  % begin    % table of nth Powers - note 0^0 is 0 for Munchausen numbers, not 1  % integer array nthPower( 0 :: 5 ); integer d1, d2, d3, d4, d1Part, d2Part, d3Part; nthPower( 0 ) := 0; nthPower( 1 ) := 1; nthPower( 2 ) := 2 * 2; nthPower( 3 ) := 3 * 3 * 3; nthPower( 4 ) := 4 * 4 * 4 * 4; nthPower( 5 ) := 5 * 5 * 5 * 5 * 5; d1 := d2 := d3 := d1Part := d2Part := d3Part := 0; d4 := 1; while d1 < 6 do begin integer number, digitPowerSum; number  := d1Part + d2Part + d3Part + d4; digitPowerSum := nthPower( d1 ) + nthPower( d2 ) + nthPower( d3 ) + nthPower( d4 ); if digitPowerSum = number then begin write( i_w := 1, number ) end; d4 := d4 + 1; if d4 > 5 then begin d4  := 0; d3  := d3 + 1; d3Part := d3Part + 10; if d3 > 5 then begin d3  := 0; d3Part := 0; d2  := d2 + 1; d2Part := d2Part + 100; if d2 > 5 then begin d2  := 0; d2Part := 0; d1  := d1 + 1; d1Part := d1Part + 1000; end end end end   end.
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , n > 0 M ( n ) = n − F ( M ( n − 1 ) ) , n > 0. {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}} (If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
#AppleScript
AppleScript
-- f :: Int -> Int on f(x) if x = 0 then 1 else x - m(f(x - 1)) end if end f   -- m :: Int -> Int on m(x) if x = 0 then 0 else x - f(m(x - 1)) end if end m     -- TEST on run set xs to range(0, 19)   {map(f, xs), map(m, xs)} end run     -- GENERIC FUNCTIONS   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to lambda(item i of xs, i, xs) end repeat return lst end tell end map   -- 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 lambda : f end script end if end mReturn   -- range :: Int -> Int -> [Int] on range(m, n) if n < m then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end range
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.
#FreePascal
FreePascal
{$mode objfpc} uses windows,math;{ windows only } var Interval:Double = 1.0594630943592953; i:integer; begin for i:= 0 to 11 do beep(Round(440.0*interval**i),500); 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.
#Go
Go
package main   import ( "encoding/binary" "log" "math" "os" "strings" )   func main() { const ( sampleRate = 44100 duration = 8 dataLength = sampleRate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 )   // buffers buf1 := make([]byte, 1) buf2 := make([]byte, 2) buf4 := make([]byte, 4)   // WAV header var sb strings.Builder sb.WriteString("RIFF") binary.LittleEndian.PutUint32(buf4, fileLen) sb.Write(buf4) // file size - 8 sb.WriteString("WAVE") sb.WriteString("fmt ") binary.LittleEndian.PutUint32(buf4, 16) sb.Write(buf4) // length of format data (= 16) binary.LittleEndian.PutUint16(buf2, 1) sb.Write(buf2) // type of format (= 1 (PCM)) sb.Write(buf2) // number of channels (= 1) binary.LittleEndian.PutUint32(buf4, sampleRate) sb.Write(buf4) // sample rate sb.Write(buf4) // sample rate * bps(8) * channels(1) / 8 (= sample rate) sb.Write(buf2) // bps(8) * channels(1) / 8 (= 1) binary.LittleEndian.PutUint16(buf2, 8) sb.Write(buf2) // bits per sample (bps) (= 8) sb.WriteString("data") binary.LittleEndian.PutUint32(buf4, dataLength) sb.Write(buf4) // size of data section wavhdr := []byte(sb.String())   // write WAV header f, err := os.Create("notes.wav") if err != nil { log.Fatal(err) } defer f.Close() f.Write(wavhdr)   // compute and write actual data freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3} for j := 0; j < duration; j++ { freq := freqs[j] omega := 2 * math.Pi * freq for i := 0; i < dataLength/duration; i++ { y := 32 * math.Sin(omega*float64(i)/float64(sampleRate)) buf1[0] = byte(math.Round(y)) f.Write(buf1) } } }
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.
#BBC_BASIC
BBC BASIC
DIM sep$(2) sep$() = "==", "!=", "=" PRINT "String splits into:" PRINT FNmultisplit("a!===b=!=c", sep$(), FALSE) PRINT "For extra credit:" PRINT FNmultisplit("a!===b=!=c", sep$(), TRUE) END   DEF FNmultisplit(s$, d$(), info%) LOCAL d%, i%, j%, m%, p%, o$ p% = 1 REPEAT m% = LEN(s$) FOR i% = 0 TO DIM(d$(),1) d% = INSTR(s$, d$(i%), p%) IF d% IF d% < m% m% = d% : j% = i% NEXT IF m% < LEN(s$) THEN o$ += """" + MID$(s$, p%, m%-p%) + """" IF info% o$ += " (" + d$(j%) + ") " ELSE o$ += ", " p% = m% + LEN(d$(j%)) ENDIF UNTIL m% = LEN(s$) = o$ + """" + MID$(s$, p%) + """"
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.
#Bracmat
Bracmat
( ( oneOf = operator .  !arg:%?operator ?arg & ( @(!sjt:!operator ?arg)&(!operator.!arg) | oneOf$!arg ) ) & "a!===b=!=c":?unparsed & "==" "!=" "=":?operators & whl ' ( @( !unparsed  : ?nonOp [%(oneOf$!operators:(?operator.?unparsed)) ) & put$(!nonOp str$("{" !operator "} ")) ) & put$!unparsed & put$\n );
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
#Pascal
Pascal
program nSmoothNumbers(output);   const primeCount = 538; {$ifDef __GPC__} {$setLimit=3889} {$endIf} cardinalMax = 3888;   type cardinal = 0..cardinalMax; cardinals = set of cardinal; cardinalPositive = 1..cardinalMax;   natural = 1..maxInt;   primeIndex = 1..primeCount; list = array[primeIndex] of cardinal;   var prime: list;   { \brief performs prime factorization   \param n the number to factorize \return list of exponents for a unique integer factorization using primes   This function requires the global `prime` variable to be initialized. } function primeFactorization(n: natural): list; var i: primeIndex; { Instead of writing `[1: 0; 2: 0; 3: 0; …]`, Extended Pascal permits us to use an “array completer” for all unspecified values. } result: list value [otherwise 0]; begin for i := 1 to primeCount do begin while n mod prime[i] = 0 do begin n := n div prime[i]; result[i] := result[i] + 1 end end;   { Nullify result if the utilized `prime` list was insufficient. } if n <> 1 then begin { `array` literals need an explicit data type specification. } result := list[otherwise 0] end;   { In a Pascal function definition there must be _one_ assignment to the (implicitly) declared variable bearing the same name as of the function. This will be returned function result. } primeFactorization := result end;   { \brief returns whether a number is an n-smooth number   \param smoothness the maximum permissible prime factor \param x the number to check \return whether \param x is smoothness-smooth } function isSmooth( protected smoothness: cardinalPositive; protected x: natural ): Boolean; { Return set of non-one factors (i.e. non-zero exponent).   Nesting this function permits most compilers to allocate memory for variables only if the function is actually needed. } function factorizationBases: cardinals; var exponent: list; i: primeIndex; result: cardinals value []; begin exponent := primeFactorization(x);   for i := 1 to primeCount do begin if exponent[i] > 0 then begin result := result + [prime[i]] end end;   factorizationBases := result end; begin case smoothness of 1: begin { The value `1` actually does not have a prime factorization, yet as per task specification “1 (unity) is always included in n‑smooth numbers.” } isSmooth := x = 1 end; { 2‑smooth numbers is an alias for powers of 2 (OEIS sequence A000079) } 2: begin isSmooth := 2 pow round(ln(x) / ln(2)) = x end { The `otherwise` catch-all-clause is an Extended Pascal extension. } otherwise begin isSmooth := card(factorizationBases - [0..smoothness]) = 0 { `card` (“cardinality”) is an Extended Pascal extension. Testing `card(M) = 0` is equivalent to `M = []` (empty set). } end end end;   { === ancillary routines =============================================== }   { This is just your regular Eratosthenes prime sieve. } procedure sieve(var primes: cardinals); var n: natural; i: integer; multiples: cardinals; begin { `1` is by definition not a prime number } primes := primes - [1];   { find the next non-crossed number } for n := 2 to cardinalMax do begin if n in primes then begin multiples := []; { We do _not_ want to remove 1 * n. } i := 2 * n; while i in [n..cardinalMax] do begin multiples := multiples + [i]; i := i + n end;   primes := primes - multiples end end end;   { This procedure transforms a `set` to an `array`. } procedure populatePrime; var primes: cardinals value [1..cardinalMax]; n: natural value 1; i: primeIndex value 1; begin sieve(primes);   for i := 1 to primeCount do begin repeat begin n := n + 1 end until n in primes;   prime[i] := n end end;   { ### MAIN ############################################################# } var i: primeIndex value primeCount; candidate: natural; count: cardinal; begin populatePrime;   { Show the first 25 n-smooth numbers […] } { […] only prime [n] are to be used. } while prime[i] > 29 do begin i := i - 1 end;   { In Pascal, `for` loop limits are evaluated _once_, so this is perfectly legal: } for i := 1 to i do begin write(prime[i]:4, '-smooth: 1');   count := 1; { `1` already listed. } candidate := 2;   while count < 25 do begin if isSmooth(prime[i], candidate) then begin write(', ', candidate:1); count := count + 1 end; candidate := candidate + 1 end;   writeLn end;   { Note, in Pascal, the `for`‑loop iteration variable is not modified. At this point in the code, `i` (still) has the value after the `while`-loop. [This statement is not true, if a `goto` prematurely exited the `for`‑loop.] }   writeLn;   { […] show three numbers starting with 3,000 […] } for i := 2 to i do begin write(prime[i]:4, '-smooth:');   count := 0; candidate := 3000;   while count < 3 do begin if isSmooth(prime[i], candidate) then begin write(' ', candidate:1); count := count + 1 end; candidate := candidate + 1 end;   writeLn end; end.
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Julia
Julia
function surround(string ; border = :default, padding = 0)   ve, ho, ul, ur, dl, dr = border == :round ? ("\u2502","\u2500","\u256d","\u256e","\u2570","\u256f") : border == :bold  ? ("\u2503","\u2501","\u250F","\u2513","\u2517","\u251b") : border == :double? ("\u2551","\u2550","\u2554","\u2557","\u255a","\u255d") : border == :dotted? ("\u254e","\u254c","\u250c","\u2510","\u2514","\u2518") : border == :cross ? ("\u2502","\u2500","\u253c","\u253c","\u253c","\u253c") : ("\u2502","\u2500","\u250c","\u2510","\u2514","\u2518")   println(ul, ho^(length(string) + 2padding), ur, "\n", ve, " "^padding, string," "^padding, ve, "\n", dl, ho^(length(string) + 2padding), dr) end
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#Kotlin
Kotlin
// version 1.0.6   fun someFunction(first: String, second: Int = 2, third: Double) { println("First = ${first.padEnd(10)}, Second = $second, Third = $third") }   fun main(args: Array<String>) { // using positional parameters someFunction("positional", 1, 2.0)   // using named parameters someFunction(first = "named", second = 1, third = 2.0)   // omitting 2nd parameter which is optional because it has a default value someFunction(first = "omitted", third = 2.0)   // using first and third parameters in reverse someFunction(third = 2.0, first = "reversed") }
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.
#FutureBasic
FutureBasic
window 1   local fn NthRoot( root as long, a as long, precision as double ) as double double x0, x1   x0 = a : x1 = a /root while ( abs( x1 - x0 ) > precision ) x0 = x1 x1 = ( ( root -1.0 ) * x1 + a / x1 ^ ( root -1.0 ) ) /root wend end fn = x1   print " 125th Root of 5643 Precision .001",, using "#.###############"; fn NthRoot( 125, 5642, 0.001 ) print " 125th Root of 5643 Precision .001",, using "#.###############"; fn NthRoot( 125, 5642, 0.001 ) print " 125th Root of 5643 Precision .00001", using "#.###############"; fn NthRoot( 125, 5642, 0.00001 ) print " Cube Root of 27 Precision .00001", using "#.###############"; fn NthRoot( 3, 27, 0.00001 ) print "Square Root of 2 Precision .00001", using "#.###############"; fn NthRoot( 2, 2, 0.00001 ) print "Square Root of 2 Precision .00001", using "#.###############"; sqr(2) // Processor floating point calc deviation print " 10th Root of 1024 Precision .00001", using "#.###############"; fn NthRoot( 10, 1024, 0.00001 ) print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )   HandleEvents
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.
#BBC_BASIC
BBC BASIC
PROCNth( 0, 25) PROCNth( 250, 265) PROCNth(1000,1025) END   DEF PROCNth(s%,e%) LOCAL i%,suff$ FOR i%=s% TO e% suff$="th" IF i% MOD 10 = 1 AND i% MOD 100 <> 11 suff$="st" IF i% MOD 10 = 2 AND i% MOD 100 <> 12 suff$="nd" IF i% MOD 10 = 3 AND i% MOD 100 <> 13 suff$="rd" PRINT STR$i%+suff$+" "; NEXT PRINT ENDPROC