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 subseque...
#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). ...
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 invisibl...
#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 "...
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 ass...
#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 ass...
#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 langu...
#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 langu...
#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...
#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   l...
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...
#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...
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, negat...
#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 reversa...
#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...
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 tur...
#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 toke...
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...
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 th...
#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>): AnsiS...
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 t...
#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 t...
#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 ma...
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 per...
#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 = systim...
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 e...
#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, s...
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...
#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 ...
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. ...
#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...
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 subseque...
#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 invisibl...
#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 digitcha...
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 ass...
#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 ass...
#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) ) ...
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 langu...
#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 langu...
#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...
#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 # ...
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, negat...
#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 reversa...
#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 numberOfT...
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 tur...
#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 ...
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 tur...
#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 ...
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 valu...
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 " %...
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 th...
#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" print...
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 th...
#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 ...
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 t...
#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 t...
#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-mak...
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 per...
#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 = cur...
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 e...
#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 i...
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...
#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 #\newl...
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. ...
#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 outpu...
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 subseque...
#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 ...
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 invisibl...
#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 no...
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 ass...
#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 pr...
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 langu...
#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 langu...
#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...
#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; } ...
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, negat...
#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", ...
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 reversa...
#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 wo...
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 tur...
#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 || playerta...
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 tur...
#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 remainin...
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 th...
#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   -----...
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 t...
#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...
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 t...
#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; ...
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 t...
#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 per...
#C.2B.2B
C++
  #include <iostream> #include <string> #include <windows.h>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class bells { public: void s...
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 e...
#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_slic...
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 e...
#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-re...
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 e...
#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...
#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 = ...
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. ...
#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...
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 subseque...
#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) [...
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 invisibl...
#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)...
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 ass...
#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 pr...
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 langu...
#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 langu...
#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 langu...
#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...
#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 ...
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, negat...
#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 ...
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 reversa...
#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 t...
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 tur...
#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 th...
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 tur...
#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 ...
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/N...
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" o...
#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:St...
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 th...
#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 ...
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 th...
#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[] {"...
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 t...
#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 t...
#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   {} |>...
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 t...
#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...
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 per...
#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() { ...
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 e...
#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'], 'P...
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...
#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, ...
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. ...
#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 cell...
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 subseque...
#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 invisibl...
#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 ...
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 ass...
#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") ...
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 ass...
#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 langu...
#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 ...
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...
#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"); } ...
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, negat...
#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 reversa...
#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 nu...
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 tur...
#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? "...
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...
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" o...
#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" o...
#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" o...
#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" o...
#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 th...
#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...
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 t...
#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 t...
#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/ r...