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/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Julia
Julia
fairshare(nplayers,len) = [sum(digits(n, base=nplayers)) % nplayers for n in 0:len-1]   for n in [2, 3, 5, 11] println("Fairshare ", n > 2 ? "among" : "between", " $n people: ", fairshare(n, 25)) end  
Give a code snippet in #Julia The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#C.23
C#
using System; using System.Collections.Generic;   class Program { static IEnumerable<int> r2cf(int n1, int n2) { while (Math.Abs(n2) > 0) { int t1 = n1 / n2; int t2 = n2; n2 = n1 - t1 * n2; n1 = t2; yield return t1; } }   ...
Give a code snippet in #C.23 Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_n-step_number_sequences
Padovan n-step number sequences
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n ==...
#REXX
REXX
/*REXX program computes and shows the Padovan sequences for M steps for N numbers. */ parse arg n m . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 15 /*Not specified? Then use the default.*/ if m=='' | m=="," then m= 8 ...
Give a code snippet in #REXX As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#PicoLisp
PicoLisp
(de happy? (N) (let Seen NIL (loop (T (= N 1) T) (T (member N Seen)) (setq N (sum '((C) (** (format C) 2)) (chop (push 'Seen N)) ) ) ) ) )   (let H 0 (do 8 (until (happy? (inc 'H))) (printsp H) ) )
Give a code snippet in #PicoLisp From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endless...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Oforth
Oforth
3.14 1.0e-12 0.13 1000.0 .22
Give a code snippet in #Oforth Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#PureBasic
PureBasic
Procedure.s stripChars(source.s, charsToStrip.s) Protected i, *ptrChar.Character, length = Len(source), result.s *ptrChar = @source For i = 1 To length If Not FindString(charsToStrip, Chr(*ptrChar\c)) result + Chr(*ptrChar\c) EndIf *ptrChar + SizeOf(Character) Next ProcedureReturn result E...
Give a code snippet in #PureBasic Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters ...
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
#AWK
AWK
~/src/opt/run $ awk 'BEGIN{printf "enter a string: "}{s=$0;i=$0+0;print "ok,"s"/"i}' enter a string: hello world ok,hello world/0 75000 ok,75000/75000
Give a code snippet in #AWK 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/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#REXX
REXX
/*REXX program determines if the STDIN is a terminal device or other. */ signal on syntax /*if syntax error, then jump ──► SYNTAX*/ say 'output device:' testSTDIN() /*displays terminal ──or── other */ exit 0 ...
Give a code snippet in #REXX Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Sidef
Sidef
say partitions(6666) # very fast
Give a code snippet in #Sidef The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) =...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#LIL
LIL
print [system date]; print [system date +%s.%N]
Give a code snippet in #LIL Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Da...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Swift
Swift
import Foundation   let dictPath: String   switch CommandLine.arguments.count { case 2: dictPath = CommandLine.arguments[1] case _: dictPath = "/usr/share/dict/words" }   let wordsData = FileManager.default.contents(atPath: dictPath)! let allWords = String(data: wordsData, encoding: .utf8)! let words = allWords.com...
Give a code snippet in #Swift Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (ass...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Swift
Swift
import BigInt import Foundation   @inlinable public func factorial<T: BinaryInteger>(_ n: T) -> T { guard n != 0 else { return 1 }   return stride(from: n, to: 0, by: -1).reduce(1, *) }   @inlinable public func lah<T: BinaryInteger>(n: T, k: T) -> T { if k == 1 { return factorial(n) } else if k == n {...
Give a code snippet in #Swift Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Delphi
Delphi
  program Arbitrary_precision_integers;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers;   var value: BigInteger; result: string;   begin value := BigInteger.pow(3, 2); value := BigInteger.pow(4, value.AsInteger); value := BigInteger.pow(5, value.AsInteger); result := value.tostring; ...
Give a code snippet in #Delphi Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
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...
#Standard_ML
Standard ML
fun compose (f, g) x = f (g x)
Give a code snippet in #Standard_ML 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Racket
Racket
#lang lazy   (define Y (λ (f) ((λ (x) (f (x x))) (λ (x) (f (x x))))))   (define Fact (Y (λ (fact) (λ (n) (if (zero? n) 1 (* n (fact (- n 1)))))))) (define Fib (Y (λ (fib) (λ (n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2))))))))
Give a code snippet in #Racket In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a v...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#BQN
BQN
Mul ← +˝∘×⎉1‿∞   (>⟨ ⟨1, 2, 3⟩ ⟨4, 5, 6⟩ ⟨7, 8, 9⟩ ⟩) Mul >⟨ ⟨1, 2, 3, 4⟩ ⟨5, 6, 7, 8⟩ ⟨9, 10, 11, 12⟩ ⟩
Give a code snippet in #BQN Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Ruby
Ruby
# Check to see whether it is defined puts "var is undefined at first check" unless defined? var   # Give it a value var = "Chocolate"   # Check to see whether it is defined after we gave it the # value "Chocolate" puts "var is undefined at second check" unless defined? var   # I don't know any way of undefining a varia...
Give a code snippet in #Ruby
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Delphi
Delphi
  program Averages_Mean_time_of_day;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   const Inputs: TArray<string> = ['23:00:17', '23:40:20', '00:12:45', '00:17:19'];   function ToTimes(ts: TArray<string>): TArray<TTime>; begin SetLength(result, length(ts)); for var i := 0 to High(ts) do Result...
Give a code snippet in #Delphi Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas...
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...
#BBC_BASIC
BBC BASIC
tst$ = "the three truths" sub$ = "th" PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """" tst$ = "ababababab" sub$ = "abab" PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """" END   DEF FNcountSubstring(A$, B$) LOCAL I%, N% I%...
Give a code snippet in #BBC_BASIC 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/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Erlang
Erlang
  -module( exceptions ).   -export( [task/0] ).   task() -> try erlang:throw( new_exception )   catch _:Exception -> io:fwrite( "Catched ~p~n", [Exception] )   end.  
Give a code snippet in #Erlang Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exception...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#D
D
IMPORT STD.STDIO, STD.DATETIME, STD.STRING, STD.CONV, STD.ALGORITHM, STD.ARRAY; VOID PRINT_CALENDAR(IN UINT YEAR, IN UINT COLS) IN { ASSERT(COLS > 0 && COLS <= 12); } BODY { STATIC ENUM CAMEL_CASE = (STRING[] PARTS) PURE => PARTS[0] ~ PARTS[1 .. $].MAP!CAPITALIZE.JOIN; IMMUTABLE ROWS = 12 /...
Give a code snippet in #D Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code f...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#11l
11l
F remove_comments(line, sep) V? p = line.find(sep) I p != N R line[0.<p].rtrim(‘ ’) R line   print(remove_comments(‘apples ; pears # and bananas’, (‘;’, ‘#’))) print(remove_comments(‘apples ; pears # and bananas’, ‘#’)) print(remove_comments(‘apples ; pears # and bananas’, ‘!’))
Give a code snippet in #11l Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#C
C
#include <stdio.h>   int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { // __builtin_popcount() for unsigned int // __builtin_popcountl() for unsigned long // __builtin_popcountll() for unsigned long long printf("%d ", __builtin_popcountll(n)); n *= 3; } ...
Give a code snippet in #C Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Scala
Scala
case class Vector3D(x:Double, y:Double, z:Double) { def dot(v:Vector3D):Double=x*v.x + y*v.y + z*v.z; def cross(v:Vector3D)=Vector3D(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x) def scalarTriple(v1:Vector3D, v2:Vector3D)=this dot (v1 cross v2) def vectorTriple(v1:Vector3D, v2:Vector3D)=this cross (v1 cross v2) ...
Give a code snippet in #Scala A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Swift
Swift
let nPoints = 100   func generatePoint() -> (Int, Int) { while true { let x = Int.random(in: -15...16) let y = Int.random(in: -15...16) let r2 = x * x + y * y   if r2 >= 100 && r2 <= 225 { return (x, y) } } }   func filteringMethod() { var rows = [[String]](repeating: Array(repeating: " ...
Give a code snippet in #Swift Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" cir...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#REBOL
REBOL
rebol [ Title: "First Class Functions" URL: http://rosettacode.org/wiki/First-class_functions ]   ; Functions "foo" and "bar" are used to prove that composition ; actually took place by attaching their signatures to the result.   foo: func [x][reform ["foo:" x]] bar: func [x][reform ["bar:" x]]   cube: func [x][x * ...
Give a code snippet in #REBOL A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other f...
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#D
D
import std.stdio, std.math, std.numeric;   T[][] cholesky(T)(in T[][] A) pure nothrow /*@safe*/ { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduc...
Give a code snippet in #D Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interprete...
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...
#Aime
Aime
o_text(argv(0)); o_byte('\n');
Give a code snippet in #Aime 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/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.
#Ruby
Ruby
$ irb irb(main):001:0> require 'matrix' => true irb(main):002:0> m=Matrix[[3,2],[2,1]] => Matrix[[3, 2], [2, 1]] irb(main):003:0> m**0 => Matrix[[1, 0], [0, 1]] irb(main):004:0> m ** 1 => Matrix[[3, 2], [2, 1]] irb(main):005:0> m ** 2 => Matrix[[13, 8], [8, 5]] irb(main):006:0> m ** 5 => Matrix[[987, 610], [610, 377]] ...
Give a code snippet in #Ruby 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/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#Racket
Racket
  #lang racket (require (planet soegaard/digest:1:2/digest)) (md4 #"Rosetta Code")  
Give a code snippet in #Racket Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsol...
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 ...
#Vala
Vala
int main (string[] args) { if (args.length < 2) { stdout.printf ("Please, input a string.\n"); return 0; } var str = new StringBuilder (); for (var i = 1; i < args.length; i++) { str.append (args[i] + " "); } stdout.printf ("%s\n", str.str.strip ().reverse ()); return 0; }
Give a code snippet in #Vala 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Hoon
Hoon
|% ++ enc |= char=@t `@ud`char ++ dec |= code=@ud `@t`code --
Give a code snippet in #Hoon Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conve...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#8th
8th
  needs combinators/bi   : mul3or5? ( 3 mod 0 = ) ( 5 mod 0 = ) bi or ;   "The sum of the multiples of 3 or 5 below 1000 is " . 0 ( mul3or5? if I n:+ then ) 1 999 loop . cr   with: n   : >triangular SED: n -- n dup 1+ * 2 / ;   : sumdiv SED: n n -- n dup >r /mod nip >triangular r> * ;   : sumdiv_3,5 SED: n -- ...
Give a code snippet in #8th Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT joblog="mlijobs.txt",jobnrout=0 log=FILE (joblog) DICT jobnrout CREATE LOOP l=log jobout=EXTRACT (l,":License :"|,": :") IF (jobout=="out") THEN time=EXTRACT (l,":@ :"|,": :"), jobnrout=jobnrout+1 DICT jobnrout APPEND/QUIET jobnrout,num,cnt,time;" " ELSE jobnrout=jobnrout-1 ENDIF ENDLOOP DIC...
Give a code snippet in #TUSCRIPT A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#REXX
REXX
/*REXX program computes and displays palindromic gapful numbers, it also can show those */ /*─────────────────────── palindromic gapful numbers listed by their last decimal digit.*/ numeric digits 20 /*ensure enough decimal digits gapfuls.*/ parse arg palGaps ...
Give a code snippet in #REXX Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful num...
christopher/rosetta-code
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 - ...
#F.23
F#
  // Generate cuban primes. Nigel Galloway: June 9th., 2019 let cubans=Seq.unfold(fun n->Some(n*n*n,n+1L)) 1L|>Seq.pairwise|>Seq.map(fun(n,g)->g-n)|>Seq.filter(isPrime64) let cL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:int64)->n.ToString("N0",g))  
Give a code snippet in #F.23 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/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#MATLAB
MATLAB
function x = rom2dec(s) % ROM2DEC converts Roman numbers to decimal   % store Roman digits values: I=1, V=5, X=10, L=50, C=100, D=500, M=1000 digitsValues = [0 0 100 500 0 0 0 0 1 0 0 50 1000 0 0 0 0 0 0 0 0 5 0 10 0 0]; % convert Roman number to array of values values = digitsValues(s-'A'+1); % change sign if next val...
Give a code snippet in #MATLAB Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, s...
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:...
#Sidef
Sidef
var content = []; Dir.cwd.open.each { |file| file ~~ < . .. > && next; content.append(file); }   content.sort.each { |file| say file; }
Give a code snippet in #Sidef 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/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#C.23
C#
// a mini chrestomathy solution   using System;   class Program {   // translated from java example static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res ...
Give a code snippet in #C.23 (This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show a maze, using the simple Depth...
#OCaml
OCaml
let seen = Hashtbl.create 7 let mark t = Hashtbl.add seen t true let marked t = Hashtbl.mem seen t   let walls = Hashtbl.create 7 let ord a b = if a <= b then (a,b) else (b,a) let join a b = Hashtbl.add walls (ord a b) true let joined a b = Hashtbl.mem walls (ord a b)   let () = let nx = int_of_string Sys.argv.(1) in...
Give a code snippet in #OCaml This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#ABAP
ABAP
  report z_http.   cl_http_client=>create_by_url( exporting url = `http://rosettacode.org/robots.txt` importing client = data(http_client) exceptions argument_not_found = 1 plugin_not_active = 2 internal_error = 3 others = 4 ).   if sy-subrc <> 0...
Give a code snippet in #ABAP Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
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...
#Raku
Raku
role DLElem[::T] { has DLElem[T] $.prev is rw; has DLElem[T] $.next is rw; has T $.payload = T;   method pre-insert(T $payload) { die "Can't insert before beginning" unless $!prev; my $elem = ::?CLASS.new(:$payload); $!prev.next = $elem; $elem.prev = $!prev; $elem.next = self; $!prev = $elem; $el...
Give a code snippet in #Raku 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#TI-83_BASIC
TI-83 BASIC
:"SHUFFLE" :L1→L2 :dim(L2)→A :For(B,1,dim(L2)-1) :randInt(1,A)→C :L2(C)→D :L2(A)→L2(C) :D→L2(A) :A-1→A :End :DelVar A :DelVar B :DelVar C :DelVar D :Return
Give a code snippet in #TI-83_BASIC The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging f...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) # computes soundex of each argument every write(x := !arglist, " => ",soundex(x)) end   procedure soundex(name) local dig,i,x static con initial { # construct mapping x[i] => i all else . x := ["bfpv","cgjkqsxz","dt","l","mn","r"] ...
Give a code snippet in #Icon_and_Unicon Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Cautio...
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.
#Icon_and_Unicon
Icon and Unicon
procedure main()   every put(A := [],1 to 10) # make a list of 1..10 every put(B := [],iseven(!A)) # make a second list and filter out odd numbers every writes(!B," ") | write() # show end   procedure iseven(x) #: return x if x is even or fail if x % 2 = 0 then return...
Give a code snippet in #Icon_and_Unicon 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/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Yabasic
Yabasic
  s$ = "nowhere ABJURER" print " Cadena original : ", s$ print " Tras codificar : ", Rot13$(s$) print "Tras decodificar : ", Rot13$(Rot13$(s$)) end   sub Rot13$ (s$) local cad$ cad$ = ""   for i = 1 to len(s$) temp = asc(mid$(s$, i, 1))   if temp >= 65 and temp <= 90 then // A to Z ...
Give a code snippet in #Yabasic Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#AWK
AWK
  # syntax: GAWK -f ZERO_TO_THE_ZERO_POWER.AWK BEGIN { print(0 ^ 0) exit(0) }  
Give a code snippet in #AWK Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#VBA
VBA
Private Function ToReducedRowEchelonForm(M As Variant) As Variant Dim lead As Integer: lead = 0 Dim rowCount As Integer: rowCount = UBound(M) Dim columnCount As Integer: columnCount = UBound(M(0)) Dim i As Integer For r = 0 To rowCount If lead >= columnCount Then Exit For ...
Give a code snippet in #VBA Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient ...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Swift
Swift
func one_of_n(n: Int) -> Int { var result = 1 for i in 2...n { if arc4random_uniform(UInt32(i)) < 1 { result = i } } return result }   var counts = [0,0,0,0,0,0,0,0,0,0] for _ in 1..1_000_000 { counts[one_of_n(10)-1]++ }   println(counts)
Give a code snippet in #Swift A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second lin...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Arturo
Arturo
; element-wise subtraction of two blocks. e.g. ; vsub [1 2 3] [1 2 3] ; [0 0 0] vsub: function [u v][ map couple u v 'pair -> pair\0 - pair\1 ]   differences: function [block][ order: attr "order" if order = null -> order: 1 loop 1..order 'n -> block: vsub block drop block 1 return block ]   print d...
Give a code snippet in #Arturo Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List ...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Euphoria
Euphoria
function min(sequence s) atom m m = s[1] for i = 2 to length(s) do if s[i] < m then m = s[i] end if end for return m end function   function levenshtein(sequence s1, sequence s2) integer n, m sequence d n = length(s1) + 1 m = length(s2) + 1   if n = 1 ...
Give a code snippet in #Euphoria This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Prolog
Prolog
| ?- length(["apple", "orange"], X).   X = 2   yes
Give a code snippet in #Prolog Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freq...
christopher/rosetta-code
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#Python
Python
import random   # Copied from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python def is_Prime(n): """ Miller-Rabin primality test.   A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if n!=int(n): return False ...
Give a code snippet in #Python A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Tcl
Tcl
proc angle2compass {angle} { set dirs { N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW } set unpack {N "north" E "east" W "west" S "south" b " by "}   # Compute the width of each compass segment set sep [expr {360...
Give a code snippet in #Tcl There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#R
R
repeat print("SPAM")
Give a code snippet in #R Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/In...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve
Sierpinski arrowhead curve
Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
#REXX
REXX
/*REXX pgm computes and displays a Sierpinski Arrowhead Curve using the characters: \_/ */ parse arg order . /*obtain optional argument from the CL.*/ if order=='' | order=="," then order= 5 /*Not specified? Then use the default.*/ say ' Sierpinski arrowhead curve of order' o...
Give a code snippet in #REXX Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C
C
#include <stdio.h>   void insertion_sort(int*, const size_t);   void insertion_sort(int *a, const size_t n) { for(size_t i = 1; i < n; ++i) { int key = a[i]; size_t j = i; while( (j > 0) && (key < a[j - 1]) ) { a[j] = a[j - 1]; --j; } a[j] = key; } }   int main (int argc, char** argv) {   int a[]...
Give a code snippet in #C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Phix
Phix
with javascript_semantics function a(integer i) printf(1,"a ") return i end function function b(integer i) printf(1,"b ") return i end function for z=0 to 1 do for i=0 to 1 do for j=0 to 1 do if z then printf(1,"a(%d) and b(%d) ",{i,j}) printf(...
Give a code snippet in #Phix Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable reso...
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
#Isabelle
Isabelle
theory Scratch imports Main begin value ‹''Hello world!''› end
Give a code snippet in #Isabelle 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 erro...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Smalltalk
Smalltalk
Object subclass: #NumberGuesser instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Rosettacode'  
Give a code snippet in #Smalltalk Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Delphi
Delphi
  program Find_common_directory_path;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function FindCommonPath(Separator: Char; Paths: TArray<string>): string; var SeparatedPath: array of TArray<string>; minLength, index: Integer; isSame: Boolean; j, i: Integer; cmp: string; begin SetLength(SeparatedPath, l...
Give a code snippet in #Delphi Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#PostScript
PostScript
  % our queue is just [] and empty? is already defined. /push {exch tadd}. /pop {uncons exch}.  
Give a code snippet in #PostScript Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Haskell
Haskell
import System.Time   main = putStrLn $ calendarTimeToString $ toUTCTime $ TOD 0 0
Give a code snippet in #Haskell Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the...
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...
#Liberty_BASIC
Liberty BASIC
src$ = "Hello" dest$ = src$ print src$ print dest$  
Give a code snippet in #Liberty_BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Haskell
Haskell
import Graphics.Gnuplot.Simple   pnts = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]   doPlot = plotPathStyle [ ( Title "plotting dots" )] (PlotStyle Points (CustomStyle [])) (zip [0..] pnts)
Give a code snippet in #Haskell Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38....
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Inverse_video
Terminal control/Inverse video
Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
#Standard_ML
Standard ML
val () = print "\^[[7mReversed\^[[m Normal\n"
Give a code snippet in #Standard_ML Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
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.
#PHP
PHP
<?php echo filesize('input.txt'), "\n"; echo filesize('/input.txt'), "\n"; ?>
Give a code snippet in #PHP 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/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Perl
Perl
use ntheory ":all"; sub isltrunc { my $n = shift; return (is_prime($n) && $n !~ /0/ && ($n < 10 || isltrunc(substr($n,1)))); } sub isrtrunc { my $n = shift; return (is_prime($n) && $n !~ /0/ && ($n < 10 || isrtrunc(substr($n,0,-1)))); } for (reverse @{primes(1e6)}) { if (isltrunc($_)) { print "ltrunc: $_\n"; ...
Give a code snippet in #Perl A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatabl...
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...
#J
J
bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_ bobw=: bob , ' on the wall'"_ beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<: beer"0 >:i.-99
Give a code snippet in #J 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 bot...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Kotlin
Kotlin
// version 1.1.51   fun findCommonDirPath(paths: List<String>, separator: Char): String { if (paths.isEmpty()) return "" if (paths.size == 1) return paths[0] val splits = paths[0].split(separator) val n = splits.size val paths2 = paths.drop(1) var k = 0 var common = "" while (true) { ...
Give a code snippet in #Kotlin Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the ...
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...
#Sidef
Sidef
say __MAIN__; if (__MAIN__ != __FILE__) { say "This file has been included!"; }
Give a code snippet in #Sidef 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable   Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function   Private Class SubMatrix Private...
Give a code snippet in #Visual_Basic_.NET linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{mat...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Raku
Raku
grammar tiny_C { rule TOP { ^ <.whitespace>? <tokens> + % <.whitespace> <.whitespace> <eoi> }   rule whitespace { [ <comment> + % <ws> | <ws> ] }   token comment { '/*' ~ '*/' .*? }   token tokens { [ | <operator> { make $/<operator>.ast } | <keyword> { make $/<keyword>...
Give a code snippet in #Raku Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or sc...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Elena
Elena
import forms; import extensions;   public class MainWindow : SDIDialog { Button btmIncrement; Button btmRandom; Edit txtNumber;   constructor new() <= new() { btmIncrement := Button.new(); btmRandom  := Button.new(); txtNumber  := Edit.new();   self ...
Give a code snippet in #Elena Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check i...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(s := "knight"," --> ", s[2:0]) # drop 1st char write(s := "sock"," --> ", s[1:-1]) # drop last write(s := "brooms"," --> ", s[2:-1]) # drop both end
Give a code snippet in #Icon_and_Unicon The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters r...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#GlovePIE
GlovePIE
debug="⡧⢼⣟⣋⣇⣀⣇⣀⣏⣹⠀⠀⣇⣼⣏⣹⡯⡽⣇⣀⣏⡱⢘⠀"
Give a code snippet in #GlovePIE Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Quackery
Quackery
[ stack ] is switch.arg ( --> [ )   [ switch.arg put ] is switch ( x --> )   [ switch.arg release ] is otherwise ( --> )   [ switch.arg share != iff ]else[ done otherwise ]'...
Give a code snippet in #Quackery Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly imp...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
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 |...
#SkookumScript
SkookumScript
!logic: (a? b?) [ println("a and b: " a and b) println("a or b: " a or b) println("not a: " not a) println("a xor b: " a xor b) println("a nand b: " a nand b) println("a nor b: " a nor b) println("a not xor b: " a nxor b) ]  
Give a code snippet in #SkookumScript 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 Ope...
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 ...
#F.23
F#
let rec ackermann m n = match m, n with | 0, n -> n + 1 | m, 0 -> ackermann (m - 1) 1 | m, n -> ackermann (m - 1) ackermann m (n - 1)   do printfn "%A" (ackermann (int fsi.CommandLineArgs.[1]) (int fsi.CommandLineArgs.[2]))
Give a code snippet in #F.23 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/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin...
#Vlang
Vlang
import rand import rand.seed   fn sleeping_beauty(reps int) f64 { mut wakings := 0 mut heads := 0 for _ in 0..reps { coin := rand.intn(2) or {0} // heads = 0, tails = 1 say wakings++ if coin == 0 { heads++ } else { wakings++ } } println...
Give a code snippet in #Vlang Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Su...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
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 ...
#Lua
Lua
function shellsort( a ) local inc = math.ceil( #a / 2 ) while inc > 0 do for i = inc, #a do local tmp = a[i] local j = i while j > inc and a[j-inc] > tmp do a[j] = a[j-inc] j = j - inc end a[j] = tmp end ...
Give a code snippet in #Lua 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...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program nullobj64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM6...
Give a code snippet in #AArch64_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#PureBasic
PureBasic
Procedure IsPangram_fast(String$) String$ = LCase(string$) char_a=Asc("a") ; sets bits in a variable if a letter is found, reads string only once For a = 1 To Len(string$) char$ = Mid(String$, a, 1) pos = Asc(char$) - char_a check.l | 1 << pos Next If check & $3FFFFFF = $3FFFFFF Procedure...
Give a code snippet in #PureBasic Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#XBasic
XBasic
  PROGRAM "pascal" VERSION "0.0001"   DECLARE FUNCTION Entry()   FUNCTION Entry() r@@ = UBYTE(INLINE$("Number of rows? ")) FOR i@@ = 0 TO r@@ - 1 c%% = 1 FOR k@@ = 0 TO i@@ PRINT FORMAT$("####", c%%); c%% = c%% * (i@@ - k@@) / (k@@ + 1) NEXT k@@ PRINT NEXT i@@ END FUNCTION END PROGRAM ...
Give a code snippet in #XBasic Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eithe...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#Action.21
Action!
SET EndProg=*
Give a code snippet in #Action.21 Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#FreeBASIC
FreeBASIC
  Dim Shared As Integer ancho = 64   Sub Hilbert(x As Integer, y As Integer, lg As Integer, i1 As Integer, i2 As Integer) If lg = 1 Then Line - ((ancho-x) * 10, (ancho-y) * 10) Return End If lg = lg / 2 Hilbert(x+i1*lg, y+i1*lg, lg, i1, 1-i2) Hilbert(x+i2*lg, y+(1-i2)*lg, lg, i1, i2)...
Give a code snippet in #FreeBASIC Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#Java
Java
import java.util.Scanner; import java.util.Random;   public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks...
Give a code snippet in #Java The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function to compute the arithmetic-geomet...
#C
C
#include<math.h> #include<stdio.h> #include<stdlib.h>   double agm( double a, double g ) { /* arithmetic-geometric mean */ double iota = 1.0E-16; double a1, g1;   if( a*g < 0.0 ) { printf( "arithmetic-geometric mean undefined when x*y<0\n" ); exit(1); }   while( fabs(a-g)>iota ) { a1...
Give a code snippet in #C This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function to co...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#C.2B.2B
C++
#include <string> #include <iostream>   int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word....
Give a code snippet in #C.2B.2B The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
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...
#Red
Red
Red ["Arithmetic mean"]   print average [] print average [2 3 5]
Give a code snippet in #Red 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 establ...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Clojure
Clojure
(use 'speech-synthesis.say) (say "This is an example of speech synthesis.")
Give a code snippet in #Clojure Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#jq
jq
jq -R . Find_the_missing_permutation.txt | jq -s -f Find_the_missing_permutation.jq
Give a code snippet in #jq ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
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
#M2000_Interpreter
M2000 Interpreter
  Function Master { Module Alfa { Gosub 100 Global M=1000 \\ delta print 1000 delta End 100 Print Module(Beta)=False Print Module(Delta)=True Return } Group Object1 { Function Master { =M } Module Final Beta { \\ delta print 500 delta alfa() Sub alfa() Local N=@Kappa(3) Gl...
Give a code snippet in #M2000_Interpreter 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/Substring
Substring
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 |...
#Racket
Racket
  #lang racket   (define str "abcdefghijklmnopqrstuvwxyz")   (define n 10) (define m 2) (define start-char #\x) (define start-str "xy")   ;; starting from n characters in and of m length; (substring str n (+ n m)) ; -> "kl"   ;; starting from n characters in, up to the end of the string; (substring str m) ; -> "klmnopq...
Give a code snippet in #Racket 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Gambas
Gambas
Public Sub Main()   Shell "echo Hello World"   End
Give a code snippet in #Gambas Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementat...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Rust
Rust
fn test_string(input: &str) { println!("Checking string {:?} of length {}:", input, input.chars().count());   let mut chars = input.chars();   match chars.next() { Some(first) => { if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() { printl...
Give a code snippet in #Rust Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each s...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Raku
Raku
sub pick-FEN { # First we chose how many pieces to place my $n = (2..32).pick;   # Then we pick $n squares my @n = (^64).pick($n);   # We try to find suitable king positions on non-adjacent squares. # If we could not find any, we return recursively return pick-FEN() unless my @kings[2] =...
Give a code snippet in #Raku Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent sq...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#EasyLang
EasyLang
print timestr systime
Give a code snippet in #EasyLang Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task ...
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 ...
#Ruby
Ruby
class Array def heapsort self.dup.heapsort! end   def heapsort! # in pseudo-code, heapify only called once, so inline it here ((length - 2) / 2).downto(0) {|start| siftdown(start, length - 1)}   # "end" is a ruby keyword (length - 1).downto(1) do |end_| self[end_], self[0] = self[0], sel...
Give a code snippet in #Ruby 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 sor...
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...
#Modula-2
Modula-2
MODULE ggTkgV;   FROM InOut IMPORT ReadCard, WriteCard, WriteLn, WriteString, WriteBf;   VAR x, y, u, v : CARDINAL;   BEGIN WriteString ("x = "); WriteBf; ReadCard (x); WriteString ("y = "); WriteBf; ReadCard (y); u := x; v := y; WHILE x # y DO (* gg...
Give a code snippet in #Modula-2 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   great...
christopher/rosetta-code