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/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Delphi
Delphi
var xs = Array.Empty(10) var ys = Array(1, 2, 3) var str = xs.ToString()   type Maybe = Some(x) or None() var x = Maybe.Some(42)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Dyalect
Dyalect
var xs = Array.Empty(10) var ys = Array(1, 2, 3) var str = xs.ToString()   type Maybe = Some(x) or None() var x = Maybe.Some(42)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Factor
Factor
\ fetch and store usage examples VARIABLE MYINT1 VARIABLE MYINT2 2VARIABLE DOUBLE1 2VARIABLE DOUBLE2   MYINT1 @ MYINT2 ! MYDOUBLE 2@ MYDOUBLE 2!   \ record example using this convention   1000000 RECORDS PERSONEL   1 PERSONEL RECORD@ \ read Record 1 and put pointer on data stack   HR_RECORD 992 PERSONEL RECORD! \ store HR_RECORD  
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If there is no next highest integer return zero. *1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   N which can be obtained by reordering the (base ten) digits of   N". Algorithm 1   Generate all the permutations of the digits and sort into numeric order.   Find the number in the list.   Return the next highest number from the list. The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness. Algorithm 2   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.   Exchange that digit with the digit on the right that is both more than it, and closest to it.   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) E.g.: n = 12453 <scan> 12_4_53 <swap> 12_5_43 <order-right> 12_5_34 return: 12534 This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task),   is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle. Task requirements Calculate the next highest int from the digits of the following numbers:   0   9   12   21   12453   738440   45072010   95322020 Optional stretch goal   9589776899767587796600
#REXX
REXX
/*REXX program finds the next highest positive integer from a list of decimal digits. */ parse arg n /*obtain optional arguments from the CL*/ if n='' | n="," then n= 0 9 12 21 12453 738440 45072010 95322020 /*use the defaults?*/ w= length( commas( word(n, words(n) ) ) ) /*maximum width number (with commas). */   do j=1 for words(n); y= word(n, j) /*process each of the supplied numbers.*/ masky= mask(y) /*build a digit mask for a supplied int*/ lim= copies(9, length(y) ) /*construct a LIMIT for the DO loop. */   do #=y+1 to lim until mask(#)==masky /*search for a number that might work. */ if verify(y, #) \== 0 then iterate /*does # have all the necessary digits?*/ end /*#*/   if #>lim then #= 0 /*if # > lim, then there is no valid #*/ say 'for ' right(commas(y),w) " ─── the next highest integer is: " right(commas(#),w) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do ?=length(_)-3 to 1 by -3; _= insert(',', _, ?); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ mask: parse arg z, $; @.= 0 /* [↓] build an unsorted digit mask. */ do k=1 for length(z); parse var z _ +1 z; @._= @._ + 1 end /*k*/ do m=0 for 10; if @.m==0 then iterate; $= $ || copies(m, @.m) end /*m*/; return $ /* [↑] build a sorted digit mask.*/
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Nanoquery
Nanoquery
def makeList(separator) counter = 1   def makeItem(item) result = str(counter) + separator + item + "\n" counter += 1 return result end   return makeItem("first") + makeItem("second") + makeItem("third") end   println makeList(". ")
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Nim
Nim
proc makeList(separator: string): string = var counter = 1   proc makeItem(item: string): string = result = $counter & separator & item & "\n" inc counter   makeItem("first") & makeItem("second") & makeItem("third")   echo $makeList(". ")
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Objective-C
Objective-C
NSString *makeList(NSString *separator) { __block int counter = 1;   NSString *(^makeItem)(NSString *) = ^(NSString *item) { return [NSString stringWithFormat:@"%d%@%@\n", counter++, separator, item]; };   return [NSString stringWithFormat:@"%@%@%@", makeItem(@"first"), makeItem(@"second"), makeItem(@"third")]; }   int main() { NSLog(@"%@", makeList(@". ")); return 0; }
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. Related task Sleep
#Phix
Phix
with javascript_semantics constant watches = {"First","Middle","Morning","Forenoon","Afternoon","First dog","Last dog","First"}, watch_ends = {"00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59"}, bells = {"One","Two","Three","Four","Five","Six","Seven","Eight"}, ding = "ding!" procedure nb(integer h,m) integer bell = mod(floor((h*60+m)/30),8) if bell==0 then bell = 8 end if string hm = sprintf("%02d:%02d",{h,m}) integer watch=1 while hm>watch_ends[watch] do watch += 1 end while string plural = iff(bell==1?" ":"s") string dings = ding for i=2 to bell do dings &= iff(mod(i,2)?" ":"")&ding end for printf(1,"%s %9s watch %5s bell%s  %s\n", {hm,watches[watch],bells[bell],plural,dings}) end procedure procedure simulate1day() for h=0 to 23 do for m=0 to 30 by 30 do nb(h,m) end for end for nb(0,0) -- (again) end procedure simulate1day() if platform()!=JS then -- (no sleep() function) while 1 do sequence d = date(DT_GMT) integer m = d[DT_SECOND] + mod(d[DT_MINUTE],30)*60 if m=0 then nb(d[DT_HOUR],d[DT_MINUTE]) end if sleep(30*60-m) end while end if
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
#Perl
Perl
my ($max, @current); sub non_continuous { my ($idx, $has_gap) = @_; my $found;   for ($idx .. $max) { push @current, $_; # print "@current\n" if $has_gap; # uncomment for huge output $found ++ if $has_gap; $found += non_continuous($_ + 1, $has_gap) if $_ < $max; pop @current; $has_gap = @current; # don't set gap flag if it's empty still } $found; }   $max = 20; print "found ", non_continuous(1), " sequences\n";
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Factor
Factor
USE: math.parser   12345 16 >base . "3039" 16 base> .
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Sidef
Sidef
var dec = '0123459'; var hex_noprefix = 'abcf123'; var hex_withprefix = '0xabcf123'; var oct_noprefix = '7651'; var oct_withprefix = '07651'; var bin_noprefix = '101011001'; var bin_withprefix = '0b101011001';   say dec.num; # => 123459 say hex_noprefix.hex; # => 180154659 say hex_withprefix.hex; # => 180154659 say oct_noprefix.oct; # => 4009 say oct_withprefix.oct; # => 4009 say bin_noprefix.bin; # => 345 say bin_withprefix.bin; # => 345
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Standard_ML
Standard ML
- Int.fromString "0123459"; val it = SOME 123459 : int option - StringCvt.scanString (Int.scan StringCvt.HEX) "0xabcf123"; val it = SOME 180154659 : int option - StringCvt.scanString (Int.scan StringCvt.HEX) "abcf123"; val it = SOME 180154659 : int option - StringCvt.scanString (Int.scan StringCvt.OCT) "7651"; val it = SOME 4009 : int option - StringCvt.scanString (Int.scan StringCvt.BIN) "101011001"; val it = SOME 345 : int option
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Ruby
Ruby
for n in 0..33 puts " %6b %3o %2d %2X" % [n, n, n, n] end puts [2,8,10,16,36].each {|i| puts " 100.to_s(#{i}) => #{100.to_s(i)}"}
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Rust
Rust
fn main() { // To render the number as string, use format! macro instead println!("Binary: {:b}", 0xdeadbeefu32); println!("Binary with 0b prefix: {:#b}", 0xdeadbeefu32); println!("Octal: {:o}", 0xdeadbeefu32); println!("Octal with 0o prefix: {:#o}", 0xdeadbeefu32); println!("Decimal: {}", 0xdeadbeefu32); println!("Lowercase hexadecimal: {:x}", 0xdeadbeefu32); println!("Lowercase hexadecimal with 0x prefix: {:#x}", 0xdeadbeefu32); println!("Uppercase hexadecimal: {:X}", 0xdeadbeefu32); println!("Uppercase hexadecimal with 0x prefix: {:#X}", 0xdeadbeefu32); }
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.
#Nim
Nim
import algorithm, sugar, tables   const Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Values = collect(initTable): for i, c in Digits: {c: i} # Maps the digits to their values in base 10.   type Number = object ## Representation of a number in any base. base: int value: string   func toBase(n, base: int): Number = ## Convert an integer into a number in base 'base'. assert base notin -1..1, "wrong value for base: " & $base if n == 0: return Number(base: base, value: "0") result.base = base var n = n while n != 0: var m = n mod base n = n div base if m < 0: inc m, abs(base) inc n result.value.add Digits[m] result.value.reverse()   func `$`(n: Number): string = ## String representation of a number. $n.value   func toInt(n: Number): int = ## Convert a number in some base into an integer in base 10. for d in n.value: result = n.base * result + Values[d]     when isMainModule:   proc process(n, base: int) = let s = n.toBase(base) echo "The value ", n, " is encoded in base ", base, " as: ", s echo "and is decoded back in base 10 as: ", s.toInt echo ""   process(10, -2) process(146, -3) process(15, -10)   const Nim = Number(base: -62, value: "Nim") echo "The string “Nim” is decoded from base -62 to base 10 as: ", Nim.toInt
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.
#ooRexx
ooRexx
/* REXX --------------------------------------------------------------- * Adapt for ooRexx (use of now invalid variable names) * and make it work for base -63 (Algol example) *--------------------------------------------------------------------*/ Numeric Digits 20 digits='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ' txt=' converted to base ' n= 10; b= -2; nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() n= 146; b= -3; nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() n= 15; b=-10; nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() n= -15; b=-10; nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() n= 0; b= -5; nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() n=-6284695; b=-62; nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() n=-36492107981104; b=-63;nb=nBase(n,b); Say right(n,20) txt right(b,3) '---->' nb ok() Exit   nBase: Procedure Expose digits /*--------------------------------------------------------------------- * convert x (base 10) to result (base r) *--------------------------------------------------------------------*/ Parse arg x,r result='' Do While x\==0 /*keep Processing while X isn't zero.*/ z=x//r x=x%r /*calculate remainder; calculate int ÷.*/ If z<0 Then Do z=z-r /*subtract a negative R from Z ?--+ */ x=x+1 /*bump X by one. ¦ */ End result=substr(digits,z+1,1)result /*prepend the new digit */ End If result='' Then result=0 Return result   pBase: Procedure Expose digits; /*--------------------------------------------------------------------- * convert x (base r) to result (base 10) *--------------------------------------------------------------------*/ Parse arg x,r; result=0; p=0 len=length(x) Do j=len by -1 For len /*Process each of the X's digits */ v=pos(substr(x,j,1),digits)-1 /*use digit's numeric value. */ result=result+v*r**p; /*add it to result */ p=p+1 /*bump power by 1 */ End Return result   ok: /*--------------------------------------------------------------------- * check back conversion *--------------------------------------------------------------------*/ back=pBase(nb,b) If back\=n Then r='Error backward conversion results in' back Else r='ok' Return r
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#XPL0
XPL0
code ChOut=8, CrLf=9, Text=12;   proc NumName(Dev, Num); \Output integer Num in prose to device Dev int Dev, Num; int OneTbl, TenTbl, ThoTbl, ThoPwr, I, Quot;   proc Out999(N); \Output number in range 0..999 (0 does nothing) int N; int Huns, Tens, Ones; [Huns:= N/100; \0..9 N:= rem(0); \0..99 Tens:= N/10; \0..9 Ones:= rem(0); \0..9 if Huns # 0 then [Text(Dev, OneTbl(Huns)); \1..9 Text(Dev, " hundred ")]; if Tens >= 2 then [Text(Dev, TenTbl(Tens)); if Ones # 0 then [ChOut(Dev, ^-); Text(Dev, OneTbl(Ones))]; ] else if N # 0 then Text(Dev, OneTbl(N)); \N = 1..19 ];   [if Num = 0 then [Text(Dev, "zero"); return]; if Num < 0 then [Num:= -Num; Text(Dev, "minus ")];   OneTbl:=[0, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; TenTbl:=[0, 0, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; ThoTbl:=[" billion ", " million ", " thousand "];   ThoPwr:= 1000000000; for I:= 0 to 2 do [Quot:= Num/ThoPwr; Num:= rem(0); if Quot # 0 then [Out999(Quot); Text(Dev, ThoTbl(I))]; ThoPwr:= ThoPwr/1000; ]; Out999(Num); ];   [NumName(0, 0); CrLf(0); NumName(0, 13); CrLf(0); NumName(0, 789); CrLf(0); NumName(0, -604_001); CrLf(0); NumName(0, 1_000_000); CrLf(0); NumName(0, 1_234_567_890); CrLf(0); ]
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.
#Perl
Perl
use strict; use warnings; use feature 'say';   my $tokens = 12; say "$tokens tokens remaining.\n";   while (1) { print "How many tokens do you want to remove; 1, 2 or 3? : "; (my $player = <>) =~ s/\s//g; say "Nice try. $tokens tokens remaining.\n" and next unless $player =~ /^[123]$/; $tokens -= 4; say "Computer takes @{[4 - $player]}.\n$tokens tokens remaining.\n"; say "Computer wins." and last if $tokens <= 0; }
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.
#Agena
Agena
scope # print the first 25 narcissistic numbers   local power := reg( 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ); local count  := 0; local maxCount  := 25; local candidate  := 0; local prevDigits := 0; local digits  := 1;   for d9 from 0 to 2 while count < maxCount do if d9 > 0 and digits < 9 then digits := 9 fi; for d8 from 0 to 9 while count < maxCount do if d8 > 0 and digits < 8 then digits := 8 fi; for d7 from 0 to 9 while count < maxCount do if d7 > 0 and digits < 7 then digits := 7 fi; for d6 from 0 to 9 while count < maxCount do if d6 > 0 and digits < 6 then digits := 6 fi; for d5 from 0 to 9 while count < maxCount do if d5 > 0 and digits < 5 then digits := 5 fi; for d4 from 0 to 9 while count < maxCount do if d4 > 0 and digits < 4 then digits := 4 fi; for d3 from 0 to 9 while count < maxCount do if d3 > 0 and digits < 3 then digits := 3 fi; for d2 from 0 to 9 while count < maxCount do if d2 > 0 and digits < 2 then digits := 2 fi; for d1 from 0 to 9 do if prevDigits <> digits then # number of digits has increased - increase the powers prevDigits := digits; for i from 2 to 9 do mul power[ i + 1 ], i od; fi; # sum the digits'th powers of the digits of candidate local sum := power[ d1 + 1 ] + power[ d2 + 1 ] + power[ d3 + 1 ] + power[ d4 + 1 ] + power[ d5 + 1 ] + power[ d6 + 1 ] + power[ d7 + 1 ] + power[ d8 + 1 ] + power[ d9 + 1 ]  ; if candidate = sum then # found another narcissistic decimal number io.write( " ", candidate ); inc count, 1 fi; inc candidate, 1 od; # d1 od; # d2 od; # d3 od; # d4 od; # d5 od; # d6 od; # d7 od; # d8 od; # d9 io.writeline()   epocs
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
#AppleScript
AppleScript
on getName(x) set {firstName, lastName} to {"?", "?"} try set firstName to x's firstName end try try set lastName to x's lastName end try   return firstName & ", " & lastName end getName
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.
#C.2B.2B
C++
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };  
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.
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Given a 16-bit unsigned integer in HL, return a string ;; consisting of its ASCII representation plus an ordinal ;; suffix in HL. nth: lxi b,-10 ; Divisor for digit loop push h ; Push integer to stack lxi h,nthsfx ; Pointer to end of digit area xthl ; Swap digit pointer with integer nthdigit: lxi d,-1 ; Get current digit - DE holds quotient nthdiv10: inx d ; Increment quotient, dad b ; subtract 10 from integer, jc nthdiv10 ; Keep going until HL<0 mvi a,'0'+10 ; Calculate ASCII value for digit add l ; Modulus is in (H)L xthl ; Swap integer with pointer dcx h ; Point to one digit further left mov m,a ; Store the digit xthl ; Swap pointer with integer xchg ; Put quotient in HL mov a,h ; Is it zero? ora l jnz nthdigit ; If not, go calculate next digit mvi e,0 ; Default suffix is 'th'. lxi h,nthnum+3 ; Look at tens digit mov a,m cpi '1' ; Is it '1'? jz nthsetsfx ; Then it is always 'th'. inx h ; Look at zeroes digit mov a,m sui '0' ; Subtract ASCII '0' cpi 4 ; 4 or higher? jnc nthsetsfx ; Then it is always 'th'. rlc ; Otherwise, suffix is at N*2+nthord mov e,a nthsetsfx: mvi d,0 ; Look up suffix in list lxi h,nthord dad d ; Pointer to suffix in HL lxi d,nthsfx ; Pointer to space for suffix in DE mov a,m ; Get first letter of suffix stax d ; Store it in output inx h ; Increment both pointers inx d mov a,m ; Get second letter of suffix stax d ; Store it in output pop h ; Return pointer to leftmost digit ret nthord: db 'thstndrd' ; Ordinal suffixes nthnum: db '*****' ; Room for digits nthsfx: db '**$' ; Room for suffix ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; demo: ;; Demo code lxi h,0 ; Starting at 0... mvi b,26 ; ...print 26 numbers [0..25] call printnums lxi h,250 ; Starting at 250... mvi b,16 ; ...print 16 numbers [250..265] call printnums lxi h,1000 ; Starting at 1000... mvi b,26 ; ...print 26 numbers [1000..1025] ;; Print values from HL up to HL+B printnums: push h ; Keep number push b ; Keep counter call nth ; Get string for current HL xchg ; Put it in DE mvi c,9 ; CP/M print string call 5 mvi e,' ' ; Separate numbers with spaces mvi c,2 ; CP/M print character call 5 pop b ; Restore counter pop h ; Restore number inx h ; Increment number dcr b ; Decrement counter jnz printnums ; If not zero, print next number ret
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
#Arturo
Arturo
mobius: function [n][ if n=0 -> return "" if n=1 -> return 1 f: factors.prime n   if f <> unique f -> return 0 if? odd? size f -> return neg 1 else -> return 1 ]   loop split.every:20 map 0..199 => mobius 'a -> print map a => [pad to :string & 3]
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']
#Fortran
Fortran
  MODULE STASHTEXTS !Using COMMON is rather more tedious. INTEGER MSG,KBD !I/O unit numbers. DATA MSG,KBD/6,5/ !Output, input.   INTEGER LSTASH,NSTASH,MSTASH !Prepare a common text stash. PARAMETER (LSTASH = 2468, MSTASH = 234) !LSTASH characters for MSTASH texts. INTEGER ISTASH(MSTASH + 1) !Index to start positions. CHARACTER*(LSTASH) STASH !One pool. DATA NSTASH,ISTASH(1)/0,1/ !Which is empty. CONTAINS SUBROUTINE CROAK(GASP) !A dying remark. CHARACTER*(*) GASP !The last words. WRITE (MSG,*) "Oh dear." !Shock. WRITE (MSG,*) GASP !Aargh! STOP "How sad." !Farewell, cruel world. END SUBROUTINE CROAK !Farewell...   SUBROUTINE UPCASE(TEXT) !In the absence of an intrinsic... Converts any lower case letters in TEXT to upper case... Concocted yet again by R.N.McLean (whom God preserve) December MM. Converting from a DO loop evades having both an iteration counter to decrement and an index variable to adjust. CHARACTER*(*) TEXT !The stuff to be modified. c CHARACTER*26 LOWER,UPPER !Tables. a-z may not be contiguous codes. c PARAMETER (LOWER = "abcdefghijklmnopqrstuvwxyz") c PARAMETER (UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ") CAREFUL!! The below relies on a-z and A-Z being contiguous, as is NOT the case with EBCDIC. INTEGER I,L,IT !Fingers. L = LEN(TEXT) !Get a local value, in case LEN engages in oddities. I = L !Start at the end and work back.. 1 IF (I.LE.0) RETURN !Are we there yet? Comparison against zero should not require a subtraction. c IT = INDEX(LOWER,TEXT(I:I)) !Well? c IF (IT .GT. 0) TEXT(I:I) = UPPER(IT:IT) !One to convert? IT = ICHAR(TEXT(I:I)) - ICHAR("a") !More symbols precede "a" than "A". IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A")) !In a-z? Convert! I = I - 1 !Back one. GO TO 1 !Inspect.. END SUBROUTINE UPCASE !Easy.   SUBROUTINE SHOWSTASH(BLAH,I) !One might be wondering. CHARACTER*(*) BLAH !An annotation. INTEGER I !The desired stashed text. IF (I.LE.0 .OR. I.GT.NSTASH) THEN !Paranoia rules. WRITE (MSG,1) BLAH,I !And is not always paranoid. 1 FORMAT (A,': Text(',I0,') is not in the stash!') !Hopefully, helpful. ELSE !But surely I will only be asked for what I have. WRITE (MSG,2) BLAH,I,STASH(ISTASH(I):ISTASH(I + 1) - 1) !Whee! 2 FORMAT (A,': Text(',I0,')=>',A,'<') !Hopefully, informative. END IF !So, it is shown. END SUBROUTINE SHOWSTASH !Ah, debugging.   INTEGER FUNCTION STASHIN(L2) !Assimilate the text ending at L2. Careful: furrytran regards "blah" and "blah " as equal, so, compare lengths first. INTEGER L2 !The text to add is at ISTASH(NSTASH + 1):L2. INTEGER I,L1 !Assistants. L1 = ISTASH(NSTASH + 1)!Where the scratchpad starts. L = L2 - L1 + 1 !The length of the text. Check to see if I already have stashed this exact text. DO I = 1,NSTASH !Search my existing texts. IF (L.EQ.ISTASH(I + 1) - ISTASH(I)) THEN !Matching lengths? IF (STASH(L1:L2) !Yes. Does the scratchpad 1 .EQ.STASH(ISTASH(I):ISTASH(I + 1) - 1)) THEN !Match the stashed text? STASHIN = I !Yes! I already have this exact text. RETURN !And there is no need to duplicate it. END IF !So much for matching text, furrytran style. END IF !This time, trailing space differences will count. END DO !On to the next stashed text. Can't find it. Assimilate the scratchpad. No text is moved, just extend the fingers. IF (NSTASH.GE.MSTASH) CALL CROAK("The text pool is crowded!") !Alas. IF (L2.GT.LSTASH) CALL CROAK("Overtexted!") !Alack. NSTASH = NSTASH + 1 !Count in another entry. ISTASH(NSTASH + 1) = L2 + 1 !The new "first available" position. STASHIN = NSTASH !Fingered for the caller. END FUNCTION STASHIN !Rather than assimilating a supplied text. END MODULE STASHTEXTS !Others can extract text as they wish.   MODULE BADCHARACTER !Some characters are not for glyphs but for action. CHARACTER*1 BS,HT,LF,VT,FF,CR !Nicknames for a bunch of troublemakers. CHARACTER*6 BADC,GOODC !I want a system. INTEGER*1 IBADC(6) !Initialisation syntax is restricive. PARAMETER (GOODC="btnvfr") !Mnemonics. EQUIVALENCE (BADC(1:1),BS),(BADC(2:2),HT),(BADC(3:3),LF),!Match the names 1 (BADC(4:4),VT),(BADC(5:5),FF),(BADC(6:6),CR), !To their character. 2 (IBADC,BADC) !Alas, a PARAMETER style is rejected. DATA IBADC/8,9,10,11,12,13/ !ASCII encodements. PRIVATE IBADC !Keep this quiet. END MODULE BADCHARACTER !They can disrupt layout.   MODULE COMPOUND !Stores entries, each of multiple parts, each part a text and a number. USE STASHTEXTS !Gain access to the text repository. INTEGER LENTRY,NENTRY,MENTRY !Entry counting. PARAMETER (MENTRY = 28) !Should be enough for the test runs. INTEGER TENTRY(MENTRY) !Each entry has a source text somewhere in STASH. INTEGER IENTRY(MENTRY + 1) !This fingers its first part in PARTT and PARTI. INTEGER MPART,NPART !Now for the pool of parts. PARAMETER (MPART = 120) !Should suffice. INTEGER PARTT(MPART) !A part's text number in STASH. INTEGER PARTI(MPART) !A part's number, itself. DATA NENTRY,NPART,IENTRY(1)/0,0,1/ !There are no entries, with no parts either. CONTAINS !The fun begins. INTEGER FUNCTION ADDENTRY(X) !Create an entry holding X. Chops X into many parts, alternating <text><integer>,<text><integer>,... Converts the pieces' texts to upper case, as they will be used as a sort key later. CHARACTER*(*) X !The text. INTEGER BORED,GRIST,NUMERIC !Might as well supply some mnemonics. PARAMETER (BORED = 0, GRIST = 1, NUMERIC = 2) !For nearly arbitrary integers. INTEGER I,STATE,D !For traipsing through the text. INTEGER L1,L2 !Bounds of the scratchpad in STASH. CHARACTER*1 C !Save on some typing. Create a new entry. First, save its source text exactly as supplied. IF (NENTRY.GE.MENTRY) CALL CROAK("Too many entries!") !Perhaps I can't. NENTRY = NENTRY + 1 !Another entry. L2 = ISTASH(NSTASH + 1) - 1 !Find my scratchpad. STASH(L2 + 1:L2 + LEN(X)) = X !Place the text as it stands. TENTRY(NENTRY) = STASHIN(L2 + LEN(X)) !Find a finger to it in my text stash. CALL SHOWSTASH("Entering",TENTRY(NENTRY)) !Ah, debugging. ADDENTRY = NENTRY !I shall return this. Contemplate the text of the entry. Leading spaces, multiple spaces, numeric portions... STATE = BORED !As if in leading space stuff. L2 = ISTASH(NSTASH + 1) - 1 !Syncopation for text piece placement. N = 0 !A number may be encountered. DO I = 1,LEN(X) !Step through the text. C = X(I:I) !Grab a character. IF (C.LE." ") THEN !A space, or somesuch. SELECT CASE(STATE) !What were we doing? CASE(BORED) !Ignoring spaces. !Do nothing with this one too. CASE(GRIST) !We were in stuff. CALL ONESPACE !So accept one space only. CASE(NUMERIC) !We were in a number. CALL ADDPART !So, the number has been ended. STATE = BORED !But the space wot did it is ignored. CASE DEFAULT !This should never happen. CALL CROAK("Confused state!") !So this shouldn't. END SELECT !So much for encountering spaceish stuff. ELSE IF ("0".LE.C .AND. C.LE."9") THEN !A digit? D = ICHAR(C) - ICHAR("0") !Yes. Convert to a numerical digit. N = N*10 + D !Assimilate into a proper number. STATE = NUMERIC !Perhaps more digits follow. ELSE !All other characters are accepted as they stand. IF (STATE.EQ.NUMERIC) CALL ADDPART !A number has just ended. L2 = L2 + 1 !Starting a new pair's text. STASH(L2:L2) = C !With this. STATE = GRIST !And anticipating more to come. END IF !Types are: spaceish, grist, digits. END DO !On to the next character. CALL ADDPART !Ended by the end-of-text. IENTRY(NENTRY + 1) = NPART + 1 !Thus be able to find an entry's last part. CONTAINS !Odd assistants. SUBROUTINE ONESPACE !Places a space, then declares BORED. L2 = L2 + 1 !Advance one. STASH(L2:L2) = " " !An actual blank. STATE = BORED !Any subsequent spaces are to be ignored. END SUBROUTINE ONESPACE!Skipping them. SUBROUTINE ADDPART !Augment the paired PARTT and PARTI. IF (NPART.GE.MPART) CALL CROAK("Too many parts!") !If space remains. NPART = NPART + 1 !So, another part. IF (STASH(L2:L2).EQ." ") L2 = L2 - 1 !A trailing space trimmed. BORED means at most only one. L1 = ISTASH(NSTASH + 1) !My scratchpad starts after the last stashed text. CALL UPCASE(STASH(L1:L2)) !Simplify the text to be a sort key part. IF (IENTRY(NENTRY).EQ.NPART) CALL LIBRARIAN !The first part of an entry? PARTT(NPART) = STASHIN(L2) !Finger the text part. PARTI(NPART) = N !Save the numerical value. L2 = ISTASH(NSTASH + 1) - 1 !The text may not have been a newcomer. N = 0 !Ready for another number. END SUBROUTINE ADDPART !Always paired, even if no number was found. SUBROUTINE LIBRARIAN !Adjusts names starting "The ..." or "An ..." or "A ...", library style. CHARACTER*4 ARTICLE(3) !By chance, three, by happy chance, lengths 1, 2, 3! PARAMETER (ARTICLE = (/"A","AN","THE"/)) !These each have trailing space. INTEGER I !A stepper. DO I = 1,3 !So step through the known articles. IF (L1 + I.GT.L2) RETURN !Insufficient text? Give up. IF (STASH(L1:L1 + I).EQ.ARTICLE(I)(1:I + 1)) THEN !Starts with this one? STASH(L1:L2 - I - 1) = STASH(L1 + I + 1:L2) !Yes! Shift the rest back over it. STASH(L2 - I:L2 + 1) = ", "//ARTICLE(I)(1:I) !Place the article at the end. L2 = L2 + 1 !One more, for the comma. RETURN !Done! END IF !But if that article didn't match, END DO !Try the next. END SUBROUTINE LIBRARIAN !Ah, catalogue order. Blah, The. END FUNCTION ADDENTRY !That was fun!   SUBROUTINE SHOWENTRY(BLAH,E) !Ah, debugging. CHARACTER*(*) BLAH !With distinguishing mark. INTEGER E,P !Entry and part fingering. INTEGER L1,L2 !Fingers. L1 = ISTASH(TENTRY(E)) !The source text is stashed as text #TENTRY(E). L2 = ISTASH(TENTRY(E) + 1) - 1 !ISTASH(i) is where in STASH text #i starts. WRITE (MSG,1) BLAH,E,IENTRY(E),IENTRY(E + 1) - 1,STASH(L1:L2) 1 FORMAT (/,A," Entry(",I0,")=Pt ",I0," to ",I0,", text >",A,"<") DO P = IENTRY(E),IENTRY(E + 1) - 1 !Step through the part list. L1 = ISTASH(PARTT(P)) !Find the text of the part. L2 = ISTASH(PARTT(P) + 1) - 1 !Saved in STASH. WRITE (MSG,2) P,PARTT(P),PARTI(P),STASH(L1:L2) !The text is of variable length, 2 FORMAT ("Part(",I0,") = text#",I0,", N = ",I0," >",A,"<") !So present it *after* the number. END DO !On to the next part. END SUBROUTINE SHOWENTRY !Shows entry = <text><number>, <text><number>, ...   INTEGER FUNCTION ENTRYORDER(E1,E2) !Report on the order of entries E1 and E2. Chug through the parts list of the two entries, for each part comparing the text, then the number. INTEGER E1,E2 !Finger entries via TENTRY(i) and IENTRY(i)... INTEGER T1,T2 !Fingers texts in STASH. INTEGER I1,N1,I2,N2 !Fingers and counts. INTEGER I,D !A stepper and a difference. c CALL SHOWENTRY("E1",E1) c CALL SHOWENTRY("E2",E2) P1 = IENTRY(E1) !Finger the first parts P2 = IENTRY(E2) !Of the two entries. Compare the text part of the two parts. 10 T1 = PARTT(P1) !So, what is the number of the text, T2 = PARTT(P2) !Safely stored in STASH. IF (T1.NE.T2) THEN !Inspect text only if the text parts differ. I1 = ISTASH(T1) !Where its text is stashed. N1 = ISTASH(T1 + 1) - I1 !Thus the length of that text. I2 = ISTASH(T2) !First character of the other text. N2 = ISTASH(T2 + 1) - I2 !Thus its length. DO I = 1,MIN(N1,N2) !Step along both texts while they have characters to match. D = ICHAR(STASH(I2:I2)) - ICHAR(STASH(I1:I1)) !The difference. IF (D.NE.0) GO TO 666 !Is there a difference? I1 = I1 + 1 !No. I2 = I2 + 1 !Advance to the next character for both. END DO !And try again. Can't compare character pairs beyond the shorter of the two texts. D = N2 - N1 !Very well, which text is the shorter? IF (D.NE.0) GO TO 666 !No difference in length? END IF !So much for the text comparison. Compare the numeric part. D = PARTI(P2) - PARTI(P1) !Righto, compare the numeric side. IF (D.NE.0) GO TO 666 !A difference here? Can't find any difference between those two parts. P1 = P1 + 1 !Move on to the next part. P2 = P2 + 1 !For both entries. N1 = IENTRY(E1 + 1) - P1 !Knowing where the next entry's parts start N2 = IENTRY(E2 + 1) - P2 !Means knowing where an entry's parts end. IF (N1.GT.0 .AND. N2.GT.0) GO TO 10 !At least one for both, so compare the next pair. D = N2 - N1 !Thus, the shorter precedes the longer. Conclusion. 666 ENTRYORDER = D !Zero sez "equal". END FUNCTION ENTRYORDER !That was a struggle.   SUBROUTINE ORDERENTRY(LIST,N) Crank up a Comb sort of the entries fingered by LIST. Working backwards, just for fun. Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3. INTEGER LIST(*) !This is an index to the items being compared. INTEGER T !In the absence of a SWAP(a,b). Same type as LIST. INTEGER N !The number of entries. INTEGER I,H !Tools. H ought not be a small integer. LOGICAL CURSE !Annoyance. H = N - 1 !Last - First, and not +1. IF (H.LE.0) RETURN !Ha ha. 1 H = MAX(1,H*10/13) !The special feature. IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. CURSE = .FALSE. !So far, so good. DO I = N - H,1,-1 !If H = 1, this is a BubbleSort. IF (ENTRYORDER(LIST(I),LIST(I + H)).LT.0) THEN !One compare. T=LIST(I); LIST(I)=LIST(I+H); LIST(I+H)=T !One swap. CURSE = .TRUE. !One curse. END IF !One test. END DO !One loop. IF (CURSE .OR. H.GT.1) GO TO 1 !Work remains? END SUBROUTINE ORDERENTRY   CHARACTER*44 FUNCTION ENTRYTEXT(E) !Ad-hoc extraction of an entry's source text. INTEGER E !The desired entry's number. INTEGER P !A stage in the dereferencing. P = TENTRY(E) !Entry E's source text is #P. ENTRYTEXT = STASH(ISTASH(P):ISTASH(P + 1) - 1) !Stashed here. END FUNCTION ENTRYTEXT !Fixed size only, with trailing spaces.   CHARACTER*44 FUNCTION ENTRYTEXTCHAR(E) !The same, but with nasty characters defanged. USE BADCHARACTER !Just so. INTEGER E !The desired entry's number. INTEGER P !A stage in the dereferencing. CHARACTER*44 TEXT !A scratchpad, to avoid confusing the compiler. INTEGER I,L,H !Fingers. CHARACTER*1 C !A waystation. L = 0 !No text has been extracted. P = TENTRY(E) !Entry E's source text is #P. DO I = ISTASH(P),ISTASH(P + 1) - 1 !Step along the stash.. C = STASH(I:I) !Grab a character. H = INDEX(BADC,C) !Scan the shit list. IF (H.LE.0) THEN !One of the troublemakers? CALL PUT(C) !No. Just copy it. ELSE !Otherwise, CALL PUT("!") !Place a context changer. CALL PUT(GOODC(H:H)) !Place the corresponding mnemonic. END IF !So much for that character. END DO !On to the next. ENTRYTEXTCHAR = TEXT(1:MIN(L,44)) !Protect against overflow. CONTAINS !A trivial assistant. SUBROUTINE PUT(C) !But too messy to have in-line. CHARACTER*1 C !The character of the moment. L = L + 1 !Advance to place it. IF (L.LE.44) TEXT(L:L) = C !If within range. END SUBROUTINE PUT !Simple enough. END FUNCTION ENTRYTEXTCHAR !On output, the troublemakers make trouble.   SUBROUTINE ORDERENTRYTEXT(LIST,N) Crank up a Comb sort of the entries fingered by LIST. Working backwards, just for fun. Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3. INTEGER LIST(*) !This is an index to the items being compared. INTEGER T !In the absence of a SWAP(a,b). Same type as LIST. INTEGER N !The number of entries. INTEGER I,H !Tools. H ought not be a small integer. LOGICAL CURSE !Annoyance. H = N - 1 !Last - First, and not +1. IF (H.LE.0) RETURN !Ha ha. 1 H = MAX(1,H*10/13) !The special feature. IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. CURSE = .FALSE. !So far, so good. DO I = N - H,1,-1 !If H = 1, this is a BubbleSort. IF (ENTRYTEXT(LIST(I)).GT.ENTRYTEXT(LIST(I+H))) THEN !One compare. T=LIST(I); LIST(I)=LIST(I+H); LIST(I+H)=T !One swap. CURSE = .TRUE. !One curse. END IF !One test. END DO !One loop. IF (CURSE .OR. H.GT.1) GO TO 1 !Work remains? END SUBROUTINE ORDERENTRYTEXT END MODULE COMPOUND !Accepts, stores, lists and sorts the content.   PROGRAM MR NATURAL !Presents a list in sorted order. USE COMPOUND !Stores text in a complicated way. USE BADCHARACTER !Some characters wreck the layout. INTEGER I,ITEM(30),PLAIN(30) !Two sets of indices. I = 0 !An array must have equal-length items, so trailing spaces would result. I=I+1;ITEM(I) = ADDENTRY("ignore leading spaces: 2-2") I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2-1") I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2+0") I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2+1") I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2-2") I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2-1") I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2+0") I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2+1") I=I+1;ITEM(I) = ADDENTRY("Equiv."//" "//"spaces: 3-3") I=I+1;ITEM(I) = ADDENTRY("Equiv."//CR//"spaces: 3-2") !CR can't appear as itself. I=I+1;ITEM(I) = ADDENTRY("Equiv."//FF//"spaces: 3-1") !As it is used to mark line endings. I=I+1;ITEM(I) = ADDENTRY("Equiv."//VT//"spaces: 3+0") !And if typed in an editor, I=I+1;ITEM(I) = ADDENTRY("Equiv."//LF//"spaces: 3+1") !It is acted upon there and then. I=I+1;ITEM(I) = ADDENTRY("Equiv."//HT//"spaces: 3+2") !So, name instead of value. I=I+1;ITEM(I) = ADDENTRY("cASE INDEPENDENT: 3-2") I=I+1;ITEM(I) = ADDENTRY("caSE INDEPENDENT: 3-1") I=I+1;ITEM(I) = ADDENTRY("casE INDEPENDENT: 3+0") I=I+1;ITEM(I) = ADDENTRY("case INDEPENDENT: 3+1") I=I+1;ITEM(I) = ADDENTRY("foo100bar99baz0.txt") I=I+1;ITEM(I) = ADDENTRY("foo100bar10baz0.txt") I=I+1;ITEM(I) = ADDENTRY("foo1000bar99baz10.txt") I=I+1;ITEM(I) = ADDENTRY("foo1000bar99baz9.txt") I=I+1;ITEM(I) = ADDENTRY("The Wind in the Willows") I=I+1;ITEM(I) = ADDENTRY("The 40th step more") I=I+1;ITEM(I) = ADDENTRY("The 39 steps") I=I+1;ITEM(I) = ADDENTRY("Wanda") c I=I+1;ITEM(I) = ADDENTRY("A Dinosaur Grunts: Fortran Emerges") c I=I+1;ITEM(I) = ADDENTRY("The Joy of Text Twiddling with Fortran") c I=I+1;ITEM(I) = ADDENTRY("An Aversion to Unused Trailing Spaces") WRITE (MSG,*) "nEntry=",NENTRY !Reach into the compound storage area. PLAIN = ITEM !Copy the list of entries. CALL ORDERENTRY(ITEM,NENTRY) !"Natural" order. CALL ORDERENTRYTEXT(PLAIN,NENTRY) !Plain text order. WRITE (MSG,1) "Character","'Natural'" !Provide a heading. 1 FORMAT (2("Entry|Text ",A9," Order",24X)) !Usual trickery. DO I = 1,NENTRY !Step through the lot. WRITE (MSG,2) PLAIN(I),ENTRYTEXTCHAR(PLAIN(I)), !Plain order, 1 ITEM(I), ENTRYTEXTCHAR(ITEM(I)) !Followed by natural order. 2 FORMAT (2(I5,"|",A44)) !This follows function ENTRYTEXT. END DO !On to the next. END !A handy hint from Mr. Natural: "At home or at work, get the right tool for the job!"  
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#PicoLisp
PicoLisp
(de narcissist (Str) (= Str (str narcissist)) )
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#PowerShell
PowerShell
  function Narcissist { Param ( [string]$String ) If ( $String -eq $MyInvocation.MyCommand.Definition ) { 'Accept' } Else { 'Reject' } }  
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Python
Python
  import sys with open(sys.argv[0]) as quine: code = raw_input("Enter source code: ") if code == quine.read(): print("Accept") else: print("Reject")  
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Quackery
Quackery
Welcome to Quackery.   Enter "leave" to leave the shell.   /O> [ this copy unbuild = ] is narcissist ... $ "[ this copy unbuild = ]" narcissist ...   Stack: 1   /O> drop ... $ "Nothing is more important than my egomania. -- Clara Oswald" narcissist ...   Stack: 0   /O> leave ...   Cheerio.
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Forth
Forth
\ fetch and store usage examples VARIABLE MYINT1 VARIABLE MYINT2 2VARIABLE DOUBLE1 2VARIABLE DOUBLE2   MYINT1 @ MYINT2 ! MYDOUBLE 2@ MYDOUBLE 2!   \ record example using this convention   1000000 RECORDS PERSONEL   1 PERSONEL RECORD@ \ read Record 1 and put pointer on data stack   HR_RECORD 992 PERSONEL RECORD! \ store HR_RECORD  
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Fortran
Fortran
IMPLICIT REAL(A-H,O-Z), INTEGER(I-M)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Free_Pascal
Free Pascal
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   class SolarSystem(val star: Star) { private val planets = mutableListOf<Planet>() // some people might prefer _planets   init { for (planet in Planet.values()) planets.add(planet) }   fun listPlanets() { println(planets) } }   fun main(args: Array<String>) { val sun = Star("sun") val ss = SolarSystem(sun) sun.showDiameter() println("\nIts planetary system comprises : ") ss.listPlanets() }
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If there is no next highest integer return zero. *1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   N which can be obtained by reordering the (base ten) digits of   N". Algorithm 1   Generate all the permutations of the digits and sort into numeric order.   Find the number in the list.   Return the next highest number from the list. The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness. Algorithm 2   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.   Exchange that digit with the digit on the right that is both more than it, and closest to it.   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) E.g.: n = 12453 <scan> 12_4_53 <swap> 12_5_43 <order-right> 12_5_34 return: 12534 This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task),   is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle. Task requirements Calculate the next highest int from the digits of the following numbers:   0   9   12   21   12453   738440   45072010   95322020 Optional stretch goal   9589776899767587796600
#Ring
Ring
  load "stdlib.ring"   nhi = [0,9,12,21,12453,738440,45072010,95322020]   for p2 = 1 to len(nhi) permut = [] num2 = nhi[p2] nextHighestInt(num2) next   func nextHighestInt(num)   list = [] numStr = string(num) lenNum = len(numStr)   if lenNum = 1 see "" + num + " => " + "0" + nl return ok   for n = 1 to len(numStr) p = number(substr(numStr,n,1)) add(list,p) next   lenList = len(list) calmo = []   permut(list)   for n = 1 to len(permut)/lenList str = "" for m = (n-1)*lenList+1 to n*lenList str = str + string(permut[m]) next if str != "" strNum = number(str) add(calmo,strNum) ok next   for n = len(calmo) to 1 step -1 lenCalmo = len(string(calmo[n])) if lenCalmo < lenNum del(calmo,n) ok next   calmo = sort(calmo)   for n = len(calmo) to 2 step -1 if calmo[n] = calmo[n-1] del(calmo,n) ok next   ind = find(calmo,num) if ind = len(calmo) see "" + num + " => " + "0" + nl else see "" + num + " => " + calmo[ind+1] + nl ok   func permut(list) for perm = 1 to factorial(len(list)) for i = 1 to len(list) add(permut,list[i]) next perm(list) next   func perm(a) elementcount = len(a) if elementcount < 1 then return ok pos = elementcount-1 while a[pos] >= a[pos+1] pos -= 1 if pos <= 0 permutationReverse(a, 1, elementcount) return ok end last = elementcount while a[last] <= a[pos] last -= 1 end temp = a[pos] a[pos] = a[last] a[last] = temp permReverse(a, pos+1, elementcount)   func permReverse(a,first,last) while first < last temp = a[first] a[first] = a[last] a[last] = temp first += 1 last -= 1 end  
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If there is no next highest integer return zero. *1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   N which can be obtained by reordering the (base ten) digits of   N". Algorithm 1   Generate all the permutations of the digits and sort into numeric order.   Find the number in the list.   Return the next highest number from the list. The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness. Algorithm 2   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.   Exchange that digit with the digit on the right that is both more than it, and closest to it.   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) E.g.: n = 12453 <scan> 12_4_53 <swap> 12_5_43 <order-right> 12_5_34 return: 12534 This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task),   is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle. Task requirements Calculate the next highest int from the digits of the following numbers:   0   9   12   21   12453   738440   45072010   95322020 Optional stretch goal   9589776899767587796600
#Rust
Rust
fn next_permutation<T: PartialOrd>(array: &mut [T]) -> bool { let len = array.len(); if len < 2 { return false; } let mut i = len - 1; while i > 0 { let j = i; i -= 1; if array[i] < array[j] { let mut k = len - 1; while array[i] >= array[k] { k -= 1; } array.swap(i, k); array[j..len].reverse(); return true; } } false }   fn next_highest_int(n: u128) -> u128 { use std::iter::FromIterator; let mut chars: Vec<char> = n.to_string().chars().collect(); if !next_permutation(&mut chars) { return 0; } String::from_iter(chars).parse::<u128>().unwrap() }   fn main() { for n in &[0, 9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600] { println!("{} -> {}", n, next_highest_int(*n)); } }
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#OCaml
OCaml
let make_list separator = let counter = ref 1 in   let make_item item = let result = string_of_int !counter ^ separator ^ item ^ "\n" in incr counter; result in   make_item "first" ^ make_item "second" ^ make_item "third"   let () = print_string (make_list ". ")
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Pascal
Pascal
sub makeList { my $separator = shift; my $counter = 1;   sub makeItem { $counter++ . $separator . shift . "\n" }   makeItem("first") . makeItem("second") . makeItem("third") }   print makeList(". ");
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Perl
Perl
sub makeList { my $separator = shift; my $counter = 1;   sub makeItem { $counter++ . $separator . shift . "\n" }   makeItem("first") . makeItem("second") . makeItem("third") }   print makeList(". ");
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. Related task Sleep
#PL.2FI
PL/I
  nautical: procedure options (main); /* 29 October 2013 */ declare (hour, t, i) fixed binary;   do until (substr(time(), 3, 4) = '0000'); delay (1000); end; hour = substr(time(), 1, 2);   do while ('1'b); do i = 1 to hour; put edit ('07'X) (a); put skip edit ('gong ') (a); delay (500); end; t = substr(time(), 5); delay (60*60*1000 - t); end; end nautical;  
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. Related task Sleep
#PowerShell
PowerShell
  function Get-Bell { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position=0)] [ValidateRange(1,12)] [int] $Hour,   [Parameter(Mandatory=$true, Position=1)] [ValidateSet(0,30)] [int] $Minute )   $bells = @{ OneBell = 1 TwoBells = 2 ThreeBells = 2, 1 FourBells = 2, 2 FiveBells = 2, 2, 1 SixBells = 2, 2, 2 SevenBells = 2, 2, 2, 1 EightBells = 2, 2, 2, 2 }   filter Invoke-Bell { if ($_ -eq 1) { [System.Media.SystemSounds]::Asterisk.Play() Write-Host -NoNewline "♪" } else { [System.Media.SystemSounds]::Exclamation.Play() Write-Host -NoNewline "♪♪ " }   Start-Sleep -Milliseconds 500 }     $time = New-TimeSpan -Hours $Hour -Minutes $Minute   switch ($time.Hours) { 1 {if ($time.Minutes -eq 0) {$bells.TwoBells | Invoke-Bell} else {$bells.ThreeBells | Invoke-Bell}; break} 2 {if ($time.Minutes -eq 0) {$bells.FourBells | Invoke-Bell} else {$bells.FiveBells | Invoke-Bell}; break} 3 {if ($time.Minutes -eq 0) {$bells.SixBells | Invoke-Bell} else {$bells.SevenBells | Invoke-Bell}; break} 4 {if ($time.Minutes -eq 0) {$bells.EightBells | Invoke-Bell} else {$bells.OneBell | Invoke-Bell}; break} 5 {if ($time.Minutes -eq 0) {$bells.TwoBells | Invoke-Bell} else {$bells.ThreeBells | Invoke-Bell}; break} 6 {if ($time.Minutes -eq 0) {$bells.FourBells | Invoke-Bell} else {$bells.FiveBells | Invoke-Bell}; break} 7 {if ($time.Minutes -eq 0) {$bells.SixBells | Invoke-Bell} else {$bells.SevenBells | Invoke-Bell}; break} 8 {if ($time.Minutes -eq 0) {$bells.EightBells | Invoke-Bell} else {$bells.OneBell | Invoke-Bell}; break} 9 {if ($time.Minutes -eq 0) {$bells.TwoBells | Invoke-Bell} else {$bells.ThreeBells | Invoke-Bell}; break} 10 {if ($time.Minutes -eq 0) {$bells.FourBells | Invoke-Bell} else {$bells.FiveBells | Invoke-Bell}; break} 11 {if ($time.Minutes -eq 0) {$bells.SixBells | Invoke-Bell} else {$bells.SevenBells | Invoke-Bell}; break} 12 {if ($time.Minutes -eq 0) {$bells.EightBells | Invoke-Bell} else {$bells.OneBell | Invoke-Bell}} }   Write-Host }   Write-Host "Time Bells`n---- -----`n"   1..12 | ForEach-Object {   $date = Get-Date -Hour $_ -Minute 0 Write-Host -NoNewline "$($date.ToString("hh:mm")) " Get-Bell -Hour $_ -Minute 0   $date = $date.AddMinutes(30) Write-Host -NoNewline "$($date.ToString("hh:mm")) " Get-Bell -Hour $_ -Minute 30 }  
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
#Phix
Phix
with javascript_semantics integer count = 0 procedure ncs(sequence rest, object taken, integer ri=0, bool contig=false, bool gap=false) if ri>=length(rest) then if contig then if integer(taken) then count += 1 else ?taken end if end if else ri += 1 ncs(rest,iff(integer(taken)?taken+1:deep_copy(taken)&rest[ri]),ri,gap,gap) ncs(rest,taken,ri,contig,iff(integer(taken)?taken!=0:length(taken)!=0)) end if end procedure ncs({1,2,3},{}) ?"===" ncs({1,2,3,4},{}) ?"===" atom t0 = time() sequence s = {} for i=1 to 20 do count = 0 ncs(tagset(i),0) s = append(s,count) end for ?elapsed(time()-t0) pp(s)
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Forth
Forth
42 dup 2 base ! . \ 101010 hex . \ 2A decimal
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Tcl
Tcl
package require Tcl 8.6; # For easy scanning of binary   # The strings to parse set dec1 "0123459" set hex2 "abcf123" set oct3 "7651" set bin4 "101011001"   # Parse the numbers scan $dec1 "%d" v1 scan $hex2 "%x" v2 scan $oct3 "%o" v3 scan $bin4 "%b" v4; # Only 8.6-specific operation; others work in all versions   # Print out what happened puts "$dec1->$v1 $hex2->$v2 $oct3->$v3 $bin4->$v4"
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Wren
Wren
import "/fmt" for Conv, Fmt   var tests = [ ["0b1110", 2], ["112", 3], ["0o16", 8], ["14", 10], ["0xe", 16], ["e", 19] ] for (test in tests) { System.print("%(Fmt.s(6, test[0])) in base %(Fmt.d(-2, test[1])) = %(Conv.atoi(test[0], test[1]))") }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Run_BASIC
Run BASIC
  print asc("X") ' convert to ascii print chr$(169) ' ascii to character print dechex$(255) ' decimal to hex print hexdec("FF") ' hex to decimal print str$(467) ' decimal to string print val("27") ' string to decimal  
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Scala
Scala
object Main extends App { val radices = List(2, 8, 10, 16, 19, 36) for (base <- radices) print(f"$base%6d") println(s"""\n${"-" * (6 * radices.length)}""") for (i <- BigInt(0) to 35; // BigInt has a toString(radix) method radix <- radices; eol = if (radix == radices.last) '\n' else '\0' ) print(f"${i.toString(radix)}%6s$eol") }
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.
#Perl
Perl
use strict; use feature 'say'; use POSIX qw(floor); use ntheory qw/fromdigits todigits/;   sub encode { my($n, $b) = @_; my @out; my $r = 0;   while ($n) { $r = $n % $b; $n = floor $n/$b; $n += 1, $r -= $b if $r < 0; push @out, todigits($r, -$b) || 0; } join '', reverse @out; }   sub decode { my($s, $b) = @_; my $total = 0; my $i = 0; for my $c (reverse split '', $s) { $total += (fromdigits($c, -$b) * $b**$i); $i++; } $total }   say ' 10 in base -2: ', encode(10, -2); say ' 15 in base -10: ', encode(15, -10); say '146 in base -3: ', encode(146, -3); say ''; say '11110 from base -2: ', decode("11110", -2); say '21102 from base -3: ', decode("21102", -3); say ' 195 from base -10: ', decode("195", -10);
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#zkl
zkl
var ns =[1..20].chain([30..90,10]).walk(), names=T("one","two","three","four","five","six","seven","eight","nine", "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen", "seventeen","eighteen","nineteen","twenty", "thirty","forty","fifty","sixty","seventy","eighty","ninety"), hs =T( 100, 1000, 1000000, 1000000000,1000000000000), hnames=T("hundred","thousand","million","billion", "trillion");   fcn numberToString(n){ // n>0 fcn(n){ if(100<=n<0d100_000_0000_000){ idx,h,name,r := hs.filter1n('>(n))-1, hs[idx], hnames[idx], n%h; String(self.fcn(n/h),name, if(r==0) "" else if(0<r<100) " and " else ", ", self.fcn(r)); }else if(0<n<=90){ idx,t,name,r := ns.filter1n('>(n))-1, ns[idx], names[idx], n-t; String(name, if(0<r<10) "-" else " ", self.fcn(r)); }else "" }(n).strip() // sometimes there is a trailing space }
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.
#Phix
Phix
without js -- getc integer tokens = 12, player = 0 while true do printf(1,"%2d tokens remaining. ",tokens) if tokens=0 then printf(1,"Computer wins.\n") exit end if printf(1,"How many tokens do you want to remove; 1, 2, or 3?:") while player<1 or player>3 do player=getc(0)-'0' end while printf(1,"%d. Computer takes %d.\n",{player,4-player}) tokens -= 4; player = 0 end while
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.
#Pike
Pike
int tokens = 12;   void get_tokens(int cur_tokens) { write("How many tokens would you like to take? "); int take = (int)Stdio.stdin->gets();   if (take < 1 || take > 3) { write("Number must be between 1 and 3.\n"); get_tokens(cur_tokens); } else { tokens = cur_tokens - take; write("You take " + (string)take + " tokens\n"); write((string)tokens + " tokens remaing\n\n"); } }   void comp_turn(int cur_tokens) { int take = cur_tokens % 4; tokens = cur_tokens - take; write("Computer take " + (string)take + " tokens\n"); write((string)tokens + " tokens remaing\n\n"); }   int main() { write("Pike Nim\n\n"); while(tokens > 0) { get_tokens(tokens); comp_turn(tokens); } write("Computer wins!\n"); return 0; }
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.
#ALGOL_68
ALGOL 68
# find some narcissistic decimal numbers #   # returns TRUE if n is narcissitic, FALSE otherwise; n should be >= 0 # PROC is narcissistic = ( INT n )BOOL: BEGIN # count the number of digits in n # INT digits := 0; INT number := n; WHILE digits +:= 1; number OVERAB 10; number > 0 DO SKIP OD; # sum the digits'th powers of the digits of n # INT sum := 0; number := n; TO digits DO sum +:= ( number MOD 10 ) ^ digits; number OVERAB 10 OD; # n is narcissistic if n = sum # n = sum END # is narcissistic # ;   # print the first 25 narcissistic numbers # INT count := 0; FOR n FROM 0 WHILE count < 25 DO IF is narcissistic( n ) THEN # found another narcissistic number # print( ( " ", whole( n, 0 ) ) ); count +:= 1 FI OD; print( ( newline ) )
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
#Applesoft_BASIC
Applesoft BASIC
100 IF LAST$ = "" THEN PRINT "?"; 110 IF LAST$ < > "" THEN PRINT LAST$; 120 IF FIRST$ < > "" THEN PRINT ", "FIRST$; 200 FIRST$ = "" 210 LAST$ = "" 220 RETURN
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
#Arturo
Arturo
func: function [x][ print ["argument x:" x] print ["attribute foo:" attr 'foo] print ["attribute bar:" attr 'bar] print "" ]   func 1 func .foo:"foo" 2 func .bar:"bar" 3 func .foo:123 .bar:124 4 func .bar:124 .foo:123 5
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Clojure
Clojure
  (ns test-project-intellij.core (:gen-class))   ;; define abs & power to avoid needing to bring in the clojure Math library (defn abs [x] " Absolute value" (if (< x 0) (- x) x))   (defn power [x n] " x to power n, where n = 0, 1, 2, ... " (apply * (repeat n x)))   (defn calc-delta [A x n] " nth rooth algorithm delta calculation " (/ (- (/ A (power x (- n 1))) x) n))   (defn nth-root " nth root of algorithm: A = numer, n = root" ([A n] (nth-root A n 0.5 1.0)) ; Takes only two arguments A, n and calls version which takes A, n, guess-prev, guess-current ([A n guess-prev guess-current] ; version take takes in four arguments (A, n, guess-prev, guess-current) (if (< (abs (- guess-prev guess-current)) 1e-6) guess-current (recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion    
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.
#8086_Assembly
8086 Assembly
bits 16 cpu 8086 segment .text org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Given a number in AX, return string with ordinal suffix ;; in DX. nth: mov cx,10 ; Divisor mov bx,.sfx ; Pointer to end of number .digit: xor dx,dx ; Zero DX div cx ; AX = DX:AX/10; DX=remainder add dl,'0' ; Make digit dec bx ; Back up the pointer mov [bx],dl ; Store digit and ax,ax ; Done yet? (AX=0?) jnz .digit ; If not, get next digit mov dx,bx ; Keep string pointer in DX xor bx,bx ; Default suffix is 'th'. cmp byte [.num+3],'1' ; Is the tens digit '1'? je .setsfx ; Then the suffix is 'th'. mov cl,[.num+4] ; Get the ones digit cmp cl,'4' ; Is it '4' or higher? jae .setsfx ; Then the suffix is 'th'. mov bl,cl sub bl,'0' ; Calculate offset. shl bl,1 ; [0..3]*2 + .ord .setsfx: mov ax,[bx+.ordsfx] ; Set suffix mov [.sfx],ax ret .ordsfx: db 'thstndrd' .num: db '*****' .sfx: db '**$' ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Print numbers. demo: mov ax,0 ; Starting at 0... mov bl,26 ; ...print 26 numbers [0..25] call printn mov ax,250 ; Starting at 250... mov bl,16 ; ...print 16 numbers [250..265] call printn mov ax,1000 ; Starting at 1000... mov bl,26 ; ...print 26 numbers [1000..1025] ;; Print BL numbers starting at AX printn: push ax ; Keep number push bx ; Keep counter call nth ; Get string for current AX mov ah,9 ; MS-DOS print string int 21h mov dl,' ' ; Separate numbers by spaces mov ah,2 ; MS-DOS print character int 21h pop bx ; Restore counter pop ax ; Restore number inc ax ; Next number dec bl ; Are we done yet? jnz printn ret
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
#AWK
AWK
  # syntax: GAWK -f MOBIUS_FUNCTION.AWK # converted from Java BEGIN { printf("first 199 terms of the mobius sequence:\n ") for (n=1; n<200; n++) { printf("%3d",mobius(n)) if ((n+1) % 20 == 0) { printf("\n") } } exit(0) } function mobius(n, i,j,mu_max) { if (n in MU) { return(MU[n]) } mu_max = 1000000 for (i=0; i<mu_max; i++) { # populate array MU[i] = 1 } for (i=2; i<=int(sqrt(mu_max)); i++ ) { if (MU[i] == 1) { for (j=i; j<=mu_max; j+=i) { # for each factor found, swap + and - MU[j] *= -i } for (j=i*i; j<=mu_max; j+=i*i) { # square factor = 0 MU[j] = 0 } } } for (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']
#Go
Go
package main   import ( "fmt" "regexp" "sort" "strconv" "strings" )   var tests = []struct { descr string list []string }{ {"Ignoring leading spaces", []string{ "ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1", }}, {"Ignoring multiple adjacent spaces", []string{ "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", }}, {"Equivalent whitespace characters", []string{ "Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\fspaces: 3-1", "Equiv.\bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2", }}, {"Case Indepenent sort", []string{ "cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1", }}, {"Numeric fields as numerics", []string{ "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt", }}, }   func main() { for _, test := range tests { fmt.Println(test.descr) fmt.Println("Input order:") for _, s := range test.list { fmt.Printf("  %q\n", s) } fmt.Println("Natural order:") l := make(list, len(test.list)) for i, s := range test.list { l[i] = newNatStr(s) } sort.Sort(l) for _, s := range l { fmt.Printf("  %q\n", s.s) } fmt.Println() } }   // natStr associates a string with a preprocessed form type natStr struct { s string // original t []tok // preprocessed "sub-fields" }   func newNatStr(s string) (t natStr) { t.s = s s = strings.ToLower(strings.Join(strings.Fields(s), " ")) x := dx.FindAllString(s, -1) t.t = make([]tok, len(x)) for i, s := range x { if n, err := strconv.Atoi(s); err == nil { t.t[i].n = n } else { t.t[i].s = s } } return t }   var dx = regexp.MustCompile(`\d+|\D+`)   // rule is to use s unless it is empty, then use n type tok struct { s string n int }   // rule 2 of "numeric sub-fields" from talk page func (f1 tok) Cmp(f2 tok) int { switch { case f1.s == "": switch { case f2.s > "" || f1.n < f2.n: return -1 case f1.n > f2.n: return 1 } case f2.s == "" || f1.s > f2.s: return 1 case f1.s < f2.s: return -1 } return 0 }   type list []natStr   func (l list) Len() int { return len(l) } func (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l list) Less(i, j int) bool { ti := l[i].t for k, t := range l[j].t { if k == len(ti) { return true } switch ti[k].Cmp(t) { case -1: return true case 1: return false } } return false }
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Racket
Racket
  -> ((lambda (x) (equal? (read) (list x (list 'quote x)))) '(lambda (x) (equal? (read) (list x (list 'quote x))))) ((lambda (x) (equal? (read) (list x (list 'quote x)))) '(lambda (x) (equal? (read) (list x (list 'quote x))))) #t  
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Raku
Raku
EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#REXX
REXX
/*REXX*/ say arg(1)=sourceline(1)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#FreeBASIC
FreeBASIC
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   class SolarSystem(val star: Star) { private val planets = mutableListOf<Planet>() // some people might prefer _planets   init { for (planet in Planet.values()) planets.add(planet) }   fun listPlanets() { println(planets) } }   fun main(args: Array<String>) { val sun = Star("sun") val ss = SolarSystem(sun) sun.showDiameter() println("\nIts planetary system comprises : ") ss.listPlanets() }
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Go
Go
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   class SolarSystem(val star: Star) { private val planets = mutableListOf<Planet>() // some people might prefer _planets   init { for (planet in Planet.values()) planets.add(planet) }   fun listPlanets() { println(planets) } }   fun main(args: Array<String>) { val sun = Star("sun") val ss = SolarSystem(sun) sun.showDiameter() println("\nIts planetary system comprises : ") ss.listPlanets() }
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If there is no next highest integer return zero. *1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   N which can be obtained by reordering the (base ten) digits of   N". Algorithm 1   Generate all the permutations of the digits and sort into numeric order.   Find the number in the list.   Return the next highest number from the list. The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness. Algorithm 2   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.   Exchange that digit with the digit on the right that is both more than it, and closest to it.   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) E.g.: n = 12453 <scan> 12_4_53 <swap> 12_5_43 <order-right> 12_5_34 return: 12534 This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task),   is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle. Task requirements Calculate the next highest int from the digits of the following numbers:   0   9   12   21   12453   738440   45072010   95322020 Optional stretch goal   9589776899767587796600
#Sidef
Sidef
func next_from_digits(n, b = 10) {   var a = n.digits(b).flip   while (a.next_permutation) { with (a.flip.digits2num(b)) { |t| return t if (t > n) } }   return 0 }   say 'Next largest integer able to be made from these digits, or zero if no larger exists:'   for n in ( 0, 9, 12, 21, 12453, 738440, 3345333, 45072010, 95322020, 982765431, 9589776899767587796600, ) { printf("%30s ->  %s\n", n, next_from_digits(n)) }
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Phix
Phix
function MakeList(string sep=". ") function MakeItem(integer env, string sep) integer counter = getd("counter",env)+1 setd("counter",counter,env) return sprintf("%d%s%s",{counter,sep,{"first","second","third"}[counter]}) end function integer counter = new_dict({{"counter",0}}) sequence res = {} for i=1 to 3 do res = append(res,MakeItem(counter,sep)) end for return res end function   ?MakeList()
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#PHP
PHP
<? function makeList($separator) { $counter = 1;   $makeItem = function ($item) use ($separator, &$counter) { return $counter++ . $separator . $item . "\n"; };   return $makeItem("first") . $makeItem("second") . $makeItem("third"); }   echo makeList(". "); ?>
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. Related task Sleep
#Python
Python
import time, calendar, sched, winsound   duration = 750 # Bell duration in ms freq = 1280 # Bell frequency in hertz bellchar = "\u2407" watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')   def gap(n=1): time.sleep(n * duration / 1000) off = gap   def on(n=1): winsound.Beep(freq, n * duration)   def bong(): on(); off(0.5)   def bongs(m): for i in range(m): print(bellchar, end=' ') bong() if i % 2: print(' ', end='') off(0.5) print('')   scheds = sched.scheduler(time.time, time.sleep)   def ships_bell(now=None): def adjust_to_half_hour(atime): atime[4] = (atime[4] // 30) * 30 atime[5] = 0 return atime   debug = now is not None rightnow = time.gmtime() if not debug: now = adjust_to_half_hour( list(rightnow) ) then = now[::] then[4] += 30 hr, mn = now[3:5] watch, b = divmod(int(2 * hr + mn // 30 - 1), 8) b += 1 bells = '%i bell%s' % (b, 's' if b > 1 else ' ') if debug: print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ') else: print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ') bongs(b) if not debug: scheds.enterabs(calendar.timegm(then), 0, ships_bell) #print(time.struct_time(then)) scheds.run()   def dbg_tester(): for h in range(24): for m in (0, 30): if (h,m) == (24,30): break ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )     if __name__ == '__main__': ships_bell()
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
#Picat
Picat
import util.   go => println(1..4=non_cont(1..4)), L = "abcde".reverse(), println(L=non_cont(L)), println(ernit=non_cont("ernit")), println(aaa=non_cont("aaa")), println(aeiou=non_cont("aeiou")), nl,   println("Printing just the lengths for 1..N for N = 1..20:"), foreach(N in 1..20) println(1..N=non_cont(1..N).length) % just the length end, nl.   % get all the non-continuous subsequences non_cont(L) = [ [L[I] : I in S] : S in non_cont_ixs(L.length)].   % get all the index positions that are non-continuous non_cont_ixs(N) = [ P: P in power_set(1..N), length(P) > 1, P.last() - P.first() != P.length-1].
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
#PicoLisp
PicoLisp
(de ncsubseq (Lst) (let S 0 (recur (S Lst) (ifn Lst (and (>= S 3) '(NIL)) (let (X (car Lst) XS (cdr Lst)) (ifn (bit? 1 S) # even (conc (mapcar '((YS) (cons X YS)) (recurse (inc S) XS) ) (recurse S XS) ) (conc (mapcar '((YS) (cons X YS)) (recurse S XS) ) (recurse (inc S) 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.
#Fortran
Fortran
MODULE Conversion IMPLICIT NONE CHARACTER(36) :: alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"   CONTAINS   FUNCTION ToDecimal(base, instr) INTEGER :: ToDecimal INTEGER :: length, i, n, base CHARACTER(*) :: instr   ToDecimal = 0 length = LEN(instr) DO i = 1, length n = INDEX(alphanum, instr(i:i)) - 1 n = n * base**(length-i) Todecimal = ToDecimal + n END DO END FUNCTION ToDecimal   FUNCTION ToBase(base, number) CHARACTER(31) :: ToBase INTEGER :: base, number, i, rem   ToBase = " " DO i = 31, 1, -1 IF(number < base) THEN ToBase(i:i) = alphanum(number+1:number+1) EXIT END IF rem = MOD(number, base) ToBase(i:i) = alphanum(rem+1:rem+1) number = number / base END DO ToBase = ADJUSTL(ToBase) END FUNCTION ToBase   END MODULE Conversion   PROGRAM Base_Convert USE Conversion   WRITE (*,*) ToDecimal(16, "1a") WRITE (*,*) ToBase(16, 26)   END PROGRAM
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#XPL0
XPL0
include c:\cxpl\codes; int N; real R; [Text(8, "123_456"); N:= IntIn(8); IntOut(0, N); CrLf(0); Text(8, "ABcd12"); N:= HexIn(8); HexOut(0, N); CrLf(0); Text(8, "-3.14159e3"); R:= RlIn(8); RlOut(0, R); CrLf(0); ]
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#zkl
zkl
fcn b2b(base){ ns:=[20..30].pump(List,T("toString",base)); ns.println(); ns.pump(List,T("toInt",base)).println("\n") } b2b(2); b2b(10); b2b(16); b2b(19);
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Scheme
Scheme
(do ((i 0 (+ i 1))) ((>= i 33)) (display (number->string i 2)) ; binary (display " ") (display (number->string i 8)) ; octal (display " ") (display (number->string i 10)) ; decimal, the "10" is optional (display " ") (display (number->string i 16)) ; hex (newline))
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: i is 0; begin for i range 1 to 33 do writeln(i lpad 6 <& i radix 8 lpad 6 <& i radix 16 lpad 6); end for; end func;
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.
#Phix
Phix
with javascript_semantics constant digits = "0123456789"& "ABCDEFGHIJKLMNOPQRSTUVWXYZ"& "abcdefghijklmnopqrstuvwxyz" type base(integer b) return b<=-1 and b>=-length(digits) end type function encodeNegBase(atom n, base b) string res = iff(n?"":"0") while n!=0 do atom r = remainder(n,b) n = trunc(n/b) if r<0 then n += 1 r -= b end if res &= digits[r+1] end while return reverse(res) end function function decodeNegBase(string ns, base b) atom total = 0, bb = 1 for i=length(ns) to 1 by -1 do integer k = find(ns[i],digits)-1 if k=-1 or k>-b then return "invalid digit" end if total += k*bb bb *= b end for return total end function -- decimal, base, expected constant tests = {{10, -2, "11110"}, {146, -3, "21102"}, {15, -10, "195"}, {-5795577,-62, "Phix"}} for i=1 to length(tests) do {atom n, atom b, string e} = tests[i] string ns = encodeNegBase(n, b) printf(1,"%9d in base %-3d is %6s\n", {n, b, ns}) atom nn = decodeNegBase(ns, b) string ok = iff(ns=e and nn=n?""," ????") printf(1,"%9d <--------------'%s\n",{nn,ok}) end for
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.
#Plain_English
Plain English
To run: Start up. Play the game of Nim. Write "The computer wins! Press esc to exit." on the console. Wait for the escape key. Shut down.   A piece is a number.   To play the game of Nim: Put 12 into a piece count. Loop. If the piece count is 0, exit. Write "There are " then the piece count then " pieces remaining." on the console. Ask the player to take some pieces. Subtract the pieces from the piece count. Ask the computer to take some other pieces given the pieces. Subtract the other pieces from the piece count. Repeat.   To ask the player to take some pieces: Write "Would you like to take 1, 2, or 3 pieces? " on the console without advancing. Read a count from the console. If the count is not between 1 and 3, repeat. Format the count and "piece" or "pieces" into a string. Write "You took " then the string then "." on the console. Put the count into the pieces.   To ask the computer to take some pieces given some other pieces: Put 4 minus the other pieces into a count. Format the count and "piece" or "pieces" into a string. Write "The computer took " then the string then "." on the console. Put the count into the pieces.
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.
#Prolog
Prolog
nim :- next_turn(12), !.   next_turn(N) :- % Player Turn format('How many dots would you like to take? '), read_line_to_codes(user_input, Line), number_codes(PlayerGuess, Line), member(PlayerGuess,[1,2,3]), N1 is N - PlayerGuess, format('You take ~d dots~n~d dots remaining.~n~n', [PlayerGuess, N1]),   % Computer Turn CompGuess is 4 - PlayerGuess, N2 is N1 - CompGuess, format('Computer takes ~d dots~n~d dots remaining.~n~n', [CompGuess, N2]), ( N2 = 0 -> format('Computer wins!') ; next_turn(N2) ).
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.
#ALGOL_W
ALGOL W
begin  % print the first 25 narcissistic numbers  %   integer array power( 0 :: 9 ); integer count, candidate, prevDigits, digits;   power( 0 ) := 0; for i := 1 until 9 do power( i ) := 1;   count  := 0; candidate  := 0; prevDigits := 0; digits  := 1;   for d9 := 0 until 2 do begin if d9 > 0 and digits < 9 then digits := 9; for d8 := 0 until 9 do begin if d8 > 0 and digits < 8 then digits := 8; for d7 := 0 until 9 do begin if d7 > 0 and digits < 7 then digits := 7; for d6 := 0 until 9 do begin if d6 > 0 and digits < 6 then digits := 6; for d5 := 0 until 9 do begin if d5 > 0 and digits < 5 then digits := 5; for d4 := 0 until 9 do begin if d4 > 0 and digits < 4 then digits := 4; for d3 := 0 until 9 do begin if d3 > 0 and digits < 3 then digits := 3; for d2 := 0 until 9 do begin if d2 > 0 and digits < 2 then digits := 2; for d1 := 0 until 9 do begin integer number, sum; if prevDigits <> digits then begin  % number of digits has increased %  % - increase the powers  % prevDigits := digits; for i := 2 until 9 do power( i ) := power( i ) * i; end;    % sum the digits'th powers of the  %  % digits of candidate  % sum := power( d1 ) + power( d2 ) + power( d3 ) + power( d4 ) + power( d5 ) + power( d6 ) + power( d7 ) + power( d8 ) + power( d9 )  ; if candidate = sum then begin  % found another narcissistic  %  % decimal number  % writeon( i_w := 1, s_w := 1, candidate ); count := count + 1; if count >= 25 then goto done end; candidate := candidate + 1 end d1; end d2; end d3; end d4; end d5; end d6; end d7; end d8; end d9; done: write()   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
#11l
11l
V primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]   F isPrime(n) I n < 2 R 0B   L(i) :primes I n == i R 1B I n % i == 0 R 0B I i * i > n R 1B print(‘Oops, ’n‘ is too large’) R 0B   F init() V s = 24 L s < 600 I isPrime(s - 1) & s - 1 > :primes.last  :primes.append(s - 1) I isPrime(s + 1) & s + 1 > :primes.last  :primes.append(s + 1) s += 6   F nsmooth(n, size) assert(n C 2..521) assert(size >= 1)   V bn = n V ok = 0B L(prime) :primes I bn == prime ok = 1B L.break assert(ok, ‘must be a prime number’)   V ns = [BigInt(0)] * size ns[0] = 1   [BigInt] next L(prime) :primes I prime > bn L.break next.append(prime)   V indicies = [0] * next.len L(m) 1 .< size ns[m] = min(next) L(i) 0 .< indicies.len I ns[m] == next[i] indicies[i]++ next[i] = :primes[i] * ns[indicies[i]]   R ns   init()   L(p) primes I p >= 30 L.break print(‘The first ’p‘ -smooth numbers are:’) print(nsmooth(p, 25)) print()   L(p) primes[1..] I p >= 30 L.break print(‘The 3000 to 3202 ’p‘ -smooth numbers are:’) print(nsmooth(p, 3002)[2999..]) print()   L(p) [503, 509, 521] print(‘The 30000 to 3019 ’p‘ -smooth numbers are:’) print(nsmooth(p, 30019)[29999..]) print()
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called. For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2. func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before. Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL. See also: Varargs Optional parameters Wikipedia: Named parameter
#AutoHotkey
AutoHotkey
MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )   MyFunc( _overrides="" ) { Static x=5, y=5, w=100, h=100, Count Name:="AutoHotkey", Type:="Scripting", Text:="qwerty", Val:=True   Loop, Parse, _overrides,`,=, %A_Space% ; Override routine for Local/Static variables A_Index & 1  ? (_:=A_LoopField) : (%_%:=A_LoopField)   Listvars WinWaitClose, %A_ScriptFullPath% }
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
#Bracmat
Bracmat
( ( testproc = i x y z . out$"Calling testproc" & (=~):(=?i:?x:?y:?z) { initialise variables to 'failure' } &  !arg  : (? (i,?i) ?|?) { if "i" found, assign value to i. Otherwise just match with no side effect. }  : (? (x,?x) ?|?) { if "x" found, assign value to x. Otherwise just match with no side effect. }  : (? (y,?y) ?|?) { likewise }  : (? (z,?z) ?|?) { likewise } & (~!i|put$(" i:=" !i)) { if variable doesn't fail, show its value } & (~!x|put$(" x:=" !x)) & (~!y|put$(" y:=" !y)) & (~!z|put$(" z:=" !z)) & put$\n { add new line } ) & testproc$((x,1) (y,2) (z,3)) & testproc$((x,3) (y,1) (z,2)) & testproc$((z,4) (x,2) (y,3)) { order is not important } & testproc$((i,1) (y,2) (z,3)) );
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.
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. Nth-Root. AUTHOR. Bill Gunshannon. INSTALLATION. DATE-WRITTEN. 4 Feb 2020. ************************************************************ ** Program Abstract: ** Compute the Nth Root of a positive real number. ** ** Takes values from console. If Precision is left ** blank defaults to 0.001. ** ** Enter 0 for first value to terminate program. ************************************************************   ENVIRONMENT DIVISION.   INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT Root-File ASSIGN TO "Root-File" ORGANIZATION IS LINE SEQUENTIAL.   DATA DIVISION.   FILE SECTION.   FD Root-File DATA RECORD IS Parameters. 01 Parameters. 05 Root PIC 9(5). 05 Num PIC 9(5)V9(5). 05 Precision PIC 9V9(9).     WORKING-STORAGE SECTION.   01 TEMP0 PIC 9(9)V9(9). 01 TEMP1 PIC 9(9)V9(9). 01 RESULTS. 05 Field1 PIC ZZZZZ.ZZZZZ. 05 FILLER PIC X(5). 05 Field2 PIC ZZZZ9. 05 FILLER PIC X(14). 05 Field3 PIC 9.999999999.   01 HEADER. 05 FILLER PIC X(72) VALUE " Number Root Precision.".   01 Disp-Root PIC ZZZZZ.ZZZZZ.   PROCEDURE DIVISION.   Main-Program. PERFORM FOREVER   PERFORM Get-Input IF Precision = 0.0 THEN MOVE 0.001 to Precision END-IF   PERFORM Compute-Root   MOVE Root TO Field2 MOVE Num TO Field1 MOVE Precision TO Field3 DISPLAY HEADER DISPLAY RESULTS DISPLAY " " MOVE TEMP1 TO Disp-Root DISPLAY "The Root is: " Disp-Root END-PERFORM.   Get-Input. DISPLAY "Input Base Number: " WITH NO ADVANCING ACCEPT Num IF Num EQUALS ZERO THEN DISPLAY "Good Bye." STOP RUN END-IF DISPLAY "Input Root: " WITH NO ADVANCING ACCEPT Root DISPLAY "Input Desired Precision: " WITH NO ADVANCING ACCEPT Precision.   Compute-Root. MOVE Root TO TEMP0 DIVIDE Num BY Root GIVING TEMP1   PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) LESS THAN Precision MOVE TEMP1 TO TEMP0 COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num / TEMP1 ** (Root - 1.0)) / Root END-PERFORM.   END-PROGRAM.    
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.
#Action.21
Action!
PROC Nth(CARD val,CHAR ARRAY s) CHAR ARRAY sfx BYTE d   StrC(val,s) s(0)=s(0)+1 s(s(0))=''   d=val MOD 100 IF d>10 AND d<14 THEN sfx="th" ELSE d=val MOD 10 IF d=1 THEN sfx="st" ELSEIF d=2 THEN sfx="nd" ELSEIF d=3 THEN sfx="rd" ELSE sfx="th" FI FI   s(0)=s(0)+2 SAssign(s,sfx,s(0)-1,s(0)+1) RETURN   PROC Main() CARD ARRAY n=[0 250 1000] CHAR ARRAY s(10) CARD i,j   FOR i=0 TO 2 DO FOR j=n(i) TO n(i)+25 DO Nth(j,s) PrintF("%S ",s) OD PutE() PutE() OD RETURN
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
#BASIC256
BASIC256
function mobius(n) if n = 1 then return 1 for d = 2 to int(sqr(n)) if n mod d = 0 then if n mod (d*d) = 0 then return 0 return -mobius(n/d) end if next d return -1 end function   outstr$ = " . " for i = 1 to 200 if mobius(i) >= 0 then outstr$ += " " outstr$ += string(mobius(i)) + " " if i mod 10 = 9 then print outstr$ outstr$ = "" end if next i 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
#C
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   int main() { const int MU_MAX = 1000000; int i, j; int *mu; int sqroot;   sqroot = (int)sqrt(MU_MAX);   mu = malloc((MU_MAX + 1) * sizeof(int));   for (i = 0; i < MU_MAX;i++) { mu[i] = 1; }   for (i = 2; i <= sqroot; i++) { if (mu[i] == 1) { // for each factor found, swap + and - for (j = i; j <= MU_MAX; j += i) { mu[j] *= -i; } // square factor = 0 for (j = i * i; j <= MU_MAX; j += i * i) { mu[j] = 0; } } }   for (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; } }   printf("First 199 terms of the möbius function are as follows:\n "); for (i = 1; i < 200; i++) { printf("%2d ", mu[i]); if ((i + 1) % 20 == 0) { printf("\n"); } }   free(mu); return 0; }
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a human reader. There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include: 1. Ignore leading, trailing and multiple adjacent spaces 2. Make all whitespace characters equivalent. 3. Sorting without regard to case. 4. Sorting numeric portions of strings in numeric order. That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers. foo9.txt before foo10.txt As well as ... x9y99 before x9y100, before x10y0 ... (for any number of groups of integers in a string). 5. Title sorts: without regard to a leading, very common, word such as 'The' in "The thirty-nine steps". 6. Sort letters without regard to accents. 7. Sort ligatures as separate letters. 8. Replacements: Sort German eszett or scharfes S (ß)       as   ss Sort ſ, LATIN SMALL LETTER LONG S     as   s Sort ʒ, LATIN SMALL LETTER EZH           as   s ∙∙∙ Task Description Implement the first four of the eight given features in a natural sorting routine/function/method... Test each feature implemented separately with an ordered list of test strings from the   Sample inputs   section below,   and make sure your naturally sorted output is in the same order as other language outputs such as   Python. Print and display your output. For extra credit implement more than the first four. Note:   it is not necessary to have individual control of which features are active in the natural sorting routine at any time. Sample input • Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2', 'ignore leading spaces: 2-1', 'ignore leading spaces: 2+0', 'ignore leading spaces: 2+1'] • Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2', 'ignore MAS spaces: 2-1', 'ignore MAS spaces: 2+0', 'ignore MAS spaces: 2+1'] • Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3', 'Equiv. \rspaces: 3-2', 'Equiv. \x0cspaces: 3-1', 'Equiv. \x0bspaces: 3+0', 'Equiv. \nspaces: 3+1', 'Equiv. \tspaces: 3+2'] • Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2', 'caSE INDEPENDENT: 3-1', 'casE INDEPENDENT: 3+0', 'case INDEPENDENT: 3+1'] • Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] • Title sorts. Text strings: ['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] • Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] • Separated ligatures. Text strings: [u'\u0132 ligatured ij', 'no ligature'] • Character replacements. Text strings: [u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1']
#Haskell
Haskell
  import Data.List import Data.Char import Data.String.Utils import Data.List.Utils import Data.Function (on)     printOutput = do putStrLn "# Ignoring leading spaces \n" printBlockOfMessages sample1Rule ignoringStartEndSpaces putStrLn "\n # Ignoring multiple adjacent spaces (m.a.s) \n" printBlockOfMessages sample2Rule ignoringMultipleAdjacentSpaces putStrLn "\n # Equivalent whitespace characters \n" printBlockOfMessages sample3Rule ignoringMultipleAdjacentSpaces putStrLn "\n # Case Indepenent sorts \n" printBlockOfMessages sample4Rule caseIndependent putStrLn "\n # Numeric fields as numerics \n" printBlockOfMessages sample5Rule numericFieldsAsNumbers putStrLn "\n # Title sorts \n" printBlockOfMessages sample6Rule removeLeadCommonWords   printMessage message content = do putStrLn message mapM_ print content   printBlockOfMessages list function = do printMessage "Text strings:" list printMessage "Normally sorted:" (sort list) printMessage "Naturally sorted:" (sortListWith list function)     -- samples sample1Rule = ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"] sample2Rule = ["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"] sample3Rule = ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"] sample4Rule = ["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"] sample5Rule = ["foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"] sample6Rule = ["The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"]     -- function to execute all sorts sortListWith l f = sort $ f l   -- 1. Ignore leading, trailing and multiple adjacent spaces   -- Ignoring leading spaces   -- receive a String and remove all spaces from the start and end of that String, a String is considered an List os Char -- ex: " a string " = "a string" ignoringStartEndSpaces :: [String] -> [String] ignoringStartEndSpaces = map strip   -- Ignoring multiple adjacent spaces and Equivalent whitespace characters   ignoringMultipleAdjacentSpaces :: [String] -> [String] ignoringMultipleAdjacentSpaces = map (unwords . words)   -- 2. Equivalent whitespace characters -- 3. Case independent sort -- lower case of an entire String -- ex "SomeCAse" = "somecase" caseIndependent :: [String] -> [String] caseIndependent = map (map toLower)   -- 4. Numeric fields as numerics (deals with up to 20 digits) numericFieldsAsNumbers :: [String] -> [[Int]] numericFieldsAsNumbers = map findOnlyNumerics   findOnlyNumerics :: String -> [Int] findOnlyNumerics s = convertDigitAsStringToInt $ makeListOfDigitsAsString $ extractDigitsAsString s extractDigitsAsString :: String -> [String] extractDigitsAsString s = map (filter isNumber) $ groupBy ((==) `on` isNumber ) s makeListOfDigitsAsString :: [String] -> [String] makeListOfDigitsAsString l = tail $ nub l convertDigitAsStringToInt :: [String] -> [Int] convertDigitAsStringToInt = map (joiner . map digitToInt)   -- join a list of numbers into a single number -- ex [4,2] = 42 joiner :: [Int] -> Int joiner = read . concatMap show   -- 5. Title sort removeLeadCommonWords l = map removeLeadCommonWord $ splitList l   splitList = map words removeLeadCommonWord a = unwords $ if f a commonWords then tail a else a where f l1 = elem (map toLower (head l1)) commonWords = ["the","a","an","of"]    
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Ruby
Ruby
s = "s = %s%s%s; puts(gets.chomp == (s %% [34.chr, s, 34.chr]) ? 'accept' : 'reject')"; puts(gets.chomp == (s % [34.chr, s, 34.chr]) ? 'accept' : 'reject')
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Rust
Rust
use std::io::{stdin, prelude::*}; fn main() { let src = include_str!("main.rs"); let mut input = String::new(); stdin() .lock() .read_to_string(&mut input) .expect("Could not read from STDIN"); println!("{}", src == input); }
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
#Scala
Scala
import scala.io.StdIn   object Narcissist extends App { val text = scala.io.Source.fromFile("Narcissist.scala", "UTF-8").toStream println("Enter the number of lines to be input followed by those lines:\n") val n = StdIn.readInt() val lines = Stream { StdIn.readLine() } if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject") }
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#Haskell
Haskell
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   class SolarSystem(val star: Star) { private val planets = mutableListOf<Planet>() // some people might prefer _planets   init { for (planet in Planet.values()) planets.add(planet) }   fun listPlanets() { println(planets) } }   fun main(args: Array<String>) { val sun = Star("sun") val ss = SolarSystem(sun) sun.showDiameter() println("\nIts planetary system comprises : ") ss.listPlanets() }
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters. The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.) Document (with simple examples where possible) the evolution and current status of these naming conventions. For example, name conventions for: Procedure and operator names. (Intrinsic or external) Class, Subclass and instance names. Built-in versus libraries names. If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary. Any tools that enforced the the naming conventions. Any cases where the naming convention as commonly violated. If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private". See also Wikipedia: Naming convention (programming)
#J
J
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   class SolarSystem(val star: Star) { private val planets = mutableListOf<Planet>() // some people might prefer _planets   init { for (planet in Planet.values()) planets.add(planet) }   fun listPlanets() { println(planets) } }   fun main(args: Array<String>) { val sun = Star("sun") val ss = SolarSystem(sun) sun.showDiameter() println("\nIts planetary system comprises : ") ss.listPlanets() }
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If there is no next highest integer return zero. *1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   N which can be obtained by reordering the (base ten) digits of   N". Algorithm 1   Generate all the permutations of the digits and sort into numeric order.   Find the number in the list.   Return the next highest number from the list. The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness. Algorithm 2   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.   Exchange that digit with the digit on the right that is both more than it, and closest to it.   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) E.g.: n = 12453 <scan> 12_4_53 <swap> 12_5_43 <order-right> 12_5_34 return: 12534 This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task),   is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle. Task requirements Calculate the next highest int from the digits of the following numbers:   0   9   12   21   12453   738440   45072010   95322020 Optional stretch goal   9589776899767587796600
#Wren
Wren
import "/sort" for Sort, Find import "/fmt" for Fmt import "/str" for Str   var permute = Fn.new { |s| var res = [] if (s.count == 0) return res var bytes = s.bytes.toList var rc // recursive closure rc = Fn.new { |np| if (np == 1) { res.add(bytes.map { |b| String.fromByte(b) }.join()) return } var np1 = np - 1 var pp = bytes.count - np1 rc.call(np1) var i = pp while (i > 0) { var t = bytes[i] bytes[i] = bytes[i-1] bytes[i-1] = t rc.call(np1) i = i - 1 } var w = bytes[0] for (i in 1...pp+1) bytes[i-1] = bytes[i] bytes[pp] = w } rc.call(bytes.count) return res }   var algorithm1 = Fn.new { |nums| System.print("Algorithm 1") System.print("-----------") for (num in nums) { var perms = permute.call(num) var le = perms.count if (le > 0) { // ignore blanks Sort.quick(perms) var ix = Find.all(perms, num)[2].from var next = "" if (ix < le-1) { for (i in ix + 1...le) { if (Str.gt(perms[i], num)) { next = perms[i] break } } } if (next.count > 0) { Fmt.print("$,29s -> $,s", num, next) } else { Fmt.print("$,29s -> 0", num) } } } System.print() }   var algorithm2 = Fn.new { |nums| System.print("Algorithm 2") System.print("-----------") for (num in nums) { var bytes = num.bytes.toList var le = bytes.count var outer = false if (le > 0) { // ignore blanks var max = num[-1].bytes[0] var mi = le - 1 var i = le - 2 while (i >= 0) { if (bytes[i] < max) { var min = max - bytes[i] var j = mi + 1 while (j < le) { var min2 = bytes[j] - bytes[i] if (min2 > 0 && min2 < min) { min = min2 mi = j } j = j + 1 } var t = bytes[i] bytes[i] = bytes[mi] bytes[mi] = t var c = bytes[i+1..-1] Sort.quick(c) var next = bytes[0...i+1].map { |b| String.fromByte(b) }.join() next = next + c.map { |b| String.fromByte(b) }.join() Fmt.print("$,29s -> $,s", num, next) outer = true break } else if (bytes[i] > max) { max = num[i].bytes[0] mi = i } i = i - 1 } } if (!outer) Fmt.print("$29s -> 0", num) } }   var nums = ["0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600"] algorithm1.call(nums[0...-1]) // exclude the last one algorithm2.call(nums) // include the last one
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#PicoLisp
PicoLisp
(de makeList (Sep) (let (Cnt 0 makeItem '((Str) (prinl (inc 'Cnt) Sep Str))) (makeItem "first") (makeItem "second") (makeItem "third") ) )   (makeList ". ")
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#Python
Python
def makeList(separator): counter = 1   def makeItem(item): nonlocal counter result = str(counter) + separator + item + "\n" counter += 1 return result   return makeItem("first") + makeItem("second") + makeItem("third")   print(makeList(". "))
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. References Nested function
#R
R
MakeList <- function(sep) { counter <- 0 MakeItem <- function() paste0(counter <<- counter + 1, sep, c("first", "second", "third")[counter]) cat(replicate(3, MakeItem()), sep = "\n") } MakeList(". ")
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. Related task Sleep
#Racket
Racket
#lang racket   (require racket/date)   (define HALF-HOUR-SECS (* 60 30))   ;; given a date, return the seconds corresponding to the beginning ;; of that day (in local time) (define (beginning-of-date d) (find-seconds 0 0 0 (date-day d) (date-month d) (date-year d)))   ;; the seconds at the beginning of today: (define today-secs (beginning-of-date (seconds->date (current-seconds))))   ;; hours -> watch : given an hour, return the watch name (define (hours->watch hours) (cond [(= 0 hours) "first"] [(< 0 hours 4.5) "middle"] [(< 4 hours 8.5) "morning"] [(< 8 hours 12.5) "forenoon"] [(< 12 hours 16.5) "afternoon"] [(< 16 hours 20.5) "dog"] [(< 20 hours 24.5) "first"]))   ;; wait until current-seconds is the given number (define (wait-til secs) (sleep (- secs (current-seconds))))   ;; display the appropriate message (define (format-and-print hours bells) (define int-hours (floor hours)) (define minutes (cond [(integer? hours) "00"] [else "30"])) (display (~a (~a (floor hours) #:min-width 2 #:pad-string "0" #:align 'right) ":" minutes ", " bells " bell(s) of the " (hours->watch hours) " watch "))  ;; play the bells, if possible: (for ([i bells]) (display "\a♪") (flush-output) (cond [(even? i) (sleep 0.5)] [(odd? i) (display " ") (sleep 1)])) (display "\n"))   ;; start the loop: (for ([s (in-range today-secs +inf.0 HALF-HOUR-SECS)] [bells (sequence-tail (in-cycle (in-range 8)) 7)] [hours (in-cycle (in-range 0 24 1/2))])  ;; ignore the ones that have already happened: (when (< (current-seconds) s) (wait-til s) (format-and-print hours (add1 bells))))  
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. Related task Sleep
#Raku
Raku
my @watch = <Middle Morning Forenoon Afternoon Dog First>; my @ordinal = <One Two Three Four Five Six Seven Eight>;   my $thishour; my $thisminute = '';   loop { my $utc = DateTime.new(time); if $utc.minute ~~ any(0,30) and $utc.minute != $thisminute { $thishour = $utc.hour; $thisminute = $utc.minute; bell($thishour, $thisminute); } printf "%s%02d:%02d:%02d", "\r", $utc.hour, $utc.minute, $utc.second; sleep(1); }   sub bell ($hour, $minute) {   my $bells = (($hour % 4) * 2 + $minute div 30) || 8;   printf "%s%02d:%02d %9s watch, %6s Bell%s Gone: \t", "\b" x 9, $hour, $minute, @watch[($hour div 4 - !?($minute + $hour % 4) + 6) % 6], @ordinal[$bells - 1], $bells == 1 ?? '' !! 's';   chime($bells);   sub chime ($count) { for 1..$count div 2 { print "\a♫ "; sleep .25; print "\a"; sleep .75; } if $count % 2 { print "\a♪"; sleep 1; } print "\n"; } }
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Pop11
Pop11
define ncsubseq(l); lvars acc = [], gap_started = false, is_continuous = true; define do_it(l1, l2); dlocal gap_started; lvars el, save_is_continuous = is_continuous; if l2 = [] then if not(is_continuous) then cons(l1, acc) -> acc; endif; else front(l2) -> el; back(l2) -> l2; not(gap_started) and is_continuous -> is_continuous; do_it(cons(el, l1), l2); save_is_continuous -> is_continuous; not(l1 = []) or gap_started -> gap_started; do_it(l1, l2); endif; enddefine; do_it([], rev(l)); acc; enddefine;   ncsubseq([1 2 3 4 5]) =>
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
#PowerShell
PowerShell
Function SubSequence ( [Array] $S, [Boolean] $all=$false ) { $sc = $S.count if( $sc -gt ( 2 - [Int32] $all ) ) { [void] $sc-- 0..$sc | ForEach-Object { $gap = $_ "$( $S[ $_ ] )" if( $gap -lt $sc ) { SubSequence ( ( $gap + 1 )..$sc | Where-Object { $_ -ne $gap } ) ( ( $gap -ne 0 ) -or $all ) | ForEach-Object { [String]::Join( ',', ( ( [String]$_ ).Split(',') | ForEach-Object { $lt = $true } { if( $lt -and ( $_ -gt $gap ) ) { $S[ $gap ] $lt = $false } $S[ $_ ] } { if( $lt ) { $S[ $gap ] } } ) ) } } } #[String]::Join( ',', $S) } else { $S | ForEach-Object { [String] $_ } } }   Function NonContinuous-SubSequence ( [Array] $S ) { $sc = $S.count if( $sc -eq 3 ) { [String]::Join( ',', $S[ ( 0,2 ) ] ) } elseif ( $sc -gt 3 ) { [void] $sc-- $gaps = @() $gaps += ( ( NonContinuous-SubSequence ( 1..$sc ) ) | ForEach-Object { $gap1 = ",$_," "0,{0}" -f ( [String]::Join( ',', ( 1..$sc | Where-Object { $gap1 -notmatch "$_," } ) ) ) } ) $gaps += 1..( $sc - 1 ) 2..( $sc - 1 ) | ForEach-Object { $gap2 = $_ - 1 $gaps += ( ( SubSequence ( $_..$sc ) ) | ForEach-Object { "$gap2,$_" } ) } #Write-Host "S $S gaps $gaps" $gaps | ForEach-Object { $gap3 = ",$_," "$( 0..$sc | Where-Object { $gap3 -notmatch ",$_," } | ForEach-Object { $S[$_] } )" -replace ' ', ',' } } else { $null } }   ( NonContinuous-SubSequence 'a','b','c','d','e' ) | Select-Object length, @{Name='value';Expression={ $_ } } | Sort-Object length, value | ForEach-Object { $_.value }
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function min(x As Integer, y As Integer) As Integer Return IIf(x < y, x, y) End Function   Function convertToBase (n As UInteger, b As UInteger) As String If n < 2 OrElse b < 2 OrElse b = 10 OrElse b > 36 Then Return Str(n) Dim result As String = "" Dim digit As Integer While n > 0 digit = n Mod b If digit < 10 Then result = digit & result Else result = Chr(digit + 87) + result End If n \= b Wend Return result End Function   Function convertToDecimal (s As Const String, b As UInteger) As UInteger If b < 2 OrElse b > 36 Then Return 0 Dim t As String = LCase(s) Dim result As UInteger = 0 Dim digit As Integer Dim multiplier As Integer = 1 For i As Integer = Len(t) - 1 To 0 Step - 1 digit = -1 If t[i] >= 48 AndAlso t[i] <= min(57, 47 + b) Then digit = t[i] - 48 ElseIf b > 10 AndAlso t[i] >= 97 AndAlso t[i] <= min(122, 87 + b) Then digit = t[i] - 87 End If If digit = -1 Then Return 0 '' invalid digit present If digit > 0 Then result += multiplier * digit multiplier *= b Next Return result End Function   Dim s As String   For b As UInteger = 2 To 36 Print "36 base "; Print Using "##"; b; s = ConvertToBase(36, b) Print " = "; s; Tab(21); " -> base "; Print Using "##"; b; Print " = "; convertToDecimal(s, b) Next   Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Sidef
Sidef
range(0, 33).each { |n| printf(" %6b %3o %2d %2X\n", ([n]*4)...); }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Smalltalk
Smalltalk
1 to: 33 do: [ :i | ('%1 %2 %3' % { i printStringRadix: 8. i printStringRadix: 16. i printStringRadix: 2 }) printNl. ].
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.
#Python
Python
#!/bin/python from __future__ import print_function   def EncodeNegBase(n, b): #Converts from decimal if n == 0: return "0" out = [] while n != 0: n, rem = divmod(n, b) if rem < 0: n += 1 rem -= b out.append(rem) return "".join(map(str, out[::-1]))   def DecodeNegBase(nstr, b): #Converts to decimal if nstr == "0": return 0   total = 0 for i, ch in enumerate(nstr[::-1]): total += int(ch) * b**i return total   if __name__=="__main__":   print ("Encode 10 as negabinary (expect 11110)") result = EncodeNegBase(10, -2) print (result) if DecodeNegBase(result, -2) == 10: print ("Converted back to decimal") else: print ("Error converting back to decimal")   print ("Encode 146 as negaternary (expect 21102)") result = EncodeNegBase(146, -3) print (result) if DecodeNegBase(result, -3) == 146: print ("Converted back to decimal") else: print ("Error converting back to decimal")   print ("Encode 15 as negadecimal (expect 195)") result = EncodeNegBase(15, -10) print (result) if DecodeNegBase(result, -10) == 15: print ("Converted back to decimal") else: print ("Error converting back to decimal")