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-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...
#Raku
Raku
say 0b11011; # -> 27 say 0o11011; # -> 4617 say 0d11011; # -> 11011 say 0x11011; # -> 69649
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...
#REXX
REXX
╔══════════════════════════════════════════════════════════════════════════════════╗ ║ In REXX, there are no numeric-type variables (integer, float, real, unsigned, ║ ║ logical, binary, complex, double, etc), only character. Everything is stored ║ ║ as a character string. Arithmetic is done almost exac...
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...
#PureBasic
PureBasic
For i=105 To 115 Bin$=RSet(Bin(i),8,"0") ;- Convert to wanted type & pad with '0' Hex$=RSet(Hex(i),4,"0") Dec$=RSet(Str(i),3) PrintN(Dec$+" decimal = %"+Bin$+" = $"+Hex$+".") 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...
#Python
Python
for n in range(34): print " %3o %2d %2X" % (n, n, n)
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...
#J
J
>>> # python divmod >>> [divmod(i, -2) for i in (2, 3, 4, 5)] [(-1, 0), (-2, -1), (-2, 0), (-3, -1)] >>>
http://rosettacode.org/wiki/Negative_base_numbers
Negative base numbers
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the decimal number 146 as negaternary...
#Java
Java
import java.util.List; import java.util.Map; import java.util.Objects;   public class NegativeBaseNumbers { private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";   private static String encodeNegBase(long n, int b) { if (b < -62 || b > -1) throw new Illeg...
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...
#Visual_Basic
Visual Basic
Option Explicit   Private small As Variant, tens As Variant, big As Variant   Sub Main() small = Array("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", _ "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", _ "eighteen", "ni...
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...
#XPL0
XPL0
int Taken, I, Digit, Num, Score, Rev, Temp; char List(9); include c:\cxpl\codes; \make jumbled list of digits 1 to 9 [loop [Taken:= 0; \bit array indicates which digits are taken for I:= 0 to 9-1 do [repeat Digit:= Ran(9)+1 until (Taken & 1<<Digit) = 0; ...
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Julia
Julia
function nimgame() tcount = 12 takenum = 0 while true while true permitted = collect(1:min(3,tcount)) println("$tcount tokens remain.\nHow many do you take ($permitted)? ") takenum = parse(Int, strip(readline(stdin))) if takenum in permitted ...
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...
#Kotlin
Kotlin
// Version 1.3.21   fun showTokens(tokens: Int) { println("Tokens remaining $tokens\n") }   fun main() { var tokens = 12 while (true) { showTokens(tokens) print(" How many tokens 1, 2 or 3? ") var t = readLine()!!.toIntOrNull() if (t == null || t < 1 || t > 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.
#bc
bc
/* Take the nth root of 'a' (a positive real number). * 'n' must be an integer. * Result will have 'd' digits after the decimal point. */ define r(a, n, d) { auto e, o, x, y, z   if (n == 0) return(1) if (a == 0) return(0)   o = scale scale = d e = 1 / 10 ^ d   if (n < 0) { n = -...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation" use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>   on naturalSort(listOfText) -- Produce versions of the strings for sorting purposes, doctored to get rou...
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...
#J
J
#!/j602/bin/jconsole main=:3 : 0 self=: '#!/j602/bin/jconsole',LF,'main=:',(5!:5<'main'),LF,'main''''',LF echo self -: stdin'' ) main''
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...
#Java
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;   public class Narcissist { private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n private static final String ...
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#360_Assembly
360 Assembly
MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR); PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;   PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;   PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1...
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#6502_Assembly
6502 Assembly
MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR); PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;   PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;   PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1...
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#ALGOL_68
ALGOL 68
MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR); PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;   PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;   PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1...
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...
#Phix
Phix
function nigh(string n) sequence p = repeat("",factorial(length(n))) for i=1 to length(p) do p[i] = permute(i,n) end for p = sort(p) integer k = rfind(n,p) return iff(k=length(p)?"0",p[k+1]) end function constant tests = {"0","9","12","21","12453", "738440","45072010"...
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...
#Julia
Julia
function makelist(sep::String) cnt = 1   function makeitem(item::String) rst = string(cnt, sep, item, '\n') cnt += 1 return rst end   return makeitem("first") * makeitem("second") * makeitem("third") end   print(makelist(". "))
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Kotlin
Kotlin
// version 1.0.6   fun makeList(sep: String): String { var count = 0 fun makeItem(item: String): String { count++ return "$count$sep$item\n" } return makeItem("first") + makeItem("second") + makeItem("third") }   fun main(args: Array<String>) { print(makeList(". ")) }
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
LocalSubmit[ScheduledTask[ EmitSound[Sound[Table[{ SoundNote["C",750/1000,"TubularBells"],SoundNote[None,500/1000,"TubularBells"] },Mod[Round[Total[DateList[][[{4,5}]]{2,1/30}]],8,1]]]] ,DateObject[{_,_,_,_,_,30|0}]]]
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Nim
Nim
import os, strformat, times   const Watches = ["First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First"] WatchEnds = [(0, 0), (4, 0), (8, 0), (12, 0), (16, 0), (18, 0), (20, 0), (23, 59)] Bells = array[1..8, string](["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"]) ...
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...
#REXX
REXX
/*REXX*/ Parse Arg fn Parse Var fn ou'.' maxpn = 10000 /* maximum possibilities to check through */ output = ou'.out.txt' /* read row/col values into rowpp. and colpp. arrays */ cc = linein(fn) rows = words(cc) dd = linein(fn) cols = words(dd) char = '0ABCDEFGHIJKLMNOP...
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...
#Nim
Nim
import sequtils   proc ncsub[T](se: seq[T], s = 0): seq[seq[T]] = result = @[] if se.len > 0: let x = se[0..0] xs = se[1 .. ^1] p2 = s mod 2 p1 = (s + 1) mod 2 for ys in ncsub(xs, s + p1): result.add(x & ys) result.add(ncsub(xs, s + p2)) elif s >= 3: result.add(@[])  ...
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...
#OCaml
OCaml
let rec fence s = function [] -> if s >= 3 then [[]] else []   | x :: xs -> if s mod 2 = 0 then List.map (fun ys -> x :: ys) (fence (s + 1) xs) @ fence s xs else List.map (fun ys -> x :: ys) (fence 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 invisibl...
#Elixir
Elixir
iex(1)> String.to_integer("ffff", 16) 65535 iex(2)> Integer.to_string(255, 2) "11111111" iex(3)> String.to_integer("NonDecimalRadices", 36) 188498506820338115928429652
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...
#Ring
Ring
  see number("0") + nl see number("123456789") + nl see number("-987654321") + nl  
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...
#Ruby
Ruby
dec1 = "0123459" hex2 = "abcf123" oct3 = "7651" bin4 = "101011001"   p dec1.to_i # => 123459 p hex2.hex # => 180154659 p oct3.oct # => 4009 # nothing for binary
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...
#R
R
# dec to oct as.octmode(x) # dec to hex as.hexmode(x) # oct or hex to dec as.integer(x) # or as.numeric(x)
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...
#Racket
Racket
  #lang racket   ;; Explicit conversion of numbers can use the standard radices (map (λ(r) (number->string 123 r)) '(2 8 10 16)) ;; -> '("1111011" "173" "123" "7b")   ;; There is also the `~r' formatting function that works with any radix ;; up to 36 (for/list ([r (in-range 2 37)]) (~r 123 #:base r)) ;; -> '("1111011" ...
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...
#jq
jq
def trunc: if . >= 0 then floor else -(-(.)|trunc) 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...
#Julia
Julia
  function negbase(n, b) if n == 0 return "0" end out = IOBuffer() while n != 0 n, r = divrem(n, b) if r < 0 n += 1 r -= b end print(out, r) end return reverse(String(out)) end   invnegbase(nst, b) = sum((ch - '0') * b ^ (i - 1) for (i, ch) in ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim i As Integer Console.WriteLine("Enter a number") i = Console.ReadLine() Console.WriteLine(words(i)) Console.ReadLine() End Sub   Function words(ByVal Number As Integer) As String Dim small() As String = {"zero", "one", "two", "t...
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...
#Yabasic
Yabasic
// Rosetta Code problem: https://www.rosettacode.org/wiki/Number_reversal_game // by Jjuanhdez, 06/2022   print "Given a jumbled list of the numbers 1 to 9, " print "you must select how many digits from the left " print "to reverse. Your goal is to get the digits in " print "order with 1 on the left and 9 on the righ...
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...
#Lua
Lua
  tokens = 12   print("Nim Game\n") print("Starting with " .. tokens .. " tokens.\n\n")   function printRemaining() print(tokens .. " tokens remaining.\n") end   function playerTurn(take) take = math.floor(take) if (take < 1 or take > 3) then print ("\nTake must be between 1 and 3.\n") return false end   token...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
n = 12; While[n > 0, c = ChoiceDialog["Current amount = " <> ToString[n] <> "\nHow many do you want to pick?", {1 -> 1, 2 -> 2, 3 -> 3}]; n -= c; ChoiceDialog["Current amount = " <> ToString[n] <> "\nComputer takes " <> ToString[4 - c]]; n -= (4 - c); ] ChoiceDialog["Current amount = " <> ToString[n] <> "\n You lo...
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.
#BQN
BQN
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} Root ← √ Root1 ← ⋆⟜÷˜ Root2 ← { n 𝕊 a‿prec: 1⊑{ p‿x: ⟨ x ((p × n - 1) + a ÷ p ⋆ n - 1) ÷ n ⟩ } _while_ { p‿x: prec ≤ | p - x } ⟨a, ⌊a÷n⟩; 𝕨 𝕊 𝕩: 𝕨 𝕊 𝕩‿1E¯5 }   •Show 3 Root 5 •Show 3 Root1 5 •Show 3 Root2 5 •Show 3 Root2 5‿1E¯16
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Bracmat
Bracmat
( ( root = n a d x0 x1 d2 rnd 10-d . ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. } = N r .  !arg:(?N.?r) & div$(!N*!r+1/2.1)*!r^-1 ) & !arg:(?n,?a,?d) & !a*!n^-1:?x0 & 10^(-1*!d):?10-d & whl ' (...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <wctype.h> #include <string.h> #include <locale.h>   typedef struct wstr { wchar_t *s; int n, alloc; } wstr;   #define w_del(w) { free(w->s); free(w); } #define forchars(i, c, w) for(i = 0, c = w->s[0]; i < w->n && c; c = w->s[++i]) wstr *w_new() { w...
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...
#JavaScript
JavaScript
var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code)
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...
#Julia
Julia
mysource = Base.read(Base.source_path(), String) println(Int(ARGS[1] == mysource))
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...
#Kotlin
Kotlin
// version 1.1.0 (run on Windows 10)   fun main(args: Array<String>) { val text = java.io.File("narcissist.kt").readText() println("Enter the number of lines to be input followed by those lines:\n") val n = readLine()!!.toInt() val lines = Array<String>(n) { readLine()!! } if (lines.joinToString("\r...
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#AntLang
AntLang
variables-are-often-lower-case-and-seperated-like-this-one
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Arturo
Arturo
  # Field names begin with $ so $1 is the first field, $2 the second and $NF the # last. $0 references the entire input record. # # Function and variable names are case sensitive and begin with an alphabetic # character or underscore followed by any number of: a-z, A-Z, 0-9, _ # # The awk language is type less; variab...
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#AWK
AWK
  # Field names begin with $ so $1 is the first field, $2 the second and $NF the # last. $0 references the entire input record. # # Function and variable names are case sensitive and begin with an alphabetic # character or underscore followed by any number of: a-z, A-Z, 0-9, _ # # The awk language is type less; variab...
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...
#Python
Python
def closest_more_than(n, lst): "(index of) closest int from lst, to n that is also > n" large = max(lst) + 1 return lst.index(min(lst, key=lambda x: (large if x <= n else x)))   def nexthigh(n): "Return nxt highest number from n's digits using scan & re-order" assert n == int(abs(n)), "n >= 0" t...
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...
#Lua
Lua
function makeList (separator) local counter = 0 local function makeItem(item) counter = counter + 1 return counter .. separator .. item .. "\n" end return makeItem("first") .. makeItem("second") .. makeItem("third") end   print(makeList(". "))
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Make_List(". ") Sub Make_List(Separator$) Local Counter=0 Make_Item("First") Make_Item("Second") Make_Item("Third") End Sub Sub Make_Item(Item_Name$) Counter++ Print Str$(Counter,"")+Separator$+Item_Name$ ...
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...
#Maple
Maple
  makelist:=proc() local makeitem,i; i:=1; makeitem:=proc(i) if i=1 then printf("%a\n", "1. first"); elif i=2 then printf("%a\n","2. second"); elif i=3 then printf("%a\n", "3. third"); else return NULL; end if; end proc; while i<4 do makeitem(i); i:=i+1; end do; end proc;    
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...
#OoRexx
OoRexx
/*REXX pgm beep's "bells" (using PC speaker) when running (perpetually).*/ Parse Arg msg If msg='?' Then Do Say 'Ring a nautical bell' Exit End Signal on Halt /* allow a clean way to stop prog.*/ Do Forever Parse Value time() With hh ':' mn ':' ss ct=time('C') hhmmc=lef...
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...
#Wren
Wren
import "/pattern" for Pattern import "/math" for Nums, Boolean import "/fmt" for Conv   var p = Pattern.new("/s")   var genSequence // recursive genSequence = Fn.new { |ones, numZeros| if (ones.isEmpty) return ["0" * numZeros] var result = [] var x = 1 while (x < numZeros - ones.count + 2) { var...
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...
#Oz
Oz
declare fun {NCSubseq SeqList} Seq = {FS.value.make SeqList} proc {Script Result} %% the result is a subset of Seq {FS.subset Result Seq}   %% at least one element of Seq is missing local Gap in {FS.include Gap Seq} {FS.exclude Gap Result} %% ...
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...
#Erlang
Erlang
12> erlang:list_to_integer("ffff", 17). 78300 13> erlang:integer_to_list(63, 3). "2100"
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...
#Rust
Rust
fn main() { println!( "Parse from plain decimal: {}", "123".parse::<u32>().unwrap() );   println!( "Parse with a given radix (2-36 supported): {}", u32::from_str_radix("deadbeef", 16).unwrap() ); }
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...
#Scala
Scala
object Main extends App {   val (s, bases) = ("100", Seq(2, 8, 10, 16, 19, 36)) bases.foreach(base => println(f"String $s in base $base%2d is $BigInt(s, base)%5d")) }
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...
#Raku
Raku
say 30.base(2); # "11110" say 30.base(8); # "36" say 30.base(10); # "30" say 30.base(16); # "1E" say 30.base(30); # "10"
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...
#REXX
REXX
/*REXX pgm shows REXX's ability to show decimal numbers in binary & hex.*/   do j=0 to 50 /*show some low-value num conversions*/ say right(j,3) ' in decimal is', right(d2b(j),12) " in binary", right(d2x(j),12) ' in hexadecimal.' end /*j*/ exit ...
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...
#Kotlin
Kotlin
// version 1.1.2   const val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"   fun encodeNegBase(n: Long, b: Int): String { require(b in -62 .. -1) if (n == 0L) return "0" val out = mutableListOf<Char>() var nn = n while (nn != 0L) { var rem = (nn % b).toInt() ...
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...
#Vlang
Vlang
const ( small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] illions...
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...
#zkl
zkl
correctList,scrambledList,N:=[1..9].walk(), correctList.shuffle(),correctList.len(); correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string attempts:=0; while(scrambledList!=correctList){ // Repeat until the sequence is correct n:=ask(("[%d] %s How many numbers (from the left) ...
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...
#MiniScript
MiniScript
tokens = 12   print "Nim Game" print "Starting with " + tokens + " tokens." print   printRemaining = function() print tokens + " tokens remaining." print end function   playerTurn = function(take) take = floor(val(take)) if take < 1 or take > 3 then print "Take must be between 1 and 3." return false end if   ...
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...
#Nim
Nim
import strutils import terminal   var tokens = 12   styledEcho(styleBright, "Nim in Nim\n")   proc echoTokens() = styledEcho(styleBright, "Tokens remaining: ", resetStyle, $tokens, "\n")   proc player() = var take = '0' styledEcho(styleBright, "- Your turn -") echo "How many tokens will you take?" while true:...
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#11l
11l
F narcissists(m) [Int] result L(digits) 0.. V digitpowers = (0.<10).map(i -> i ^ @digits) L(n) Int(10 ^ (digits - 1)) .< 10 ^ digits V (div, digitpsum) = (n, 0) L div != 0 (div, V mod) = divmod(div, 10) digitpsum += digitpowers[mod] I n == digitpsum ...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#11l
11l
F sqlen(x = 0, y = 0, z = 0) R x*x + y*y + z*z   print(sqlen(z' 3)) // equivalent to print(sqlen(0, 0, 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.
#C
C
#include <stdio.h> #include <float.h>   double pow_ (double x, int e) { int i; double r = 1; for (i = 0; i < e; i++) { r *= x; } return r; }   double root (int n, double x) { double d, r = 1; if (!x) { return 0; } if (n < 1 || (x < 0 && !(n&1))) { return 0.0 /...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
import std.stdio, std.string, std.algorithm, std.array, std.conv, std.ascii, std.range;   string[] naturalSort(string[] arr) /*pure @safe*/ { static struct Part { string s;   int opCmp(in ref Part other) const pure { return (s[0].isDigit && other.s[0].isDigit) ? cmp([...
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...
#Liberty_BASIC
Liberty BASIC
  s$ = "s$ = Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100)) + Mid$(s$, 23, 3)" : Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100))  
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
prog = "prog = ``;\nPrint[InputString[] == \n ToString[StringForm[prog, ToString[prog, InputForm]]]];"; Print[InputString[] == ToString[StringForm[prog, ToString[prog, InputForm]]]];
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...
#Nanoquery
Nanoquery
import Nanoquery.IO   // get a file tied to this program's source $f = new(File, $args[len($args) - 1])   // get the source and split across lines $source = split($f.readAll(), "\n")   // read that amount of lines from the console $in = list(len($source)) for ($i = 0) ($i < len($source)) ($i = $i + 1) append $in input...
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Nim
Nim
  import strutils; let a = "import strutils; let a = $#; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))"; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))  
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#BASIC
BASIC
DEF PROC_foo(bar, baz$(), quux%, RETURN fred%, RETURN jim%)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#BBC_BASIC
BBC BASIC
DEF PROC_foo(bar, baz$(), quux%, RETURN fred%, RETURN jim%)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#C
C
O_RDONLY, O_WRONLY, or O_RDWR. O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#C.23
C#
public enum Planet { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune }   [Flags] public enum Days { None = 0, Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, Workdays = Monday | Tuesday | Wednesday | Thursday | Friday ...
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...
#Raku
Raku
use Lingua::EN::Numbers;   sub next-greatest-index ($str, &op = &infix:«<» ) { my @i = $str.comb; (1..^@i).first: { &op(@i[$_ - 1], @i[$_]) }, :end, :k; }   multi next-greatest-integer (Int $num where * >= 0) { return 0 if $num.chars < 2; return $num.flip > $num ?? $num.flip !! 0 if $num.chars == 2; ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
makeList[sep_String]:=Block[ {counter=0, makeItem}, makeItem[item_String]:=ToString[++counter]<>sep<>item; makeItem /@ {"first", "second", "third"} ] Scan[Print, makeList[". "]]
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#min
min
(  :separator 1 :counter (  :item item separator counter string ' append append "" join counter succ @counter ) :make-item ("first" "second" "third") 'make-item map "\n" join ) :make-list   ". " make-list print
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...
#MiniScript
MiniScript
makeList = function(sep) counter = 0 makeItem = function(item) outer.counter = counter + 1 return counter + sep + item end function return [makeItem("first"), makeItem("second"), makeItem("third")] end function   print makeList(". ")
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Perl
Perl
use utf8; binmode STDOUT, ":utf8"; use DateTime;   $| = 1; # to prevent output buffering   my @watch = <Middle Morning Forenoon Afternoon Dog First>; my @ordinal = <One Two Three Four Five Six Seven Eight>;   my $thishour; my $thisminute = '';   while () { my $utc = DateTime->now( time_zone => 'UTC' ); if ($utc...
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...
#PARI.2FGP
PARI/GP
noncontig(n)=n>>=valuation(n,2);n++;n>>=valuation(n,2);n>1; nonContigSubseq(v)={ for(i=5,2^#v-1, if(noncontig(i), print(vecextract(v,i)) ) ) }; nonContigSubseq([1,2,3]) nonContigSubseq(["a","b","c","d","e"])
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...
#Euphoria
Euphoria
function to_base(integer i, integer base) integer rem sequence s s = "" while i > 0 do rem = remainder(i,base) if rem < 10 then s = prepend(s, '0'+rem) else s = prepend(s, 'a'-10+rem) end if i = floor(i/base) end while   if length(s...
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...
#Scheme
Scheme
> (string->number "abcf123" 16) ; hex 180154659 > (string->number "123459" 10) ; decimal, the "10" is optional 123459 > (string->number "7651" 8) ; octal 4009 > (string->number "101011001" 2) ; binary 345
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(integer("0123459", 10)); writeln(integer("abcf123", 16)); writeln(integer("7651", 8)); writeln(integer("1010011010", 2)); writeln(integer("tplig0", 32)); writeln(integer("gc0uy9", 36)); end func;
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...
#Ring
Ring
  # Project : Non Decimal radices/Output   see string(0) + nl see string(123456789) + nl see string(-987654321) + nl   see upper(hex(43981)) + nl see upper(hex(-1)) + nl  
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
EncodeBase[number_,base_]:=Module[{ out={}, rem,n=number,b=base }, While[ n!=0, {n,rem}={Floor[Divide[n,b]],Mod[n,b]}; If[ rem<0, n+=1; rem-=b ]; PrependTo[out,rem] ]; out ]; DecodeBase[list_,base_]:=Total[list*base^Range[Length[list]-1,0,-1]];   Print[EncodeNegBase[10,-2],"=",DecodeBase[Enco...
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...
#Modula-2
Modula-2
MODULE NegativeBase; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   CONST DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; TYPE String = ARRAY[0..63] OF CHAR;   PROCEDURE EncodeNegativeBase(n : LONGINT; base : LONGINT) : String; PROCEDURE Mod(a,...
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...
#Wren
Wren
var small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]   var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]   v...
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...
#OCaml
OCaml
let rec player_turn () = print_string "How many tokens would you like to take? "; let n = read_int_opt () |> Option.value ~default:0 in if n >= 1 && n <= 3 then n else ( print_endline "Number must be between 1 and 3"; player_turn ())   let computer_turn tokens = tokens mod 4   let plural_suffix = functi...
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Ada
Ada
with Ada.Text_IO;   procedure Narcissistic is   function Is_Narcissistic(N: Natural) return Boolean is Decimals: Natural := 1; M: Natural := N; Sum: Natural := 0; begin while M >= 10 loop M := M / 10; Decimals := Decimals + 1; end loop; M := N; while M >= 1 loop Sum...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Ada
Ada
procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.0);
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#ALGOL_68
ALGOL 68
BEGIN MODE OPTNAME = STRUCT(STRING name), OPTSPECIES = STRUCT(STRING species), OPTBREED = STRUCT(STRING breed), OWNER=STRUCT(STRING first name, middle name, last name);   # Version 2 of Algol 68G would not allow empty options to be specified as () so # # VOID would need to be included in ...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#C.23
C#
  static void Main(string[] args) { Console.WriteLine(NthRoot(81,2,.001)); Console.WriteLine(NthRoot(1000,3,.001)); Console.ReadLine(); }   public static double NthRoot(double A,int n, double p) { double _n= (double) n; double[] x = new double[2]; x[0] = A; x[1] = A/_n; while(Math.Abs(x[0] -x[1...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#11l
11l
V _suffix = [‘th’, ‘st’, ‘nd’, ‘rd’, ‘th’, ‘th’, ‘th’, ‘th’, ‘th’, ‘th’]   F nth(n) R ‘#.'#.’.format(n, I n % 100 <= 10 | n % 100 > 20 {:_suffix[n % 10]} E ‘th’)   L(j) (0..1000).step(250) print_elements(Array(j.+25).map(i -> nth(i)))
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#ALGOL_68
ALGOL 68
BEGIN # show the first 199 values of the moebius function # INT sq root = 1 000; INT mu max = sq root * sq root; [ 1 : mu max ]INT mu; FOR i FROM LWB mu TO UPB mu DO mu[ i ] := 1 OD; FOR i FROM 2 TO sq root DO IF mu[ i ] = 1 THEN # for each factor found, swap...
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Elixir
Elixir
defmodule Natural do def sorting(texts) do Enum.sort_by(texts, fn text -> compare_value(text) end) end   defp compare_value(text) do text |> String.downcase |> String.replace(~r/\A(a |an |the )/, "") |> String.split |> Enum.map(fn word -> Regex.scan(~r/\d+|\D+/, word) |> ...
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...
#PARI.2FGP
PARI/GP
narcissist()=input()==narcissist
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Perl
Perl
# this is file narc.pl local $/; print do { open 0; <0> } eq <> ? "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...
#Phix
Phix
without js -- (file i/o) puts(1,{"\n\ntrue\n\n","\n\nfalse\n\n"}[1+(gets(open(command_line()[2],"r"))!=gets(0))])
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Clojure
Clojure
var xs = Array.Empty(10) var ys = Array(1, 2, 3) var str = xs.ToString()   type Maybe = Some(x) or None() var x = Maybe.Some(42)
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Common_Lisp
Common Lisp
var xs = Array.Empty(10) var ys = Array(1, 2, 3) var str = xs.ToString()   type Maybe = Some(x) or None() var x = Maybe.Some(42)