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/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Wren
Wren
import "/crypto" for Md5 import "/fmt" for Fmt   var strings = [ "The quick brown fox jumps over the lazy dog", "The quick brown fox jumps over the lazy dog.", "" ]   for (s in strings) { var digest = Md5.digest(s) Fmt.print("$s <== '$0s'", digest, s) }
Give a code snippet in #Wren Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the W...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe
Bitmap/Read an image through a pipe
This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PP...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Export["data/bitmapOutputTest.ppm",Import["data/bitmapOutputTest.jpg"]];
Give a code snippet in #Mathematica.2FWolfram_Language This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can als...
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...
#Wren
Wren
class Caesar { static encrypt(s, key) { var offset = key % 26 if (offset == 0) return s var chars = List.filled(s.count, 0) for (i in 0...s.count) { var c = s[i].bytes[0] var d = c if (c >= 65 && c <= 90) { // 'A' to 'Z' d = c + off...
Give a code snippet in #Wren 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/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(mergesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end   procedure mergesort(X,op,lower,upper) #: return sorted list ascending(or descending) local mi...
Give a code snippet in #Icon_and_Unicon 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Fantom
Fantom
  class Node { Float probability := 0.0f }   class Leaf : Node { Int character   new make (Int character, Float probability) { this.character = character this.probability = probability } }   class Branch : Node { Node left Node right   new make (Node left, Node right) { this.left = left ...
Give a code snippet in #Fantom Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const func float: agm (in var float: a, in var float: g) is func result var float: agm is 0.0; local const float: iota is 1.0E-7; var float: a1 is 0.0; var float: g1 is 0.0; begin if a * g < 0.0 then raise RANGE_ERR...
Give a code snippet in #Seed7 This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function t...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Standard_ML
Standard ML
fun takeWhileEq ([], _) = [] | takeWhileEq (_, []) = [] | takeWhileEq (x :: xs, y :: ys) = if x = y then x :: takeWhileEq (xs, ys) else []   fun commonPath sep = let val commonInit = fn [] => [] | x :: xs => foldl takeWhileEq x xs and split = String.fields (fn c => c = sep) and join = String.con...
Give a code snippet in #Standard_ML Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Oz
Oz
{System.showInfo {OS.getHostByName 'localhost'}.name}
Give a code snippet in #Oz Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statemen...
#Clojure
Clojure
(use '[clojure.math.combinatorics]   (defn xor? [& args] (odd? (count (filter identity args))))   (defn twelve-statements [] (for [[a b c d e f g h i j k l] (selections [true false] 12)  :when (true? a)  :when (if (= 3 (count (filter true? [g h i j k l]))) (true? b) (false? b))  :when (if (= 2 (count (filt...
Give a code snippet in #Clojure This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If s...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Smalltalk
Smalltalk
  Pharo Smalltalk   [ :yr | | firstDay firstFriday | firstDay := Date year: yr month: 1 day: 1. firstFriday := firstDay addDays: (6 - firstDay dayOfWeek). (0 to: 53) collect: [ :each | firstFriday addDays: (each * 7) ] thenSelect: [ :each | (((Date daysInMonth: each monthIndex forYear: yr) - each ...
Give a code snippet in #Smalltalk Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#D
D
import std.stdio, std.range, std.algorithm, std.conv, arithmetic_rational;   auto bernoulli(in uint n) pure nothrow /*@safe*/ { auto A = new Rational[n + 1]; foreach (immutable m; 0 .. n + 1) { A[m] = Rational(1, m + 1); foreach_reverse (immutable j; 1 .. m + 1) A[j - 1] = j * (A[j -...
Give a code snippet in #D Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Factor
Factor
USING: io kernel math math.parser locals qw sequences ; IN: rosetta-code.nested-functions   :: make-list ( separator -- str ) 1 :> counter! [| item | counter number>string separator append item append counter 1 + counter! ] :> make-item qw{ first second third } [ make-item call ] map...
Give a code snippet in #Factor In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of tw...
christopher/rosetta-code
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#Python
Python
N = 13   def method1(N=N): squares = [x**2 for x in range(0, N+1)] sqrset = set(squares) tri90, tri60, tri120 = (set() for _ in range(3)) for a in range(1, N+1): a2 = squares[a] for b in range(1, a + 1): b2 = squares[b] c2 = a2 + b2 if c2 in sqrset: ...
Give a code snippet in #Python The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#EchoLisp
EchoLisp
  (lib 'sequences)   (define (a n) (+ n (floor (+ 0.5 (sqrt n))))) (define A000037 (iterator/n a 1))   (take A000037 22) → (2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27) (filter square? (take A000037 1000000)) → null  
Give a code snippet in #EchoLisp Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A00...
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 ...
#Aime
Aime
integer fibs(integer n) { integer w;   if (n == 0) { w = 0; } elif (n == 1) { w = 1; } else { integer a, b, i;   i = 1; a = 0; b = 1; while (i < n) { w = a + b; a = b; b = w; i += 1; } }  ...
Give a code snippet in #Aime The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Phix
Phix
with javascript_semantics ?{26,0b11010,0o32,0x1A,0X1a,#1A,0(16)1A} -- displays {26,26,26,26,26,26,26} printf(1,"%d == 0b%b == 0x%x\n",26) -- displays 26 == 0b11010 == 0x1A printf(1,"%d == o(62)%A\n",{26,{62,26}}) -- displays 26 == 0(62)Q ?to_number("1a",{},16) -- displ...
Give a code snippet in #Phix Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary,...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Perl
Perl
my @arr1 = (1, 2, 3); my @arr2 = (4, 5, 6); my @arr3 = (@arr1, @arr2);
Give a code snippet in #Perl Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#J
J
vdc=: ([ %~ %@[ #. #.inv)"0 _
Give a code snippet in #J When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Scala
Scala
object Main extends App {   val raining = true val needUmbrella = raining println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}") }
Give a code snippet in #Scala Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#PL.2FM
PL/M
100H: /* FIND SOME PERFECT NUMBERS: NUMBERS EQUAL TO THE SUM OF THEIR PROPER */ /* DIVISORS */ /* CP/M SYSTEM CALL AND I/O ROUTINES */ BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */ DECLARE FN BYTE...
Give a code snippet in #PL.2FM Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itsel...
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
#Wortel
Wortel
@hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3}
Give a code snippet in #Wortel 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/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#Ruby
Ruby
#encoding: UTF-8 # superfluous in Ruby >1.9.3   if ENV.values_at("LC_ALL","LC_CTYPE","LANG").compact.first.include?("UTF-8") puts "△" else raise "Terminal can't handle UTF-8" end  
Give a code snippet in #Ruby The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Wren
Wren
/* hostname.wren */ class Host { foreign static name() // the code for this is provided by Go }   System.print(Host.name())
Give a code snippet in #Wren Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#D
D
import std.stdio; const N = 101; // #doors + 1 void main() { bool[N] doors = false; for(auto door=1; door<N; door++ ) { for(auto i=door; i<N; i+=door ) doors[i] = !doors[i]; if (doors[door]) write(door, " "); } }
Give a code snippet in #D There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...), ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#Crystal
Crystal
enum Direction RIGHT UP LEFT DOWN end   def generate(n : Int32, i : Int32, c : Int32 | String) s = Array.new(n) { Array.new(n) { "" } }   dir = Direction::RIGHT y = n // 2 x = n % 2 == 0 ? y - 1 : y   j = 1 while j <= n * n - 1 + i s[y][x] = is_prime(j) ? j.to_s : c.to_s   # printf "j: %s, x...
Give a code snippet in #Crystal An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is s...
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...
#AntLang
AntLang
factorial:{1 */ 1+range[x]} /Call: factorial[1000]
Give a code snippet in #AntLang 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/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#Perl
Perl
  use threads; use threads::shared; my @names = qw(Aristotle Kant Spinoza Marx Russell);   my @forks = ('On Table') x @names; share $forks[$_] for 0 .. $#forks;   sub pick_up_forks { my $philosopher = shift; my ($first, $second) = ($philosopher, $philosopher-1); ($first, $second) = ($second, $first) if $philos...
Give a code snippet in #Perl The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eatin...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Fortran
Fortran
  SUBROUTINE STARTS(A,B) !Text A starts with text B? CHARACTER*(*) A,B IF (INDEX(A,B).EQ.1) THEN !Searches A to find B. WRITE (6,*) ">",A,"< starts with >",B,"<" ELSE WRITE (6,*) ">",A,"< does not start with >",B,"<" END IF END SUBROUTINE STARTS   SU...
Give a code snippet in #Fortran Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Smalltalk
Smalltalk
  poem := '---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I''ve what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------'.   (poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ...
Give a code snippet in #Smalltalk Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by ...
christopher/rosetta-code
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#Perl
Perl
package Elementwise;   use Exporter 'import';   use overload '=' => sub { $_[0]->clone() }, '+' => sub { $_[0]->add($_[1]) }, '-' => sub { $_[0]->sub($_[1]) }, '*' => sub { $_[0]->mul($_[1]) }, '/' => sub { $_[0]->div($_[1]) }, '**' => sub { $_[0]->exp($_[1]) }, ;   sub new { my ($class, $v) = @_; return bless ...
Give a code snippet in #Perl This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   expone...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Quackery
Quackery
  [ over size - space swap of swap join ] is justify ( $ n --> $ )   [ 0 swap [ dup $ "" != while cr over number$ 4 justify echo$ 5 times [ dup $ "" = iff conclude done sp 10 split swap echo$ ] dip [ 50 + ] again ...
Give a code snippet in #Quackery Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGA...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#C.23
C#
using System; using System.Collections.Generic; using System.IO;   namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { ...
Give a code snippet in #C.23 The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Ada
Ada
with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Discrete_Random;   procedure Flip_Bits is   subtype Letter is Character range 'a' .. 'z';   Last_Col: constant letter := Ada.Command_Line.Argument(1)(1); Last_Row: constant Positive := Positive'Value(Ada.Command_Line.Argument(2));   package Boolean_Rand is ne...
Give a code snippet in #Ada The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move)...
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#zkl
zkl
var t=Time.Clock.time; try{ n:=0; while(1){(n+=1).println(); Atomic.sleep(0.5)} } catch{ println("ran for ",Time.Clock.time-t," seconds"); System.exit() }
Give a code snippet in #zkl Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Common_Lisp
Common Lisp
()
Give a code snippet in #Common_Lisp Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#Wren
Wren
import "/fmt" for Fmt   for (i in 0...16) { var j = 32 + i while (j < 128) { var k = "%(String.fromByte(j))" if (j == 32) { k = "Spc" } else if (j == 127) { k = "Del" } System.write("%(Fmt.d(3, j)) : %(Fmt.s(-3, k)) ") j = j + 16 } ...
Give a code snippet in #Wren Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I ...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#Delphi
Delphi
  program Doubly_linked;   {$APPTYPE CONSOLE}   uses System.SysUtils, boost.LinkedList;   var List: TLinkedList<string>; Head, Tail,Current: TLinkedListNode<string>; Value:string;   begin List := TLinkedList<string>.Create;   List.AddFirst('.AddFirst() adds at the head.'); List.AddLast('.AddLast() adds ...
Give a code snippet in #Delphi Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data typ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#BaCon
BaCon
OPTION GUI TRUE PRAGMA GUI gtk3   gui = GUIDEFINE(" \ { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=300 } \ { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \ { type=LABEL name=label parent=box height-request=50 label=\"There have been no clicks...
Give a code snippet in #BaCon Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#APL
APL
  sv ← 'defg' 'hijklm' 'abc' 'abcd' ⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv] 6 hijklm 4 defg 4 abcd 3 abc  
Give a code snippet in #APL Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#EasyLang
EasyLang
cx = -0.7 cy = 0.27015 for y range 300 for x range 300 zx = (x - 150) / 100 zy = (y - 150) / 150 color3 0 0 0 for iter range 128 if zx * zx + zy * zy > 4 color3 iter / 16 0 0 break 1 . h = zx * zx - zy * zy + cx zy = 2 * zx * zy + cy zx = h . move ...
Give a code snippet in #EasyLang Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind
Stirling numbers of the second kind
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 ...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1   Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)   Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function   Private Shared...
Give a code snippet in #Visual_Basic_.NET Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurren...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclops_numbers
Cyclops numbers
A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10. There are many different ...
#Ruby
Ruby
require 'prime'   NONZEROS = %w(1 2 3 4 5 6 7 8 9)   cyclopes = Enumerator.new do |y| (0..).each do |n| NONZEROS.repeated_permutation(n) do |lside| NONZEROS.repeated_permutation(n) do |rside| y << (lside.join + "0" + rside.join).to_i end end end end   prime_cyclopes = Enumera...
Give a code snippet in #Ruby A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base ...
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...
#Malbolge
Malbolge
  b'BA@?>=<;:9876543210/.-,+*)('&%$#"!Q=+^:('&Y$#m!1So.QOO=v('98$65a`_^]\[ZYXWVUTSRQ#I2MLKJIHGFE DCBA@#!7~|4{y1xv.us+rp(om%lj"ig}fd"cx``uz]rwvYnslkTonPfOjiKgJeG]\EC_X]@[Z<R;VU7S6QP2N1LK-I,GF( D'BA#?>7~;:9y16w43s10)p-,l*#(i&%e#d!~``{tyxZpuXsrTTongOkdMhg`Hd]ba`_^W@[ZYXW9UNSRQPOHMLKJ-++FE ''<A$?>=<;:387xw43s10/(-&m*)('&}$...
Give a code snippet in #Malbolge Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#CLU
CLU
% This program uses the 'bigint' cluster from PCLU's 'misc.lib'   % Integer square root of a bigint isqrt = proc (x: bigint) returns (bigint)  % Initialize a couple of bigints we will reuse own zero: bigint := bigint$i2bi(0) own one: bigint := bigint$i2bi(1) own two: bigint := bigint$i2bi(2) own four...
Give a code snippet in #CLU Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer p...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Elixir
Elixir
defmodule RC do def multiplication_tables(n) do IO.write " X |" Enum.each(1..n, fn i -> :io.fwrite("~4B", [i]) end) IO.puts "\n---+" <> String.duplicate("----", n) Enum.each(1..n, fn j ->  :io.fwrite("~2B |", [j]) Enum.each(1..n, fn i -> if i<j, do: (IO.write " "), else: :io.fwri...
Give a code snippet in #Elixir Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Printer
Colour pinstripe/Printer
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence...
#Nim
Nim
import gintro/[glib, gobject, gtk, gio, cairo]   const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0], [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], [255.0, 0.0, 255.0], [0.0, 255.0, 255.0], [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]   #--------------------------------------------...
Give a code snippet in #Nim The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included....
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#8086_Assembly
8086 Assembly
#!/usr/local/bin/a68g --script #   PRAGMAT portcheck PRAGMAT PR portcheck PR   BEGIN PR heap=256M PR # algol68g pragma # ~ END;   PROC (REAL)REAL s = sin();   SKIP
Give a code snippet in #8086_Assembly Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and dem...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#ALGOL_68
ALGOL 68
BEGIN print (("Integer range: ", -max int, " .. ", max int, new line)); print (("Integer digits: ", int width, new line)); print (("Float range: ", -max real, " .. ", max real, new line)); print (("Float digits: ", real width, new line)) END
Give a code snippet in #ALGOL_68 Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute ...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Scheme
Scheme
(load "filename")
Give a code snippet in #Scheme Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Free_Pascal
Free Pascal
echo "begin writeLn('Hi'); end." | ifpc /dev/stdin
Give a code snippet in #Free_Pascal Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implem...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#XBS
XBS
const Amount:number = toint(window.prompt("Input an amount")); set Stream = []; <|(*1..Amount)=>Stream.push(window.prompt("Input a number")); Stream=Stream.join(" "); const Inputs = <|(*Stream.split(" "))toint(_); set Result = 0; <|(*Inputs)Result+=_; log(Result);
Give a code snippet in #XBS A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated ...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Kotlin
Kotlin
fun main(args: Array<String>) { val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) val a = list.map({ x -> x + 2 }).average() val h = list.map({ x -> x * x }).average() val g = list.map({ x -> x * x * x }).average() println("A = %f G = %f H = %f".format(a, g, h)) }
Give a code snippet in #Kotlin Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Haskell
Haskell
import Data.List (group, sort) import Text.Printf (printf) import Data.Numbers.Primes (primes)   freq :: [(Int, Int)] -> Float freq xs = realToFrac (length xs) / 100   line :: [(Int, Int)] -> IO () line t@((n1, n2):xs) = printf "%d -> %d count: %5d frequency: %2.2f %%\n" n1 n2 (length t) (freq t)   main :: IO () main ...
Give a code snippet in #Haskell A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided prefer...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#EDSAC_order_code
EDSAC order code
  [Calculate e] [EDSAC program, Initial Orders 2]   [Library subroutine M3. Prints header and is then overwritten] [Here, last character sets teleprinter to figures] PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF @&*CALCULATION!OF!E@&# ..PZ [blank tape, needed to mark end of header text]   [Library subroutine D6....
Give a code snippet in #EDSAC_order_code Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#PARI.2FGP
PARI/GP
ways(k,v,s=[])={ if(k==0,return([])); if(k==1,return(vector(#v,i,concat(s,[v[i]])))); if(#v==1,return(ways(k-1,v,concat(s,v)))); my(u=vecextract(v,2^#v-2)); concat(ways(k-1,v,concat(s,[v[1]])),ways(k,u,s)) }; xc(k,v)=binomial(#v+k-1,k); ways(2, ["iced","jam","plain"])
Give a code snippet in #PARI.2FGP The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Groovy
Groovy
  class GameOfLife {   int generations int dimensions def board   GameOfLife(generations = 5, dimensions = 5) { this.generations = generations this.dimensions = dimensions this.board = createBlinkerBoard() }   static def createBlinkerBoard() { [ [].withDefault{0}, [0,0,1].withDefault{0}, [0,0,1]....
Give a code snippet in #Groovy The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Halt_and_catch_fire
Halt and catch fire
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an...
#Crystal
Crystal
raise "fire"
Give a code snippet in #Crystal Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help deb...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#PARI.2FGP
PARI/GP
one_of_n(n)={ my(chosen=1); for(k=2,n, if(random(k)==0, chosen=k) ); chosen; } v=vector(10); for(i=1,1e6, v[one_of_n(10)]++); v
Give a code snippet in #PARI.2FGP A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Go
Go
package main   import ( "fmt" "math/bits" )   func main() { fmt.Println("Pop counts, powers of 3:") n := uint64(1) // 3^0 for i := 0; i < 30; i++ { fmt.Printf("%d ", bits.OnesCount64(n)) n *= 3 } fmt.Println() fmt.Println("Evil numbers:") var od [30]uint64 var ne,...
Give a code snippet in #Go Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Fortran
Fortran
DIMENSION ATWT(12) PRINT 1 1 FORMAT (12HElement Name,F9.4) DO 10 I = 1,12 READ 1,ATWT(I) 10 PRINT 1,ATWT(I) END
Give a code snippet in #Fortran Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters ...
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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 ...
#zkl
zkl
fcn jort(list){ False!=list.reduce(fcn(a,b){ (a>b) and return(Void.Stop,False); b }) }
Give a code snippet in #zkl Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#OCaml
OCaml
# #load "unix.cma";; # open Unix;;   # let t = time() ;; val t : float = 1219997516.   # let gmt = gmtime t ;; val gmt : Unix.tm = {tm_sec = 56; tm_min = 11; tm_hour = 8; tm_mday = 29; tm_mon = 7; tm_year = 108; tm_wday = 5; tm_yday = 241; tm_isdst = false}   # Printf.sprintf "%d-%02d-%02d" (1900 + gmt.tm_year) (1...
Give a code snippet in #OCaml 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/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Racket
Racket
  #lang racket   ;; To see these calls we do two things: mutate the binding to prevent ;; Racket from inlining the value; use a (void) call at the end so the ;; calls are not tail calls (which will otherwise not show on the ;; stack). (define foo #f) (set! foo (λ() (bar) (void))) (define bar #f) (set! bar (λ() (show-st...
Give a code snippet in #Racket Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 ...
#Arturo
Arturo
lst: ["violet" "red" "green" "indigo" "blue" "yellow" "orange"] count: 0   findSpot: function [l,e][ if empty? l -> return 0   loop.with:'i l 'item [ answer: input ~"Is |item| greater than |e| [y/n]? " if answer="y" -> return i ] return dec size l ]   sortedLst: new []   loop lst 'elemen...
Give a code snippet in #Arturo 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/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...
#Nim
Nim
import random   while true: let a = random(19) echo a if a == 10: break let b = random(19) echo b
Give a code snippet in #Nim 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Lasso
Lasso
// create file local(f) = file handle => { #f->close } #f->openWriteOnly('output.txt')   // make directory, just like a file local(d = dir('docs')) #d->create   // create file in root file system (requires permissions at user OS level) local(f) = file handle => { #f->close } #f->openWriteOnly('//output.txt')   // creat...
Give a code snippet in #Lasso In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Perl
Perl
use strict; use warnings; use Math::AnyNum;   sub ramanujan_const { my ($x, $decimals) = @_;   $x = Math::AnyNum->new($x); my $prec = (Math::AnyNum->pi * $x->sqrt)/log(10) + $decimals + 1; local $Math::AnyNum::PREC = 4*$prec->round->numify;   exp(Math::AnyNum->pi * $x->sqrt)->round(-$decimals)->stri...
Give a code snippet in #Perl Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Racket
Racket
#lang racket (define (sum-of-squared-digits number (result 0)) (if (zero? number) result (sum-of-squared-digits (quotient number 10) (+ result (expt (remainder number 10) 2)))))   (define (happy-number? number (seen null)) (define next (sum-of-squared-digits number)) (cond...
Give a code snippet in #Racket From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#11l
11l
V dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,...
Give a code snippet in #11l W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
Search in paragraph's text
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output. So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within wha...
#J
J
NB. read file, separate on blank lines paragraphs=: ((LF,LF)&E. <;.2 ])fread 'traceback.txt'   NB. ignore text preceding 'Traceback (most recent call last)' cleaned=: {{y}.~{.I.'Traceback (most recent call last)'&E.y}}each paragraphs   NB. limit to paragraphs containing 'SystemError' searched=: (#~ (1 e.'SystemError'&...
Give a code snippet in #J The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output. So here, let’s imagine that we are trying to verify the presence of a keywo...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Racket
Racket
#lang racket   ;; Represent a balanced-ternary number as a list of 0's, 1's and -1's. ;; ;; e.g. 11 = 3^2 + 3^1 - 3^0 ~ "++-" ~ '(-1 1 1) ;; 6 = 3^2 - 3^1 ~ "+-0" ~ '(0 -1 1) ;; ;; Note: the list-rep starts with the least signifcant tert, while ;; the string-rep starts with the most significsnt tert. ...
Give a code snippet in #Racket Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Harmonic_series
Harmonic series
This page uses content from Wikipedia. The original article was at Harmonic number. 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 mathematics, the n-th harmonic number is the sum of the recipr...
#Forth
Forth
  warnings off   1.000.000.000.000.000 drop constant 1.0fx \ fractional part is 15 decimal digits.   : .h ( n -- ) s>d <# 14 for # next [char] . hold #s #> type space ;   1.0fx 1 2constant first-harmonic   : round 5 + 10 / ;   : next-harmonic ( h n -- h' n' ) 1+ tuck [ 1.0fx 10 * ] literal swap / round + s...
Give a code snippet in #Forth This page uses content from Wikipedia. The original article was at Harmonic number. 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 mathematics, the n-th harmonic ...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#GAP
GAP
# return a list of two lists : # first is the list of months with five weekends between years y1 and y2 (included) # second is the list of years without such months, in the same interval FiveWeekends := function(y1, y2) local L, yL, badL, d, m, y; L := [ ]; badL := [ ]; for y in [y1 .. y2] do yL := [ ]; ...
Give a code snippet in #GAP The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there ...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#BASIC
BASIC
DECLARE FUNCTION RLDecode$ (i AS STRING) DECLARE FUNCTION RLEncode$ (i AS STRING)   DIM initial AS STRING, encoded AS STRING, decoded AS STRING   INPUT "Type something: ", initial encoded = RLEncode(initial) decoded = RLDecode(encoded) PRINT initial PRINT encoded PRINT decoded   FUNCTION RLDecode$ (i AS STRING) DIM...
Give a code snippet in #BASIC Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a func...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_literals,_with_continuations
Long literals, with continuations
This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The literal is to be in the form ...
#Standard_ML
Standard ML
(* space in \ .. \ is ignored *)   val elements = "\ \hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine \ \neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon \ \potassium calcium scandium titanium vanadium chromium manganese iron cobalt \ \nickel copper zinc gallium g...
Give a code snippet in #Standard_ML This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms)....
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#Java
Java
import java.util.*;   public class RankingMethods {   final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"};   public static void main(String[] args) { int len = input.length;   Map<String, int[]> map = new TreeMap<>((a, ...
Give a code snippet in #Java Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#ERRE
ERRE
  !-------------------------------------------------------------------- ! risolve Sudoku: in input il file SUDOKU.TXT ! Metodo seguito : cancellazioni successive e quando non possibile ! ricerca combinatoria sulle celle con due valori ! possibili - max. 30 livelli di ricorsione ! ...
Give a code snippet in #ERRE Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Picat
Picat
  animals({"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}).   elements({"Wood", "Fire", "Earth", "Metal", "Water"}).   animal_chars({"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"}).   element_chars({{"甲", "丙", "戊", "庚", "壬"}, {"乙", "丁", "己", "辛", "癸"}}).   years...
Give a code snippet in #Picat Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities result...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#zkl
zkl
"\t\n hoho\n\t\ ".strip() //-->"hoho"
Give a code snippet in #zkl Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace remo...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#REXX
REXX
/*REXX program demonstrates how to set and display values for an associative array. */ /*╔════════════════════════════════════════════════════════════════════════════════════╗ ║ The (below) two REXX statements aren't really necessary, but it shows how to ║ ║ define any and all entries in a associative arr...
Give a code snippet in #REXX Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Comp...
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  ...
#R
R
  topswops <- function(x){ i <- 0 while(x[1] != 1){ first <- x[1] if(first == length(x)){ x <- rev(x) } else{ x <- c(x[first:1], x[(first+1):length(x)]) } i <- i + 1 } return(i) }   library(iterpc)   result <- NULL   for(i in 1:10){ I <- iterpc(i, labels = 1:i, ordered = T) ...
Give a code snippet in #R 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 compos...
christopher/rosetta-code
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Standard_ML
Standard ML
fun a (k, x1, x2, x3, x4, x5) = if k <= 0 then x4 () + x5 () else let val m = ref k fun b () = ( m := !m - 1; a (!m, b, x1, x2, x3, x4) ) in b () end   val () = print (Int.toString (a (10, fn () => 1, fn () => ~1, fn () => ~1, fn () => 1, fn () => 0)) ^ "\n")
Give a code snippet in #Standard_ML Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#min
min
"alphaBETA" uppercase "alphaBETA" lowercase "alphaBETA" capitalize
Give a code snippet in #min Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not rev...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/2
Text processing/2
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters...
#Aime
Aime
check_format(list l) { integer i; text s;   if (~l != 49) { error("bad field count"); }   s = l[0]; if (match("????-??-??", s)) { error("bad date format"); } l[0] = s.delete(7).delete(4).atoi;   i = 1; while (i < 49) { atof(l[i]); i += 1; l...
Give a code snippet in #Aime The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one o...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#PowerShell
PowerShell
Write-Host -NoNewLine "Goodbye, " Write-Host -NoNewLine "World!"
Give a code snippet in #PowerShell Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#ooRexx
ooRexx
a = .array~Of(4, 65, 2, -31, 0, 99, 83, 782, 1) say 'before:' a~toString( ,', ') a = quickSort(a) say ' after:' a~toString( ,', ') exit   ::routine quickSort use arg arr -- the array to be sorted less = .array~new pivotList = .array~new more = .array~new if arr~items <= 1 then ...
Give a code snippet in #ooRexx 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/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Arturo
Arturo
pi: 3.14 print [pi "->" type pi]
Give a code snippet in #Arturo Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#Go
Go
package main   import "fmt"   const n = 64   func pow2(x uint) uint64 { return uint64(1) << x }   func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 ...
Give a code snippet in #Go Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting succe...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Perl
Perl
sub tokenize { my ($string, $sep, $esc) = (shift, quotemeta shift, quotemeta shift);   my @fields = split /$esc . (*SKIP)(*FAIL) | $sep/sx, $string, -1; return map { s/$esc(.)/$1/gsr } @fields; }
Give a code snippet in #Perl Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for split...
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 ...
#Yorick
Yorick
func bubblesort(&items) { itemCount = numberof(items); do { hasChanged = 0; itemCount--; for(index = 1; index <= itemCount; index++) { if(items(index) > items(index+1)) { items([index,index+1]) = items([index+1,index]); hasChanged = 1; } } } while(hasChanged); }
Give a code snippet in #Yorick 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/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#R
R
# Generates a new board - either a random one, sample blinker or gliders, or user specified. gen.board <- function(type="random", nrow=3, ncol=3, seeds=NULL) { if(type=="random") { return(matrix(runif(nrow*ncol) > 0.5, nrow=nrow, ncol=ncol)) } else if(type=="blinker") { seeds <- list(c(2,1...
Give a code snippet in #R The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#F.23
F#
open Microsoft.FSharp.Collections   let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1]...
Give a code snippet in #F.23 Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpr...
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  ...
#Tcl
Tcl
package require struct::list   proc swap {listVar} { upvar 1 $listVar list set n [lindex $list 0] for {set i 0; set j [expr {$n-1}]} {$i<$j} {incr i;incr j -1} { set tmp [lindex $list $i] lset list $i [lindex $list $j] lset list $j $tmp } }   proc swaps {list} { for {set i 0} {[lindex $list 0] > ...
Give a code snippet in #Tcl 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 comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Lingo
Lingo
-- create new (movie) script at runtime m = new(#script)   -- the following line triggers compilation to bytecode m.scriptText = "on fac10"&RETURN&"return "&(10*9*8*7*6*5*4*3*2)&RETURN&"end"   put fac10() -- 3628800
Give a code snippet in #Lingo Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Pascal
Pascal
  Program ls; {To list the names of all files/directories in the current directory.} Uses DOS; var DirInfo: SearchRec; {Predefined. See page 403 of the Turbo Pascal 4 manual.} BEGIN FindFirst('*.*',AnyFile,DirInfo); {AnyFile means any file name OR directory name.} While DOSerror = 0 do {Result of FindFirst/Nex...
Give a code snippet in #Pascal Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#Rust
Rust
fn integral<F>(f: F, range: std::ops::Range<f64>, n_steps: u32) -> f64 where F: Fn(f64) -> f64 { let step_size = (range.end - range.start)/n_steps as f64;   let mut integral = (f(range.start) + f(range.end))/2.; let mut pos = range.start + step_size; while pos < range.end { integral += f(pos...
Give a code snippet in #Rust Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to mak...
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...
#Forth
Forth
: f+! ( x addr -- ) dup f@ f+ f! ;   : st-count ( stats -- n ) f@ ; : st-sum ( stats -- sum ) float+ f@ ; : st-sumsq ( stats -- sum*sum ) 2 floats + f@ ;   : st-mean ( stats -- mean ) dup st-sum st-count f/ ;   : st-variance ( stats -- var ) dup st-sumsq dup st-mean fdup f* dup st-count...
Give a code snippet in #Forth 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 funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#F.23
F#
  // Longest ascending and decending sequences of difference between consecutive primes: Nigel Galloway. April 5th., 2021 let fN g fW=primes32()|>Seq.takeWhile((>)g)|>Seq.pairwise|>Seq.fold(fun(n,i,g)el->let w=fW el in match w>n with true->(w,el::i,g) |_->(w,[el],if List.length i>List.length g then i else g))(0,[],[]) ...
Give a code snippet in #F.23 Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for prime...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Java
Java
import java.io.StringWriter;   import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamR...
Give a code snippet in #Java Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> ele...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#360_Assembly
360 Assembly
* Last Sunday of each month 31/01/2017 LASTSUND CSECT USING LASTSUND,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) ...
Give a code snippet in #360_Assembly Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04...
christopher/rosetta-code