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/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
#Erlang
Erlang
-module(rosetta). -export([ncs/1]).   masks(N) -> MaxMask = trunc(math:pow(2, N)), Total = lists:map(fun(X) -> integer_to_list(X, 2) end, lists:seq(3, MaxMask)), Filtered = lists:filter(fun(X) -> contains_noncont(X) end, Total), lists:map(fun(X) -> string:right(X, N, $0) end, Filtered). % padding   contains_noncont(N) -> case re:run(N, "10+1") of {match, _} -> true; nomatch -> false end.   apply_mask_to_list(Mask, List) -> Zipped = lists:zip(Mask, List), Filtered = lists:filter(fun({Include, _}) -> Include > 48 end, Zipped), lists:map(fun({_, Value}) -> Value end, Filtered).   ncs(List) -> lists:map(fun(Mask) -> apply_mask_to_list(Mask, List) end, masks(length(List))).
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.
#BBC_BASIC
BBC BASIC
PRINT " 0 (decimal) -> " FNtobase(0, 16) " (base 16)" PRINT " 26 (decimal) -> " FNtobase(26, 16) " (base 16)" PRINT "383 (decimal) -> " FNtobase(383, 16) " (base 16)" PRINT " 26 (decimal) -> " FNtobase(26, 2) " (base 2)" PRINT "383 (decimal) -> " FNtobase(383, 2) " (base 2)" PRINT " 1a (base 16) -> " ;FNfrombase("1a", 16) " (decimal)" PRINT " 1A (base 16) -> " ;FNfrombase("1A", 16) " (decimal)" PRINT "17f (base 16) -> " ;FNfrombase("17f", 16) " (decimal)" PRINT "101111111 (base 2) -> " ;FNfrombase("101111111", 2) " (decimal)" END   DEF FNtobase(N%, B%) LOCAL D%,A$ REPEAT D% = N% MOD B% N% DIV= B% A$ = CHR$(48 + D% - 39*(D%>9)) + A$ UNTIL N% = FALSE =A$   DEF FNfrombase(A$, B%) LOCAL N% REPEAT N% *= B% N% += ASC(A$) - 48 + 7*(ASCA$>64) + 32*(ASCA$>96) A$ = MID$(A$,2) UNTIL A$ = "" = N%
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.
#Nim
Nim
import strutils   echo parseInt "10" # 10   echo parseHexInt "0x10" # 16 echo parseHexInt "10" # 16   echo parseOctInt "0o120" # 80 echo parseOctInt "120" # 80
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.
#OCaml
OCaml
# int_of_string "123459";; - : int = 123459 # int_of_string "0xabcf123";; - : int = 180154659 # int_of_string "0o7651";; - : int = 4009 # int_of_string "0b101011001";; - : int = 345
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.
#JavaScript
JavaScript
var bases = [2, 8, 10, 16, 24]; for (var n = 0; n <= 33; n++) { var row = []; for (var i = 0; i < bases.length; i++) row.push( n.toString(bases[i]) ); print(row.join(', ')); }
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.
#Julia
Julia
using Primes, Printf   println("Primes ≤ $hi written in common bases.") @printf("%8s%8s%8s%8s", "bin", "oct", "dec", "hex") for i in primes(50) @printf("%8s%8s%8s%8s\n", bin(i), oct(i), dec(i), hex(i)) end  
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.
#Action.21
Action!
CHAR ARRAY digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!"   INT FUNC MyMod(INT a,b) IF b>=0 THEN RETURN (a MOD b) FI RETURN (a-(b*(a/b)))   PROC Encode(INT n,base CHAR ARRAY res) INT i,d,len CHAR tmp   IF base<-63 OR base>-1 THEN Break() FI IF n=0 THEN SAssign(res,"0") FI   len=0 WHILE n#0 DO d=MyMod(n,base) n==/base IF d<0 THEN n==+1 d==-base FI len==+1 res(len)=digits(d+1) OD res(0)=len   FOR i=1 to len/2 DO tmp=res(i) res(i)=res(len-i+1) res(len-i+1)=tmp OD RETURN   BYTE FUNC Index(CHAR ARRAY s CHAR c) BYTE i   FOR i=1 TO s(0) DO IF s(i)=c THEN RETURN (i) FI OD RETURN (0)   INT FUNC Decode(CHAR ARRAY s INT base) INT res,b,i,pos   IF base<-63 OR base>-1 THEN Break() FI IF s(0)=1 AND s(1)='0 THEN RETURN (0) FI   res=0 b=1 pos=s(0) WHILE pos>=1 DO i=Index(digits,s(pos))-1 res==+i*b b==*base pos==-1 OD RETURN (res)   PROC Test(INT n,base) CHAR ARRAY s(20) INT v   Encode(n,base,s) PrintF("%I encoded in base %I is %S%E",n,base,s) v=Decode(s,base) PrintF("%S decoded in base %I is %I%E%E",s,base,v) RETURN   PROC Main() INT v Test(10,-2) Test(146,-3) Test(15,-10) Test(-568,-63) RETURN
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.
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;   package Negative_Base_Numbers is   subtype base_t is Long_Long_Integer range -62 .. -1;   function Encode_Negative_Base (N : in Long_Long_Integer; Base : in base_t) return Unbounded_String; function Decode_Negative_Base (N : in Unbounded_String; Base : in base_t) return Long_Long_Integer;   end Negative_Base_Numbers;   with Ada.Text_IO; package body Negative_Base_Numbers is   Digit_Chars : constant String := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";   -------------------------- -- Encode_Negative_Base -- --------------------------   function Encode_Negative_Base (N : in Long_Long_Integer; Base : in base_t) return Unbounded_String is procedure swap (a, b : in out Character) is temp : Character := a; begin a := b; b := temp; end swap;   Result  : Unbounded_String  := Null_Unbounded_String; Local_N  : Long_Long_Integer := N; Remainder : Long_Long_Integer;   begin if Local_N = 0 then Result := To_Unbounded_String ("0"); else while Local_N /= 0 loop Remainder := Local_N rem Base; Local_N  := Local_N / Base; if Remainder < 0 then Local_N  := Local_N + 1; Remainder := Remainder - Base; end if; Append (Result, Digit_Chars (Integer (Remainder + 1))); end loop; end if;   declare Temp_Result : String  := To_String (Result); Low  : Positive := Temp_Result'First; High  : Positive := Temp_Result'Last; begin while Low < High loop swap (Temp_Result (Low), Temp_Result (High)); Low  := Low + 1; High := High - 1; end loop; Result := To_Unbounded_String (Temp_Result); end;   return Result; end Encode_Negative_Base;   -------------------------- -- Decode_Negative_Base -- --------------------------   function Decode_Negative_Base (N : in Unbounded_String; Base : in base_t) return Long_Long_Integer is Total : Long_Long_Integer := 0; bb  : Long_Long_Integer := 1; Temp  : String  := To_String (N); begin if Length (N) = 0 or else (Length (N) = 1 and Element (N, 1) = '0') then return 0; end if;   for char of reverse Temp loop for J in Digit_Chars'Range loop if char = Digit_Chars (J) then Total := Total + Long_Long_Integer (J - 1) * bb; bb  := bb * Base; end if; end loop; end loop;   return Total; end Decode_Negative_Base;   end Negative_Base_Numbers;   with Ada.Text_IO; use Ada.Text_IO; with Negative_Base_Numbers; use Negative_Base_Numbers; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;   procedure Main is   procedure driver (N : in Long_Long_Integer; B : in base_t) is package long_IO is new Integer_IO (Long_Long_Integer); use long_IO;   ns  : Unbounded_String := Encode_Negative_Base (N, B); P  : Long_Long_Integer; Output : String (1 .. 12);   begin Put (Item => N, Width => 12); Put (" encoded in base "); Put (Item => B, Width => 3); Put_Line (" = " & To_String (ns));   Move (Source => To_String (ns), Target => Output, Justify => Ada.Strings.Right); P := Decode_Negative_Base (ns, B); Put (Output & " decoded in base "); Put (Item => B, Width => 3); Put (" = "); Put (Item => P, Width => 1); New_Line (2); end driver;   begin driver (10, -2); driver (146, -3); driver (15, -10); driver (36_058, -62); end Main;
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "stdio.s7i"; include "wrinum.s7i";   const proc: main is func local var integer: number is 0; begin for number range 1 to 999999 do writeln(str(ENGLISH, number)); end for; end func;
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local const array integer: sortedList is [] ( 1, 2, 3, 4, 5, 6, 7, 8, 9); var array integer: list is 0 times 0; var array integer: reversedList is 0 times 0; var integer: score is 0; var integer: index is 0; var integer: number is 0; var integer: reverse is 0; begin for number range sortedList do index := rand(1, succ(length(list))); list := list[.. pred(index)] & [] (number) & list[index ..]; end for; repeat write("Current list: "); for number range list do write(number <& " "); end for; repeat write(" Digits to reverse? "); readln(reverse); if reverse < 2 or reverse > 9 then write("Please enter a value between 2 and 9."); end if; until reverse >= 2 and reverse <= 9; incr(score); reversedList := 0 times 0; for index range reverse downto 1 do reversedList &:= list[index]; end for; list := reversedList & list[succ(reverse) ..]; until list = sortedList; writeln("Congratulations, you sorted the list in " <& score <& " reversals."); end func;
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.
#C.23
C#
  using System;   namespace nimGame { class Program { static void Main(string[] args) { Console.WriteLine("There are twelve tokens.\n" + "You can take 1, 2, or 3 on your turn.\n" + "Whoever takes the last token wins.\n");   int tokens = 12;   while (tokens > 0) { Console.WriteLine("There are " + tokens + " remaining."); Console.WriteLine("How many do you take?"); int playertake = Convert.ToInt32(Console.ReadLine());   if (playertake < 1 | playertake > 3) { Console.WriteLine("1, 2, or 3 only."); } else { tokens -= playertake; Console.WriteLine("I take " + (4 - playertake) + "."); tokens -= (4 - playertake); } } Console.WriteLine("I win again."); Console.ReadLine(); }   } }  
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.
#ALGOL_68
ALGOL 68
REAL default p = 0.001;   PROC nth root = (INT n, LONG REAL a, p)LONG REAL: ( [2]LONG REAL x := (a, a/n);   WHILE ABS(x[2] - x[1]) > p DO x := (x[2], ((n-1)*x[2] + a/x[2]**(n-1))/n ) OD; x[2] );   PRIO ROOT = 8; OP ROOT = (INT n, LONG REAL a)LONG REAL: nth root(n, a, default p); OP ROOT = (INT n, INT a)LONG REAL: nth root(n, a, default p);   main: ( printf(($2(" "gl)$, nth root(10, LONG 7131.5 ** 10, default p), nth root(5, 34, default p))); printf(($2(" "gl)$, 10 ROOT ( LONG 7131.5 ** 10 ), 5 ROOT 34)) )
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
#Delphi
Delphi
  program Next_highest_int_from_digits;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   function StrToBytes(str: AnsiString): TArray<byte>; begin SetLength(result, Length(str)); Move(Pointer(str)^, Pointer(result)^, Length(str)); end;   function BytesToStr(bytes: TArray<byte>): AnsiString; begin SetLength(Result, Length(bytes)); Move(Pointer(bytes)^, Pointer(Result)^, Length(bytes)); end;   function Commatize(s: string): string; begin var le := length(s); var i := le - 3; while i >= 1 do begin s := s.Substring(0, i) + ',' + s.Substring(i); inc(i, -3); end; Result := s; end;   function Permute(s: string): TArray<string>; var res: TArray<string>; b: string;   procedure rc(np: Integer); begin if np = 1 then begin SetLength(res, Length(res) + 1); res[High(res)] := b; exit; end;   var np1 := np - 1; var pp := length(b) - np1; rc(np1); for var i := pp downto 1 do begin var tmp := b[i + 1]; b[i + 1] := b[i]; b[i] := tmp; rc(np1); end;   var w := b[1]; delete(b, 1, 1); Insert(w, b, pp + 1); end;   begin if s.Length = 0 then exit;   res := []; b := s; rc(length(b)); result := res; end;   procedure Algorithm1(nums: TArray<string>); begin writeln('Algorithm 1'); writeln('-----------'); for var num in nums do begin var perms := permute(num); var le := length(perms); if le = 0 then Continue;   TArray.Sort<string>(perms); var ix := 0; TArray.BinarySearch<string>(perms, num, ix);   var next := ''; if ix < le - 1 then for var i := ix + 1 to le - 1 do if perms[i] > num then begin next := perms[i]; Break; end; if length(next) > 0 then writeln(format('%29s -> %s', [Commatize(num), Commatize(next)])) else writeln(format('%29s -> 0', [Commatize(num)])); end; writeln; end;   procedure Algorithm2(nums: TArray<string>); var ContinueMainFor: boolean; begin   writeln('Algorithm 2'); writeln('-----------');   for var num in nums do begin ContinueMainFor := false; var le := num.Length; if le = 0 then Continue;   var b := StrToBytes(num);   var max := b[le - 1]; var mi := le - 1; for var i := le - 2 downto 0 do begin if b[i] < max then begin var min := max - b[i]; for var j := mi + 1 to le - 1 do begin var min2 := b[j] - b[i]; if (min2 > 0) and (min2 < min) then begin min := min2; mi := j; end; end; var tmp := b[i]; b[i] := b[mi]; b[mi] := tmp; var c := copy(b, i + 1, le); TArray.Sort<byte>(c);   var next: string := BytesToStr(copy(b, 0, i + 1)); next := next + BytesToStr(c); writeln(format('%29s -> %s', [Commatize(num), Commatize(next)])); ContinueMainFor := true; Break; end else if b[i] > max then begin max := b[i]; mi := i; end; end; if ContinueMainFor then Continue; writeln(format('%29s -> 0', [Commatize(num)])); end; end;   begin var nums: TArray<string> := ['0', '9', '12', '21', '12453', '738440', '45072010', '95322020']; algorithm1(nums); // exclude the last one   SetLength(nums, Length(nums) + 1); nums[High(nums)] := '9589776899767587796600';   algorithm2(nums); // include the last one {$IFNDEF UNIX} readln; {$ENDIF} end.
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
#C.23
C#
string MakeList(string separator) { int counter = 1;   Func<string, string> makeItem = item => counter++ + separator + item + "\n";   return makeItem("first") + makeItem("second") + makeItem("third"); }   Console.WriteLine(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
#C.2B.2B
C++
#include <iostream> #include <string> #include <vector>   std::vector<std::string> makeList(std::string separator) { auto counter = 0; auto makeItem = [&](std::string item) { return std::to_string(++counter) + separator + item; }; return {makeItem("first"), makeItem("second"), makeItem("third")}; }   int main() { for (auto item : makeList(". ")) std::cout << item << "\n"; }
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
#AWK
AWK
  # syntax: GAWK -f NAUTICAL_BELL.AWK BEGIN { # sleep_cmd = "sleep 55s" # Unix sleep_cmd = "TIMEOUT /T 55 >NUL" # MS-Windows split("Middle,Morning,Forenoon,Afternoon,Dog,First",watch_arr,",") split("One,Two,Three,Four,Five,Six,Seven,Eight",bells_arr,",") simulate1day() while (1) { t = systime() h = strftime("%H",t) + 0 m = strftime("%M",t) + 0 if (m == 0 || m == 30) { nb(h,m) while (systime() < t + 5) {} } system(sleep_cmd) } exit(0) } function nb(h,m, bells,hhmm,plural,sounds,watch) { # hhmm = sprintf("%02d:%02d",h,m) # if (hhmm == "00:00") { watch = 6 } # else if (hhmm <= "04:00") { watch = 1 } # else if (hhmm <= "08:00") { watch = 2 } # else if (hhmm <= "12:00") { watch = 3 } # else if (hhmm <= "16:00") { watch = 4 } # else if (hhmm <= "20:00") { watch = 5 } # else { watch = 6} # determining watch: verbose & readable (above) vs. terse & cryptic (below) watch = 60 * h + m watch = (watch < 1 ) ? 6 : int((watch - 1) / 240 + 1) bells = (h % 4) * 2 + int(m / 30) if (bells == 0) { bells = 8 } plural = (bells == 1) ? " " : "s" sounds = strdup("\x07",bells) printf("%02d:%02d %9s watch %5s bell%s  %s\n",h,m,watch_arr[watch],bells_arr[bells],plural,sounds) } function simulate1day( h,m) { for (h=0; h<=23; h++) { for (m=0; m<=59; m+=30) { nb(h,m) } } } function strdup(str,n, i,new_str) { for (i=1; i<=n; i++) { new_str = new_str str } gsub(str str,"& ",new_str) return(new_str) }  
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#Phix
Phix
constant template = { { { 1, 2 }, { 3, 4, 1, }, 5 } }, template2 = { { { 1, 2 }, { 10, 4, 1 }, 5 } }, payload = {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"} sequence unused = repeat(true,length(payload)), missing = {} function fill(object t, sequence p) if integer(t) then if t>=length(p) then if not find(t,missing) then missing &= t end if return sprintf("*** index error (%d>%d) ***",{t,length(p)-1}) end if unused[t+1] = false return p[t+1] end if for i=1 to length(t) do t[i] = fill(t[i],p) end for return t end function ppOpt({pp_Nest,2}) pp(fill(template,payload)) pp(fill(template2,payload)) sequence idx = {} for i=1 to length(unused) do if unused[i] then idx &= i-1 end if end for printf(1,"\nThe unused payloads have indices of :%s\n", {sprint(idx)}) if length(missing) then printf(1,"Missing payloads: %s\n", {sprint(missing)}) end if
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#Nim
Nim
import bitops, math, sequtils, strutils   type   # Lengths of distinct runs of occupied cells. Lengths = seq[int]   # Possibility, i.e. sequence of bits managed as an integer. Possibility = int   # Possibilities described by tow masks and a list of integer values. Possibilities = object mask0: int # Mask indicating the positions of free cells. mask1: int # Mask indicating the positions of occupied cells. list: seq[int] # List of possibilities.     proc genSequence(ones: seq[int]; numZeroes: Natural): seq[Possibility] = ## Generate a sequence of possibilities. if ones.len == 0: return @[0] for x in 1..(numZeroes - ones.len + 1): for tail in genSequence(ones[1..^1], numZeroes - x): result.add (tail shl countSetBits(ones[0]) or ones[0]) shl x     proc initPossibilities(lengthsList: openArray[Lengths]; length: Positive): seq[Possibilities] = ## Initialize the list of possibilities from a list of lengths.   let initMask0 = 1 shl length - 1 for lengths in lengthsList: let sumLengths = sum(lengths) let prep = lengths.mapIt(1 shl it - 1) let possList = genSequence(prep, length - sumLengths + 1).mapIt(it shr 1) result.add Possibilities(mask0: initMask0, mask1: 0, list: possList)     func updateUnset(possList: var seq[Possibilities]; mask, rank: int) = ## Update the lists of possibilities keeping only those ## compatible with the mask (for bits not set only). var mask = mask for poss in possList.mitems: if (mask and 1) == 0: for i in countdown(poss.list.high, 0): if poss.list[i].testBit(rank): # Bit is set, so the value is not compatible: remove it. poss.list.delete(i) mask = mask shr 1     func updateSet(possList: var seq[Possibilities]; mask, rank: int) = ## Update the lists of possibilities keeping only those ## compatible with the mask (for bits set only). var mask = mask for poss in possList.mitems: if (mask and 1) != 0: for i in countdown(poss.list.high, 0): if not poss.list[i].testBit(rank): # Bit is not set, so the value is not compatible: remove it. poss.list.delete(i) mask = mask shr 1     proc process(poss1, poss2: var seq[Possibilities]): bool = ## Look at possibilities in list "poss1", compute the masks for ## bits unset and bits set and update "poss2" accordingly.   var num = 0 for poss in poss1.mitems:   # Check bits unset. var mask = 0 for value in poss.list: mask = mask or value if mask != poss.mask0: # Mask has changed: update. result = true poss2.updateUnset(mask, num) poss.mask0 = mask   # Check bits set. mask = 1 shl poss2.len - 1 for value in poss.list: mask = mask and value if mask != poss.mask1: # Mask has changed: update. result = true poss2.updateSet(mask, num) poss.mask1 = mask   inc num     proc solve(rowLengths, colLengths: openArray[Lengths]) = ## Solve nonogram defined by "rowLengths" and "colLengths".   var rowPoss = initPossibilities(rowLengths, colLengths.len) colPoss = initPossibilities(colLengths, rowLengths.len)   # Solve nonogram. var hasChanged = true while hasChanged: hasChanged = process(rowPoss, colPoss) or process(colPoss, rowPoss)   # Check if solved. for poss in rowPoss: if poss.list.len != 1: echo "Unable to solve the nonogram." return   # Display the solution. for poss in rowPoss: var line = "" var val = poss.list[0] for i in 0..colPoss.high: line.add if val.testBit(i): "# " else: " " echo line     func expand(s: string): seq[Lengths] = ## Expand a compact description into a sequence of lengths. for elem in s.splitWhitespace(): result.add elem.mapIt(ord(it) - ord('A') + 1)     proc solve(rows, cols: string) = ## Solve using compact description parameters. solve(rows.expand(), cols.expand())     when isMainModule:   const   Data1 = ("C BA CB BB F AE F A B", "AB CA AE GA E C D C")   Data2 = ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA")   Data3 = ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC")   Data4 = ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM")   for (rows, cols) in [Data1, Data2, Data3, Data4]: echo rows echo cols echo "" solve(rows, cols) echo ""
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Ruby
Ruby
def nonoblocks(cell, blocks) raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1 nblock(cell, blocks, '', []) end   def nblock(cell, blocks, position, result) if cell <= 0 result << position[0..cell-1] elsif blocks.empty? or blocks[0].zero? result << position + '.' * cell else rest = cell - blocks.inject(:+) - blocks.size + 2 bl, *brest = blocks rest.times.inject(result) do |res, i| nblock(cell-i-bl-1, brest, position + '.'*i + '#'*bl + '.', res) end end end   conf = [[ 5, [2, 1]], [ 5, []], [10, [8]], [15, [2, 3, 2, 3]], [ 5, [2, 3]], ] conf.each do |cell, blocks| begin puts "#{cell} cells and #{blocks} blocks" result = nonoblocks(cell, blocks) puts result, result.size, "" rescue => e p e end end
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
#F.23
F#
  (* A function to generate only the non-continuous subsequences. Nigel Galloway July 20th., 2017 *) let N n = let fn n = Seq.map (fun g->(2<<<n)+g) let rec fg n = seq{if n>0 then yield! seq{1..((1<<<n)-1)}|>fn n; yield! fg (n-1)|>fn n} Seq.collect fg ({1..(n-2)})  
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.
#BCPL
BCPL
get "libhdr";   // Reverse a string let reverse(str) = valof $( let i = 1 let j = str%0 while i<j $( let c = str%i str%i := str%j str%j := c i := i+1 j := j-1 $) resultis str $)   // Convert number to string given base let itoa(n, base, buf) = valof $( let digitchar(n) = n < 10 -> n + '0', (n - 10) + 'A' buf%0 := 0 $( buf%0 := buf%0 + 1 buf%(buf%0) := digitchar(n rem base) n := n / base $) repeatuntil n<=0 resultis reverse(buf) $)   // Convert string to number given base let atoi(str, base) = valof $( let digitval(d, base) = '0' <= d <= '9' -> d - '0', 'A' <= d <= 'Z' -> (d - 'A') + 10, 'a' <= d <= 'z' -> (d - 'a') + 10, 0 let result = 0 for i=1 to str%0 do result := result * base + digitval(str%i, base) resultis result $)   // Examples let start() be $( let buffer = vec 64   writes("1234 in bases 2-36:*N") for base=2 to 36 do writef("Base %I2: %S*N", base, itoa(1234, base, buffer))   writes("*N*"25*" in bases 10-36:*N") for base=10 to 36 do writef("Base %I2: %N*N", base, atoi("25", 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.
#Oz
Oz
{String.toInt "42"} %% decimal = {String.toInt "0x2a"} %% hexadecimal = {String.toInt "052"} %% octal = {String.toInt "0b101010"} %% binary
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.
#PARI.2FGP
PARI/GP
convert(numb1,b1,b2)={ my(B=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],a=0,c=""); numb1=Vec(Str(numb1)); forstep(y=#numb1,1,-1, for(x=1,b1, if(numb1[y]==B[x], a=a+(x-1)*b1^(#numb1-y) ) ) ); until(a/b2==0, c=concat(B[a%b2+1],c); a=a\b2 ); c };
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.
#Klingphix
Klingphix
include ..\Utilitys.tlhy   33 [ ( "decimal: " swap " bin: " over 8 itob reverse ) lprint nl ] for   "End " input
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.
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { val bases = intArrayOf(2, 8, 10, 16, 19, 36) for (base in bases) print("%6s".format(base)) println() println("-".repeat(6 * bases.size)) for (i in 0..35) { for (base in bases) print("%6s".format(i.toString(base))) println() } }
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.
#ALGOL_68
ALGOL 68
# Conversion to/from negative base numbers # # Note - no checks for valid bases or digits bases -2 .. -63 are handled # # A-Z represent the digits 11 .. 35, a-z represent the digits 36 .. 61 # # the digit 62 is represented by a space #   # 1 2 3 4 5 6 # # 01234567890123456789012345678901234567890123456789012 # []CHAR base digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "[ AT 0 ];   # returns s decoded to an integer from the negative base b # PRIO FROMNBASE = 9; OP FROMNBASE = ( STRING s, INT b )LONG INT: BEGIN LONG INT result := 0; LONG INT base multiplier := 1; FOR d pos FROM UPB s BY -1 TO LWB s DO INT digit = IF s[ d pos ] = " " THEN 62 ELIF s[ d pos ] >= "a" THEN ( ABS s[ d pos ] + 36 ) - ABS "a" ELIF s[ d pos ] >= "A" THEN ( ABS s[ d pos ] + 10 ) - ABS "A" ELSE ABS s[ d pos ] - ABS "0" FI; result +:= base multiplier * digit; base multiplier *:= b OD; result END # FROMNBASE # ; OP FROMNBASE = ( CHAR c, INT b )LONG INT: STRING(c) FROMNBASE b;   # returns n encoded as a string in the negative base b # PRIO TONBASE = 9; OP TONBASE = ( LONG INT n, INT b )STRING: BEGIN STRING result := ""; LONG INT v := n; WHILE INT d := SHORTEN IF v < 0 THEN - ( ABS v MOD b ) ELSE v MOD b FI; v OVERAB b; IF d < 0 THEN d -:= b; v +:= 1 FI; base digits[ d ] +=: result; v /= 0 DO SKIP OD; result END # TONBASE # ;   # tests the TONBASE and FROMNBASE operators # PROC test n base = ( LONG INT number, INT base, STRING expected )VOID: BEGIN PROC expect = ( BOOL result )STRING: IF result THEN "" ELSE " INCORRECT" FI; STRING encoded = number TONBASE base; LONG INT decoded = encoded FROMNBASE base; print( ( whole( number, 0 ), " encodes to: ", encoded ) ); print( ( " base ", whole( base, 0 ), expect( encoded = expected ), newline ) ); print( ( encoded, " decodes to: ", whole( decoded, 0 ) ) ); print( ( " base ", whole( base, 0 ), expect( decoded = number ), newline ) ) END # test n base # ;   test n base( 10, -2, "11110" ); test n base( 146, -3, "21102" ); test n base( 15, -10, "195" ); # The defining document for ALGOL 68 spells the name "Algol 68" on the cover, though inside it is "ALGOL 68" # # at the risk of "judging a language by it's cover", we use "Algol 68" as the name here... # test n base( - LONG 36492107981104, -63, "Algol 68" )
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.
#SenseTalk
SenseTalk
  set numbers to [0,1,7,22,186,pi,-48.6,-3451,925734, 12570902378]   repeat with each number in numbers put number into output put numberWords of number into character 15 of output put output end repeat  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#SenseTalk
SenseTalk
  // set the initial list of digits set currentList to 1..9 sorted by random of a million   // make sure we don't start off already sorted repeat while currentList equals 1..9 sort currentList by random of a million end repeat   // ask until it is solved repeat while currentList isn't equal to 1..9 add 1 to numberOfTurns set headline to "Turn #" & numberOfTurns & ": You have " & currentList joined by empty   ask "How many digits do you want to reverse?" titled headline message "On each turn, specify the number of initial digits to reverse." if it isn't a number then exit all -- allow the user to exit   sort items 1 to it of currentList descending by the counter end repeat   answer "You sorted it in " & numberOfTurns & " turns!" titled "Congratulations!"  
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.
#Common_Lisp
Common Lisp
  (defun pturn (curTokens) (write-string "How many tokens would you like to take?: ") (setq ans (read)) (setq tokensRemaining (- curTokens ans)) (format t "You take ~D tokens~%" ans) (printRemaining tokensRemaining) tokensRemaining)   (defun cturn (curTokens) (setq take (mod curTokens 4)) (setq tokensRemaining (- curTokens take)) (format t "Computer takes ~D tokens~%" take) (printRemaining tokensRemaining) tokensRemaining)   (defun printRemaining (remaining) (format t "~D tokens remaining~%~%" remaining))     (format t "LISP Nim~%~%") (setq tok 12) (loop (setq tok (pturn tok)) (setq tok (cturn tok)) (if (<= tok 0) (return))) (write-string "Computer wins!")  
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.
#Crystal
Crystal
tokens = 12   until tokens <= 0 puts "There are #{tokens} tokens remaining.\nHow many tokens do you take?" until (input = (gets || "").to_i?) && (1..3).includes? input puts "Enter an integer between 1 and 3." end puts "Player takes #{input} tokens.\nComputer takes #{4-input} tokens." tokens -= 4 end   puts "Computer wins."
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.
#ALGOL_W
ALGOL W
begin  % nth root algorithm  %  % returns the nth root of A, A must be > 0  %  % the required precision should be specified in precision % long real procedure nthRoot( long real value A  ; integer value n  ; long real value precision ) ; begin long real xk, xd; integer n1; n1 := n - 1; xk := A / n; while begin xd := ( ( A / ( xk ** n1 ) ) - xk ) / n; xk := xk + xd; abs( xd ) > precision end do begin end; xk end nthRoot ;  % test cases % r_format := "A"; r_w := 15; r_d := 6; % set output format % write( nthRoot( 7131.5 ** 10, 10, 1'-5 ) ); write( nthRoot( 64, 6, 1'-5 ) ); end.
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program nroot.s */ /* compile with option -mfpu=vfpv3 -mfloat-abi=hard */ /* link with gcc. Use C function for display float */   /* Constantes */ .equ EXIT, 1 @ Linux syscall   /* Initialized data */ .data szFormat1: .asciz " %+09.15f\n" .align 4 iNumberA: .int 1024   /* UnInitialized data */ .bss .align 4   /* code section */ .text .global main main: @ entry of program push {fp,lr} @ saves registers   /* root 10ieme de 1024 */ ldr r0,iAdriNumberA @ number address ldr r0,[r0] vmov s0,r0 @ vcvt.f64.s32 d0, s0 @conversion in float single précision (32 bits) mov r0,#10 @ N bl nthRoot ldr r0,iAdrszFormat1 @ format vmov r2,r3,d0 bl printf @ call C function !!! @ Attention register dn lost !!! /* square root of 2 */ vmov.f64 d1,#2.0 @ conversion 2 in float register d1 mov r0,#2 @ N bl nthRoot ldr r0,iAdrszFormat1 @ format vmov r2,r3,d0 bl printf @ call C function !!!   100: @ standard end of the program mov r0, #0 @ return code pop {fp,lr} @restaur registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call   iAdrszFormat1: .int szFormat1 iAdriNumberA: .int iNumberA   /******************************************************************/ /* compute nth root */ /******************************************************************/ /* r0 contains N */ /* d0 contains the value */ /* d0 return result */ nthRoot: push {r1,r2,lr} @ save registers vpush {d1-d8} @ save float registers FMRX r1,FPSCR @ copy FPSCR into r1 BIC r1,r1,#0x00370000 @ clears STRIDE and LEN FMXR FPSCR,r1 @ copy r1 back into FPSCR   vmov s2,r0 @ vcvt.f64.s32 d6, s2 @ N conversion in float double précision (64 bits) sub r1,r0,#1 @ N - 1 vmov s8,r1 @ vcvt.f64.s32 d4, s8 @conversion in float double précision (64 bits) vmov.f64 d2,d0 @ a = A vdiv.F64 d3,d0,d6 @ b = A/n adr r2,dfPrec @ load précision vldr d8,[r2] 1: @ begin loop vmov.f64 d2,d3 @ a <- b vmul.f64 d5,d3,d4 @ (N-1)*b   vmov.f64 d1,#1.0 @ constante 1 -> float mov r2,#0 @ loop indice 2: @ compute pow (n-1) vmul.f64 d1,d1,d3 @ add r2,#1 cmp r2,r1 @ n -1 ? blt 2b @ no -> loop vdiv.f64 d7,d0,d1 @ A / b pow (n-1) vadd.f64 d7,d7,d5 @ + (N-1)*b vdiv.f64 d3,d7,d6 @ / N -> new b vsub.f64 d1,d3,d2 @ compute gap vabs.f64 d1,d1 @ absolute value vcmp.f64 d1,d8 @ compare float maj FPSCR fmstat @ transfert FPSCR -> APSR @ or use VMRS APSR_nzcv, FPSCR bgt 1b @ if gap > précision -> loop vmov.f64 d0,d3 @ end return result in d0   100: vpop {d1-d8} @ restaur float registers pop {r1,r2,lr} @ restaur arm registers bx lr dfPrec: .double 0f1E-10 @ précision    
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
#Factor
Factor
USING: formatting grouping kernel math math.combinatorics math.parser sequences ;   : next-highest ( m -- n ) number>string dup [ >= ] monotonic? [ drop 0 ] [ next-permutation string>number ] if ;   { 0 9 12 21 12453 738440 45072010 95322020 9589776899767587796600 } [ dup next-highest "%d -> %d\n" printf ] each
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
#Go
Go
package main   import ( "fmt" "sort" )   func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) // recursive closure rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := np - 1 pp := len(b) - np1 rc(np1) for i := pp; i > 0; i-- { b[i], b[i-1] = b[i-1], b[i] rc(np1) } w := b[0] copy(b, b[1:pp+1]) b[pp] = w } rc(len(b)) return res }   func algorithm1(nums []string) { fmt.Println("Algorithm 1") fmt.Println("-----------") for _, num := range nums { perms := permute(num) le := len(perms) if le == 0 { // ignore blanks continue } sort.Strings(perms) ix := sort.SearchStrings(perms, num) next := "" if ix < le-1 { for i := ix + 1; i < le; i++ { if perms[i] > num { next = perms[i] break } } } if len(next) > 0 { fmt.Printf("%29s -> %s\n", commatize(num), commatize(next)) } else { fmt.Printf("%29s -> 0\n", commatize(num)) } } fmt.Println() }   func algorithm2(nums []string) { fmt.Println("Algorithm 2") fmt.Println("-----------") outer: for _, num := range nums { b := []byte(num) le := len(b) if le == 0 { // ignore blanks continue } max := num[le-1] mi := le - 1 for i := le - 2; i >= 0; i-- { if b[i] < max { min := max - b[i] for j := mi + 1; j < le; j++ { min2 := b[j] - b[i] if min2 > 0 && min2 < min { min = min2 mi = j } } b[i], b[mi] = b[mi], b[i] c := (b[i+1:]) sort.Slice(c, func(i, j int) bool { return c[i] < c[j] }) next := string(b[0:i+1]) + string(c) fmt.Printf("%29s -> %s\n", commatize(num), commatize(next)) continue outer } else if b[i] > max { max = num[i] mi = i } } fmt.Printf("%29s -> 0\n", commatize(num)) } }   func commatize(s string) string { le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s }   func main() { nums := []string{"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600"} algorithm1(nums[:len(nums)-1]) // exclude the last one algorithm2(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
#Clojure
Clojure
(defn make-list [separator] (let [x (atom 0)] (letfn [(make-item [item] (swap! x inc) (println (format "%s%s%s" @x separator item)))] (make-item "first") (make-item "second") (make-item "third"))))   (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
#Common_Lisp
Common Lisp
(defun my-make-list (separator) (let ((counter 0)) (flet ((make-item (item) (format nil "~a~a~a~%" (incf counter) separator item))) (concatenate 'string (make-item "first") (make-item "second") (make-item "third")))))   (format t (my-make-list ". "))
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
#C
C
  #include<unistd.h> #include<stdio.h> #include<time.h>   #define SHORTLAG 1000 #define LONGLAG 2000   int main(){ int i,times,hour,min,sec,min1,min2;   time_t t; struct tm* currentTime;   while(1){ time(&t); currentTime = localtime(&t);   hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec;   hour = 12; min = 0; sec = 0;   if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; }   if(min==0){ min1 = 0; min2 = 0; }   else{ min1 = 3; min2 = 0; }   if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times);   for(i=1;i<=times;i++){ printf("\a");   (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }    
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#Python
Python
from pprint import pprint as pp   class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], []   def inject_payload(self, id2data):   def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d) missed.extend(f'??#{x}' for x in substruct if type(x) is not tuple and x not in i2d) return tuple(_inject_payload(x, i2d, used, missed) if type(x) is tuple else i2d.get(x, f'??#{x}') for x in substruct)   ans = _inject_payload(self.structure, id2data, self.used_payloads, self.missed_payloads) self.unused_payloads = sorted(set(id2data.values()) - set(self.used_payloads)) self.missed_payloads = sorted(set(self.missed_payloads)) return ans   if __name__ == '__main__': index2data = {p: f'Payload#{p}' for p in range(7)} print("##PAYLOADS:\n ", end='') print('\n '.join(list(index2data.values()))) for structure in [ (((1, 2), (3, 4, 1), 5),),   (((1, 2), (10, 4, 1), 5),)]: print("\n\n# TEMPLATE:") pp(structure, width=13) print("\n TEMPLATE WITH PAYLOADS:") t = Template(structure) out = t.inject_payload(index2data) pp(out) print("\n UNUSED PAYLOADS:\n ", end='') unused = t.unused_payloads print('\n '.join(unused) if unused else '-') print(" MISSING PAYLOADS:\n ", end='') missed = t.missed_payloads print('\n '.join(missed) if missed else '-')
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#Ol
Ol
  (import (owl parse))   ; notation parser (define (subA x) (- x #\A -1))   (define line (let-parse* ( (words (greedy+ (let-parse* ( (* (greedy* (imm #\space))) (word (greedy+ (byte-if (lambda (x) (<= #\A x #\Z)))))) (map subA word)))) (* (maybe (imm #\newline) #f))) words))   (define nonogram-parser (let-parse* ( (rows line) (cols line)) (cons rows cols)))   ; nonogram printer (define (print-nonogram ng solve) (for-each (lambda (row y) (for-each (lambda (x) (if (list-ref (list-ref (car solve) y) x) (display "X ") (display ". "))) (iota (length (cdr ng)))) (for-each (lambda (i) (display " ") (display i)) row) (print)) (car ng) (iota (length (car ng)))) (for-each (lambda (i) (for-each (lambda (col) (let ((n (lref col i))) (if n (display n) (display " "))) (display " ")) (cdr ng)) (print)) (iota (fold (lambda (f col) (max f (length col))) 0 (cdr ng)) 0)))   ; possible permutation generator (define (permutate blacks len) ; empty cells distibutions (with minimal count) (define whites (append '(0) (repeat 1 (- (length blacks) 1)) '(0))) (define total (- len (apply + blacks))) ; total summ of empty cells   (define (combine whites blacks) ; size of whites is always equal to size of blacks+1 (let loop ((line #null) (v #f) (w (reverse whites)) (b (reverse blacks))) (if (null? w) line else (loop (append (repeat v (car w)) line) (not v) b (cdr w)))))   (map (lambda (whites) (combine whites blacks)) (let loop ((ll whites) (max total)) (if (null? (cdr ll)) (list (list max)) else (define sum (apply + ll)) (define left (- max sum)) (if (eq? left 0) (list ll) else (define head (car ll)) (fold (lambda (f i) (define sublist (loop (cdr ll) (- max head i))) (fold (lambda (f x) (cons (cons (+ head i) x) f)) f sublist)) #null (iota (+ left 1))))))))   ; siever of impossible combinations (define (sieve rows cols) ; -> new cols (fold (lambda (cols i) ; for every cell define a "definitely black" and "definitely white" cells (define blacks (fold (lambda (f x) (map (lambda (a b) (and a b)) f x)) (repeat #t (length cols)) (list-ref rows i))) (define whites (fold (lambda (f x) (map (lambda (a b) (or a b)) f x)) (repeat #f (length cols)) (list-ref rows i))) ; now filter the second list (map (lambda (cols j) (filter (lambda (col) (not (or (and (list-ref blacks j) (not (list-ref col i))) (and (not (list-ref whites j)) (list-ref col i))))) cols)) cols (iota (length cols)))) cols (iota (length rows))))   ; main solver cycle (define (solve rows-permuted cols-permuted) (let loop ((rows rows-permuted) (cols cols-permuted) (flip #f)) (define new-cols (sieve rows cols))   (define fail (fold (lambda (f l) (or f (null? l))) #f new-cols)) (define done (fold (lambda (f l) (and f (null? (cdr l)))) #t new-cols))   (cond (fail #false) (done (if flip (cons (map car new-cols) (map car rows)) (cons (map car rows) (map car new-cols)))) (else (loop new-cols rows (not flip))))))   ; -=( main )=---------------------------------- (define first "C BA CB BB F AE F A B AB CA AE GA E C D C")   (define second "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA")   (define third "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC")   (define fourth "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM")   (for-each (lambda (str) (print "nonogram:") (print str) (print) ; decode nonogram notation (define nonogram (parse nonogram-parser (str-iter str) #f #f #f))   ; prepare arrays of all possible line b/w permutations (define rows (car nonogram)) (define cols (cdr nonogram))   (define row-length (length cols)) (define col-length (length rows))   (define rows-permuted (map (lambda (x) (permutate x row-length)) rows)) (define cols-permuted (map (lambda (x) (permutate x col-length)) cols))   ; solve nonogram (define answer (solve rows-permuted cols-permuted))   ; show the output (if answer (print-nonogram nonogram answer) (print "Sorry, no aorrect answer found.")) (print)) (list first second third fourth))  
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Rust
Rust
struct Nonoblock { width: usize, config: Vec<usize>, spaces: Vec<usize>, }   impl Nonoblock { pub fn new(width: usize, config: Vec<usize>) -> Nonoblock { Nonoblock { width: width, config: config, spaces: Vec::new(), } }   pub fn solve(&mut self) -> Vec<Vec<i32>> { let mut output: Vec<Vec<i32>> = Vec::new(); self.spaces = (0..self.config.len()).fold(Vec::new(), |mut s, i| { s.push(match i { 0 => 0, _ => 1, }); s }); if self.spaces.iter().sum::<usize>() + self.config.iter().sum::<usize>() <= self.width { 'finished: loop { match self.spaces.iter().enumerate().fold((0, vec![0; self.width]), |mut a, (i, s)| { (0..self.config[i]).for_each(|j| a.1[a.0 + j + *s] = 1 + i as i32); return (a.0 + self.config[i] + *s, a.1); }) { (_, out) => output.push(out), } let mut i: usize = 1; 'calc: loop { let len = self.spaces.len(); if i > len { break 'finished; } else { self.spaces[len - i] += 1 } if self.spaces.iter().sum::<usize>() + self.config.iter().sum::<usize>() > self.width { self.spaces[len - i] = 1; i += 1; } else { break 'calc; } } } } output } }   fn main() { let mut blocks = [ Nonoblock::new(5, vec![2, 1]), Nonoblock::new(5, vec![]), Nonoblock::new(10, vec![8]), Nonoblock::new(15, vec![2, 3, 2, 3]), Nonoblock::new(5, vec![2, 3]), ];   for block in blocks.iter_mut() { println!("{} cells and {:?} blocks", block.width, block.config); println!("{}",(0..block.width).fold(String::from("="), |a, _| a + "==")); let solutions = block.solve(); if solutions.len() > 0 { for solution in solutions.iter() { println!("{}", solution.iter().fold(String::from("|"), |s, f| s + &match f { i if *i > 0 => (('A' as u8 + ((*i - 1) as u8) % 26) as char).to_string(), _ => String::from("_"), }+ "|")); } } else { println!("No solutions. "); } println!(); } }
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
#FreeBASIC
FreeBASIC
Sub Subsecuencias_no_continuas(l() As String) Dim As Integer i, j, g, n, r, s, w Dim As String a, b, c n = Ubound(l) For s = 0 To n-2 For g = s+1 To n-1 a = "[" For i = s To g-1 a += l(i) + ", " Next i For w = 1 To n-g r = n+1-g-w For i = 1 To 2^r-1 Step 2 b = a For j = 0 To r-1 If i And 2^j Then b += l(g+w+j) + ", " Next j 'Print Left(Left(b)) + "]" c = (Left(b, Len (b)-1)) Print Left(c, Len(c)-1) + "]" Next i Next w Next g Next s End Sub   Dim lista1(3) As String = {"1", "2", "3", "4"} Print "Para [1, 2, 3, 4] las subsecuencias no continuas son:" Subsecuencias_no_continuas(lista1()) Dim lista2(4) As String = {"e", "r", "n", "i", "t"} Print "Para [e, r, n, i, t] las subsecuencias no continuas son:" Subsecuencias_no_continuas(lista2()) Sleep
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.
#Bracmat
Bracmat
( display = .  !arg:<10 | !arg:<36&chr$(asc$a+!arg+-10) | "Base too big" ) & ( base = n b .  !arg:(?n.?b) & !n:<!b & ( !n:~<0&display$!n | NOTSUPPORTED ) | base$(div$(!n.!b).!b) display$(mod$(!n.!b)) ) & whl ' ( put $ "Enter non-negative integer in decimal notation (or something else to stop):" & get':~/#>-1:?n & put$"Enter base (less than 37):" & get$:~/#>1:~>36:?b & out$(!n " in base " !b " is " str$(base$(!n.!b))) );
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.
#Pascal
Pascal
my $dec = "0123459"; my $hex_noprefix = "abcf123"; my $hex_withprefix = "0xabcf123"; my $oct_noprefix = "7651"; my $oct_withprefix = "07651"; my $bin_withprefix = "0b101011001";   print 0 + $dec, "\n"; # => 123459 print hex($hex_noprefix), "\n"; # => 180154659 print hex($hex_withprefix), "\n"; # => 180154659 print oct($hex_withprefix), "\n"; # => 180154659 print oct($oct_noprefix), "\n"; # => 4009 print oct($oct_withprefix), "\n"; # => 4009 print oct($bin_withprefix), "\n"; # => 345 # nothing for binary without prefix
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.
#Locomotive_Basic
Locomotive Basic
10 FOR i=1 TO 20 20 PRINT i,BIN$(i),HEX$(i) 30 NEXT
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.
#Lua
Lua
for i = 1, 33 do print( string.format( "%o \t %d \t %x", i, i, i ) ) end
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.
#C
C
#include <stdio.h>   const char DIGITS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const int DIGITS_LEN = 64;   void encodeNegativeBase(long n, long base, char *out) { char *ptr = out;   if (base > -1 || base < -62) { /* Bounds check*/ out = ""; return; } if (n == 0) { /* Trivial case */ out = "0"; return; }   /* Convert the number into a string (in reverse) */ while (n != 0) { long rem = n % base; n = n / base; if (rem < 0) { n++; rem = rem - base; } *ptr = DIGITS[rem]; ptr++; } *ptr = 0;   /* Reverse the current string to get the final result */ ptr--; while (out < ptr) { char t = *out; *out = *ptr; *ptr = t; out++; ptr--; } return; }   long decodeNegativeBase(const char* ns, long base) { long value, bb; int i; const char *ptr;   if (base < -62 || base > -1) { /* Bounds check */ return 0; } if (ns[0] == 0 || (ns[0] == '0' && ns[1] == 0)) { /* Trivial case */ return 0; }   /* Find the end of the string */ ptr = ns; while (*ptr != 0) { ptr++; }   /* Convert */ value = 0; bb = 1; ptr--; while (ptr >= ns) { for (i = 0; i < DIGITS_LEN; i++) { if (*ptr == DIGITS[i]) { value = value + i * bb; bb = bb * base; break; } } ptr--; }   return value; }   void driver(long n, long b) { char buf[64]; long value;   encodeNegativeBase(n, b, buf); printf("%12d encoded in base %3d = %12s\n", n, b, buf);   value = decodeNegativeBase(buf, b); printf("%12s decoded in base %3d = %12d\n", buf, b, value);   printf("\n"); }   int main() { driver(10, -2); driver(146, -3); driver(15, -10); driver(12, -62);   return 0; }
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.
#SequenceL
SequenceL
import <Utilities/Math.sl>; import <Utilities/Sequence.sl>; import <Utilities/Conversion.sl>; import <Utilities/String.sl>;   main(argv(2)) := delimit(numberToEnglish(stringToInt(argv)), '\n');   ones := ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; teens := ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; tens := ["ten", "twenty", "thrity", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];   magnitudes := ["", "thousand", "million", "billion", "trillion"];   numberToEnglish(num(0)) := let triplets[i] := (num / integerPower(1000, i - 1)) mod 1000 foreach i within 1 ... ceiling(log(1000, num + 1));   englishtTriplets[j] := numberToEnglishHelper(triplets[j]);   partials[j] := englishtTriplets[j] ++ magnitudes[j] ++ ", " when size(englishtTriplets[j]) > 0 foreach j within reverse(1 ... size(triplets)); in "zero" when num = 0 else "negative " ++ numberToEnglish(-num) when num < 0 else trim(allButLast(trim(join(partials))));     numberToEnglishHelper(num(0)) := let onesPlace := num mod 10; tensPlace := (num mod 100) / 10; hundredsPlace := (num mod 1000) / 100;   onesWord := "ten " when tensPlace = 1 and onesPlace = 0 else "" when onesPlace = 0 else teens[onesPlace] ++ " " when tensPlace = 1 else ones[onesPlace] ++ " ";   tensWord := "" when tensPlace = 0 or tensPlace = 1 else tens[tensPlace] ++ " " when onesPlace = 0 else tens[tensPlace] ++ "-";   hundredsWord := "" when hundredsPlace = 0 else ones[hundredsPlace] ++ " hundred ";   andWord := "" when hundredsPlace = 0 or (tensPlace = 0 and onesPlace = 0) else "and ";     in hundredsWord ++ andWord ++ tensWord ++ onesWord;
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Sidef
Sidef
var turn = 0; var jumble = @(1..9).bshuffle; # best-shuffle   for (turn; jumble != 1..9; ++turn) { printf("%2d: %s - Flip how many digits ? ", turn, jumble.join(' ')); var d = read(Number) \\ break; jumble[0 .. d-1] = [jumble[0 .. d-1]].reverse...; }   print " #{jumble.join(' ')}\n"; print "You won in #{turn} turns.\n";
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To win every time,   the second player simply takes 4 minus the number the first player took.   So if the first player takes 1,   the second takes 3 ─── if the first player takes 2,   the second should take 2 ─── and if the first player takes 3,   the second player will take 1. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#Dyalect
Dyalect
print("There are twelve tokens.") print("You can take 1, 2, or 3 on your turn.") print("Whoever takes the last token wins.\n")   var tokens = 12 while tokens > 0 { print("There are \(tokens) remaining.") print("How many do you take?") var playertake = Integer(readLine())   if playertake < 1 || playertake > 3 { print("1, 2, or 3 only.") } else { tokens -= playertake print("I take \(4 - playertake).") tokens -= (4 - playertake) } }   print("I win again.")
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.
#Factor
Factor
USING: interpolate io kernel math math.parser sequences ; IN: rosetta-code.nim-game   : get-input ( -- n ) "Number of tokens to take (1, 2, or 3): " write readln string>number dup { 1 2 3 } member? [ drop "Invalid move." print get-input ] unless ;   : .remaining ( n -- ) nl [I -~~==[ ${} tokens remaining ]==~~-I] nl nl ;   : .choice ( str n -- ) dup 1 = "" "s" ? [I ${} took ${} token${}I] nl ;   : (round) ( -- ) "You" get-input "Computer" 4 pick - [ .choice ] 2bi@ ;   : round ( n -- n-4 ) dup dup .remaining [ drop (round) 4 - round ] unless-zero ;   : nim-game ( -- ) 12 round drop "Computer wins!" print ;   MAIN: nim-game
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.
#Arturo
Arturo
nthRoot: function [a,n][ N: to :floating n result: a x: a / N while [0.000000000000001 < abs result-x][ x: result result: (1//n) * add (n-1)*x a/pow x n-1 ] return result ]   print nthRoot 34.0 5 print nthRoot 42.0 10 print nthRoot 5.0 2
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
#Haskell
Haskell
import Data.List (nub, permutations, sort)   digitShuffleSuccessors :: Integer -> [Integer] digitShuffleSuccessors n = (fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n where go ds | 0 >= delta = [] | otherwise = [delta] where delta = (read ds :: Integer) - n   --------------------------- TEST --------------------------- main :: IO () main = putStrLn $ fTable "Taking up to 5 digit-shuffle successors of a positive integer:\n" show (\xs -> let harvest = take 5 xs in rjust 12 ' ' (show (length harvest) <> " of " <> show (length xs) <> ": ") <> show harvest) digitShuffleSuccessors [0, 9, 12, 21, 12453, 738440, 45072010, 95322020]   ------------------------- DISPLAY -------------------------- fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String fTable s xShow fxShow f xs = unlines $ s : fmap (((<>) . rjust w ' ' . xShow) <*> ((" -> " <>) . fxShow . f)) xs where w = maximum (length . xShow <$> xs)   rjust :: Int -> Char -> String -> String rjust n c = drop . length <*> (replicate n c <>)
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
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh";   sub MakeList(sep: [uint8], buf: [uint8]): (out: [uint8]) is out := buf; # return begin of buffer for ease of use var counter: uint32 := 0;   # Add item to string sub AddStr(str: [uint8]) is var length := StrLen(str); MemCopy(str, length, buf); buf := buf + length; end sub;   sub MakeItem(item: [uint8]) is counter := counter + 1; buf := UIToA(counter, 10, buf); AddStr(sep); AddStr(item); AddStr("\n"); end sub;   MakeItem("first"); MakeItem("second"); MakeItem("third"); [buf] := 0; # terminate string end sub;   var buffer: uint8[100];   print(MakeList(". ", &buffer as [uint8]));
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
#D
D
string makeList(string seperator) { int counter = 1;   string makeItem(string item) { import std.conv : to; return to!string(counter++) ~ seperator ~ item ~ "\n"; }   return makeItem("first") ~ makeItem("second") ~ makeItem("third"); }   void main() { import std.stdio : writeln; writeln(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
#Delphi
Delphi
import extensions;   MakeList(separator) { var counter := 1;   var makeItem := (item){ var retVal := counter.toPrintable() + separator + item + (forward newLine); counter += 1; ^ retVal };   ^ makeItem("first") + makeItem("second") + makeItem("third") }   public program() { console.printLine(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
#C.2B.2B
C++
  #include <iostream> #include <string> #include <windows.h>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight"; _inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL ); } private: static DWORD WINAPI bell( LPVOID p ) { DWORD wait = _inst->waitTime(); while( true ) { Sleep( wait ); _inst->playBell(); wait = _inst->waitTime(); } return 0; }   DWORD waitTime() { GetLocalTime( &st ); int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute; return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) ); }   void playBell() { GetLocalTime( &st ); int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b; int w = ( 60 * st.wHour + st.wMinute ); if( w < 1 ) w = 5; else w = ( w - 1 ) / 240; char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );   cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell"; if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;   for( int x = 0, c = 1; x < b; x++, c++ ) { cout << "\7"; Sleep( 500 ); if( !( c % 2 ) ) Sleep( 300 ); } }   SYSTEMTIME st; string watch[7], count[8]; static bells* _inst; }; //-------------------------------------------------------------------------------------------------- bells* bells::_inst = 0; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { bells b; b.start(); while( 1 ); // <- runs forever! return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#R
R
fill_template <- function(x, template, prefix = "Payload#") { for (i in seq_along(template)) { temp_slice <- template[[i]] if (is.list(temp_slice)) { template[[i]] <- fill_template(x, temp_slice, prefix) } else { temp_slice <- paste0(prefix, temp_slice) template[[i]] <- x[match(temp_slice, x)] } } return(template) }   library("jsonlite") # for printing the template and result template <- list(list(c(1, 2), c(3, 4), 5)) payload <- paste0("Payload#", 0:6) result <- fill_template(payload, template)   cat(sprintf( "Template\t%s\nPayload\t%s\nResult\t%s", toJSON(template, auto_unbox = TRUE), toJSON(payload, auto_unbox = TRUE), toJSON(result, auto_unbox = TRUE) ))
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#Racket
Racket
#lang racket   (define current-not-found-handler (make-parameter (λ (idx max) (raise-range-error 'substitute-template "integer?" "" idx 0 max))))   (define ((substitute-template template) payloads) (define match-function (match-lambda [(? nonnegative-integer? idx) #:when (< idx (length payloads)) (list-ref payloads idx)] [(? nonnegative-integer? idx) ((current-not-found-handler) idx (sub1 (length payloads)))] [(list (app match-function substitutions) ...) substitutions])) (match-function template))   (module+ test (require rackunit)   (define substitute-in-t (substitute-template '(((1 2) (3 4 1) 5))))   (define p '(Payload#0 Payload#1 Payload#2 Payload#3 Payload#4 Payload#5 Payload#6))   (check-equal? (substitute-in-t p) '(((Payload#1 Payload#2) (Payload#3 Payload#4 Payload#1) Payload#5)))   (define out-of-bounds-generating-template-substitution (substitute-template '(7)))   (check-exn exn:fail:contract? (λ () (out-of-bounds-generating-template-substitution p)))   (parameterize ((current-not-found-handler (λ (idx max) (format "?~a" idx)))) (check-equal? (out-of-bounds-generating-template-substitution p) '("?7"))))
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#Raku
Raku
say join "\n ", '##PAYLOADS:', |my @payloads = 'Payload#' X~ ^7;   for [ (((1, 2), (3, 4, 1), 5),),   (((1, 2), (10, 4, 1), 5),) ] { say "\n Template: ", $_.raku; say "Data structure: { @payloads[|$_].raku }"; }
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#Perl
Perl
use strict; use warnings;   my $file = 'nonogram_problems.txt'; open my $fd, '<', $file or die "$! opening $file";   while(my $row = <$fd> ) { $row =~ /\S/ or next; my $column = <$fd>; my @rpats = makepatterns($row); my @cpats = makepatterns($column); my @rows = ( '.' x @cpats ) x @rpats; for( my $prev = ''; $prev ne "@rows"; ) { $prev = "@rows"; try(\@rows, \@rpats); my @cols = map { join '', map { s/.//; $& } @rows } 0..$#cpats; try(\@cols, \@cpats); @rows = map { join '', map { s/.//; $& } @cols } 0..$#rpats; } print "\n", "@rows" =~ /\./ ? "Failed\n" : map { tr/01/.#/r, "\n" } @rows; }   sub try { my ($lines, $patterns) = @_; for my $i ( 0 .. $#$lines ) { while( $lines->[$i] =~ /\./g ) { for my $try ( 0, 1 ) { $lines->[$i] =~ s/.\G/$try/r =~ $patterns->[$i] or $lines->[$i] =~ s// 1 - $try /e; } } } }   sub makepatterns { # numbered to show the 'logical' order of operations map { qr/^$_$/ # 7 convert strings to regex } map { '[0.]*' # 6a prepend static pattern . join('[0.]+', # 5 interleave with static pattern map { "[1.]{$_}" # 4 require to match exactly 'n' times } map { -64+ord # 3 convert letter value to repetition count 'n' } split // # 2 for each letter in group ) . '[0.]*' # 6b append static pattern } split ' ', shift; # 1 for each letter grouping }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Swift
Swift
import Foundation   func nonoblock(cells: Int, blocks: [Int]) { print("\(cells) cells and blocks \(blocks):") let totalBlockSize = blocks.reduce(0, +) if cells < totalBlockSize + blocks.count - 1 { print("no solution") return }   func solve(cells: Int, index: Int, totalBlockSize: Int, offset: Int) { if index == blocks.count { count += 1 print("\(String(format: "%2d", count)) \(String(output))") return } let blockSize = blocks[index] let maxPos = cells - (totalBlockSize + blocks.count - index - 1) let t = totalBlockSize - blockSize var c = cells - (blockSize + 1) for pos in 0...maxPos { fill(value: ".", offset: offset, count: maxPos + blockSize) fill(value: "#", offset: offset + pos, count: blockSize) solve(cells: c, index: index + 1, totalBlockSize: t, offset: offset + blockSize + pos + 1) c -= 1 } }   func fill(value: Character, offset: Int, count: Int) { output.replaceSubrange(offset..<offset+count, with: repeatElement(value, count: count)) }   var output: [Character] = Array(repeating: ".", count: cells) var count = 0 solve(cells: cells, index: 0, totalBlockSize: totalBlockSize, offset: 0) }   nonoblock(cells: 5, blocks: [2, 1]) print()   nonoblock(cells: 5, blocks: []) print()   nonoblock(cells: 10, blocks: [8]) print()   nonoblock(cells: 15, blocks: [2, 3, 2, 3]) print()   nonoblock(cells: 5, blocks: [2, 3])
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
#Go
Go
package main   import "fmt"   const ( // state: m = iota // missing: all elements missing so far c // continuous: all elements included so far are continuous cm // one or more continuous followed by one or more missing cmc // non-continuous subsequence )   func ncs(s []int) [][]int { if len(s) < 3 { return nil } return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...) }   var skip = []int{m, cm, cm, cmc} var incl = []int{c, c, cmc, cmc}   func n2(ss, tail []int, seq int) [][]int { if len(tail) == 0 { if seq != cmc { return nil } return [][]int{ss} } return append(n2(append([]int{}, ss...), tail[1:], skip[seq]), n2(append(ss, tail[0]), tail[1:], incl[seq])...) }   func main() { ss := ncs([]int{1, 2, 3, 4}) fmt.Println(len(ss), "non-continuous subsequences:") for _, s := range ss { fmt.Println(" ", 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.
#C
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h>   char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base); return 0; }   /* safe against most negative integer */ n = ((neg = num < 0)) ? (~num) + 1 : num;   do { buf[len++] = tbl[n % base]; } while(n /= base);   out = malloc(len + neg + 1); for (i = neg; len > 0; i++) out[i] = buf[--len]; if (neg) out[0] = '-';   return out; }   long from_base(const char *num_str, int base) { char *endptr; /* there is also strtoul() for parsing into an unsigned long */ /* in C99, there is also strtoll() and strtoull() for parsing into long long and * unsigned long long, respectively */ int result = strtol(num_str, &endptr, base); return result; }   int main() { int64_t x; x = ~(1LL << 63) + 1; printf("%lld in base 2: %s\n", x, to_base(x, 2)); x = 383; printf("%lld in base 16: %s\n", x, to_base(x, 16)); return 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.
#Perl
Perl
my $dec = "0123459"; my $hex_noprefix = "abcf123"; my $hex_withprefix = "0xabcf123"; my $oct_noprefix = "7651"; my $oct_withprefix = "07651"; my $bin_withprefix = "0b101011001";   print 0 + $dec, "\n"; # => 123459 print hex($hex_noprefix), "\n"; # => 180154659 print hex($hex_withprefix), "\n"; # => 180154659 print oct($hex_withprefix), "\n"; # => 180154659 print oct($oct_noprefix), "\n"; # => 4009 print oct($oct_withprefix), "\n"; # => 4009 print oct($bin_withprefix), "\n"; # => 345 # nothing for binary without prefix
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Table[IntegerString[n,b], {n,Range@38}, {b,{2,8,16,36}}] // Grid
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.
#MATLAB_.2F_Octave
MATLAB / Octave
fprintf('%3d  %3o  %3x\n',repmat(1:20,3,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.
#Modula-3
Modula-3
MODULE Conv EXPORTS Main;   IMPORT IO, Fmt;   BEGIN FOR i := 1 TO 33 DO IO.Put(Fmt.Int(i, base := 10) & " "); IO.Put(Fmt.Int(i, base := 16) & " "); IO.Put(Fmt.Int(i, base := 8) & " "); IO.Put("\n"); END; END Conv.
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace NegativeBaseNumbers { class Program { const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";   static string EncodeNegativeBase(long n, int b) { if (b < -62 || b > -1) { throw new ArgumentOutOfRangeException("b"); } if (n == 0) { return "0"; } StringBuilder output = new StringBuilder(); long nn = n; while (nn != 0) { int rem = (int)(nn % b); nn /= b; if (rem < 0) { nn++; rem -= b; } output.Append(DIGITS[rem]); } return new string(output.ToString().Reverse().ToArray()); }   static long DecodeNegativeBase(string ns, int b) { if (b < -62 || b > -1) { throw new ArgumentOutOfRangeException("b"); } if (ns == "0") { return 0; } long total = 0; long bb = 1; for (int i = ns.Length - 1; i >= 0; i--) { char c = ns[i]; total += DIGITS.IndexOf(c) * bb; bb *= b; } return total; }   static void Main(string[] args) { List<Tuple<long, int>> nbl = new List<Tuple<long, int>>() { new Tuple<long, int>(10,-2), new Tuple<long, int>(146,-3), new Tuple<long, int>(15,-10), new Tuple<long, int>(-34025238427,-62), }; foreach (var p in nbl) { string ns = EncodeNegativeBase(p.Item1, p.Item2); Console.WriteLine("{0,12} encoded in base {1,-3} = {2}", p.Item1, p.Item2, ns); long n = DecodeNegativeBase(ns, p.Item2); Console.WriteLine("{0,12} decoded in base {1,-3} = {2}", ns, p.Item2, n); Console.WriteLine(); } } } }
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.
#Shale
Shale
#!/usr/local/bin/shale   maths library   0 ones:: dup var "zero" = 1 ones:: dup var "one" = 2 ones:: dup var "two" = 3 ones:: dup var "three" = 4 ones:: dup var "four" = 5 ones:: dup var "five" = 6 ones:: dup var "six" = 7 ones:: dup var "seven" = 8 ones:: dup var "eight" = 9 ones:: dup var "nine" = 10 teens:: dup var "ten" = 11 teens:: dup var "eleven" = 12 teens:: dup var "twelve" = 13 teens:: dup var "thirteen" = 14 teens:: dup var "fourteen" = 15 teens:: dup var "fifteen" = 16 teens:: dup var "sixteen" = 17 teens:: dup var "seventeen" = 18 teens:: dup var "eighteen" = 19 teens:: dup var "nineteen" = 2 tens:: dup var "twenty" = 3 tens:: dup var "thirty" = 4 tens:: dup var "forty" = 5 tens:: dup var "fifty" = 6 tens:: dup var "sixty" = 7 tens:: dup var "seventy" = 8 tens:: dup var "eighty" = 9 tens:: dup var "ninety" =   say dup var { commaFlag dup var swap = andFlag dup var swap = n dup var swap = h dup var n 100 / = t dup var n 100 % = o dup var n 10 % =   h 0 > { commaFlag { "," print commaFlag false = } ifthen h.value ones:: " %s hundred" printf } ifthen   h 0 > t 0 > and t 0 > andFlag and or { " and" print commaFlag false = } ifthen   t 9 > { t 19 > { commaFlag { "," print commaFlag false = } ifthen t 10 / tens:: " %s" printf o 0 > { o.value ones:: "-%s" printf } ifthen } { t 9 > { commaFlag { "," print } ifthen t.value teens:: " %s" printf } ifthen } if } { o 0 > { commaFlag { "," print } ifthen o.value ones:: " %s" printf } ifthen } if } =   speak dup var { n dup var swap = m dup var n 1000000 / = t dup var n 1000 / 1000 % = h dup var n 1000 % =   n "%10d ->" printf m 0 > { m.value false false say() " million" print } ifthen t 0 > { t.value false m 0 > say() " thousand" print } ifthen h 0 > m 0 == t 0 == and or { h.value m 0 > t 0 > or dup say() } ifthen "" println } =   "Stock numbers" println 1 speak() 10 speak() 100 speak() 1000 speak() 1001 speak() 100001000 speak() 100001001 speak() 123456789 speak() 987654321 speak() 100200300 speak() 10020030 speak()   "" println "Randomly generated numbers" println i var i 0 = { i 10 < } { random maths::() 1000000000 % speak() // Cap it to less than 1 billion. i++ } while
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Tcl
Tcl
package require Tcl 8.5 # Simple shuffler, not very efficient but good enough for here proc shuffle list { set result {} while {[llength $list]} { set i [expr {int([llength $list] * rand())}] lappend result [lindex $list $i] set list [lreplace $list $i $i] } return $result } # Returns the list with the prefix of it reversed proc flipfirst {list n} { concat [lreverse [lrange $list 0 $n-1]] [lrange $list $n end] }   # Core game engine; list to play with is optional argument proc nrgame {{target "1 2 3 4 5 6 7 8 9"}} { set nums $target while {$nums eq $target} {set nums [shuffle $nums]} set goes 0 while {$nums ne $target} { incr goes puts -nonewline "#${goes}: List is '[join $nums {, }]', how many to reverse? " flush stdout gets stdin n if {$n eq "q"} {return quit} # Input validation would go here set nums [flipfirst $nums $n] } return $goes }   # Print some instructions and wait for the user to win puts "Welcome to the Number Reversal Game!" puts "------------------------------------" puts "I'll show you a list of numbers, you need to reverse prefixes of them" puts "to get the whole list in ascending order. A 'q' will quit early.\n" puts "" set outcome [nrgame] if {$outcome ne "quit"} { puts "\nYou took $outcome attempts to put the digits in order." }
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.
#Fermat
Fermat
heap:=12; while heap>0 do  !!('There are ',heap,' tokens left. How many do you want to take?');  ?take; while take<1 or take>3 or take>heap do  !!('You cannot take that number. Choose again.');  ?take; od;  !!('On my turn I will take ',4-take,' tokens.'); heap:-(4); od;   !!('I got the last token. Better luck next time!');
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.
#FreeBASIC
FreeBASIC
dim as ubyte heap=12, take   while heap > 0 print using "There are ## tokens remaining. How many would you like to take?"; heap input take while take=0 orelse take>3 print "You must take 1, 2, or 3 tokens. How many would you like to take?" input take wend   print using "On my turn I will take ## tokens."; 4-take heap = heap - 4 wend   print "I got the last token. I win! Better luck next time."
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.
#AutoHotkey
AutoHotkey
p := 0.000001   MsgBox, % nthRoot( 10, 7131.5**10, p) "`n" . nthRoot( 5, 34.0 , p) "`n" . nthRoot( 2, 2 , p) "`n" . nthRoot(0.5, 7 , p) "`n"     ;--------------------------------------------------------------------------- nthRoot(n, A, p) { ; http://en.wikipedia.org/wiki/Nth_root_algorithm ;--------------------------------------------------------------------------- x1 := A x2 := A / n While Abs(x1 - x2) > p { x1 := x2 x2 := ((n-1)*x2+A/x2**(n-1))/n } Return, x2 }
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.
#Ada
Ada
with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='';A:String:=;B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;";B:String:=A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last);C:String:=Ada.Text_IO.Get_Line;begin Ada.Text_IO.Put_Line(Boolean'Image(B=C));end Self;
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
#J
J
permutations=: A.&i.~ ! ordered_numbers_from_digits=: [: /:~ ({~ permutations@#)&.": next_highest=: (>:@i:~ { 0 ,~ ]) ordered_numbers_from_digits (,. next_highest)&>0 9 12 21 12453 738440 45072010 95322020 0 0 9 0 12 21 21 0 12453 12534 738440 740348 45072010 45072100 95322020 95322200
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
#Java
Java
  import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;   public class NextHighestIntFromDigits {   public static void main(String[] args) { for ( String s : new String[] {"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600", "3345333"} ) { System.out.printf("%s -> %s%n", format(s), format(next(s))); } testAll("12345"); testAll("11122"); }   private static NumberFormat FORMAT = NumberFormat.getNumberInstance();   private static String format(String s) { return FORMAT.format(new BigInteger(s)); }   private static void testAll(String s) { System.out.printf("Test all permutations of:  %s%n", s); String sOrig = s; String sPrev = s; int count = 1;   // Check permutation order. Each is greater than the last boolean orderOk = true; Map <String,Integer> uniqueMap = new HashMap<>(); uniqueMap.put(s, 1); while ( (s = next(s)).compareTo("0") != 0 ) { count++; if ( Long.parseLong(s) < Long.parseLong(sPrev) ) { orderOk = false; } uniqueMap.merge(s, 1, (v1, v2) -> v1 + v2); sPrev = s; } System.out.printf(" Order: OK =  %b%n", orderOk);   // Test last permutation String reverse = new StringBuilder(sOrig).reverse().toString(); System.out.printf(" Last permutation: Actual = %s, Expected = %s, OK = %b%n", sPrev, reverse, sPrev.compareTo(reverse) == 0);   // Check permutations unique boolean unique = true; for ( String key : uniqueMap.keySet() ) { if ( uniqueMap.get(key) > 1 ) { unique = false; } } System.out.printf(" Permutations unique: OK =  %b%n", unique);   // Check expected count. Map<Character,Integer> charMap = new HashMap<>(); for ( char c : sOrig.toCharArray() ) { charMap.merge(c, 1, (v1, v2) -> v1 + v2); } long permCount = factorial(sOrig.length()); for ( char c : charMap.keySet() ) { permCount /= factorial(charMap.get(c)); } System.out.printf(" Permutation count: Actual = %d, Expected = %d, OK = %b%n", count, permCount, count == permCount);     }   private static long factorial(long n) { long fact = 1; for (long num = 2 ; num <= n ; num++ ) { fact *= num; } return fact; }   private static String next(String s) { StringBuilder sb = new StringBuilder(); int index = s.length()-1; // 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. while ( index > 0 && s.charAt(index-1) >= s.charAt(index)) { index--; } // Reached beginning. No next number. if ( index == 0 ) { return "0"; }   // Find digit on the right that is both more than it, and closest to it. int index2 = index; for ( int i = index + 1 ; i < s.length() ; i++ ) { if ( s.charAt(i) < s.charAt(index2) && s.charAt(i) > s.charAt(index-1) ) { index2 = i; } }   // Found data, now build string // Beginning of String if ( index > 1 ) { sb.append(s.subSequence(0, index-1)); }   // Append found, place next sb.append(s.charAt(index2));   // Get remaining characters List<Character> chars = new ArrayList<>(); chars.add(s.charAt(index-1)); for ( int i = index ; i < s.length() ; i++ ) { if ( i != index2 ) { chars.add(s.charAt(i)); } }   // Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. Collections.sort(chars); for ( char c : chars ) { sb.append(c); } return sb.toString(); } }  
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
#Elena
Elena
import extensions;   MakeList(separator) { var counter := 1;   var makeItem := (item){ var retVal := counter.toPrintable() + separator + item + (forward newLine); counter += 1; ^ retVal };   ^ makeItem("first") + makeItem("second") + makeItem("third") }   public program() { console.printLine(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
#Elixir
Elixir
defmodule Nested do def makeList(separator) do counter = 1   makeItem = fn {}, item -> {"#{counter}#{separator}#{item}\n", counter+1} {result, counter}, item -> {result <> "#{counter}#{separator}#{item}\n", counter+1} end   {} |> makeItem.("first") |> makeItem.("second") |> makeItem.("third") |> elem(0) end end   IO.write Nested.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
#Factor
Factor
USING: io kernel math math.parser locals qw sequences ; IN: rosetta-code.nested-functions   :: make-list ( separator -- str ) 1 :> counter! [| item | counter number>string separator append item append counter 1 + counter! ] :> make-item qw{ first second third } [ make-item call ] map "\n" join ;   ". " make-list write
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
#D
D
import std.stdio, core.thread, std.datetime;   class NauticalBell : Thread { private shared bool stopped;   this() { super(&run); }   void run() { uint numBells; auto time = cast(TimeOfDay)Clock.currTime(); auto next = TimeOfDay();   void setNextBellTime() { next += minutes(30); numBells = 1 + (numBells % 8); }   while (next < time) setNextBellTime();   while (!this.stopped) { time = cast(TimeOfDay)Clock.currTime(); if (next.minute == time.minute && next.hour == time.hour) { immutable bells = numBells == 1 ? "bell" : "bells"; writefln("%s : %d %s", time, numBells, bells); setNextBellTime(); } sleep(dur!"msecs"(100)); yield(); } }   void stop() { this.stopped = true; } }   void main() { auto bells = new NauticalBell(); bells.isDaemon(true); bells.start(); try { bells.join(); } catch (ThreadException e) { writeln(e.msg); } }
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#REXX
REXX
/* REXX */ tok.='' Do i=0 To 6 tok.i="'Payload#"i"'" End t1='[[[1,2],[3,4,1],5]]' t2='[[[1,6],[3,4,7,0],5]]' Call transform t1 Call transform t2 Exit   transform: Parse Arg t 1 tt /* http://rosettacode.org/wiki/Nested_templated_data */ /* [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] */ lvl=0 n.=0 o='' w='' used.=0 Do While t<>'' Parse Var t c +1 1 c3 +3 1 c2 +2 u=' ' v=' ' Select When c3='],[' Then Do o=o' ' w=w' ' t=substr(t,3) End When c2='],' Then Do o=o' ' w=w' ' t=substr(t,2) lvl=lvl-1 End When c='[' Then lvl=lvl+1 When c=']' Then lvl=lvl-1 When c=',' Then Nop Otherwise Do u=lvl v=c End End t=substr(t,2) o=o||u w=w||v End Say 'Template' tt Do i=1 By 1 While w<>'' If i=1 Then Do w=substr(w,4) p=pos(' ',w) Call o '[[['cont(left(w,p-1))'],' w=substr(w,p) End Else Do If left(w,3)='' Then Do w=substr(w,4) p=pos(' ',w) Call o ' ['cont(left(w,p-1))'],' w=substr(w,p) End Else Do w=substr(w,3) p=pos(' ',w) Call o ' 'cont(left(w,p-1))']]' w=substr(w,p) End End End Do i=0 To 6 If used.i=0 Then Say 'Payload' i 'not used' End Call o ' ' Return   o: Say arg(1) Return   cont: Procedure Expose tok. used. Parse Arg list res='' Do while list>'' Parse Var list i list res= res tok(i)',' End res=strip(res) res=strip(res,'T',',') Return res   tok: Procedure Expose tok. used. Parse Arg i If tok.i<>'' Then Do used.i=1 Return tok.i End Else Return "'Payload#" i "not defined'"
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#Phix
Phix
with javascript_semantics sequence x, y, grid integer unsolved function count_grid() integer res = length(x)*length(y) for i=1 to length(x) do for j=1 to length(y) do res -= grid[i][j]!='?' end for end for return res end function function match_mask(string neat, string mask, integer ms, integer me) for i=ms to me do if mask[i]!='?' then if mask[i]!=neat[i] then return 0 end if end if end for return 1 end function function innr(string mask, sequence blocks, integer mi=1, string res="", string neat=mask) if length(blocks)=0 then for i=mi to length(neat) do neat[i] = ' ' end for if match_mask(neat,mask,mi,length(mask)) then if length(res)=0 then res = neat else for i=1 to length(neat) do if neat[i]!=res[i] then res[i] = '?' end if end for end if end if else integer b = blocks[1] blocks = blocks[2..$] integer l = (sum(blocks)+length(blocks)-1), e = length(neat)-l-b for i=mi to e do for j=i to i+b-1 do neat[j] = '#' end for if i+b<=length(neat) then neat[i+b] = ' ' end if if match_mask(neat,mask,mi,min(i+b,length(mask))) then res = innr(mask,blocks,i+b+1,res,neat) end if neat[i] = ' ' end for end if return res end function function inner(string mask, sequence blocks) string res = innr(mask,blocks) return iff(length(res)?res:mask) end function global function vmask(sequence source, integer column) string res = repeat(' ',length(source)) for i=1 to length(source) do res[i] = source[i][column] end for return res end function function logic() integer wasunsolved = unsolved for i=1 to length(x) do grid[i] = inner(grid[i],x[i]) end for for j=1 to length(y) do string tmp = inner(vmask(grid,j),y[j]) for i=1 to length(tmp) do grid[i][j] = tmp[i] end for end for unsolved = count_grid() return wasunsolved!=unsolved end function sequence tests=split(""" C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM""",'\n') --Alternatively: --integer fn = open("nonogram_problems.txt","r") --tests = get_text(fn,GT_LF_STRIPPED) --close(fn) function unpack(string s) sequence res = split(s) for i=1 to length(res) do string ri = res[i] sequence r = {} for j=1 to length(ri) do r &= ri[j]-'A'+1 end for res[i] = r end for return res end function for i=1 to length(tests) by 3 do x = unpack(tests[i]) y = unpack(tests[i+1]) grid = repeat(repeat('?',length(y)),length(x)) unsolved = length(x)*length(y) while unsolved do if not logic() then ?"partial" exit end if end while puts(1,join(grid,"\n")&"\n") end for
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Tcl
Tcl
package require Tcl 8.6 package require generator   generator define nonoblocks {blocks cells} { set sum [tcl::mathop::+ {*}$blocks] if {$sum == 0 || [lindex $blocks 0] == 0} { generator yield {{0 0}} return } elseif {$sum + [llength $blocks] - 1 > $cells} { error "those blocks will not fit in those cells" }   set brest [lassign $blocks blen] for {set bpos 0} {$bpos <= $cells - $sum - [llength $brest]} {incr bpos} { if {![llength $brest]} { generator yield [list [list $bpos $blen]] return } set offset [expr {$bpos + $blen + 1}] generator foreach subpos [nonoblocks $brest [expr {$cells - $offset}]] { generator yield [linsert [lmap b $subpos { lset b 0 [expr {[lindex $b 0] + $offset}] }] 0 [list $bpos $blen]] } } }   if {[info script] eq $::argv0} { proc pblock {cells {vec {}}} { set vector [lrepeat $cells "_"] set ch 64 foreach b $vec { incr ch lassign $b bp bl for {set i $bp} {$i < $bp + $bl} {incr i} { lset vector $i [format %c $ch] } } return |[join $vector "|"]| } proc flist {items} { return [format "\[%s\]" [join $items ", "]] } foreach {blocks cells} { {2 1} 5 {} 5 {8} 10 {2 3 2 3} 15 {2 3} 5 } { puts "\nConfiguration:" puts [format "%s # %d cells and %s blocks" \ [pblock $cells] $cells [flist $blocks]] puts " Possibilities:" set i 0 try { generator foreach vector [nonoblocks $blocks $cells] { puts " [pblock $cells $vector]" incr i } puts " A total of $i possible configurations" } on error msg { puts " --> ERROR: $msg" } } }   package provide nonoblock 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
#Haskell
Haskell
action p x = if p x then succ x else x   fenceM p q s [] = guard (q s) >> return [] fenceM p q s (x:xs) = do (f,g) <- p ys <- fenceM p q (g s) xs return $ f x ys   ncsubseq = fenceM [((:), action even), (flip const, action odd)] (>= 3) 0
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.
#C.23
C#
  public static class BaseConverter {   /// <summary> /// Converts a string to a number /// </summary> /// <returns>The number.</returns> /// <param name="s">The string to convert.</param> /// <param name="b">The base number (between 2 and 36).</param> public static long stringToLong(string s, int b) {   if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b");   checked {   int slen = s.Length; long result = 0; bool isNegative = false;   for ( int i = 0; i < slen; i++ ) {   char c = s[i]; int num;   if ( c == '-' ) { // Negative sign if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s");   isNegative = true; continue; }   if ( c > 0x2F && c < 0x3A ) // Numeric character (subtract from 0x30 ('0') to get numerical value) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) // Uppercase letter // Subtract from 0x41 ('A'), then add 10 num = c - 0x37; // 0x37 = 0x41 - 10 else if ( c > 0x60 && c < 0x7B ) // Lowercase letter // Subtract from 0x61 ('a'), then add 10 num = c - 0x57; // 0x57 = 0x61 - 10 else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s");   // Check that the digit is allowed by the base.   if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s");   // Multiply the result by the base, then add the next digit   result *= b; result += num;   }   if ( isNegative ) result = -result;   return result;   }   }   /// <summary> /// Converts a number to a string. /// </summary> /// <returns>The string.</returns> /// <param name="n">The number to convert.</param> /// <param name="b">The base number (between 2 and 36).</param> public static string longToString(long n, int b) {   // This uses StringBuilder, so it only works with .NET 4.0 or higher. For earlier versions, the StringBuilder // can be replaced with simple string concatenation.   if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b");   // If the base is 10, call ToString() directly, which returns a base-10 string.   if ( b == 10 ) return n.ToString();   checked { long longBase = b;   StringBuilder sb = new StringBuilder();   if ( n < 0 ) { // Negative numbers n = -n; sb.Append('-'); }   long div = 1; while ( n / div >= b ) // Continue multiplying the dividend by the base until it reaches the greatest power of // the base which is less than or equal to the number. div *= b;   while ( true ) { byte digit = (byte) (n / div);   if ( digit < 10 ) // Numeric character (0x30 = '0') sb.Append((char) (digit + 0x30)); else // Alphabetic character (for digits > 10) (0x61 = 'a') sb.Append((char) (digit + 0x57)); // 0x61 - 10   if ( div == 1 ) // Stop when the dividend reaches 1 break;   n %= div; div /= b; }   return sb.ToString(); }   }   }  
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.
#Phix
Phix
with javascript_semantics ?to_integer("1234") -- 1234 ?to_integer("10101010",0,2) -- 170, 0 on failure ?to_number("FFFFFFFF","?",16) -- 4294967295.0, "?" on failure ?scanf("#FFFFFFFF","%f") -- {{4294967295.0}}, {} on failure ?scanf("0o377","%o") -- {{255}} ?scanf("1234","%d") -- {{1234}} include mpfr.e mpz z = mpz_init() mpz_set_str(z,"377",8) ?mpz_get_str(z) -- "255" mpfr f = mpfr_init() mpfr_set_str(f,"110.01",2) ?mpfr_get_fixed(f) -- "6.25" (which is correct in 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.
#PHP
PHP
<?php echo +"0123459", "\n"; // prints 123459 echo intval("0123459"), "\n"; // prints 123459 echo hexdec("abcf123"), "\n"; // prints 180154659 echo octdec("7651"), "\n"; // prints 4009 echo bindec("101011001"), "\n"; // prints 345 ?>
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.Formatter   loop i_ = 1 to 3 loop n_ = 20 to 20000 by 2131 select case i_ when 1 then say useBif(n_) when 2 then say useJavaFormat(n_) when 3 then say useJavaNumber(n_) otherwise nop end end n_ say end i_   return   -- NetRexx doesn't have a decimal to octal conversion method useBif(n_) public static d_ = '_' return '[Base 16='n_.d2x().right(8)',Base 10='n_.right(8)',Base 8='d_.right(8)',Base 2='n_.d2x().x2b().right(20)']'   -- Some of Java's java.lang.Number classes have conversion methods method useJavaNumber(n_) public static nx = Long.toHexString(n_) nd = Long.toString(n_) no = Long.toOctalString(n_) nb = Long.toBinaryString(n_) return '[Base 16='Rexx(nx).right(8)',Base 10='Rexx(nd).right(8)',Base 8='Rexx(no).right(8)',Base 2='Rexx(nb).right(20)']'   -- Java Formatter doesn't have a decimal to binary conversion method useJavaFormat(n_) public static fb = StringBuilder() fm = Formatter(fb) fm.format("[Base 16=%1$8x,Base 10=%1$8d,Base 8=%1$8o,Base 2=%2$20s]", [Object Long(n_), String('_')]) return fb.toString()  
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.
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <tuple> #include <vector>   const std::string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";   std::string encodeNegativeBase(int64_t n, int b) { if (b < -62 || b > -1) { throw std::runtime_error("Argument out of range: b"); } if (n == 0) { return "0"; }   std::string output; int64_t nn = n; while (nn != 0) { int rem = nn % b; nn /= b; if (rem < 0) { nn++; rem -= b; } output += DIGITS[rem]; }   std::reverse(output.begin(), output.end()); return output; }   int64_t decodeNegativeBase(const std::string& ns, int b) { if (b < -62 || b > -1) { throw std::runtime_error("Argument out of range: b"); } if (ns == "0") { return 0; }   int64_t total = 0; int64_t bb = 1;   for (auto it = ns.crbegin(); it != ns.crend(); it = std::next(it)) { auto ptr = std::find(DIGITS.cbegin(), DIGITS.cend(), *it); if (ptr != DIGITS.cend()) { auto idx = ptr - DIGITS.cbegin(); total += idx * bb; } bb *= b; } return total; }   int main() { using namespace std;   vector<pair<int64_t, int>> nbl({ make_pair(10, -2), make_pair(146, -3), make_pair(15, -10), make_pair(142961, -62) });   for (auto& p : nbl) { string ns = encodeNegativeBase(p.first, p.second); cout << setw(12) << p.first << " encoded in base " << setw(3) << p.second << " = " << ns.c_str() << endl;   int64_t n = decodeNegativeBase(ns, p.second); cout << setw(12) << ns.c_str() << " decoded in base " << setw(3) << p.second << " = " << n << endl;   cout << endl; }   return 0; }
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.
#Sidef
Sidef
var l = frequire('Lingua::EN::Numbers'); say l.num2en(123456789);
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#True_BASIC
True BASIC
  RANDOMIZE   PRINT "Dada una lista aleatoria de números del 1 al 9," PRINT "indica cuantos dígitos de la izquierda voltear." PRINT " El objetivo es obtener los dígitos en orden " PRINT " con el 1 a la izquierda y el 9 a la derecha." PRINT   DIM nums(1 to 9) DIM temp(1 to 9) !valores iniciales FOR x = 1 to 9 LET nums(x) = x NEXT x   DO  !barajamos FOR x = 9 to 2 step -1 LET n = round(int(rnd*(x))+1) IF n <> x then  !swap (nums(n), nums(x)) !no existe comado SWAP LET temp(n) = nums(x) LET nums(x) = nums(n) LET nums(n) = temp(n) END IF NEXT x FOR x = 1 to 8  !nos aseguramos que no estén en orden IF nums(x) > nums(x+1) then EXIT DO NEXT x LOOP   LET denuevo = -1 DO IF intentos < 10 then PRINT " "; PRINT intentos; ":"; FOR x = 1 to 9 PRINT nums(x); NEXT x   IF (not denuevo <> 0) then EXIT DO   INPUT prompt " -- ¿Cuántos volteamos? ": volteo IF volteo < 0 or volteo > 9 then LET volteo = 0   FOR x = 1 to (ip(volteo/2))  !swap (nums(x), nums(volteo-x+1))  !no existe SWAP LET temp(n) = nums(volteo-x+1) LET nums(volteo-x+1) = nums(x) LET nums(x) = temp(n) NEXT x   LET denuevo = 0  !comprobamos el orden FOR x = 1 to 8 IF nums(x) > nums(x+1) then LET denuevo = -1 EXIT FOR END IF NEXT x   IF volteo > 0 then LET intentos = intentos+1 LOOP   PRINT PRINT PRINT "Necesitaste "; ltrim$(rtrim$(str$(intentos))); " intentos." END  
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.
#Go
Go
package main   import ( "bufio" "fmt" "os" "strconv" )   func showTokens(tokens int) { fmt.Println("Tokens remaining", tokens, "\n") }   func main() { tokens := 12 scanner := bufio.NewScanner(os.Stdin) for { showTokens(tokens) fmt.Print(" How many tokens 1, 2 or 3? ") scanner.Scan() if scerr := scanner.Err(); scerr != nil { fmt.Println("Error reading standard input:", scerr) return } t, err := strconv.Atoi(scanner.Text()) if err != nil || t < 1 || t > 3 { fmt.Println("\nMust be a number between 1 and 3, try again.\n") } else { ct := 4 - t s := "s" if ct == 1 { s = "" } fmt.Print(" Computer takes ", ct, " token", s, "\n\n") tokens -= 4 } if tokens == 0 { showTokens(0) fmt.Println(" Computer wins!") return } } }
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.
#AutoIt
AutoIt
;AutoIt Version: 3.2.10.0 $A=4913 $n=3 $x=20 ConsoleWrite ($n& " root of "& $A & " is " &nth_root_it($A,$n,$x)) ConsoleWrite ($n& " root of "& $A & " is " &nth_root_rec($A,$n,$x))   ;Iterative Func nth_root_it($A,$n,$x) $x0="0" While StringCompare(string($x0),string($x)) ConsoleWrite ($x&@CRLF) $x0=$x $x=((($n-1)*$x)+($A/$x^($n-1)))/$n WEnd Return $x EndFunc   ;Recursive Func nth_root_rec($A,$n,$x) ConsoleWrite ($x&@CRLF) If $x==((($n-1)*$x)+($A/$x^($n-1)))/$n Then Return $x EndIf Return nth_root_rec($A,$n,((($n-1)*$x)+($A/$x^($n-1)))/$n) EndFunc
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.
#ALGOL_68
ALGOL 68
STRINGs="STRINGs="";print(readstring=2*s[:9]+2*s[9:])";print(readstring=2*s[:9]+2*s[9:])
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.
#AppleScript
AppleScript
(display dialog "" default answer "")'s text returned = (do shell script ("osadecompile " & (path to me)'s POSIX path's quoted form))
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.
#AutoHotkey
AutoHotkey
Narcissist(Input) { FileRead, Source, % A_ScriptFullPath return Input == Source ? "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.
#BBC_BASIC
BBC BASIC
INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM INPUT a$:PRINT -(a$=$(PAGE+34)+$(PAGE+33)):REM
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
#JavaScript
JavaScript
const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x); const toString = x => x + ''; const reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []); const minBiggerThanN = (arr, n) => arr.filter(e => e > n).sort()[0]; const remEl = (arr, e) => { const r = arr.indexOf(e); return arr.filter((e,i) => i !== r); }   const nextHighest = itr => { const seen = []; let result = 0; for (const [i,v] of itr.entries()) { const n = +v; if (Math.max(n, ...seen) !== n) { const right = itr.slice(i + 1); const swap = minBiggerThanN(seen, n); const rem = remEl(seen, swap); const rest = [n, ...rem].sort(); result = [...reverse(right), swap, ...rest].join(''); break; } else { seen.push(n); } } return result; };   const check = compose(nextHighest, reverse, toString);   const test = v => { console.log(v, '=>', check(v)); }   test(0); test(9); test(12); test(21); test(12453); test(738440); test(45072010); test(95322020); test('9589776899767587796600');  
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
#Fortran
Fortran
FUNCTION F(X) REAL X DIST(U,V,W) = X*SQRT(U**2 + V**2 + W**2) !The contained function. T = EXP(X) F = T + DIST(T,SIN(X),ATAN(X) + 7) !Invoked... END
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
#Free_Pascal
Free Pascal
// In Pascal, functions always _have_ to return _some_ value, // but the the task doesn’t specify what to return. // Hence makeList and makeItem became procedures. procedure makeList(const separator: string); // The var-section for variables that ought to be accessible // in the routine’s body as well as the /nested/ routines // has to appear /before/ the nested routines’ definitions. var counter: 1..high(integer);   procedure makeItem; begin write(counter, separator); case counter of 1: begin write('first'); end; 2: begin write('second'); end; 3: begin write('third'); end; end; writeLn(); counter := counter + 1; end; // You can insert another var-section here, but variables declared // in this block would _not_ be accessible in the /nested/ routine. begin counter := 1; makeItem; makeItem; makeItem; end;