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/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...
#Python
Python
  print("Py Nim\n")   def getTokens(curTokens): global tokens   print("How many tokens would you like to take? ", end='') take = int(input())   if (take < 1 or take > 3): print("Number must be between 1 and 3.\n") getTokens(curTokens) return   tokens = curTokens - take print(f'You take {take} tokens.') pri...
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...
#R
R
## Nim game ##   tokens <- 12   while(tokens > 0) { print(paste("Tokens remaining:",tokens)) playertaken <- 0 while(playertaken == 0) { playeropts <- c(1:min(c(tokens,3))) playertaken <- menu(playeropts, title = "Your go, how many tokens will you take? ") tokens <- tokens - playertaken if(tokens =...
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...
#APL
APL
  ∇r ← digitsOf n;digitList digitList ← ⍬ loop:→((⌊n)=0)/done digitList ← digitList,(⌊n|⍨10) n ← n÷10 →loop done: r ← ⊖digitList ∇   ∇r ← getASN n;idx;list idx ← 0 list ← 0⍴0 loop: →(n=⍴list)/done →(isArmstrongNumber idx)/add →next add: list ← list,idx next: idx ← idx+1 →loop done: r ← list ∇ ...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <gmp.h>   void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } return ptr; }   void* xrealloc(void* p, size_t n) { void* ptr = reallo...
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...
#C
C
#include <stdio.h>   // 1. Named parameters   typedef struct { int x, y, z; } FTest_args;   void FTest (FTest_args args) { printf("x: %d, y: %d, z: %d\n", args.x, args.y, args.z); }   #define FT(...) FTest((FTest_args){ __VA_ARGS__ })     // 2. Default parameters   #define DFT(...) FTest((FTest_args){ .x = 142, .y = 1...
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.
#CoffeeScript
CoffeeScript
  nth_root = (A, n, precision=0.0000000000001) -> x = 1 while true x_new = (1 / n) * ((n - 1) * x + A / Math.pow(x, n - 1)) return x_new if Math.abs(x_new - x) < precision x = x_new   # tests do -> tests = [ [8, 3] [16, 4] [32, 5] [343, 3] [1024, 10] [1000000000, 3] [10000...
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...
#Ada
Ada
with Ada.Text_IO;   procedure Nth is   function Suffix(N: Natural) return String is begin if N mod 10 = 1 and then N mod 100 /= 11 then return "st"; elsif N mod 10 = 2 and then N mod 100 /= 12 then return "nd"; elsif N mod 10 = 3 and then N mod 100 /= 13 then return "rd"; else return "t...
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...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <vector>   constexpr int MU_MAX = 1'000'000; std::vector<int> MU;   int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; }   // Populate array MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX);   for (int i = 2; i <= root; i++) { ...
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 ...
#J
J
require'strings regex'   lines=: <;.2 titleFix=: ('^\s*(the|a|an)\b';'')&rxrplc isNum=: e.&'0123456789' num=: ".^:(isNum@{.) split=: <@num/.~ [:+/\1,2 ~:/\ isNum norm=: [: split (32 9 12 13 14 15{a.) -.~ [: titleFix tolower   natSor=: lines ;@/: norm&.>@lines
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...
#Sidef
Sidef
say (File.new(__FILE__).open_r.slurp == ARGF.slurp);
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...
#Swift
Swift
#! /usr/bin/swift import Foundation   let script = CommandLine.arguments[0] print(script) let mytext = try? String.init(contentsOfFile: script, encoding: .utf8)   var enteredtext = readLine() if mytext == enteredtext { print("Accept") } else { print("Reject") }
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Tcl
Tcl
apply {{} {puts [expr {[gets stdin] eq [info level 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...
#jq
jq
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   clas...
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...
#Julia
Julia
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   clas...
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...
#zkl
zkl
fcn nextHightest(N){ // N is int, BigInt or string -->String. Algorithm 2 // ds:=N.split().copy(); // mutable, int ds:=N.toString().split("").apply("toInt").copy(); // handle "234" or BigInt if(ds.len()<2) return(0); m:=ds[-1]; foreach i in ([ds.len()-1 .. 0,-1]){ d:=ds[i]; if(d<m){ ...
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...
#Racket
Racket
#lang racket   (define (make-list separator) (define counter 1)   (define (make-item item) (begin0 (format "~a~a~a~%" counter separator item) (set! counter (add1 counter))))   (apply string-append (map make-item '(first second third))))   (display (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...
#Raku
Raku
sub make-List ($separator = ') '){ my $count = 1;   sub make-Item ($item) { "{$count++}$separator$item" }   join "\n", <first second third>».&make-Item; }   put 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...
#REXX
REXX
/*REXX program demonstrates that functions can be nested (an outer and inner function).*/ ctr= 0 /*initialize the CTR REXX variable.*/ call MakeList '. ' /*invoke MakeList with the separator.*/ exit 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...
#REXX
REXX
/*REXX program sounds "ship's bells" (using PC speaker) when executing (perpetually).*/ echo= ( arg()\==0 ) /*echo time and bells if any arguments.*/ signal on halt /*allow a clean way to stop the program*/ t.1= '00:30 01:00 01:30...
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Prolog
Prolog
  % fetch all the subsequences ncsubs(L, LNCSL) :- setof(NCSL, one_ncsubs(L, NCSL), LNCSL).   % how to build one subsequence one_ncsubs(L, NCSL) :- extract_elem(L, NCSL); ( sublist(L, L1), one_ncsubs(L1, NCSL)).   % extract one element of the list % this element is neither the first nor the last. extract_elem...
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...
#FunL
FunL
$stdout = int( '1a', 16 )
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...
#Go
Go
package main   import ( "fmt" "math/big" "strconv" )   func main () { s := strconv.FormatInt(26, 16) // returns the string "1a" fmt.Println(s)   i, err := strconv.ParseInt("1a", 16, 64) // returns the integer (int64) 26 if err == nil { fmt.Println(i) } b, ok := new(big.Int).S...
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...
#Standard_ML
Standard ML
let fun loop i = if i < 34 then ( print (Int.fmt StringCvt.BIN i ^ "\t" ^ Int.fmt StringCvt.OCT i ^ "\t" ^ Int.fmt StringCvt.DEC i ^ "\t" ^ Int.fmt StringCvt.HEX i ^ "\n"); loop (i+1) ) else () in loop 0 end
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...
#Tcl
Tcl
for {set n 0} {$n <= 33} {incr n} { puts [format " %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...
#Quackery
Quackery
[ dup dip /mod over iff [ - dip 1+ ] else drop ] is /mod+ ( n n --> n n )   [ over 0 = iff [ 2drop $ "0" ] done temp put $ "" swap [ temp share /mod+ digit rot join swap dup 0 = until ] drop temp release ] is ->negabase$ ( 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...
#Racket
Racket
#lang racket   (define all-digits (string->list "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"))   (define d->i-map (for/hash ((i (in-naturals)) (d all-digits)) (values d i)))   (define max-base (length all-digits))   (define (q/r n d) (let-values (((q r) (quotient/remainder n d))) (if (negativ...
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...
#Racket
Racket
  #lang racket   (define (print-remaining tokens-remaining) (printf "~a tokens remain.\n" tokens-remaining))   (define (read-tokens) (define num (read)) (cond [(and (natural? num) (< num 4)) num] [else (display "Please enter a number between 1 to 3\n") (read-tokens)]))   (define (pturn tokens-re...
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...
#Raku
Raku
say my $tokens = 12, " tokens remaining.\n";   loop { my $player = trim prompt "How many tokens do you want to remove; 1, 2 or 3? : "; say "Nice try. $tokens tokens remaining.\n" and next unless $player eq any <1 2 3>; $tokens -= 4; say "Computer takes {4 - $player}.\n$tokens tokens remaining.\n"; ...
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...
#AppleScript
AppleScript
------------------------- NARCISSI -----------------------   -- isDaffodil :: Int -> Int -> Bool on isDaffodil(e, n) set ds to digitList(n) (e = length of ds) and (n = powerSum(e, ds)) end isDaffodil   -- digitList :: Int -> [Int] on digitList(n) if n > 0 then {n mod 10} & digitList(n div 10) el...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector>   std::vector<uint64_t> primes; std::vector<uint64_t> smallPrimes;   template <typename T> std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend();   os << '[';   if (it != end) { ...
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#C.23
C#
using System;   namespace NamedParams { class Program { static void AddWidget(string parent, float x = 0, float y = 0, string text = "Default") { Console.WriteLine("parent = {0}, x = {1}, y = {2}, text = {3}", parent, x, y, text); }   static void Main(string[] args) ...
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...
#C.2B.2B
C++
class foo_params{ friend void foo(foo_params p); public: foo_params(int r): required_param_(r), optional_x_(0), optional_y_(1), optional_z_(3.1415) {} foo_params& x(int i){ optional_x_=i; return *this; } foo_params& y(int i){ optional_y_=i; return *this; } foo_params& z(flo...
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.
#Common_Lisp
Common Lisp
(defun nth-root (n a &optional (epsilon .0001) (guess (1- n))) (assert (and (> n 1) (> a 0))) (flet ((next (x) (/ (+ (* (1- n) x) (/ a (expt x (1- n)))) n))) (do* ((xi guess xi+1) (xi+1 (next xi) (next xi))) ((< (abs (- xi+1 xi)) epsilon) xi+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...
#ALGOL_68
ALGOL 68
# PROC to suffix a number with st, nd, rd or th as appropriate # PROC nth = ( INT number )STRING: BEGIN   INT number mod 100 = number MOD 100;   # RESULT # whole( number, 0 ) + IF number mod 100 >= 10 AND number mod 100 <= 20 THEN # numbers in the range 10 .. 20 always have "th" # "th" ...
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...
#D
D
import std.math; import std.stdio;   immutable MU_MAX = 1_000_000;   int mobiusFunction(int n) { static initialized = false; static int[MU_MAX + 1] MU;   if (initialized) { return MU[n]; }   // populate array MU[] = 1; int root = cast(int) sqrt(cast(real) MU_MAX);   for (int i = ...
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 ...
#JavaScript
JavaScript
  var nsort = function(input) { var e = function(s) { return (' ' + s + ' ').replace(/[\s]+/g, ' ').toLowerCase().replace(/[\d]+/, function(d) { d = '' + 1e20 + d; return d.substring(d.length - 20); }); }; return input.sort(function(a, b) { return e(a).localeCompare(e(b)); }); };   conso...
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...
#TXR
TXR
@(bind my64 "QChuZXh0IDphcmdzKUBmaWxlbmFtZUAobmV4dCBmaWxlbmFtZSlAZmlyc3RsaW5lQChmcmVlZm9ybSAiIilAcmVzdEAoYmluZCBpbjY0IEAoYmFzZTY0LWVuY29kZSByZXN0KSlAKGNhc2VzKUAgIChiaW5kIGZpcnN0bGluZSBgXEAoYmluZCBteTY0ICJAbXk2NCIpYClAICAoYmluZCBpbjY0IG15NjQpQCAgKGJpbmQgcmVzdWx0ICIxIilAKG9yKUAgIChiaW5kIHJlc3VsdCAiMCIpQChlbmQpQChvdXRwdXQ...
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...
#UNIX_Shell
UNIX Shell
cmp "$0" >/dev/null && echo accept || echo 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...
#VBA
VBA
Public Sub narcissist() quote = Chr(34) comma = Chr(44) cont = Chr(32) & Chr(95) rparen = Chr(41) n = Array( _ "Public Sub narcissist()", _ " quote = Chr(34)", _ " comma = Chr(44)", _ " cont = Chr(32) & Chr(95)", _ " rparen = Chr(41)", _ " n = Array( _", _ "How many lines?", _ "Line "...
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...
#Wren
Wren
import "os" for Process, Platform import "io" for File, Stdin, Stdout   var args = Process.allArguments var text = File.read(args[1]).trim() System.print("Enter the number of lines to be input followed by those lines:\n") Stdout.flush() var n = Num.fromString(Stdin.readLine()) var lines = List.filled(n, null) for (i in...
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...
#Kotlin
Kotlin
// version 1.0.6   const val SOLAR_DIAMETER = 864938   enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!   class Star(val name: String) { fun showDiameter() { println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles") } }   clas...
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...
#Lambdatalk
Lambdatalk
  Naming conventions   1) global names   - a name is a group of any character except space and curly braces {} for instance "add", "+", "123", "()", "a.b.c", "...", ...   - but giving a variable the name of the 9 special forms (keywords) ["lambda", "def", "if", "let", "quote", "macro", "script", "style", "requir...
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...
#Ring
Ring
  # Project : Nested function   makeList(". ") func makeitem(sep, counter, text) see "" + counter + sep + text + nl   func makelist(sep) a = ["first", "second", "third"] counter = 0 while counter < 3 counter = counter + 1 makeitem(sep, counter, a[counter]) ...
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...
#Ruby
Ruby
def makeList(separator) counter = 1   makeItem = lambda {|item| result = "#{counter}#{separator}#{item}\n" counter += 1 result }   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...
#Rust
Rust
fn make_list(sep: &str) -> String { let mut counter = 0; let mut make_item = |label| { counter += 1; format!("{}{}{}", counter, sep, label) }; format!( "{}\n{}\n{}", make_item("First"), make_item("Second"), make_item("Third") ) }   fn main() { prin...
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...
#Ring
Ring
  # Project : Nautical bell   m = 0 for n = 0 to 23 if n = 23 see "23" + ":30" + " = " + "7 bells" + nl else m = m + 1 see "" + n%23 + ":30" + " = " + m + " bells" + nl ok if n = 23 see "00" + ":00" + " = " + "8 bells" + nl else m = m + 1 see "" +...
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...
#Ruby
Ruby
watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ] watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ] words = ["One","Two","Three","Four","Five","Six","Seven","Eight"] sound = "ding!"   loop do time = Time.now if time.sec == 0 a...
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...
#Python
Python
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
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...
#Quackery
Quackery
[ dup 1 & dip [ 1 >> ] ] is 2/mod ( n --> n n )   [ 0 swap [ dup 0 != while 2/mod iff [ dip 1+ ] done again ] [ dup 0 != while 2/mod not iff [ dip 1+ ] done again ] [ dup 0 != while 2/mod iff [ dip 1+ ] done again ] drop 3 = ] ...
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...
#Groovy
Groovy
def radixParse = { s, radix -> Integer.parseInt(s, radix) } def radixFormat = { i, radix -> Integer.toString(i, radix) }
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...
#TI-89_BASIC
TI-89 BASIC
Local old getMode("Base")→old setMode("Base", "BIN") Disp string(16) setMode("Base", "HEX") Disp string(16) setMode("Base", "DEC") Disp string(16) setMode("Base", old)
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...
#Wren
Wren
import "/fmt" for Conv, Fmt   System.print(" 2 7 8 10 12 16 32") System.print("------ ---- ---- ---- ---- ---- ----") for (i in 1..33) { var b2 = Fmt.b(6, i) var b7 = Fmt.s(4, Conv.itoa(i, 7)) var b8 = Fmt.o(4, i) var b10 = Fmt.d(4, i) var b12 = Fmt.s(4, Conv.Itoa(i, 12)) va...
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...
#Raku
Raku
multi sub base ( Int $value is copy, Int $radix where -37 < * < -1) { my $result; while $value { my $r = $value mod $radix; $value div= $radix; if $r < 0 { $value++; $r -= $radix } $result ~= $r.base(-$radix); } flip $result || ~0; }   mult...
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...
#Red
Red
Red [ date: 2021-10-24 version: 0.6.4 summary: "Demonstrate the game of Nim in Red for Rosetta Code" ]   take-tokens: function [ "Ask the user to take between 1 and 3 tokens." ][ forever [ n: trim ask "Would you like to take 1, 2, or 3 tokens (q to quit)? " if n = "q" [quit] ...
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...
#REXX
REXX
/*REXX program plays the NIM game with a human opponent; the pot size can be specified. */ parse arg pot _ . 1 __ /*obtain optional argument from the CL.*/ if pot=='' | pot=="," then pot= 12 /*Not specified? Then use the default.*/ if _\=='' then do; call ser "Too many arg...
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...
#Arturo
Arturo
powers: map 0..9 'x [ map 0..9 'y [ x ^ y ] ]   getPair: function [p,sz].memoize[ if not? numeric? last p -> return powers\[to :integer to :string first p]\[sz] return powers\[to :integer to :string first p]\[sz] + powers\[to :integer to :string last p]\[sz] ]   narcissistic?: function [n][ ...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics;   namespace NSmooth { class Program { static readonly List<BigInteger> primes = new List<BigInteger>(); static readonly List<int> smallPrimes = new List<int>();   static Program() { primes.A...
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...
#Clojure
Clojure
(defn foo [& opts] (let [opts (merge {:bar 1 :baz 2} (apply hash-map opts)) {:keys [bar baz]} opts] [bar baz]))
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...
#Common_Lisp
Common Lisp
(defun print-name (&key first (last "?")) (princ last) (when first (princ ", ") (princ first)) (values))
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.
#D
D
import std.stdio, std.math;   real nthroot(in int n, in real A, in real p=0.001) pure nothrow { real[2] x = [A, A / n]; while (abs(x[1] - x[0]) > p) x = [x[1], ((n - 1) * x[1] + A / (x[1] ^^ (n-1))) / n]; return x[1]; }   void main() { writeln(nthroot(10, 7131.5 ^^ 10)); writeln(nthroot(6, 6...
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...
#APL
APL
nth←{ sfx←4 2⍴'stndrdth' tens←(10<100|⍵)∧20>100|⍵ (⍕⍵),sfx[(4×tens)⌈(⍳3)⍳10|⍵;] }
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#F.23
F#
  // Möbius function. Nigel Galloway: January 31st., 2021 let fN g=let n=primes32() let rec fN i g e l=match (l/g,l%g,e) with (1,0,false)->i |(n,0,false)->fN (0-i) g true n |(_,0,true) ->0 ...
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...
#Factor
Factor
USING: formatting grouping io math.extras math.ranges sequences ;   "First 199 terms of the Möbius sequence:" print 199 [1,b] [ mobius ] map " " prefix 20 group [ [ "%3s" printf ] each nl ] each
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 ...
#jq
jq
def splitup: def tidy: if .[0] == "" then .[1:] else . end | if .[length-1] == "" then .[0:length-1] else . end ;   # a and b are assumed to be arrays: def alternate(a;b): reduce range(0; [a,b] | map(length) | max) as $i ([]; . + [a[$i], b[$i]]);   ([splits("[0-9]+")] | tidy) as $a | ([splits("[^0-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...
#zkl
zkl
stdin:=File.stdin.read(); thisFileSrc:=File(System.argv[1]).read(); println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match");
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...
#Lua
Lua
- constants use UPCASE_SNAKE - variable names use lower_case_snake - class-like structures use CamelCase - other functions use smallCamelCase - Use _ for unneeded variables - Don't use Hungarian Notation
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...
#M2000_Interpreter
M2000 Interpreter
  Class Alfa$ { Private: myValue$ Public: Set { Read .myValue$ } Value { =.myValue$ } Module Doit { Function TwoChars$(A$) { =Left$(Left$(a$,1)+Right$(a$,1)+"??",2) ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
# Constants can start with either a lower case or upper case letter. const aConstant = 42 const FooBar = 4.2   var aVariable = "Meep" # Variables must start with a lowercase letter.   # Types must start with an uppercase letter. type FooBar = object
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...
#Nim
Nim
# Constants can start with either a lower case or upper case letter. const aConstant = 42 const FooBar = 4.2   var aVariable = "Meep" # Variables must start with a lowercase letter.   # Types must start with an uppercase letter. type FooBar = object
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...
#OASYS_Assembler
OASYS Assembler
$ALL_CAPS_HERE constants $Some_Caps_Here package-wide global/static $no_caps_here function scope my/our/local variables $_internal_use private
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...
#Scala
Scala
  def main(args: Array[String]) { val sep: String=". " var c:Int=1; def go(s: String):Unit={ println(c+sep+s) c=c+1 } go("first") go("second") go("third") }  
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...
#Scheme
Scheme
(define (make-list separator) (define counter 1)   (define (make-item item) (let ((result (string-append (number->string counter) separator item "\n"))) (set! counter (+ counter 1)) result))   (string-append (make-item "first") (make-item "second") (make-item "third")))   (display (make-list ". ")...
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i"; include "duration.s7i"; include "keybd.s7i";   const array string: watch is [] ("Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First"); const array string: bells is [] ("One Bell", "Two Bells", "Three Bells", "Four Bells", "Five Bells", "Six Bells", "Seven Bell...
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...
#Tcl
Tcl
# More sophisticated versions are possible, such as playing a bell sample # using the Snack library. proc ringTheBell {} { puts -nonewline "\a" }   # The code to convert the (parsed) time into rings of the ship's bell and # printing of the name of the bell. proc strikeBell {hour minute} { global suppressNormalO...
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...
#R
R
ncsub <- function(x) { n <- length(x) a <- seq_len(n) seqlist <- list() for(i in 2:(n-1)) { seqs <- combn(a, i) # Get all subseqs ok <- apply(seqs, 2, function(x) any(diff(x)!=1)) # Find noncts ones news...
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...
#Racket
Racket
  (define (subsets l) (if (null? l) '(()) (append (for/list ([l2 (subsets (cdr l))]) (cons (car l) l2)) (subsets (cdr l)))))  
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...
#Haskell
Haskell
Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 "" "2a" Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a" 42
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...
#XPL0
XPL0
include c:\cxpl\codes; int N; [N:= 2; repeat HexOut(0, N); Text(0, " "); IntOut(0, N); CrLf(0); N:= N*N; until N=0; ]
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...
#Yabasic
Yabasic
for i = 1 to 33 print "decimal: ", i, " hex: ", hex$(i), " bin: ", bin$(i) 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...
#zkl
zkl
const N=16; var fmt=[2..N].pump(String,"%%5.%dB".fmt); // %5.2B%5.3B%5.4B%5.5B ... foreach n in (17){fmt.fmt(n.pump(N,List,n.fp(n)).xplode()).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...
#REXX
REXX
/*REXX pgm converts & displays a base ten integer to a negative base number (up to -10).*/ @=' converted to base '; numeric digits 300 /*be able to handle ginormous numbers. */ n= 10; b= -2; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok() n= 146; b= -3; q= nBase(n, b); say right(...
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...
#Ring
Ring
  # Project : CalmoSoft Nim Game # Date  : 16/04/2020-13:27:07 # Update  : 31/03/2021-19:41:09 # Author  : Gal Zsolt (~ CalmoSoft ~) # Email  : <calmosoft@gmail.com>   load "stdlib.ring" load "guilib.ring"   limit = 4 limit1 = 1 limit2 = 3 limit3 = 5 limit4 = 7   match1 = limit1 match2 = limit2 match3 = limit3 match...
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...
#Ruby
Ruby
[12, 8, 4].each do |remaining| puts "There are #{remaining} dots.\nHow many dots would you like to take? " unless (num=gets.to_i).between?(1, 3) puts "Please enter one of 1, 2 or 3" redo end puts "You took #{num} dots, leaving #{remaining-num}.\nComputer takes #{4-num}.\n\n" end   puts "Computer took th...
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...
#AutoHotkey
AutoHotkey
  #NoEnv ; Do not try to use environment variables SetBatchLines, -1 ; Execute as quickly as you can   StartCount := A_TickCount Narc := Narc(25) Elapsed := A_TickCount - StartCount   MsgBox, Finished in %Elapsed%ms`n%Narc% return   Narc(m) { Found := 0, Lower := 0 Progress, B2 Loop { Max := 10 ** Digits:=A_Index...
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Action.21
Action!
PROC PutBigPixel(BYTE x,y,c) BYTE i   Color=c x=x*3+16 y=y*12 FOR i=0 TO 11 DO Plot(x,y+i) DrawTo(x+2,y+i) OD RETURN   PROC Main() BYTE CH=$02FC, ;Internal hardware value for last key pressed x,y   Graphics(9)   FOR y=0 TO 15 DO FOR x=0 TO 15 DO PutBigPixel(x,y,x!y) ...
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#Crystal
Crystal
require "big"   def prime?(n) # P3 Prime Generator primality test return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5 sqrt_n = Math.isqrt(n) # For Crystal < 1.2.0 use Math.sqrt(n).to_i pc = typeof(n).new(5) while pc <= sqrt_n return false if n % pc == 0 || n % (pc + 2) == 0 pc += 6 end tr...
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...
#Delphi
Delphi
  program Named_parameters;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TParams = record fx, fy, fz: Integer; function x(value: Integer): TParams; function y(value: Integer): TParams; function z(value: Integer): TParams; class function _: TParams; static; end;   function Sum(Param: TPa...
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.
#Delphi
Delphi
  USES Math;   function NthRoot(A, Precision: Double; n: Integer): Double; var x_p, X: Double; begin x_p := Sqrt(A); while Abs(A - Power(x_p, n)) > Precision do begin x := (1/n) * (((n-1) * x_p) + (A/(Power(x_p, n - 1)))); x_p := x; end; Result := x_p; end;  
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#AppleScript
AppleScript
-- ORDINAL STRINGS -----------------------------------------------------------   -- ordinalString :: Int -> String on ordinalString(n) (n as string) & ordinalSuffix(n) end ordinalString   -- ordinalSuffix :: Int -> String on ordinalSuffix(n) set modHundred to n mod 100 if (11 ≤ modHundred) and (13 ≥ modHund...
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...
#Fortran
Fortran
  program moebius use iso_fortran_env, only: output_unit   integer, parameter :: mu_max=1000000, line_break=20 integer, parameter :: sqroot=int(sqrt(real(mu_max))) integer :: i, j integer, dimension(mu_max) :: mu   mu = 1   do i = 2, sqroot if (...
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 ...
#Julia
Julia
#1 natural1(x, y) = strip(x) < strip(y)   #2 natural2(x, y) = replace(x, r"\s+" => " ") < replace(y, r"\s+" => " ")   #3 natural3(x, y) = lowercase(x) < lowercase(y)   #4 splitbynum(x) = split(x, r"(?<=\D)(?=\d)|(?<=\d)(?=\D)") numstringtonum(arr) = [(n = tryparse(Float32, e)) != nothing ? n : e for e in arr] function...
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...
#Oforth
Oforth
$ALL_CAPS_HERE constants $Some_Caps_Here package-wide global/static $no_caps_here function scope my/our/local variables $_internal_use private
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...
#Pascal
Pascal
$ALL_CAPS_HERE constants $Some_Caps_Here package-wide global/static $no_caps_here function scope my/our/local variables $_internal_use private
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...
#Perl
Perl
$ALL_CAPS_HERE constants $Some_Caps_Here package-wide global/static $no_caps_here function scope my/our/local variables $_internal_use private
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...
#Phix
Phix
- Global variables start with an asterisk '*' - Global constants may be written all-uppercase - Functions and other global symbols start with a lower case letter - Locally bound symbols start with an upper case letter - Local functions start with an underscore '_' - Classes start with a plus-sign '+', where the first l...
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...
#PicoLisp
PicoLisp
- Global variables start with an asterisk '*' - Global constants may be written all-uppercase - Functions and other global symbols start with a lower case letter - Locally bound symbols start with an upper case letter - Local functions start with an underscore '_' - Classes start with a plus-sign '+', where the first l...
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...
#PowerShell
PowerShell
#lang racket render-game-state send-message-to-client traverse-forest
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: makeList (in string: separator) is func result var string: itemList is ""; local var integer: counter is 1;   const func string: makeItem (in string: item) is func result var string: anItem is ""; begin anItem := counter <& separ...
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...
#Sidef
Sidef
func make_list(separator = ') ') {   var count = 1 func make_item(item) { [count++, separator, item].join }   <first second third>.map(make_item).join("\n") }   say 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...
#Simula
Simula
COMMENT CLASS SIMSET IS SIMULA'S STANDARD LINKED LIST DATA TYPE CLASS HEAD IS THE LIST ITSELF CLASS LINK IS THE ELEMENT OF A LIST PROCEDURE IS THE TERM USED FOR FUNCTIONS IN SIMULA TEXT IS THE TERM USED FOR STRINGS IN SIMULA ; SIMSET BEGIN   LINK CLASS ITEM(TXT); TEXT TXT;;   COM...