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/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#BCPL
BCPL
get "libhdr"   let start() be $( let eck = vec 999   for i = 0 to 999 do eck!i := 0 for i = 0 to 998 do for j = i-1 to 0 by -1 do if eck!i = eck!j then $( eck!(i+1) := i-j break $)   for i = 0 to 9 do writed(eck!i, 4) wrch('*N') for i = 9...
Give a code snippet in #BCPL The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured ...
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.
#J
J
mp=: +/ .* NB. Matrix multiplication pow=: pow0=: 4 : 'mp&x^:y =i.#x'
Give a code snippet in #J 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/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...
#Nemerle
Nemerle
using System; using System.Console;   module Program { Main() : void { WriteLine("Factorial of which number?"); def number = long.Parse(ReadLine()); WriteLine("Using Fold : Factorial of {0} is {1}", number, FactorialFold(number)); WriteLine("Using Match: Factorial of {0} is {1}", number, Fac...
Give a code snippet in #Nemerle 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...
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 ...
#AWK
AWK
$2=="OUT" { count = count + 1 time = $4 if ( count > maxcount ) { maxcount = count maxtimes = time } else { if ( count == maxcount ) { maxtimes = maxtimes " and " time } } } $2=="IN" { count = count - 1 } END {print "The biggest number of licenses is...
Give a code snippet in #AWK 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 check...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Sather
Sather
class MAIN is   move(ndisks, from, to, via:INT) is if ndisks = 1 then #OUT + "Move disk from pole " + from + " to pole " + to + "\n"; else move(ndisks-1, from, via, to); move(1, from, to, via); move(ndisks-1, via, to, from); end; end;   main is move(4, 1, 2, 3); end; end;
Give a code snippet in #Sather Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Raku
Raku
constant a = 200; constant b = 200; constant n = 2.5;   # y in terms of x sub y ($x) { sprintf "%d", b * (1 - ($x / a).abs ** n ) ** (1/n) }   # find point pairs for one quadrant my @q = flat map -> \x { x, y(x) }, (0, 1 ... 200);   # Generate an SVG image INIT say qq:to/STOP/; <?xml version="1.0" standalone="no"?>...
Give a code snippet in #Raku A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a su...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Elixir
Elixir
defmodule ISO do def long_year?(y) do {:ok, jan1} = Date.new(y,1,1) {:ok, dec31} = Date.new(y,12,31) Date.day_of_week(jan1) == 4 or Date.day_of_week(dec31) == 4 end end   IO.inspect(Enum.filter(1990..2050, &ISO.long_year?/1))
Give a code snippet in #Elixir Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#OCaml
OCaml
let rec bsort s = let rec _bsort = function | x :: x2 :: xs when x > x2 -> x2 :: _bsort (x :: xs) | x :: x2 :: xs -> x :: _bsort (x2 :: xs) | s -> s in let t = _bsort s in if t = s then t else bsort t
Give a code snippet in #OCaml 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/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Pascal
Pascal
  const s = 'abcdef'; begin writeln (length(s)) end.  
Give a code snippet in #Pascal Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme con...
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...
#jq
jq
def do_until(condition; next): def u: if condition then . else (next|u) end; u;   # n may be a decimal number or a string representing a decimal number def digital_root(n): # string-only version def dr: # state: [mdr, persist] do_until( .[0] | length == 1; [ (.[0] | explode | map(.-48) | a...
Give a code snippet in #jq 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} , rep...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Sidef
Sidef
class Modulo(n=0, m=13) {   method init { (n, m) = (n % m, m) }   method to_n { n }   < + - * ** >.each { |meth| Modulo.def_method(meth, method(n2) { Modulo(n.(meth)(n2.to_n), m) }) }   method to_s { "#{n} 「mod #{m}」" } }   func f(x) { x**100 + x + 1 } say f(Modulo(10, 13))
Give a code snippet in #Sidef Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, t...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#OCaml
OCaml
let sqr x = x *. x   let chi2UniformDistance distrib = let count, len = Array.fold_left (fun (s, c) e -> s + e, succ c) (0, 0) distrib in let expected = float count /. float len in let distance = Array.fold_left (fun s e -> s +. sqr (float e -. expected) /. expected ) 0. distrib in let dof = floa...
Give a code snippet in #OCaml Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolea...
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...
#Visual_Basic_.NET
Visual Basic .NET
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
Give a code snippet in #Visual_Basic_.NET 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 implem...
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...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PROC strip chars = (STRING mine, ore)STRING: ( STRING out := ""; FOR i FROM LWB mine TO UPB mine DO IF NOT char in string(mine[i], LOC INT, ore) THEN out +:= mine[i] FI OD; out[@LWB mine] );   printf(($gl$,stripchars("She was a soul stripper. She took my heart!",...
Give a code snippet in #ALGOL_68 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 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...
#360_Assembly
360 Assembly
* Substring/Top and tail 04/03/2017 SUBSTRTT CSECT USING SUBSTRTT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
Give a code snippet in #360_Assembly 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 remo...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#jq
jq
def assert($e; $msg): if $e then . else "assertion violation @ \($msg)" | error end;   def is_integer: type=="number" and floor == .;   # To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);  
Give a code snippet in #jq Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two ...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Ada
Ada
with Ada.Calendar; use Ada.Calendar; with Ada.Text_Io; use Ada.Text_Io;   procedure Query_Performance is type Proc_Access is access procedure(X : in out Integer); function Time_It(Action : Proc_Access; Arg : Integer) return Duration is Start_Time : Time := Clock; Finis_Time : Time; Func_Arg : In...
Give a code snippet in #Ada Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between s...
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...
#ooRexx
ooRexx
  x = .accumulator~new(1) -- new accumulator with initial value of "1" x~call(5) x~call(2.3) say "Accumulator value is now" x -- displays current value   -- an accumulator class instance can be instantiated and -- used to sum up a series of numbers ::class accumulator ::method init -- instance initializer...se...
Give a code snippet in #ooRexx 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 pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#XSLT
XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">   <xsl:template match="/numbers"> <html> <body> <ul> <xsl:apply-templates /> </ul> </body> </html> </xsl:template>   <xsl:template match...
Give a code snippet in #XSLT The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Prolog
Prolog
o(O) :- member(O, [0,1,2,3,4,5,6,7]).   octal([O]) :- o(O). octal([A|B]) :- octal(O), o(T), append(O, [T], [A|B]), dif(A, 0).   octalize :- forall( octal(X), (maplist(write, X), nl) ).
Give a code snippet in #Prolog Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Text   Module Module1   Function Gcd(a As BigInteger, b As BigInteger) As BigInteger If b = 0 Then If a < 0 Then Return -a Else Return a End If Else Return Gcd(b, a Mod b) E...
Give a code snippet in #Visual_Basic_.NET An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equa...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#11l
11l
V (target_min, target_max) = (1, 100)   print("Guess my target number that is between #. and #. (inclusive).\n".format(target_min, target_max)) V target = random:(target_min..target_max) V (answer, i) = (target_min - 1, 0) L answer != target i++ V txt = input(‘Your guess(#.): ’.format(i)) X.try answer = ...
Give a code snippet in #11l Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: high...
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Octave
Octave
  % Given struct "test" test.b=1; test = setfield (test, "c", 3);  
Give a code snippet in #Octave Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metap...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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) The Miller–Rabin primality test or Rabin–Miller prima...
#BQN
BQN
_modMul ← { n _𝕣: n|× } MillerRabin ← { 𝕊n: 10𝕊n ; iter 𝕊 n: !2|n # n = 1 + d×2⋆s s ← 0 {𝕨 2⊸|◶⟨+⟜1𝕊2⌊∘÷˜⊢,⊣⟩ 𝕩} n-1 d ← (n-1) ÷ 2⋆s   # Arithmetic mod n Mul ← n _modMul Pow ← Mul{𝔽´𝔽˜⍟(/2|⌊∘÷⟜2⍟(↕1+·⌊2⋆⁼⊢)𝕩)𝕨}   # Miller-Rabin test MR ← { 1 =𝕩 ? 𝕨≠s ; (n-1)=𝕩 ? 0  ; �...
Give a code snippet in #BQN This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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) The Miller–Rabin primali...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Nanoquery
Nanoquery
// variable definition and initialization/assignment // // variables are initialized when they are defined a = 1 b = 2 c = null   // datatypes // // variables may contain any datatype, and this can be // changed at any time by assigning a new value. they may // also contain native java types var = "a string" var = 123 ...
Give a code snippet in #Nanoquery Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#SQL_PL
SQL PL
  --#SET TERMINATOR @   SET SERVEROUTPUT ON@   CREATE OR REPLACE FUNCTION CHECK_SEDOL ( IN TEXT VARCHAR(6) ) RETURNS VARCHAR(7) BEGIN DECLARE TYPE SEDOL AS CHAR(1) ARRAY [6]; --declare text varchar(6) default 'B12345'; DECLARE WEIGHT SEDOL; DECLARE I SMALLINT; DECLARE SENTENCE VARCHAR(256); DECLARE CHAR...
Give a code snippet in #SQL_PL Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 585284...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#zkl
zkl
student:=RegExp(0'|.*<Student\s*.+Name\s*=\s*"([^"]+)"|); unicode:=RegExp(0'|.*(&#x[0-9a-fA-F]+;)|); xml:=File("foo.xml").read();   students:=xml.pump(List,'wrap(line){ if(student.search(line)){ s:=student.matched[1]; // ( (match start,len),group text ) while(unicode.search(s)){ // convert "&#x00C9;" ...
Give a code snippet in #zkl Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M...
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...
#XSLT
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:variable name="alpha">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz</xsl:variable> <xsl:variable name="rot13">NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm</xsl:variable> <xsl:templa...
Give a code snippet in #XSLT 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Maxima
Maxima
[1, 3, -5] . [4, -2, -1]; /* 3 */
Give a code snippet in #Maxima Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"CLASSLIB"   DIM Camera{TakePicture} PROC_class(Camera{})   DIM MobilePhone{MakeCall} PROC_class(MobilePhone{})   DIM CameraPhone{methods} PROC_inherit(CameraPhone{}, Camera{}) PROC_inherit(CameraPhone{}, MobilePhone{}) PROC_class(CameraPhone{})
Give a code snippet in #BBC_BASIC Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and Mobi...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Oberon-2
Oberon-2
  MODULE Animals; TYPE Animal = POINTER TO AnimalDesc; AnimalDesc = RECORD END;   Cat = POINTER TO CatDesc; CatDesc = RECORD (AnimalDesc) END;   Dog = POINTER TO DogDesc; DogDesc = RECORD (AnimalDesc) END;   Lab = POINTER TO LabDesc; LabDesc = RECORD (DogDesc) END;   Collie = POINTER TO CollieDesc; ...
Give a code snippet in #Oberon-2 This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent ty...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#PureBasic
PureBasic
EnableExplicit #SPC=Chr(32) #TB=~"\t" #TBLF=~"\t\n" Define.i a,b,l,n,count=0 Define *count.Integer=@count   Procedure.i AddCount(*c.Integer) ; *counter: by Ref *c\i+1 ProcedureReturn *c\i EndProcedure   Procedure.s FormatStr(tx$,l.i) Shared *count If AddCount(*count)%10=0 ProcedureReturn RSet(tx$,l,#SPC)...
Give a code snippet in #PureBasic Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for bein...
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...
#Modula-2
Modula-2
MODULE BoxTheCompass; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,Write,ReadChar;   PROCEDURE expand(cp : ARRAY OF CHAR); VAR i : INTEGER = 0; BEGIN WHILE cp[i] # 0C DO IF i=0 THEN CASE cp[i] OF 'N': WriteString("...
Give a code snippet in #Modula-2 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#REXX
REXX
/*REXX program implements Langton's ant walk and displays the ant's path (finite field).*/ parse arg dir char seed . /*obtain optional arguments from the CL*/ if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RANDOM SEED*/ if dir=='' | dir=="," then dir= random(1, 4)...
Give a code snippet in #REXX Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Sather
Sather
class MAIN is main is num:ARRAY{INT} := |1, 5, 4, 3, 10|; loop -- the iterator elt! behaves like a "foreach", -- yielding the next element of the array at each iteration #OUT + num.elt! + "\n"; end; end; end;
Give a code snippet in #Sather Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loop...
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...
#Integer_BASIC
Integer BASIC
require'print' print'Hello world!'
Give a code snippet in #Integer_BASIC 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. W...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Java
Java
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma;   public class Test {   static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> ...
Give a code snippet in #Java Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#AWK
AWK
  BEGIN { meaning = 6 * 7 assert(meaning == 42, "Integer mathematics failed") assert(meaning == 42) meaning = strtonum("42 also known as forty-two") assert(meaning == 42, "Built-in function failed") meaning = "42" assert(meaning == 42, "Dynamic type conversion failed") meaning = 6 * 9 assert(meaning == 42, "Fo...
Give a code snippet in #AWK Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Python
Python
from math import sqrt   def rk4(f, x0, y0, x1, n): vx = [0] * (n + 1) vy = [0] * (n + 1) h = (x1 - x0) / float(n) vx[0] = x = x0 vy[0] = y = y0 for i in range(1, n + 1): k1 = h * f(x, y) k2 = h * f(x + 0.5 * h, y + 0.5 * k1) k3 = h * f(x + 0.5 * h, y + 0.5 * k2) k...
Give a code snippet in #Python Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This e...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. 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: Def...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program transDblList.s */ /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10S see at end of this program the instruction include */   /* Constantes */ .equ STDOUT, 1 ...
Give a code snippet in #ARM_Assembly Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, El...
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 ...
#Modula-3
Modula-3
MODULE InsertSort;   PROCEDURE IntSort(VAR item: ARRAY OF INTEGER) = VAR j, value: INTEGER; BEGIN FOR i := FIRST(item) + 1 TO LAST(item) DO value := item[i]; j := i - 1; WHILE j >= FIRST(item) AND item[j] > value DO item[j + 1] := item[j]; DEC(j); END; item[j + 1] :...
Give a code snippet in #Modula-3 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/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#XLISP
XLISP
(defun calendar (year) (define months-list '(("JANUARY" 31) ("FEBRUARY" 28) ("MARCH" 31) ("APRIL" 30) ("MAY" 31) ("JUNE" 30) ("JULY" 31) ("AUGUST" 31) ("SEPTEMBER" 30) ("OCTOBER" 31) ("NOVEMBER" 30) ("DECEMBER" 31))) (define days #(" Sunday " "Monday " "Tuesday " "Wednesday ...
Give a code snippet in #XLISP Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#REXX
REXX
/*REXX program finds the persistence and multiplicative digital root of some numbers.*/ numeric digits 100 /*increase the number of decimal digits*/ parse arg x /*obtain optional arguments from the CL*/ if x='' | x="," then x=123321 7739 893 899998 ...
Give a code snippet in #REXX The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {...
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 ...
#Racket
Racket
#lang racket   (define (levenshtein a b) (define (ls0 a-index b-index) (cond [(or (= a-index -1) (= b-index -1)) (abs (- a-index b-index))] [else (define a-char (string-ref a a-index)) (define b-char (string-ref b b-index)) (if (equal? a-char b-char) (ls ...
Give a code snippet in #Racket 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 co...
christopher/rosetta-code
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If th...
#Delphi
Delphi
  program Next_highest_int_from_digits;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   function StrToBytes(str: AnsiString): TArray<byte>; begin SetLength(result, Length(str)); Move(Pointer(str)^, Pointer(result)^, Length(str)); end;   function BytesToStr(bytes: TArray<byte>): AnsiS...
Give a code snippet in #Delphi Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appea...
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 ...
#Nemerle
Nemerle
using System; using System.Console;   module Fibonacci { Fibonacci(x : long) : long { |x when x < 2 => x |_ => Fibonacci(x - 1) + Fibonacci(x - 2) }   Main() : void { def num = Int64.Parse(ReadLine()); foreach (n in $[0 .. num]) WriteLine("{0}: {1}", n, Fi...
Give a code snippet in #Nemerle 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Smalltalk
Smalltalk
(1 to: 4) permutationsDo: [ :x | Transcript show: x printString; cr ].
Give a code snippet in #Smalltalk Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#Haskell
Haskell
import Data.List.Split ( chunksOf ) import Data.List ( (!!) )   isPrime :: Int -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n   isMagnanimous :: Int -> Bool isMagnanimous n = al...
Give a code snippet in #Haskell A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime...
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 -...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[Numerify,rls] rls={"A"->2,"B"->2,"C"->2,"D"->3,"E"->3,"F"->3,"G"->4,"H"->4,"I"->4,"J"->5,"K"->5,"L"->5,"M"->6,"N"->6,"O"->6,"P"->7,"Q"->7,"R"->7,"S"->7,"T"->8,"U"->8,"V"->8,"W"->9,"X"->9,"Y"->9,"Z"->9}; Numerify[s_String]:=Characters[ToUpperCase[s]]/.rls dict=Once[Import["http://www.rosettacode.org/wiki/Texton...
Give a code snippet in #Mathematica.2FWolfram_Language 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 ...
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 ...
#TI-89_BASIC
TI-89 BASIC
fib(n) when(n<2, n, fib(n-1) + fib(n-2))
Give a code snippet in #TI-89_BASIC 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 solutio...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations def W=128, H=W; \width and height of field int X, Y; [SetVid($13); \set 320x200 graphic video mode Point(W/2, H/2, 6\brown\); \place seed in center of field loop [repeat X:= Ran(W); Y:= Ran(H); \inject particle until Re...
Give a code snippet in #XPL0 Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#IDL
IDL
function multiply ,a,b return, a* b end
Give a code snippet in #IDL A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract fr...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#D
D
  import std.stdio, std.range;   void main() { int sol = 1; writeln("\t\tFIRE\t\tPOLICE\t\tSANITATION"); foreach( f; iota(1,8) ) { foreach( p; iota(1,8) ) { foreach( s; iota(1,8) ) { if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) { ...
Give a code snippet in #D There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (differ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Tcl
Tcl
package require Tcl 8.5 namespace path ::tcl::mathop   set pyramid { {151.0 "" "" "" ""} {"" "" "" "" ""} {40.0 "" "" "" ""} {"" "" "" "" ""} {x 11.0 y 4.0 z} }   set equations {{1 -1 1 0}}   proc simplify {terms val} { set vars {0 0 0} set x 0 set y 1 set z 2 foreach term $terms...
Give a code snippet in #Tcl This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#PARI.2FGP
PARI/GP
ordered(s)=my(v=Vecsmall(s),t=97);for(i=1,#v,if(v[i]>64&&v[i]<91,v[i]+=32);if(v[i]<97||v[i]>122||v[i]<t,return(0),t=v[i]));1 v=select(ordered,readstr("~/unixdict.txt")); N=vecmax(apply(length,v)); select(s->#s==N, v)
Give a code snippet in #PARI.2FGP An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#Axe
Axe
' ANSI terminal dimensions X = COLUMNS Y = ROWS   PRINT "X,Y: ", X, ",", Y
Give a code snippet in #Axe Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Lasso
Lasso
local(x = 0) while(#x != 10) => {^ #x = integer_random(19,0) #x #x == 10 ? loop_abort ', '+integer_random(19,0)+'\r' ^}
Give a code snippet in #Lasso Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#bash
bash
  caesar_cipher() {   # michaeltd 2019-11-30 # https://en.wikipedia.org/wiki/Caesar_cipher # E n ( x ) = ( x + n ) mod 26. # D n ( x ) = ( x − n ) mod 26.   local -a _ABC=( "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" ) local -a _abc=( "a" "b" "c" "...
Give a code snippet in #bash Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of   precedence   and   associativity...
#Lambdatalk
Lambdatalk
  As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence. Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}  
Give a code snippet in #Lambdatalk This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list o...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#REXX
REXX
/*REXX program finds words with the largest set of anagrams (of the same size). */ iFID= 'unixdict.txt' /*the dictionary input File IDentifier.*/ $=;  !.=; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ ...
Give a code snippet in #REXX When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in th...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Forth
Forth
S" fsl-util.fs" REQUIRED S" complex.fs" REQUIRED   zvariable x zvariable y 1e 1e x z! pi 1.2e y z!   x z@ y z@ z+ z. x z@ y z@ z* z. 1e 0e zconstant 1+0i 1+0i x z@ z/ z. x z@ znegate z.
Give a code snippet in #Forth A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displayst...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#E
E
def gnomeSort(array) { var size := array.size() var i := 1 var j := 2 while (i < size) { if (array[i-1] <= array[i]) { i := j j += 1 } else { def t := array[i-1] array[i-1] := array[i] array[i] := t i -= 1 ...
Give a code snippet in #E 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/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
#Harbour
Harbour
? "Hello world!"
Give a code snippet in #Harbour 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/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#Tcl
Tcl
package require sound # Potentially also require driver support for particular formats   # Load some sounds in; this part can be slow snack::sound s1 s1 read $soundFile1 snack::sound s2 s2 read $soundFile2   # Play a sound for a while (0.1 seconds; this is a low-latency operation) s1 play after 100 set done 1; vwait do...
Give a code snippet in #Tcl Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#XPL0
XPL0
code ChOut=8, CrLf=9, IntOut=11; int N, Max, Card1(16), Card2(16);   proc Topswop(D); \Conway's card swopping game int D; \depth of recursion int I, J, C, T; [if D # N then \generate N! permutations of 1..N in Card1 [for I:= 0 to N-1 do [for J:= 0 to D-1 do \ch...
Give a code snippet in #XPL0 Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is com...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Java
Java
import java.util.Arrays; import java.util.stream.IntStream;   public class PerfectShuffle {   public static void main(String[] args) { int[] sizes = {8, 24, 52, 100, 1020, 1024, 10_000}; for (int size : sizes) System.out.printf("%5d : %5d%n", size, perfectShuffle(size)); }   stat...
Give a code snippet in #Java A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#BASIC
BASIC
DEFINT A-Z   DIM secret AS STRING DIM guess AS STRING DIM c AS STRING DIM bulls, cows, guesses, i   RANDOMIZE TIMER DO WHILE LEN(secret) < 4 c = CHR$(INT(RND * 10) + 48) IF INSTR(secret, c) = 0 THEN secret = secret + c LOOP   guesses = 0 DO INPUT "Guess a 4-digit number with no duplicate digits: "; gu...
Give a code snippet in #BASIC Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the ...
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/...
#jq
jq
def is_harshad: def digits: tostring | [explode[] | ([.]| implode) | tonumber]; if . >= 1 then (. % (digits|add)) == 0 else false end ;   # produce a stream of n Harshad numbers def harshads(n): # [candidate, count] def _harshads: if .[0]|is_harshad then .[0], ([.[0]+1, .[1]-1]| _harshads) elif .[1] > 0...
Give a code snippet in #jq 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/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
#BBC_BASIC
BBC BASIC
  PROCsolve24("1234") PROCsolve24("6789") PROCsolve24("1127") PROCsolve24("5566") END   DEF PROCsolve24(s$) LOCAL F%, I%, J%, K%, L%, P%, T%, X$, o$(), p$(), t$() DIM o$(4), p$(24,4), t$(11) o$() = "", "+", "-", "*", "/" RESTORE FOR T% = 1 TO 11 ...
Give a code snippet in #BBC_BASIC 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/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#VBScript
VBScript
  Function compound_duration(n) Do Until n = 0 If n >= 604800 Then wk = Int(n/604800) n = n-(604800*wk) compound_duration = compound_duration & wk & " wk" End If If n >= 86400 Then d = Int(n/86400) n = n-(86400*d) If wk > 0 Then compound_duration = compound_duration & ", " End If compound_du...
Give a code snippet in #VBScript Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e....
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#TI-89_BASIC
TI-89 BASIC
Prgm Local mat,i,j © randMat(5, 5) exists but returns -9 to 9 rather than 1 to 20 newMat(5, 5) → mat For i,1,rowDim(mat) For j,1,colDim(mat) rand(20) → mat[i,j] EndFor EndFor Disp mat Pause "Press a key." ClrIO For i,1,rowDim(mat) For j,1,colDim(mat) If mat[i,j] = 20 Then ...
Give a code snippet in #TI-89_BASIC Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} ...
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.
#Nim
Nim
import terminal   stdout.styledWrite("normal ", styleReverse, "inverse", resetStyle, " normal\n")
Give a code snippet in #Nim Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#Octave
Octave
function sorted = beadsort(a) sorted = a; m = max(a); if ( any(a < 0) ) error("can't sort"); endif t = zeros(m, m); for i = 1:numel(a) t(i, 1:a(i)) = 1; endfor for i = 1:m s = sum(t(:, i)); t(:, i) = 0; t(1:s, i) = 1; endfor for i = 1:numel(a) sorted(i) = sum(t(i, :)); endf...
Give a code snippet in #Octave 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Jsish
Jsish
/* Hash from two arrays, in Jsish */ function hashTwo(k:array, v:array):object { var hash = {}; for (var i = 0; i < k.length; i++) hash[k[i]] = v[i]; return hash; }   ;hashTwo(['a','b','c'], [1,2,3]); ;hashTwo(['a','b'], [1,[2,4,8],3]); ;hashTwo(['a','b','c'], [1,2]); ;hashTwo([], []);   /* =!EXPECTSTART!= ...
Give a code snippet in #Jsish Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
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 ...
#EDSAC_order_code
EDSAC order code
[ Fibonacci sequence ==================   A program for the EDSAC   Calculates the nth Fibonacci number and displays it at the top of storage tank 3   The default value of n is 10   To calculate other Fibonacci numbers, set the starting value of the count to n-2   Works with Initial Orders 2 ]     ...
Give a code snippet in #EDSAC_order_code 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#AWK
AWK
  # syntax: GAWK -f BRAZILIAN_NUMBERS.AWK # converted from C BEGIN { split(",odd ,prime ",kinds,",") for (i=1; i<=3; ++i) { printf("first 20 %sBrazilian numbers:",kinds[i]) c = 0 n = 7 while (1) { if (is_brazilian(n)) { printf(" %d",n) if (++c == 20) { ...
Give a code snippet in #AWK Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 ...
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...
#Elixir
Elixir
  s = "hello" t = s <> " literal"   IO.puts s IO.puts t  
Give a code snippet in #Elixir 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/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#K
K
a: `zero `one `two / symbols b: 0 1 2   d:. a,'b / create the dictionary .((`zero;0;) (`one;1;) (`two;2;))   d[`one] 1
Give a code snippet in #K Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#zkl
zkl
fcn yellowstoneW{ // --> iterator Walker.zero().tweak(fcn(a,b){ foreach i in ([1..]){ if(not b.holds(i) and i.gcd(a[-1])==1 and i.gcd(a[-2]) >1){ a.del(0).append(i); // only keep last two terms b[i]=True; return(i); } } }.fp(List(2,3), Dictionary(1,True, 2,True, 3,True))).pus...
Give a code snippet in #zkl The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#Ruby
Ruby
str = "rosetta code phrase reversal"   puts str.reverse # Reversed string. puts str.split.map(&:reverse).join(" ") # Words reversed. puts str.split.reverse.join(" ") # Word order reversed.
Give a code snippet in #Ruby Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#S-lang
S-lang
% Simplistic prime-test from prime-by-trial-division: define is_prime(n) { if (n <= 1) return(0); if (n == 2) return(1); if ((n & 1) == 0) return(0);   variable mx = int(sqrt(n)), i;   _for i (3, mx, 1) { if ((n mod i) == 0) return(0); } return(1); }   define population(n) { variable...
Give a code snippet in #S-lang A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prim...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Nim
Nim
import math   for i in 1..<5000: var sum: int64 = 0 var number = i while number > 0: var digit = number mod 10 sum += digit ^ digit number = number div 10 if sum == i: echo i
Give a code snippet in #Nim A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see T...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#ALGOL_68
ALGOL 68
main:(   OP +:= = (REF FLEX[]STRING in out, STRING item)VOID:( [LWB in out: UPB in out+1]STRING new; new[LWB in out: UPB in out]:=in out; new[UPB new]:=item; in out := new );   PROC string split = (REF STRING beetles, STRING substr)[]STRING:( """ Split beetles where substr is found """; F...
Give a code snippet in #ALGOL_68 Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks...
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...
#C.23
C#
using System; using System.Linq; using System.Numerics;   namespace LahNumbers { class Program { static BigInteger Factorial(BigInteger n) { if (n == 0) return 1; BigInteger res = 1; while (n > 0) { res *= n--; } return res; ...
Give a code snippet in #C.23 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Pascal
Pascal
program HQ9;   procedure runCode(code: string); var c_len, i, bottles: Integer; accumulator: Cardinal; begin c_len := Length(code); accumulator := 0; for i := 1 to c_len do begin case code[i] of 'Q','q': writeln(code); 'H','h': Writeln('Hello, world!'); '9': beg...
Give a code snippet in #Pascal Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Sidef
Sidef
func damm(digits) { static tbl = [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2], [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], [5, 8, 6, 9, 7, 2, ...
Give a code snippet in #Sidef The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Pike
Pike
  void handle_request(Protocols.HTTP.Server.Request request) { request->response_and_finish( ([ "data":"Goodbye, World!", "type":"text/html" ]) ); }   int main() { Protocols.HTTP.Server.Port(handle_request, 8080); return -1; // -1 is a special case that retirns control t...
Give a code snippet in #Pike The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#C.2B.2B
C++
// Display the current date in the formats of "2007-11-10" // and "Sunday, November 10, 2007".   #include <vector> #include <string> #include <iostream> #include <ctime>   /** Return the current date in a string, formatted as either ISO-8601 * or "Weekday-name, Month-name Day, Year". * * The date is initialized w...
Give a code snippet in #C.2B.2B This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
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
#BASIC
BASIC
GOTO 50: REM THIS WILL WORK IMMEDIATELY
Give a code snippet in #BASIC 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/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Component_Pascal
Component Pascal
  MODULE StandardDeviation; IMPORT StdLog, Args,Strings,Math;   PROCEDURE Mean(x: ARRAY OF REAL; n: INTEGER; OUT mean: REAL); VAR i: INTEGER; total: REAL; BEGIN total := 0.0; FOR i := 0 TO n - 1 DO total := total + x[i] END; mean := total /n END Mean;   PROCEDURE SDeviation(x : ARRAY OF REAL;n: INTEGER): REAL; VAR...
Give a code snippet in #Component_Pascal Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#OCaml
OCaml
type expression = | Const of float | Sum of expression * expression (* e1 + e2 *) | Diff of expression * expression (* e1 - e2 *) | Prod of expression * expression (* e1 * e2 *) | Quot of expression * expression (* e1 / e2 *)   let rec eval = function | Const c -> c | Sum (f, g) -> eval f +. eval...
Give a code snippet in #OCaml Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a si...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#DWScript
DWScript
PrintLn( HashSHA1.HashData('Rosetta code') );
Give a code snippet in #DWScript SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then outp...
#D
D
import std.array; import std.stdio;   void main() { auto tree = eertree("eertree"); writeln(subPalindromes(tree)); }   struct Node { int length; int[char] edges; int suffix; }   const evenRoot = 0; const oddRoot = 1;   Node[] eertree(string s) { Node[] tree = [ Node(0, null, oddRoot), ...
Give a code snippet in #D An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the ...
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...
#VBScript
VBScript
  Function LIS(arr) n = UBound(arr) Dim p() ReDim p(n) Dim m() ReDim m(n) l = 0 For i = 0 To n lo = 1 hi = l Do While lo <= hi middle = Int((lo+hi)/2) If arr(m(middle)) < arr(i) Then lo = middle + 1 Else hi = middle - 1 End If Loop newl = lo p(i) = m(newl-1) m(newl) = i If new...
Give a code snippet in #VBScript 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,1...
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.
#Forth
Forth
: array-max ( addr len -- max ) dup 0= if nip exit then over @ rot cell+ rot 1- cells bounds ?do i @ max cell +loop ;   : stack-max ( n ... m count -- max ) 1 ?do max loop ;
Give a code snippet in #Forth 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/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Scheme
Scheme
; swap elements of a vector ; vector-swap! is not part of r5rs, so we define it (define (vector-swap! v i j) (let ((a (vector-ref v i)) (b (vector-ref v j))) (vector-set! v i b) (vector-set! v j a)))   (let ((vec (vector 1 2 3 4 5))) (vector-swap! vec 0 4) vec) ; #(5 2 3 4 1)     ; we can swap also in lists (define...
Give a code snippet in #Scheme Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides generici...
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Rust
Rust
fn main() -> Result<(), Box<dyn std::error::Error>> { use std::io::{BufRead, BufReader};   for line in BufReader::new(std::fs::OpenOptions::new().read(true).open("data.txt")?).lines() { let line = line?;   let magnitude = line .split_whitespace() .nth(2) .and_...
Give a code snippet in #Rust Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines f...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#XBasic
XBasic
  PROGRAM "loopbreak"   IMPORT "xst" ' for XstGetSystemTime   DECLARE FUNCTION Entry()   ' Pseudo-random number generator ' Based on the rand, srand functions from Kernighan & Ritchie's book ' 'The C Programming Language' DECLARE FUNCTION Rand() DECLARE FUNCTION SRand(seed%%)   FUNCTION Entry() XstGetSystemTime (@mse...
Give a code snippet in #XBasic Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Python
Python
def eratosthenes2(n): multiples = set() for i in range(2, n+1): if i not in multiples: yield i multiples.update(range(i*i, n+1, i))   print(list(eratosthenes2(100)))
Give a code snippet in #Python This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Kosaraju
Kosaraju
This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size   Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Inte...
Give a code snippet in #Visual_Basic_.NET This page uses content from Wikipedia. The original article was at Graph. 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) Kosaraju's algorithm (also known...
christopher/rosetta-code