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/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   # SEMA do link OF splice = LEVEL 1 # MODE LINK = STRUCT ( REF LINK prev, REF LINK next, DATA value );   # BEGIN rosettacode task specimen code: can handle insert both before the first, and after the last link #   PROC insert after = (REF LINK #self,# prev, DATA new data)LINK: ...
Give a code snippet in #ALGOL_68 Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#PHP
PHP
header("Content-Type: image/png");   $w = 256; $h = 256;   $im = imagecreate($w, $h) or die("Cannot Initialize new GD image stream");   $color = array(); for($i=0;$i<256;$i++) { array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i)); }   for($i=0;$i<$w;$i++) { for($j=0;$j<...
Give a code snippet in #PHP Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
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 ≤...
#Hope
Hope
$ cd lib $ ../src/hope >: dec add : num # num -> num; >: --- add(a,b) <= a + b; >: add(3,99) >: ^D >> 102 : num
Give a code snippet in #Hope 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/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#Nim
Nim
echo "£" echo "札幌"   import unicode echo Rune(0xa3)
Give a code snippet in #Nim Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::Testing... call :toArabic MCMXC echo MCMXC = !arabic! call :toArabic MMVIII echo MMVIII = !arabic! call :toArabic MDCLXVI echo MDCLXVI = !arabic! call :toArabic CDXLIV echo CDXLIV = !arabic! call :toArabic XCIX echo XCIX = !arabic! pause>nul exit/b 0 ::The "function"... :to...
Give a code snippet in #Batch_File Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Symsyn
Symsyn
  x : 10 1   (2^2) x.2 (3^3) x.3 (4^4) x.4 (5^5) x.5 (6^6) x.6 (7^7) x.7 (8^8) x.8 (9^9) x.9   1 i if i <= 5000 ~ i $i | convert binary to string #$i j | length to j y | set y to 0 if j > 0 $i.j $j 1 | move digit j to string j ~ $j n | c...
Give a code snippet in #Symsyn A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Forth
Forth
: xt-array here { a } 10 cells allot 10 0 do :noname i ]] literal dup * ; [[ a i cells + ! loop a ;   xt-array 5 cells + @ execute .
Give a code snippet in #Forth Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PHP
PHP
function gnomeSort($arr){ $i = 1; $j = 2; while($i < count($arr)){ if ($arr[$i-1] <= $arr[$i]){ $i = $j; $j++; }else{ list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); $i--; if($i == 0){ $i = $j; $j++; } } } return $arr; } $arr = array(3,1,6,2,9,4,7,8,5); echo implode(',',gnom...
Give a code snippet in #PHP 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/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Raku
Raku
sub group-chars ($str) { $str.comb: / (.) $0* / }   # Testing:   for Q[gHHH5YY++///\], Q[fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦‍♂️👨‍👩‍👧‍👦] -> $string { put 'Original: ', $string; put ' Split: ', group-chars($string).join(', '); }
Give a code snippet in #Raku Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#M2000_Interpreter
M2000 Interpreter
  Module Assert { \\ This is a global object named Rec Global Group Rec { Private: document doc$="Error List at "+date$(today)+" "+time$(now)+{ } Public: lastfilename$="noname.err" Module Error(a$) { if a$="" then exit ...
Give a code snippet in #M2000_Interpreter Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Monicelli
Monicelli
  che cosè var? # switch var minore di 0: # case var < 0 ... maggiore di 0: # case var > 0 ... o tarapia tapioco: # else (none of the previous cases) ... e velocità di esecuzione  
Give a code snippet in #Monicelli Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Com...
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....
#REXX
REXX
/* call stack */ say 'Call A' call A '123' say result exit 0   A: say 'Call B' call B '456' say result return ARG(1)   B: say 'Call C' call C '789' say result return ARG(1)   C: call callstack return ARG(1)   callstack: procedure getcallstack(cs.) say 'Dump call stack with' cs.0 'items' do i = 1 to cs.0 parse var c...
Give a code snippet in #REXX 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 pla...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П1 <-> П0 П2 ИП0 ИП1 1 + - x>=0 23 ИП2 ИП0 ИП1 - * П2 ИП0 ИП1 - П1 БП 04 ИП2 С/П
Give a code snippet in #.D0.9C.D0.9A-61.2F52 The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Python
Python
def consolidate(sets): setlist = [s for s in sets if s] for i, s1 in enumerate(setlist): if s1: for s2 in setlist[i+1:]: intersection = s1.intersection(s2) if intersection: s2.update(s1) s1.clear() s1...
Give a code snippet in #Python Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#Common_Lisp
Common Lisp
(defun cursor-positioning () (with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil) (move scr 5 2) (princ "Hello" scr) (refresh scr) ;; wait for keypress (get-char scr)))
Give a code snippet in #Common_Lisp Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
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...
#Java
Java
import java.util.function.DoubleSupplier;   public class ManOrBoy {   static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {   DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDou...
Give a code snippet in #Java 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#REBOL
REBOL
print system/network/host
Give a code snippet in #REBOL Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#BBC_BASIC
BBC BASIC
PRINT FNformat(PI, 9, 3) PRINT FNformat(-PI, 9, 3) END   DEF FNformat(n, sl%, dp%) LOCAL @% @% = &1020000 OR dp% << 8 IF n >= 0 THEN = RIGHT$(STRING$(sl%,"0") + STR$(n), sl%) ENDIF = "-" + RIGHT$(STRING$(sl%,"0") + STR$(-n), sl%-1)
Give a code snippet in #BBC_BASIC Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#AWK
AWK
  # syntax: GAWK -f SMITH_NUMBERS.AWK # converted from C BEGIN { limit = 10000 printf("Smith Numbers < %d:\n",limit) for (a=4; a<limit; a++) { num_factors = num_prime_factors(a) if (num_factors < 2) { continue } prime_factors(a) if (sum_digits(a) == sum_factors(num_fact...
Give a code snippet in #AWK Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are al...
christopher/rosetta-code
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#MATLAB
MATLAB
  % Percentage difference between images function p = PercentageDifferenceBetweenImages(im1,im2)   if numel(im1)~=numel(im2), error('Error: images have to be the same size'); end   d = abs(single(im1) - single(im2))./255; p = sum(d(:))./numel(im1)*100;   disp(['Percentage difference between images is: ', num2str(p)...
Give a code snippet in #MATLAB basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The e...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#langur
langur
val .farey = f(.n) { var .a, .b, .c, .d = 0, 1, 1, .n while[=[[0, 1]]] .c <= .n { val .k = (.n + .b) // .d .a, .b, .c, .d = .c, .d, .k x .c - .a, .k x .d - .b _while ~= [[.a, .b]] } }   writeln "Farey sequence for orders 1 through 11" for .i of 11 { writeln $"\.i:2;: ", join " ",...
Give a code snippet in #langur The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a ...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Haskell
Haskell
import System.IO (hFlush, stdout) main = do putStr "Enter a string: " hFlush stdout str <- getLine putStr "Enter an integer: " hFlush stdout num <- readLn :: IO Int putStrLn $ str ++ (show num)
Give a code snippet in #Haskell User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#ALGOL_68
ALGOL 68
main:(   SHORT SHORT INT ssdec = SHORT SHORT 727, sshex = ABS SHORT SHORT 16r2d7, ssoct = ABS SHORT SHORT 8r1327, ssbin = ABS SHORT SHORT 2r1011010111;   SHORT INT sdec = SHORT 727, shex = ABS SHORT 16r2d7, soct = ABS SHORT 8r1327, sbin = ABS S...
Give a code snippet in #ALGOL_68 Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#VBScript
VBScript
  class playingcard dim suit dim pips end class   class carddeck private suitnames private pipnames private cardno private deck(52) private nTop   sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0   for suit = 1 to 4...
Give a code snippet in #VBScript Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the curren...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain *> This is GNUCOBOL 2.0 identification division. program-id. beadsort. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 filler. 03 row occurs 9 pic x(9). 03 r...
Give a code snippet in #COBOL Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Table[Last /@ Reverse@Tally[First /@ IntegerPartitions[n]], {n, 10}] // Grid
Give a code snippet in #Mathematica_.2F_Wolfram_Language This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#J
J
  IGNORE=: ;:'y(0)1',CR   Filter=: (#~`)(`:6)   NB. extract tokens from a large body newline terminated of text roughparse=: ;@(<@;: ::(''"_);._2)   NB. count frequencies and get the top x top=: top=: {. \:~@:((#;{.)/.~)   NB. read all installed script (.ijs) files and concatenate them JSOURCE=:...
Give a code snippet in #J Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#D
D
import std.stdio, std.string;   void main() { // Delimited strings: a 'q' followed by double quotes and an // opening and closing delimiter of choice:   q"[a string that you "don't" have to escape]" .writeln;   // If the delimiter is an identifier, the identifier must be // immediately followed ...
Give a code snippet in #D A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#D
D
  (require 'math) ;; converts a finite polynomial (a_0 a_1 .. a_n) to an infinite serie (a_0 ..a_n 0 0 0 ...) (define (poly->stream list) (make-stream (lambda(n) (cons (if (< n (length list)) (list-ref list n) 0) (1+ n))) 0))   ;; c = a + b , c_n = a_n + b_n (define (s-add a b) (make-stream (lambda (n) (cons (+ (str...
Give a code snippet in #D A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#OCaml
OCaml
let nums = [|2; 4; 3; 1; 2|] Array.sort compare nums
Give a code snippet in #OCaml Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <algorithm>   std::vector<int> properDivisors ( int number ) { std::vector<int> divisors ; for ( int i = 1 ; i < number / 2 + 1 ; i++ ) if ( number % i == 0 ) divisors.push_back( i ) ; return divisors ; }   int main( ) { std::vector<int> divisors ; u...
Give a code snippet in #C.2B.2B The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper div...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Forth
Forth
: accumulator create ( n -- ) , does> ( n -- acc+n ) tuck +! @ ;   0 accumulator foo   1 foo . \ 1 2 foo . \ 3 3 foo . \ 6
Give a code snippet in #Forth A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pas...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Brace
Brace
#!/usr/bin/env bx use b   Main(): num outside = 16, ox = -0.5, oy = 0, r = 1.5 long i, max_i = 100, rb_i = 30 space() uint32_t *px = pixel() num d = 2*r/h, x0 = ox-d*w_2, y0 = oy+d*h_2 for(y, 0, h): cmplx c = x0 + (y0-d*y)*I repeat(w): cmplx w = 0 for i=0; i < max_i && cabs(w) < outside; ++i w = w*w...
Give a code snippet in #Brace Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Ring
Ring
  see new point {x=10 y=20} class point x y  
Give a code snippet in #Ring Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Re...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Wren
Wren
/* speech_synthesis.wren */   class C { foreign static getInput(maxSize)   foreign static espeak(s) }   System.write("Enter something to say (up to 100 characters) : ") var s = C.getInput(100) C.espeak(s)
Give a code snippet in #Wren Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#Lingo
Lingo
---------------------------------------- -- Sends email via SMTP using senditquiet.exe (15 KB) -- @param {string} fromAddr -- @param {string} toAddr - multiple addresses separated with ; -- @param {string} subject -- @param {string} message - use "\n" for line breaks -- @param {string} [cc=VOID] - optional; multiple ad...
Give a code snippet in #Lingo Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Racket
Racket
  #lang racket/gui (require slideshow/pict)   (define-values (*width* *height*) (values 400 40))   (define (shades inc) (for/list ([scale (in-range 0 (+ 1 inc) inc)]) (round (* 255 scale))))   (define (grays increment direction) (define colors (shades increment)) (apply hc-append ((if (eq? direction ...
Give a code snippet in #Racket The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we ...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#EchoLisp
EchoLisp
  ;; implementation of Floyd algorithm to find cycles in a graph ;; see Wikipedia https://en.wikipedia.org/wiki/Cycle_detection ;; returns (cycle-length cycle-starter steps) ;; steps = 0 if no cycle found ;; it's all about a tortoise 🐢 running at speed f(x) after a hare 🐰 at speed f(f (x)) ;; when they meet, a cycle...
Give a code snippet in #EchoLisp An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classificati...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Factor
Factor
USING: formatting io io.encodings.utf8 io.files kernel math sequences sets splitting ; IN: rosetta-code.abbreviations-automatic   : map-head ( seq n -- seq' ) [ short head ] curry map ;   : unique? ( seq n -- ? ) map-head all-unique? ;   : (abbr-length) ( seq -- n ) 1 [ 2dup unique? ] [ 1 + ] until nip ;   : abbr-l...
Give a code snippet in #Factor The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or de...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#PL.2FI
PL/I
(stringrange, stringsize): /* 2 Nov. 2013 */ Mad_Libs: procedure options (main); declare (line, left, right) character (100) varying; declare true bit(1) value ('1'b), false bit (1) value ('0'b); declare name character (20) varying, seen_name bit (1) initial (false); declare...
Give a code snippet in #PL.2FI This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#Ruby
Ruby
require 'curses'   Curses.init_screen begin Curses.setpos(6, 3) # column 6, row 3 Curses.addstr("Hello")   Curses.getch # Wait until user presses some key. ensure Curses.close_screen end
Give a code snippet in #Ruby Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#11l
11l
F check_isin(a) I a.len != 12 R 0B [Int] s L(c) a I c.is_digit() I L.index < 2 R 0B s.append(c.code - 48) E I c.is_uppercase() I L.index == 11 R 0B V (d, m) = divmod(c.code - 55, 10) s [+]= [d, m] E R 0B V ...
Give a code snippet in #11l An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct f...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#SNOBOL4
SNOBOL4
terminal = "Error" output = "Normal text" end
Give a code snippet in #SNOBOL4 Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard ou...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Delphi
Delphi
  program RIPEMD160;   {$APPTYPE CONSOLE}   uses System.SysUtils, DCPripemd160;   function HashRipemd160(const Input: Ansistring): TArray<byte>; var Hasher: TDCP_ripemd160; begin Hasher := TDCP_ripemd160.Create(nil); try Hasher.Init; Hasher.UpdateStr(Input); SetLength(Result, Hasher.HashSize div 8...
Give a code snippet in #Delphi RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the A...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#jq
jq
julia> dict1 = Dict("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow") Dict{String,Any} with 3 entries: "name" => "Rocket Skates" "price" => 12.75 "color" => "yellow" julia> dict2 = Dict("price" => 15.25, "color" => "red", "year" => 1974) Dict{String,Any} with 3 entries: "price" => 15.25 "yea...
Give a code snippet in #jq Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#REXX
REXX
/*REXX program creates a new empty file and directory in current directory and root dir.*/ fn= 'input.txt' /*default name of a file. */ dn= 'docs' /*default name of a directory (folder).*/ @.1= 'current directory'; @.2= 'root directory...
Give a code snippet in #REXX Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#8086_Assembly
8086 Assembly
.model small .stack 1024 .data ;data segment is unused in this program .code   start:   mov ax,@code mov ds,ax mov es,ax   cld ;make lodsb, etc. auto-increment   mov al, byte ptr [ds:LeadingZeroes] mov cl,al mov ch,0 mov al,'0' ;30h jcxz DonePrintingLeadingZeroes ;there are le...
Give a code snippet in #8086_Assembly Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#GAP
GAP
mode := function(v) local c, m; c := Collected(SortedList(v)); m := Maximum(List(c, x -> x[2])); return List(Filtered(c, x -> x[2] = m), y -> y[1]); end;   mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]); # [ 5, 6 ]
Give a code snippet in #GAP Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if poss...
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...
#PARI.2FGP
PARI/GP
toBase(n,b)={ my(s="",t); while(n, t=n%b; n\=b; s=Str(if(t<=9,t,Strchr(Vecsmall([87+t]))),s) ); if(#s,s,"0") }; fromBase(s,b)={ my(t=0); s=Vecsmall(s); for(i=1,#s,1, t=b*t+s[i]-if(s[i]<58,48,87) ); t };
Give a code snippet in #PARI.2FGP 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 bi...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#jq
jq
# An empty queue: def fifo: [];   def push(e): [e] + .;   def pop: [.[0], .[1:]];   def pop_or_error: if length == 0 then error("pop_or_error") else pop end;   def empty: length == 0;
Give a code snippet in #jq Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the orde...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#RapidQ
RapidQ
$INCLUDE "rapidq.inc"   DIM File1 AS QFileStream DIM File2 AS QFileStream   File1.Open("input.txt", fmOpenRead) File2.Open("output.txt", fmCreate)   WHILE NOT File1.EOF data$ = File1.ReadLine File2.WriteLine(data$) WEND   File1.Close File2.Close
Give a code snippet in #RapidQ File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Nemerle
Nemerle
using System; using System.Console;   module IsNumeric { IsNumeric( input : string) : bool { mutable meh = 0.0; // I don't want it, not going to use it, why force me to declare it? double.TryParse(input, out meh) }   Main() : void { def num = "-1.2345E6"; def not = "...
Give a code snippet in #Nemerle Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Scheme
Scheme
  (define (dec x) (- x 1))   (define (halve x) (/ x 2))   (define (row*col row col) (apply + (map * row col)))   (define (matrix-multiply m1 m2) (map (lambda (row) (apply map (lambda col (row*col row col)) m2)) m1))   (define (matrix-exp mat exp) (cond ((= exp 1) mat) ((even?...
Give a code snippet in #Scheme Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Free_Pascal
Free Pascal
array2 := array0 + array1
Give a code snippet in #Free_Pascal 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/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...
#PHP
PHP
<?php function encode($str) { return preg_replace_callback('/(.)\1*/', function ($match) { return strlen($match[0]) . $match[1]; }, $str); }   function decode($str) { return preg_replace_callback('/(\d+)(\D)/', function($match) { return str_repeat($match[2], $match[1]); }, $str); }   ech...
Give a code snippet in #PHP 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 functi...
christopher/rosetta-code
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers
Index finite lists of positive integers
It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an integer to any finite, arbi...
#J
J
scrunch=:3 :0 n=.1x+>./y #.(1#~##:n),0,n,&#:n#.y )   hcnurcs=:3 :0 b=.#:y m=.b i.0 n=.#.m{.(m+1)}.b n #.inv#.(1+2*m)}.b )
Give a code snippet in #J It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#bc
bc
s = 1 /* Seed of the random number generator */   /* Random number from 1 to 20. */ define r() { auto r while (1) { /* * Formula (from POSIX) for random numbers of low * quality, from 0 to 32767. */ s = (s * 1103515245 + 12345) % 4294967296 r = (s / 65536) % 32768   /* Prevent modulo bias. */ if (r...
Give a code snippet in #bc Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#GFA_Basic
GFA Basic
  ' ' Greatest Common Divisor ' a%=24 b%=112 PRINT "GCD of ";a%;" and ";b%;" is ";@gcd(a%,b%) ' ' Function computes gcd ' FUNCTION gcd(a%,b%) LOCAL t% ' WHILE b%<>0 t%=a% a%=b% b%=t% MOD b% WEND ' RETURN ABS(a%) ENDFUNC  
Give a code snippet in #GFA_Basic Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   grea...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Scala
Scala
object Singleton { // any code here gets executed as if in a constructor }
Give a code snippet in #Scala A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Euphoria
Euphoria
sequence row row = {} for m = 1 to 10 do row = row & 1 for n = length(row)-1 to 2 by -1 do row[n] += row[n-1] end for print(1,row) puts(1,'\n') end for
Give a code snippet in #Euphoria Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eit...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"TIMERLIB"   DIM test%(9) test%() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1   FOR i% = 0 TO DIM(test%(),1) p% = EVAL("!^PROCtask" + STR$(i%)) tid% = FN_ontimer(100 + test%(i%), p%, 0) NEXT   REPEAT WAIT 0 UNTIL FALSE   DEF PROCtask0 : PRIN...
Give a code snippet in #BBC_BASIC 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 | Quic...
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...
#Lua
Lua
str = " \t \r \n String with spaces \t \r \n "   print( string.format( "Leading whitespace removed: %s", str:match( "^%s*(.+)" ) ) ) print( string.format( "Trailing whitespace removed: %s", str:match( "(.-)%s*$" ) ) ) print( string.format( "Leading and trailing whitespace removed: %s", str:match( "^%s*(.-)%s*$" ) )...
Give a code snippet in #Lua 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/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Forth
Forth
: flog2 ( f -- f ) fln 2e fln f/ ;   create freq 256 cells allot   : entropy ( str len -- f ) freq 256 cells erase tuck bounds do i c@ cells freq + 1 swap +! loop 0e 256 0 do i cells freq + @ ?dup if s>f dup s>f f/ fdup flog2 f* f- then loop drop ;   s" 1223334444" entropy f....
Give a code snippet in #Forth Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), ...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#JavaScript
JavaScript
const x = 2.0; const xi = 0.5; const y = 4.0; const yi = 0.25; const z = x + y; const zi = 1.0 / (x + y); const pairs = [[x, xi], [y, yi], [z, zi]]; const testVal = 0.5;   const multiplier = (a, b) => m => a * b * m;   const test = () => { return pairs.map(([a, b]) => { const f = multiplier(a, b); const resul...
Give a code snippet in #JavaScript In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to...
christopher/rosetta-code
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Python
Python
import sys import pygame   pygame.init()   # Create a clock (for framerating) clk = pygame.time.Clock()   # Grab joystick 0 if pygame.joystick.get_count() == 0: raise IOError("No joystick detected") joy = pygame.joystick.Joystick(0) joy.init()   # Create display size = width, height = 600, 600 screen = pygame.displ...
Give a code snippet in #Python The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the exten...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#REXX
REXX
/* REXX --------------------------------------------------------------- * 08.02.2014 Walter Pachl *--------------------------------------------------------------------*/ say xrange('a','z')
Give a code snippet in #REXX Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a r...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#APL
APL
  ⍝⍝ GNU APL ]help ⍬ niladic function: Z ← ⍬ (Zilde) Zilde is the empty numeric vector (aka. ⍳0) Not a function but rather an alias for the empty vector: ⍬≡⍳0 1  
Give a code snippet in #APL Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#Wren
Wren
import "/fmt" for Fmt   var prod = 1 var sum = 0 var x = 5 var y = -5 var z = -2 var one = 1 var three = 3 var seven = 7 var p = 11.pow(x) var j = 0   var process = Fn.new { sum = sum + j.abs if (prod.abs < (1 << 27) && j != 0) prod = prod * j }   j = -three while (j <= 3.pow(3)) { process.call() j = j ...
Give a code snippet in #Wren Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED a...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Erlang
Erlang
  -mode(compile). -import(lists, [foldl/3]).   main(_) -> {ok, Tmat} = file:open("triangle.txt", [read, raw, {read_ahead, 16384}]), Max = max_sum(Tmat, []), io:format("The maximum total is ~b~n", [Max]).   max_sum(FD, Last) -> case file:read_line(FD) of eof -> foldl(fun erlang:max/2, 0, Last); ...
Give a code snippet in #Erlang Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Ursa
Ursa
def exists (string filename) decl file f try f.open filename return true catch ioerror return false end try end exists
Give a code snippet in #Ursa Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#EchoLisp
EchoLisp
  ;; from Racket (define count-substring (compose length regexp-match*))   (count-substring "aab" "graabaabdfaabgh") ;; substring → 3 (count-substring "/ .e/" "Longtemps je me suis couché de bonne heure") ;; regexp → 4  
Give a code snippet in #EchoLisp Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Nim
Nim
import httpclient, strutils   var client = newHttpClient()   var res: string for line in client.getContent("https://rosettacode.org/wiki/Talk:Web_scraping").splitLines: let k = line.find("UTC") if k >= 0: res = line[0..(k - 3)] let k = res.rfind("</a>") res = res[(k + 6)..^1] break echo if res.len >...
Give a code snippet in #Nim Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Lua
Lua
function map_range( a1, a2, b1, b2, s ) return b1 + (s-a1)*(b2-b1)/(a2-a1) end   for i = 0, 10 do print( string.format( "f(%d) = %f", i, map_range( 0, 10, -1, 0, i ) ) ) end
Give a code snippet in #Lua Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly map...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Emacs_Lisp
Emacs Lisp
(defun series (n) (when (<= n 0) (user-error "n must be positive")) (apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))   (format "%.10f" (series 1000)) ;=> "1.6439345667"
Give a code snippet in #Emacs_Lisp Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#J
J
cf=: _1 1 ,@}. (, <.)@%@-/ ::]^:a:@(, <.)@(%&x:/)
Give a code snippet in #J Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t ...
christopher/rosetta-code
http://rosettacode.org/wiki/French_Republican_calendar
French Republican calendar
Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of...
#F.23
F#
  // French Republican Calander: Nigel Galloway. April 16th., 2021 let firstDay=System.DateTime.Parse("22/9/1792") type monthsFRC= Vendemiaire = 0 |Brumaire = 30 |Frimaire = 60 |Nivose = 90 |Pluviose = 120 |Ventose = 150 ...
Give a code snippet in #F.23 Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor...
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
#Objective-C
Objective-C
NSArray *keys = @[@"a", @"b", @"c"]; NSArray *values = @[@1, @2, @3]; NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
Give a code snippet in #Objective-C 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/Sort_stability
Sort stability
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.Arrays; import java.util.Comparator;   public class RJSortStability {   public static void main(String[] args) { String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };   String[] cn = cityList.clone(); System.out.println("\nBefore sort:"); for (Stri...
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/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Brainf.2A.2A.2A
Brainf***
[-]>,[>,]<[.<]
Give a code snippet in #Brainf.2A.2A.2A Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a str...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Ela
Ela
open monad io do putStrLn "Hello world!" ::: IO
Give a code snippet in #Ela Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Fexl
Fexl
  # (fib n) = the nth Fibonacci number \fib= ( \loop== (\x\y\n le n 0 x; \z=(+ x y) \n=(- n 1) loop y z n ) loop 0 1 )     # Now test it: for 0 20 (\n say (fib n))  
Give a code snippet in #Fexl 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/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Icon_and_Unicon
Icon and Unicon
procedure main() L:=[ thread write("Enjoy"), thread write("Rosetta"), thread write("Code") ] every wait(!L) end
Give a code snippet in #Icon_and_Unicon Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Sidef
Sidef
func lookandsay(str) { str.gsub(/((.)\2*)/, {|a,b| a.len.to_s + b }); }   var num = "1"; { say num; num = lookandsay(num); } * 10;
Give a code snippet in #Sidef The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Java
Java
  public class Main { public static void main(String[] args) { for(int i = 0 ; i <= 5000 ; i++ ){ int val = String.valueOf(i).chars().map(x -> (int) Math.pow( x-48 ,x-48)).sum(); if( i == val){ System.out.println( i + " (munchausen)"); } } } } ...
Give a code snippet in #Java A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#DCL
DCL
$ list = "1,2,3,4,5" $ call reduce list "+" $ show symbol result $ $ numbers = "5,4,3,2,1" $ call reduce numbers "-" $ show symbol result $ $ call reduce list "*" $ show symbol result $ exit $ $ reduce: subroutine $ local_list = 'p1 $ value = f$integer( f$element( 0, ",", local_list )) $ i = 1 $ loop: $ element = f$el...
Give a code snippet in #DCL Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. S...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Tailspin
Tailspin
  processor EinsteinSolver @: [{|{}|}]; // A list of possible relations, start with one relation with an empty tuple $ -> \( when <[](1..)> do def variableRange: $(1); @EinsteinSolver: [($@EinsteinSolver(1) join {|{by $variableRange...}|})]; $(2..last) -> # \) -> !VOID   sink isFact de...
Give a code snippet in #Tailspin Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Pascal
Pascal
Program TempFileDemo;   uses SysUtils;   var tempFile: text;   begin assign (Tempfile, GetTempFileName); rewrite (tempFile); writeln (tempFile, 5); close (tempFile); end.
Give a code snippet in #Pascal Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race condition...
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Tcl
Tcl
# Model the data as nested lists, as that is a natural fit for Tcl set basicRecords { { jsmith x 1001 1000 { {Joe Smith} {Room 1007} (234)555-8917 (234)555-0077 jsmith@rosettacode.org } /home/jsmith /bin/bash } { jdoe x 1002 1000 { {Jane Doe} {Room 1004} ...
Give a code snippet in #Tcl Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most use...
christopher/rosetta-code
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#J
J
NB. transform and inverse bwt=: {:"1@:(/:~ :[:)@:(|."0 1~ -@:i.@:#)@:((2{a.) , ,&(3{a.))@:(([ ('STX or ETX invalid in input' (13!:8) 21 + 0:))^:(1 e. (2 3{a.)&e.)) :.(}.@:}:@:({~ ((3{a.) [: :i.~ {:"1))@:((,"0 1 /:~ :[:)^:(#@[)&(0$00))) NB. demonstrate the transform A=: <@bwt ;._2 ] 0 :0 tests[0] = "ban...
Give a code snippet in #J This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transfor...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Clojure
Clojure
(let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]] (let [idx (.indexOf haystack "Zig")] (if (neg? idx) (throw (Error. "item not found.")) idx)))
Give a code snippet in #Clojure Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle ...
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#Nim
Nim
import random, sequtils, strutils   type Node = ref object value: int left, right: Node     proc add(tree: var Node; value: int) = ## Add a node to a tree (or subtree), insuring values are in increasing order. if tree.isNil: tree = Node(value: value) elif value <= tree.value: tree.left.add value els...
Give a code snippet in #Nim Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#D
D
import std.stdio, std.random, std.math;   struct NormalRandom { double mean, stdDev;   // Necessary because it also defines an opCall. this(in double mean_, in double stdDev_) pure nothrow { this.mean = mean_; this.stdDev = stdDev_; }   double opCall() const /*nothrow*/ { imm...
Give a code snippet in #D Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#NewLISP
NewLISP
  (context 'ABC)   (define (remove-lines-from-a-file filename start num) (setf new-content "") (setf row-counter 0) (setf start-delete-row start) (setf end-delete-row (+ start num -1)) (setf file-content (read-file filename)) (setf max-rows (length (parse file-content "\n" 0)))   (cond ...
Give a code snippet in #NewLISP Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to r...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   rn = Random() maxElmts = 100 dlist = double[maxElmts] rlist = Rexx[maxElmts] loop r_ = 0 to maxElmts - 1 nr = rn.nextGaussian * 100.0 dlist[r_] = nr rlist[r_] = Rexx(nr) end r_   say 'Max double:' Rexx(getMax(dlist)).format(4...
Give a code snippet in #NetRexx Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#BASIC
BASIC
FOR n = 1 TO 15 COLOR n PRINT "Rosetta Code" NEXT
Give a code snippet in #BASIC Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to ...
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...
#ALGOL_W
ALGOL W
begin  % algol W doesn't have standard case conversion routines, this is one way %  % such facilities could be provided  %    % converts text to upper case  %  % assumes the letters are contiguous in the character set (as in ASC...
Give a code snippet in #ALGOL_W 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...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Robotic
Robotic
  set "$str1" to "annoy" set "$str2" to "annoy" : "loop" if "$str1" === "$str2" then "case_equal" if "$str1" = "$str2" then "equal" if "$str1" > "$str2" then "greater_than" if "$str1" < "$str2" then "less_than" end   : "case_equal" * "&$str1& is case equal to &$str2&" set "$str2" to "ANNOY" goto "loop"   : "equal" * "&...
Give a code snippet in #Robotic 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/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Perl
Perl
#!/usr/bin/perl   my $min = 1; my $max = 99; my $guess = int(rand $max) + $min; my $tries = 0;   print "=>> Think of a number between $min and $max and I'll guess it!\n Press <ENTER> when are you ready... ";   <STDIN>;   { do {   $tries++; print "\n=>> My guess is: $guess Is your number higher, lo...
Give a code snippet in #Perl Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The c...
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 ...
#11l
11l
F jortsort(sequence) R Array(sequence) == sorted(sequence)   F print_for_seq(seq) print(‘jortsort(#.) is #.’.format(seq, jortsort(seq)))   print_for_seq([1, 2, 4, 3]) print_for_seq([14, 6, 8]) print_for_seq([‘a’, ‘c’]) print_for_seq(‘CVGH’) print_for_seq(‘PQRST’)
Give a code snippet in #11l 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/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#PARI.2FGP
PARI/GP
pi()={ my(x=Pi,n=0,t); print1("3."); while(1, if(n>=default(realprecision), default(realprecision,default(realprecision)*2); x=Pi ); print1(floor(x*10^n++)%10) ) };
Give a code snippet in #PARI.2FGP Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal ...
christopher/rosetta-code