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
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#Wren
Wren
import "/fmt" for Fmt   var start = System.clock var primes = [3, 5] var cutOff = 200 var bigOne = 100000 var cubans = [] var bigCuban = "" var c = 0 var showEach = true var u = 0 var v = 1   for (i in 1...(1<<20)) { var found = false u = u + 6 v = v + u var mx = v.sqrt.floor for (item in primes) {...
Give a code snippet in #Wren The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#SenseTalk
SenseTalk
  if problemCondition then exit all  
Give a code snippet in #SenseTalk Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finali...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#PL.2FI
PL/I
s = reverse(s);
Give a code snippet in #PL.2FI Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#REXX
REXX
do until userNumber==75000
Give a code snippet in #REXX User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#Ol
Ol
  (define x (* 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2)) ; 2^64   (print (* x x))  
Give a code snippet in #Ol Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Sidef
Sidef
func linear_combination(coeffs) { var res = "" for e,f in (coeffs.kv) { given(f) { when (1) { res += "+e(#{e+1})" } when (-1) { res += "-e(#{e+1})" } case (.> 0) { res += "+#{f}*e(#{e+1})" ...
Give a code snippet in #Sidef Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Seed7
Seed7
const func integer: gcd (in var integer: a, in var integer: b) is func result var integer: gcd is 0; local var integer: help is 0; begin while a <> 0 do help := b rem a; b := a; a := help; end while; gcd := b; end func;
Give a code snippet in #Seed7 Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import java.lang.management.   memoryInfo() digDeeper(0)   /** * Just keep digging * @param level depth gauge */ method digDeeper(level = int) private static binary do digDeeper(level + 1) catch ex = Error System.out.println('Re...
Give a code snippet in #NetRexx Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Haskell
Haskell
import Control.Monad.ST import Data.STRef   accumulator :: (Num a) => a -> ST s (a -> ST s a) accumulator sum0 = do sum <- newSTRef sum0 return $ \n -> do modifySTRef sum (+ n) readSTRef sum   main :: IO () main = print foo where foo = runST $ do x <- accumulator 1 x ...
Give a code snippet in #Haskell A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values p...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Lily
Lily
# This is a single-line comment
Give a code snippet in #Lily Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Sidef
Sidef
var node = Hash.new( data => 'say what', next => foo_node, );   node{:next} = bar_node; # mutable
Give a code snippet in #Sidef singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element def...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Arturo
Arturo
arr: [5 4 2 9 7 3]   print max arr
Give a code snippet in #Arturo Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Kotlin
Kotlin
// version 1.0.6   const val shades = ".:!*oe&#%@" val light = doubleArrayOf(30.0, 30.0, -50.0)   fun normalize(v: DoubleArray) { val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) v[0] /= len; v[1] /= len; v[2] /= len }   fun dot(x: DoubleArray, y: DoubleArray): Double { val d = x[0] * y[0] + x[...
Give a code snippet in #Kotlin Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a D...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Quackery
Quackery
( ---------------- zen object orientation -------------- )   [ immovable ]this[ swap do ]done[ ] is object ( --> )   [ ]'[ ] is method ( --> [ )   [ method [ dup share swap put ] ] is localise ( --> [ )   [ method [ release ] ] is delocali...
Give a code snippet in #Quackery In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static ...
christopher/rosetta-code
http://rosettacode.org/wiki/Halt_and_catch_fire
Halt and catch fire
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an...
#GW-BASIC
GW-BASIC
0 gosub 0
Give a code snippet in #GW-BASIC Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help de...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Frink
Frink
for f = sort[files["."], {|a,b| lexicalCompare[a.getName[], b.getName[]]}] println[f.getName[]]
Give a code snippet in #Frink Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Math   var stirling = Fn.new { |x| (2 * Num.pi / x).sqrt * (x / Math.e).pow(x) }   System.print(" x\tStirling\t\tLanczos\n") for (i in 1..20) { var d = i / 10 System.write("%(Fmt.f(4, d, 2))\t") System.write("%(Fmt.f(16, stirling.call(d), 14))\t") System.print("%...
Give a code snippet in #Wren Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/libr...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Golfscript
Golfscript
{  :_n; :_m; _m 0= {_n 1+} {_n 0= {_m 1- 1 ack} {_m 1- _m _n 1- ack ack} if} if }:ack;
Give a code snippet in #Golfscript The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Picat
Picat
main => println("First 61 fusc numbers:"), println([fusc(I) : I in 0..60]), nl, println("Points in the sequence whose length is greater than any previous fusc number length:\n"), println(" Index fusc Len"), largest_fusc_string(20_000_000).   table fusc(0) = 0. fusc(1) = 1. fusc(N) = fusc(N//2), eve...
Give a code snippet in #Picat Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition st...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Rust
Rust
// returns the highest power of i that is a factor of n, // and n divided by that power of i fn factor_exponent(n: i32, i: i32) -> (i32, i32) { if n % i == 0 { let (a, b) = factor_exponent(n / i, i); (a + 1, b) } else { (0, n) } }   fn tau(n: i32) -> i32 { for i in 2..(n+1) { if n % i == 0 { let (count, ...
Give a code snippet in #Rust Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Lingo
Lingo
  sx = xtra("Shell").new() if the platform contains "win" then hostname = sx.shell_cmd("hostname", ["eol":RETURN]).line[1] -- win 7 or later else hostname = sx.shell_cmd("hostname", RETURN).line[1] end if
Give a code snippet in #Lingo Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Gambas
Gambas
Public sub main() DIM bestclub AS String DIM myconcat AS String   bestclub = "Liverpool" myconcat = bestclub & " Football Club"   Print myconcat   End
Give a code snippet in #Gambas String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string li...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#UNIX_Shell
UNIX Shell
#!/bin/sh   read string read integer read -p 'Enter a number: ' number echo "The number is $number"
Give a code snippet in #UNIX_Shell User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#BCPL
BCPL
get "libhdr"   let circle(x, y, c, r) = (r*r) >= (x/2) * (x/2) + (y-c) * (y-c)   let pixel(x, y, r) = circle(x, y, -r/2, r/6) -> '#', circle(x, y, r/2, r/6) -> '.', circle(x, y, -r/2, r/2) -> '.', circle(x, y, r/2, r/2) -> '#', circle(x, y, 0, r) -> x<0 -> '.', '#', ' '   let yinyang(r) ...
Give a code snippet in #BCPL One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#ALGOL_W
ALGOL W
begin  % use the quicksort procedure from the Sorting_Algorithms/Quicksort task %  % Quicksorts in-place the array of integers v, from lb to ub - external  % procedure quicksort ( integer array v( * )  ; integer value lb, ub ) ; algol "sortingAlgorithms_Quicksort...
Give a code snippet in #ALGOL_W 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Oberon-2
Oberon-2
  MODULE ApplyCallBack; IMPORT Out := NPCT:Console;   TYPE Fun = PROCEDURE (x: LONGINT): LONGINT; Ptr2Ary = POINTER TO ARRAY OF LONGINT;   VAR a: ARRAY 5 OF LONGINT; x: ARRAY 3 OF LONGINT; r: Ptr2Ary;   PROCEDURE Min(x,y: LONGINT): LONGINT; BEGIN IF x <= y THEN RETURN x ELSE RETURN y END; END Min;...
Give a code snippet in #Oberon-2 Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Clojure
Clojure
(def files (sort (filter #(= "." (.getParent %)) (file-seq (clojure.java.io/file ".")))))   (doseq [n files] (println (.getName n)))
Give a code snippet in #Clojure Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exam...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Idris
Idris
  beerSong : Fin 100 -> String beerSong x = verses x where   bottlesOfBeer : Fin n -> String bottlesOfBeer fZ = "No more bottles of beer" bottlesOfBeer (fS fZ) = "1 bottle of beer" bottlesOfBeer k = (show (finToInteger k)) ++ " bottles of beer"   verse : Fin n -> String verse fZ ...
Give a code snippet in #Idris Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Scala
Scala
def fib(i: Int): Int = i match { case 0 => 0 case 1 => 1 case _ => fib(i - 1) + fib(i - 2) }
Give a code snippet in #Scala The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Ursala
Ursala
#import flo   x = 7.125   #show+   t = <printf/'%09.3f' x>
Give a code snippet in #Ursala Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#Phix
Phix
  Functions are normally internal to a program. If they are at the nesting level immediately within the program, they are accessible from anywhere in the program.   Functions can also be encapsuled in a package, and the function name exported.   Functions can be compiled separately, and then linked with a program in wh...
Give a code snippet in #Phix Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Kotlin
Kotlin
import java.math.BigInteger   // version 1.0.5-2   fun main(args: Array<String>) { // print until 2147483647 (0..Int.MAX_VALUE).forEach { println(it) }   // print forever var n = BigInteger.ZERO while (true) { println(n) n += BigInteger.ONE } }
Give a code snippet in #Kotlin Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations l...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#zkl
zkl
zkl: System.cmd(0'|eventcreate "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example"|)
Give a code snippet in #zkl Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Factor
Factor
"This is a mutable string." dup ! reference "Let's make a deal!" dup clone  ! copy "New" " string" append .  ! new string "New string"
Give a code snippet in #Factor This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#ALGOL_68
ALGOL 68
REAL default p = 0.001;   PROC nth root = (INT n, LONG REAL a, p)LONG REAL: ( [2]LONG REAL x := (a, a/n);   WHILE ABS(x[2] - x[1]) > p DO x := (x[2], ((n-1)*x[2] + a/x[2]**(n-1))/n ) OD; x[2] );   PRIO ROOT = 8; OP ROOT = (INT n, LONG REAL a)LONG REAL: nth root(n, a, default p); OP ROOT = (INT n, INT a)LONG...
Give a code snippet in #ALGOL_68 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.
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific la...
#Kotlin
Kotlin
// version 1.1.2   fun curriedAdd(x: Int) = { y: Int -> x + y }   fun main(args: Array<String>) { val a = 2 val b = 3 val sum = curriedAdd(a)(b) println("$a + $b = $sum") }
Give a code snippet in #Kotlin This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative exam...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#BBC_BASIC
BBC BASIC
*FLOAT64 PRINT "Digital root of 627615 is "; FNdigitalroot(627615, 10, p) ; PRINT " (additive persistence " ; p ")" PRINT "Digital root of 39390 is "; FNdigitalroot(39390, 10, p) ; PRINT " (additive persistence " ; p ")" PRINT "Digital root of 588225 is "; FNdigitalroot(588225, 10, p...
Give a code snippet in #BBC_BASIC The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X}...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM wind the colour down or use a black and white television to see greyscale bars 20 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces 25 BORDER 0: CLS 30 FOR r=0 TO 21: REM There are 22 rows 40 FOR c=0 TO 7: REM We use the native colour sequence here 50 PRINT PAPER c;" ";: REM fou...
Give a code snippet in #ZX_Spectrum_Basic The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of gre...
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#C.2B.2B
C++
#include <functional> #include <iostream> #include <random>   class BinarySearchTree { private: struct Node { int key; Node *left, *right;   Node(int k) : key(k), left(nullptr), right(nullptr) { //empty } } *root;   public: BinarySearchTree() : root(nullptr) { ...
Give a code snippet in #C.2B.2B A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hie...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Phix
Phix
function emHalf(integer n) return floor(n/2) end function function emDouble(integer n) return n*2 end function function emIsEven(integer n) return (remainder(n,2)=0) end function function emMultiply(integer a, integer b) integer sum = 0 while a!=0 do if not emIsEven(a) then sum += b end if...
Give a code snippet in #Phix Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Haskell
Haskell
-- Due to Haskell's module system, textual includes are rarely needed. In -- general, one will import a module, like so: import SomeModule -- For actual textual inclusion, alternate methods are available. The Glasgow -- Haskell Compiler runs the C preprocessor on source code, so #include may be -- used: #include "SomeM...
Give a code snippet in #Haskell Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#AutoHotkey
AutoHotkey
Lists := [[3,2,6,4,5,1], [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]]   for k, v in Lists { D := LIS(v) MsgBox, % D[D.I].seq }   LIS(L) { D := [] for i, v in L { D[i, "Length"] := 1, D[i, "Seq"] := v, D[i, "Val"] := v Loop, % i - 1 { if(D[A_Index].Val < v && D[A_Index].Length + 1 > D[i].Length) { D[i].Length...
Give a code snippet in #AutoHotkey Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Kotlin
Kotlin
// version 1.0.6   import java.io.File   fun main(args: Array<String>) { val paths = arrayOf("input.txt", "c:\\input.txt") for (path in paths) println("Length of $path is ${File(path).length()} bytes") }
Give a code snippet in #Kotlin Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#FALSE
FALSE
["'[,34,$!34,'],!"]'[,34,$!34,'],!
Give a code snippet in #FALSE A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program  ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Yabasic
Yabasic
operators$ = "*+-/" space$ = " "   sub present() clear screen print "24 Game" print "============\n" print "Computer provide 4 numbers (1 to 9). With operators +, -, * and / you try to\nobtain 24." print "Use Reverse Polish Notation (fi...
Give a code snippet in #Yabasic task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Clean
Clean
Start = "Hello world!"
Give a code snippet in #Clean Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#8080_Assembly
8080 Assembly
org 100h lxi b,0 ; Let (B)C be the array index outer: lxi d,As ; Use DE to walk the array-of-arrays inner: xchg ; Swap DE and HL (array-of-array pointer into HL) mov e,m ; Load low byte of array pointer into E inx h mov d,m ; Load high byte of array pointer into D inx h xchg ; Array base in HL, array-of-array...
Give a code snippet in #8080_Assembly Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#Scala
Scala
def heapSort[T](a: Array[T])(implicit ord: Ordering[T]) { import scala.annotation.tailrec // Ensure functions are tail-recursive import ord._   val indexOrdering = Ordering by a.apply   def numberOfLeaves(heapSize: Int) = (heapSize + 1) / 2   def children(i: Int, heapSize: Int) = { val leftChild = i * 2 +...
Give a code snippet in #Scala 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Scheme
Scheme
(define (compose f g) (lambda (x) (f (g x))))   ;; or:   (define ((compose f g) x) (f (g x)))   ;; or to compose an arbitrary list of 1 argument functions:   (define-syntax compose (lambda (x) (syntax-case x () ((_) #'(lambda (y) y)) ((_ f) #'f) ((_ f g h ...) #'(lambda (y) (f ((compose g h ......
Give a code snippet in #Scheme Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g ...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Sidef
Sidef
func encode(str) { str.gsub(/((.)(\2*))/, {|a,b| "#{a.len}#{b}" }); }   func decode(str) { str.gsub(/(\d+)(.)/, {|a,b| b * a.to_i }); }
Give a code snippet in #Sidef Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a func...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Rust
Rust
use std::env;   fn main(){ let args: Vec<_> = env::args().collect(); println!("{:?}", args); }
Give a code snippet in #Rust Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Nemerle
Nemerle
using System.Console;   module Closures { Main() : void { def f(x) { fun() { x ** 2 } } def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing   WriteLine($"$(funcs[4]())"); WriteLine($"$(funcs[2]())"); } }
Give a code snippet in #Nemerle Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i ...
christopher/rosetta-code
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...
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Integer_Text_IO is begin for I in 1..33 loop Put (I, Width =>3, Base=> 10); Put (I, Width =>7, Base=> 16); Put (I, Width =>6, Base=> 8); New_Line; end loop; end Test_Integer_Text_IO;
Give a code snippet in #Ada 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 routi...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Objeck
Objeck
  bundle Default { class Arithmetic { function : Main(args : System.String[]), Nil { array := Int->New[2]; array[0] := 13; array[1] := 7; (array[0] + array[1])->PrintLine(); } } }  
Give a code snippet in #Objeck This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retr...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#D
D
void main() { import std.algorithm: filter, equal;   immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto evens = data.filter!(x => x % 2 == 0); // Lazy. assert(evens.equal([2, 4, 6, 8, 10])); }
Give a code snippet in #D Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Aime
Aime
text dog, Dog, DOG;   dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie";   o_form("The three dogs are named ~, ~ and ~.\n", dog, Dog, DOG);
Give a code snippet in #Aime Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sam...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Aime
Aime
integer j; list l, x; text s, t;   l = list("---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", ...
Give a code snippet in #Aime Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by space...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#M2000_Interpreter
M2000 Interpreter
  Module PrependString { A$="Hello" A$+=" World" Print A$ } PrependString  
Give a code snippet in #M2000_Interpreter Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#J
J
NB. Text that follows 'NB.' has no effect on execution.   0 : 0 Multi-line comments may be placed in strings, like this. )   Note 'example' Another way to record multi-line comments as text is to use 'Note', which is actually a simple program that makes it clearer when defined text is used only to provide comment. )   ...
Give a code snippet in #J Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#ooRexx
ooRexx
/* Rexx */ do LDAP_URL = 'ldap://localhost:11389' LDAP_DN_STR = 'uid=admin,ou=system' LDAP_CREDS = '********' LDAP_BASE_DN = 'ou=users,o=mojo' LDAP_SCOPE = 'sub' LDAP_FILTER = '"(&(objectClass=person)(&(uid=*mil*)))"' LDAP_ATTRIBUTES = '"dn" "cn" "sn" "uid"'   ldapCommand = ...
Give a code snippet in #ooRexx Make sure you Connect to Active Directory
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Klong
Klong
items::[123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0]   mid3::{[d k];:[3>k::#$#x;"small":|0=k!2;"even";(-d)_(d::_(k%2)-1)_$#x]} .p(mid3'items)
Give a code snippet in #Klong Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be te...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#JavaScript
JavaScript
var assoc = {};   assoc['foo'] = 'bar'; assoc['another-key'] = 3;   // dot notation can be used if the property name is a valid identifier assoc.thirdKey = 'we can also do this!'; assoc[2] = "the index here is the string '2'";   //using JavaScript's object literal notation var assoc = { foo: 'bar', 'another-key': 3...
Give a code snippet in #JavaScript Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definit...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
Find Chess960 starting position identifier
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solution...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::AllUtils 'indexes';   sub sp_id { my $setup = shift // 'RNBQKBNR';   8 == length $setup or die 'Illegal position: should have exactly eight pieces'; 1 == @{[ $setup =~ /$_/g ]} or die "Illegal position: should ha...
Give a code snippet in #Perl As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting posit...
christopher/rosetta-code
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...
#JavaScript
JavaScript
<html> <head> <title>Number Reversal Game</title> </head>   <body> <div id="start"></div> <div id="progress"></div> <div id="score"></div> <script type="text/javascript">
Give a code snippet in #JavaScript 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. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#F.23
F#
#light (* exec fsharpi --exec $0 --quiet *)   let scriptname = let args = System.Environment.GetCommandLineArgs()   let arg0 = args.[0]   if arg0.Contains("fsi") then let arg1 = args.[1] if arg1 = "--exec" then args.[2] else arg1 else arg0   let m...
Give a code snippet in #F.23 The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script n...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#E
E
var x := 0 __loop(fn { x += 1 println(x) x % 6 != 0 # this is the return value of the function })
Give a code snippet in #E Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downw...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#REXX
REXX
/*REXX program counts and displays the number of textonyms that are in a dictionary file*/ parse arg iFID . /*obtain optional fileID from the C.L. */ if iFID=='' | iFID=="," then iFID='UNIXDICT.TXT' /*Not specified? Then use the default.*/ @.= 0 ...
Give a code snippet in #REXX When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO ...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Icon_and_Unicon
Icon and Unicon
link math, factors   procedure main() write("choose(5,3)=",binocoef(5,3)) end
Give a code snippet in #Icon_and_Unicon This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#REXX
REXX
/*REXX program generates & displays a Stern─Brocot sequence; finds 1─based indices; GCDs*/ parse arg N idx fix chk . /*get optional arguments from the C.L. */ if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/ if idx=='' | idx=="," then idx= 10 ...
Give a code snippet in #REXX For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Tcl
Tcl
# Determine if the given number is a member of the class of Harshad numbers proc isHarshad {n} { if {$n < 1} {return false} set sum [tcl::mathop::+ {*}[split $n ""]] return [expr {$n%$sum == 0}] }   # Get the first 20 numbers that satisfy the condition for {set n 1; set harshads {}} {[llength $harshads] < 2...
Give a code snippet in #Tcl The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is...
christopher/rosetta-code
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...
Give a code snippet in #C.23 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.
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#11l
11l
F fractran(prog, =val, limit) V fracts = prog.split(‘ ’).map(p -> p.split(‘/’).map(i -> Int(i))) [Float] r L(n) 0 .< limit r [+]= val L(p) fracts I val % p[1] == 0 val = p[0] * val / p[1] L.break R r   print(fractran(‘17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/...
Give a code snippet in #11l FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Lisaac
Lisaac
+ i : INTEGER; i := 1024; { i > 0 }.while_do { i.println;   i := i / 2; };
Give a code snippet in #Lisaac Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwa...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#Tcl
Tcl
proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} { # Convert the delimiters to REs by backslashing all non-alnum characters set openAsRE [regsub -all {\W} $openDelimiter {\\&}] set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]   # Now remove the blocks using a dynamic non-...
Give a code snippet in #Tcl A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should a...
christopher/rosetta-code
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#C
C
  #include <ftplib.h>   int main(void) { netbuf *nbuf;   FtpInit(); FtpConnect("kernel.org", &nbuf); FtpLogin("anonymous", "", nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir("pub/linux/kernel", nbuf); FtpDir((void*)0, ".", nbuf); FtpGet("ftp.README", "README", FTPLIB_...
Give a code snippet in #C Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Lua
Lua
--- Converts degrees to radians (summary). -- Given an angle measure in degrees, return an equivalent angle measure in radians (long description). -- @param deg the angle measure in degrees -- @return the angle measure in radians -- @see rad2deg function deg2rad(deg) return deg*math.pi/180 end
Give a code snippet in #Lua See also Related task: Comments Related task: Here_document
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#J
J
'♥♦♣♠' ♥♦♣♠
Give a code snippet in #J As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is you...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#XSLT
XSLT
<xsl:template name="compare"> <xsl:param name="a" select="1"/> <xsl:param name="b" select="2"/> <fo:block> <xsl:choose> <xsl:when test="$a &lt; $b">a &lt; b</xsl:when> <xsl:when test="$a &gt; $b">a &gt; b</xsl:when> <xsl:when test="$a = $b">a = b</xsl:when> </xsl:choose> </fo:block> </xsl:templ...
Give a code snippet in #XSLT Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#NewLISP
NewLISP
  (set 'in-file (open "filename" "read")) (while (read-line in-file) (write-line)) (close in-file)
Give a code snippet in #NewLISP Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Run_BASIC
Run BASIC
  setA$ = "John,Bob,Mary,Serena" setB$ = "Jim,Mary,John,Bob"   x$ = b$(setA$,setB$) print word$(x$,1,",") c$ = c$ + x$   x$ = b$(setB$,setA$) print word$(x$,1,",") print c$;x$ end function b$(a$,b$) i = 1 while word$(a$,i,",") <> "" a1$ = word$(a$,i,",") j = instr(b$,a1$) if j <> 0 then b$ = left$(b$,j-1) + m...
Give a code snippet in #Run_BASIC Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#VBA
VBA
Dim samplevariable as New Object Dim anothervariable as Object Set anothervariable = sameplevariable
Give a code snippet in #VBA Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program xpathXml64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
Give a code snippet in #AArch64_Assembly Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniC...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Kotlin
Kotlin
// version 1.1.0   fun main(args: Array<String>) { val i: Int = 3 // non-nullable Int type - can't be assigned null println(i) val j: Int? = null // nullable Int type - can be assigned null println(j) println(null is Nothing?) // test that null is indeed of type Nothing? }
Give a code snippet in #Kotlin Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your lang...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#HicEst
HicEst
DO i = 1, 100 IF( MOD(i, 15) == 0 ) THEN WRITE() "FizzBuzz" ELSEIF( MOD(i, 5) == 0 ) THEN WRITE() "Buzz" ELSEIF( MOD(i, 3) == 0 ) THEN WRITE() "Fizz" ELSE WRITE() i ENDIF ENDDO
Give a code snippet in #HicEst Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
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.
#J
J
'`N X NP' =. (0 { [)`(1 { [)`(2 { [) iter =. N %~ (NP * ]) + X % ] ^ NP nth_root =: (, , _1+[) iter^:_ f. ] 10 nth_root 7131.5^10 7131.5
Give a code snippet in #J 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.
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Eiffel
Eiffel
-- inline comment, continues until new line
Give a code snippet in #Eiffel Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#PicoLisp
PicoLisp
+------------> start | +--+--+-----+ | | | ---+---> end +-----+-----+
Give a code snippet in #PicoLisp Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#ABAP
ABAP
REPORT zgoodbyeworld. WRITE 'Hello world!'.
Give a code snippet in #ABAP Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Ursa
Ursa
# # arithmetic mean #   decl int<> input decl int i for (set i 1) (< i (size args)) (inc i) append (int args<i>) input end for   out (/ (+ input) (size input)) endl console
Give a code snippet in #Ursa Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an estab...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#REBOL
REBOL
s: "hello" print s1: rejoin [s " literal"] print s1
Give a code snippet in #REBOL String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string lit...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Scheme
Scheme
gosh> (use gauche.lazy) #<undef> gosh> (length (lrxmatch "th" "the three truths")) 3 gosh> (length (lrxmatch "abab" "ababababab")) 2  
Give a code snippet in #Scheme Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Logtalk
Logtalk
  /* Houses logical puzzle: who owns the zebra and who drinks water?   1) Five colored houses in a row, each with an owner, a pet, cigarettes, and a drink. 2) The English lives in the red house. 3) The Spanish has a dog. 4) They drink coffee in the green house. 5) The Ukrainian drinks tea. ...
Give a code snippet in #Logtalk Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#GAP
GAP
# Matrix exponentiation is built-in A := [[0 , 1], [1, 1]]; PrintArray(A); # [ [ 0, 1 ], # [ 1, 1 ] ] PrintArray(A^10); # [ [ 34, 55 ], # [ 55, 89 ] ]
Give a code snippet in #GAP Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if ...
#J
J
format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ]) S=: 'x = {} p = {} -x^p {} -(x)^p {} (-x)^p {} -(x^p) {}' explicit=: dyad def 'S format~ 2 2 4 4 4 4 ":&> x,y,(-x^y),(-(x)^y),((-x)^y),(-(x^y))' tacit=: S format~ 2 2 4 4 4 4 ":&> [`]`([:-^)`([:-^)`((...
Give a code snippet in #J (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exp...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Lua
Lua
function fact(n) return n > 0 and n * fact(n-1) or 1 end
Give a code snippet in #Lua Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#PostScript
PostScript
<</PageSize [595 842]>> setpagedevice  % set page size to DIN A4 /Courier findfont  % use Courier 12 scalefont setfont  % 12 pt 28 802 moveto  % 1 cm from the top and left edges (Hello world) show  % draw the string
Give a code snippet in #PostScript Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Quackery
Quackery
[ 1 over times [ over i 1+ + * ] nip ] is 2n!/n! ( n --> n )   [ times [ i 1+ / ] ] is /n! ( n --> n )   [ dup 2n!/n! swap 1+ /n! ] is catalan ( n --> n )   15 times [ i^ dup echo say " : " catalan echo cr ]
Give a code snippet in #Quackery Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#TI-89_BASIC
TI-89 BASIC
#import std #import nat #import flo   (integral_by "m") ("f","a","b","n") =   iprod ^(* ! div\float"n" minus/"b" "a",~&) ("m" "f")*ytp (ari successor "n")/"a" "b"
Give a code snippet in #TI-89_BASIC Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Wren
Wren
import "io" for Stdin, Stdout import "random" for Random   var rand = Random.new() var n = rand.int(1, 11) // computer number from 1..10 inclusive while (true) { System.write("Your guess 1-10 : ") Stdout.flush() var guess = Num.fromString(Stdin.readLine()) if (n == guess) { System.print("Well gu...
Give a code snippet in #Wren Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#PHP
PHP
<?php function accumulator($start){ return create_function('$x','static $v='.$start.';return $v+=$x;'); } $acc = accumulator(5); echo $acc(5), "\n"; //prints 10 echo $acc(10), "\n"; //prints 20 ?>
Give a code snippet in #PHP A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passe...
christopher/rosetta-code