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/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
#Perl
Perl
my $PI = 2 * atan2 1, 0;   my @nums = map { 1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand) } 1..1000;
Give a code snippet in #Perl 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#MATLAB
MATLAB
function digest = md5(message) % digest = md5(message) % Compute the MD5 digest of the message, as a hexadecimal digest.   % Follow the MD5 algorithm from RFC 1321 [1] and Wikipedia [2]. % [1] http://tools.ietf.org/html/rfc1321 % [2] http://en.wikipedia.org/wiki/MD5   % m is the modulus for 3...
Give a code snippet in #MATLAB Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the...
christopher/rosetta-code
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => {   const f90 = dct => x2 => dct[x2], f60 = dct => (x2, ab) => dct[x2 - ab], f120 = dct => (x2, ab) => dct[x2 + ab], f60unequal = dct => (x2, ab, a, b) => (a !== b) ? ( ...
Give a code snippet in #JavaScript The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   9...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
start = 97; lowerCaseLetters = Table[FromCharacterCode[start + i], {i, 0, 25}]
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#zkl
zkl
hi:= // 0==empty cell, X==not a cell #<<< "0 33 35 0 0 X X X 0 0 24 22 0 X X X 0 0 0 21 0 0 X X 0 26 0 13 40 11 X X 27 0 0 0 9 0 1 X X X 0 0 18 0 0 X X X X X 0 7 0 0 X X X X X X 5 0"; #<<<   board,given,...
Give a code snippet in #zkl The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connecte...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#LabVIEW
LabVIEW
'hello dup
Give a code snippet in #LabVIEW This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Octave
Octave
% read a string ("s") s = input("Enter a string: ", "s");   % read a GNU Octave expression, which is evaluated; e.g. % 5/7 gives 0.71429 i = input("Enter an expression: ");   % parse the input for an integer printf("Enter an integer: "); ri = scanf("%d");   % show the values disp(s); disp(i); disp(ri);
Give a code snippet in #Octave 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/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
#Oz
Oz
declare fun {ZipRecord Keys Values} {List.toRecord unit {List.zip Keys Values MakePair}} end   fun {MakePair A B} A#B end in {Show {ZipRecord [a b c] [1 2 3]}}
Give a code snippet in #Oz 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/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Stata
Stata
. mat a=1,2,3\4,5,6 . mat b=1,1,0,0\1,0,0,1\0,0,1,1 . mat c=a*b . mat list c   c[2,4] c1 c2 c3 c4 r1 3 1 3 5 r2 9 4 6 11
Give a code snippet in #Stata Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ...
#Haskell
Haskell
module Main where   import Text.Printf (printf) import System.Environment (getArgs, getProgName)   tochka = ("tochka" , 0.000254) liniya = ("liniya" , 0.00254) centimeter = ("centimeter", 0.01) diuym = ("diuym" , 0.0254) vershok = ("vershok" , 0.04445) piad = ("piad" , 0.1778) fut...
Give a code snippet in #Haskell Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert an...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Fantom
Fantom
  using xml   class XmlOutput { public static Void main () { Str[] names := ["April", "Tam O'Shanter", "Emily"] Str[] remarks := ["Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"]   doc := XDoc() root := XElem("CharacterRema...
Give a code snippet in #Fantom Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> e...
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
#Picat
Picat
main => print("Enter a string: "), String = read_line(), print("Enter a number: "), Number = read_int(), println([string=String,number=Number]).
Give a code snippet in #Picat 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/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Ursala
Ursala
choices = ^(iota@r,~&l); leql@a^& ~&al?\&! ~&arh2fabt2RDfalrtPXPRT
Give a code snippet in #Ursala Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 ...
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 ...
#Seed7
Seed7
var array integer: nums is [] (2, 4, 3, 1, 2);   nums := sort(nums);
Give a code snippet in #Seed7 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/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Niue
Niue
  [ [ , len 1 - at ! ] len 3 - times swap , ] 'map ; ( a Lisp like map, to sum the stack ) [ len 'n ; [ + ] 0 n swap-at map n / ] 'avg ;   1 2 3 4 5 avg . => 3 3.4 2.3 .01 2.0 2.1 avg . => 1.9619999999999997  
Give a code snippet in #Niue Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an estab...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
BestShuffle[data_] := Flatten[{data,First[SortBy[ List[#, StringLength[data]-HammingDistance[#,data]] & /@ StringJoin /@ Permutations[StringSplit[data, ""]], Last]]}]   Print[#[[1]], "," #[[2]], ",(", #[[3]], ")"] & /@ BestShuffle /@ {"abracadabra","seesaw","elk","grrrrrr","up","a"}  
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces th...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Action.21
Action!
SET EndProg=*
Give a code snippet in #Action.21 Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Fortran
Fortran
module convex_hulls ! ! Convex hulls by Andrew's monotone chain algorithm. ! ! For a description of the algorithm, see ! https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169 ! ! For brevity in the task, I shall use the built-in "complex" ty...
Give a code snippet in #Fortran Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (1...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Python
Python
>>> 5**3**2 1953125 >>> (5**3)**2 15625 >>> 5**(3**2) 1953125 >>> # The following is not normally done >>> try: from functools import reduce # Py3K except: pass   >>> reduce(pow, (5, 3, 2)) 15625 >>>
Give a code snippet in #Python This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#R
R
for(a in seq(2,8,2)) { cat(a, ", ") } cat("who do we appreciate?\n")
Give a code snippet in #R Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increme...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Liberty_BASIC
Liberty BASIC
' LB has inbuilt 'name' command, but can also run batch files   nomainwin   name "input.txt" as "output.txt" run "cmd.exe /c ren docs mydocs", HIDE name "C:\input.txt" as "C:\output.txt" run "cmd.exe /c ren C:\docs mydocs", HIDE   end
Give a code snippet in #Liberty_BASIC Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user ha...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Bracmat
Bracmat
( ( powerset = done todo first .  !arg:(?done.?todo) & (  !todo:%?first ?todo & (powerset$(!done !first.!todo),powerset$(!done.!todo)) | !done ) ) & out$(powerset$(.1 2 3 4)) );
Give a code snippet in #Bracmat A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Giv...
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...
#Retro
Retro
'123 a:from-string TRUE [ swap c:digit? and ] a:reduce
Give a code snippet in #Retro 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 A...
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
a k x1 x2 x3 x4 x5: local b: set :k -- k a k @b @x1 @x2 @x3 @x4 if <= k 0: + x4 x5 else: b local x i: labda: i   !. a 10 x 1 x -1 x -1 x 1 x 0
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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 lang...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Haskell
Haskell
import Data.List import Data.Function (on)   data Person = P String Int deriving (Eq)   instance Show Person where show (P name val) = "Person " ++ name ++ " with value " ++ show val   instance Ord Person where compare (P a _) (P b _) = compare a b   pVal :: Person -> Int pVal (P _ x) = x   people :: [Perso...
Give a code snippet in #Haskell Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#UNIX_Shell
UNIX Shell
string='Hello,How,Are,You,Today'   (IFS=, printf '%s.' $string echo)
Give a code snippet in #UNIX_Shell Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's sequence is an integer sequenc...
#11l
11l
F sylverster(lim) V result = [BigInt(2)] L 2..lim result.append(product(result) + 1) R result   V l = sylverster(10) print(‘First 10 terms of the Sylvester sequence:’) L(item) l print(item)   V s = 0.0 L(item) l s += 1 / Float(item) print("\nSum of the reciprocals of the first 10 terms: #.17".forma...
Give a code snippet in #11l This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's s...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ursala
Ursala
#import nat   bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC   #cast %nL   example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315>
Give a code snippet in #Ursala Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#VBA
VBA
  Option Explicit   Sub Main() Dim p As String p = length_encoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") Debug.Print p Debug.Print length_decoding(p) End Sub   Private Function length_encoding(S As String) As String Dim F As String, r As String, a As String, n As Long, c As Lon...
Give a code snippet in #VBA 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/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 ...
#Io
Io
mums := list(2,4,3,1,2) sorted := nums sort # returns a new sorted array. 'nums' is unchanged nums sortInPlace # sort 'nums' "in-place"
Give a code snippet in #Io 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/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#Racket
Racket
  #lang racket   (define (add-at l i x) (if (zero? i) (cons x l) (cons (car l) (add-at (cdr l) (sub1 i) x))))   (define (permutations l) (define (loop l) (cond [(null? l) '(())] [else (for*/list ([(p i) (in-indexed (loop (cdr l)))] [i ((if (odd? i) identity reverse) ...
Give a code snippet in #Racket Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#V
V
[1 2 3] [puts] step
Give a code snippet in #V Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Fortran
Fortran
subroutine quad_bezier(img, p1, p2, p3, color) type(rgbimage), intent(inout) :: img type(point), intent(in) :: p1, p2, p3 type(rgb), intent(in) :: color   integer :: i, j real :: pts(0:N_SEG,0:1), t, a, b, c, x, y   do i = 0, N_SEG t = real(i) / real(N_SEG) a = (1.0 - t)**2.0 b = 2.0 * t * (1...
Give a code snippet in #Fortran Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Mouse
Simulate input/Mouse
#PicoLisp
PicoLisp
(load "@lib/http.l" "@lib/scrape.l")   # Connect to the demo app at https://7fach.de/app/ (scrape "7fach.de" 80 "app")   # Log in (expect "'admin' logged in" (enter 3 "admin") # Enter user name into 3rd field (enter 4 "admin") # Enter password into 4th field (press "login") ) # Press the "log...
Give a code snippet in #PicoLisp
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#PureBasic
PureBasic
S$ = " World!" S$ = "Hello" + S$ If OpenConsole() PrintN(S$)   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
Give a code snippet in #PureBasic 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/The_sieve_of_Sundaram
The sieve of Sundaram
The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integers, mark every third starting a...
#Racket
Racket
#lang racket   (define (make-sieve-as-set limit) (let ((marked (for/mutable-set ((i limit)) (add1 i)))) (let loop ((start 4) (step 3)) (cond [(>= start limit) marked] [else (for ((i (in-range start limit step))) (set-remove! marked i)) (loop (+ start 3) (+ step 2))])) (defi...
Give a code snippet in #Racket The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#zkl
zkl
fcn f(r){r.inc()} r:= Ref(1); f(r); r.value; //-->2
Give a code snippet in #zkl Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Joy
Joy
# this is a single line comment   (* this is a multi-line comment *)
Give a code snippet in #Joy Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#SenseTalk
SenseTalk
  -- HUNT THE WUMPUS -- BY GREGORY YOB -- SenseTalk adaptation by Jonathan Gover   answer "INSTRUCTIONS (Y-N)" with "No" or "Yes" if it is "Yes" then showInstructions   -- SET UP CAVE (DODECAHEDRAL NODE LIST) set rooms to [ [2,5,8],[1,3,10],[2,4,12],[3,5,14],[1,4,6], [5,7,15],[6,8,17],[1,7,9],[8,10,18],[2,9,11], [1...
Give a code snippet in #SenseTalk This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The g...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Visual_FoxPro
Visual FoxPro
  LOCAL ARRAY a[4,2], b[2,3], c[4,3] CLOSE DATABASES ALL *!* The arrays could be created directly but I prefer to do this: CREATE CURSOR mat1 (c1 I, c2 I) CREATE CURSOR mat2 (c1 I, c2 I, c3 I) *!* Since matrix multiplication of integer arrays *!* involves only multiplication and addition, *!* the result will contain ...
Give a code snippet in #Visual_FoxPro Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#PHP
PHP
<?php function encode($symb2freq) { $heap = new SplPriorityQueue; $heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH); foreach ($symb2freq as $sym => $wt) $heap->insert(array($sym => ''), -$wt);   while ($heap->count() > 1) { $lo = $heap->extract(); $hi = $heap->extract(); ...
Give a code snippet in #PHP Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you cou...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or ri...
#D
D
import std.math; import std.stdio;   class XorShiftStar { private immutable MAGIC = 0x2545F4914F6CDD1D; private ulong state;   public void seed(ulong num) { state = num; }   public uint nextInt() { ulong x; uint answer;   x = state; x = x ^ (x >> 12); ...
Give a code snippet in #D Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits ...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#C
C
  #include<stdio.h> #include<conio.h> #include<math.h> #include<dos.h>   typedef struct{ char str[3]; int key; }note;   note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};   int main(void) { int i=0;   while(!kbhit()) { printf("\t%s",sequence[i].str); sound(261.63*po...
Give a code snippet in #C Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Arturo
Arturo
; create a dictionary d: #[ name: "john" surname: "doe" age: 34 ]   print d
Give a code snippet in #Arturo Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition,...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Forth
Forth
: leap-year? ( y -- ? ) dup 400 mod 0= if drop true exit then dup 100 mod 0= if drop false exit then 4 mod 0= ;
Give a code snippet in #Forth Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Kotlin
Kotlin
// version 1.1.0   import java.awt.Dimension import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.* import javax.swing.JFrame import javax.swing.JLabel   class Rotate : JFrame() { val text = "Hello World! " val label = JLabel(text) var rotRight = true var startIdx = 0   ...
Give a code snippet in #Kotlin Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task d...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Arc
Arc
(mac myswap (a b) (w/uniq gx `(let ,gx a (= a b) (= b ,gx))))   (with (a 1 b 2) (myswap a b) (prn "a:" a #\Newline "b:" b))  
Give a code snippet in #Arc Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity....
christopher/rosetta-code
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Picat
Picat
  import sat, util. rotate(Q) = Res => % rotate right by 90 degrees NZ = len(Q[1]), NS = len(Q), Res = new_array(NZ,NS), foreach(Z in 1..NZ, S in 1..NS) Res[Z,S] = Q[S,NZ+1-Z] end.   matprint(Q) => NZ = len(Q), NS = len(Q[1]), foreach(Z in 1..NZ, S in 1..NS) printf("%d|", Q[Z,S]), if S...
Give a code snippet in #Picat A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#VBA
VBA
'In case of problem this will terminate the program (without cleanup): If problem then End 'As VBA is run within an application, such as Excel, a more rigorous way would be: If problem then Application.Quit 'This will stop the application, but will prompt you to save work.
Give a code snippet in #VBA Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/d...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Java
Java
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO;   public enum ImageProcessing { ;   public static void main(String[] args) throws IOException { BufferedImage img = ImageIO.read(new File("example.png"));   BufferedImage bwimg = t...
Give a code snippet in #Java Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Wee_Basic
Wee Basic
keyhide plot 0 100,100,5 end
Give a code snippet in #Wee_Basic Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Wren
Wren
import "io" for File import "/ioutil" for FileUtil import "/dynamic" for Tuple import "/str" for Str   var fields = ["favouriteFruit", "needsPeeling", "seedsRemoved", "numberOfBananas", "numberOfStrawberries"] var ConfigData = Tuple.create("ConfigData", fields)   var updateConfigFile = Fn.new { |fileName, cData| va...
Give a code snippet in #Wren We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non c...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Haskell
Haskell
import Data.List (maximumBy, permutations, delete) import Data.Ord (comparing) import Data.Bool (bool)   unDigits :: [Int] -> Int unDigits = foldl ((+) . (10 *)) 0   ds :: [Int] ds = [1, 2, 3, 4, 6, 7, 8, 9] -- 0 (and thus 5) are both unworkable   lcmDigits :: Int lcmDigits = foldr1 lcm ds -- 504   sevenDigits :: [[Int...
Give a code snippet in #Haskell Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and...
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 ...
#RLaB
RLaB
  >> isdir("docs") 0 >> isfile("input.txt") 0  
Give a code snippet in #RLaB 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/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#ECL
ECL
  Doors := RECORD UNSIGNED1 DoorNumber; STRING6 State; END;   AllDoors := DATASET([{0,0}],Doors);   Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM SELF.DoorNumber := Cnt; SELF.State  := IF((CNT * 10) % (SQRT(CNT)*10)<>0,'Closed','Opened'); END;   OpenDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER...
Give a code snippet in #ECL There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...)...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#zkl
zkl
// Solve Hidato/Hopido/Numbrix puzzles class Puzzle{ // hold info concerning this puzzle var board, nrows,ncols, cells, start, // (r,c) where 1 is located, Void if no 1 terminated, // if board holds highest numbered cell given, // all the pre-loaded cells adj, // a li...
Give a code snippet in #zkl Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end nod...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Pony
Pony
true false
Give a code snippet in #Pony Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#ALGOL_68
ALGOL 68
MODE ADDRESS = STRUCT( INT page, FLEX[50]CHAR street, FLEX[25]CHAR city, FLEX[2]CHAR state, FLEX[10]CHAR zip ); FORMAT address repr = $"Page: "gl"Street: "gl"City: "gl"State: "gl"Zip: "gll$;   INT errno; FILE sequence; errno := open(sequence, "sequence.txt", stand back channel); SEMA sequence sema := LEVEL 1;   OP...
Give a code snippet in #ALGOL_68 Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Maple
Maple
  printf( "Goodbye, World!" );  
Give a code snippet in #Maple Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#LabVIEW
LabVIEW
: even? 2 % not ; : odd? 2 % ; 1 even? . # 0 1 odd? . # 1
Give a code snippet in #LabVIEW Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Di...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#AWK
AWK
function repeat( str, n, rep, i ) { for( ; i<n; i++ ) rep = rep str return rep }   BEGIN { print repeat( "ha", 5 ) }
Give a code snippet in #AWK Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =>...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Phix
Phix
with javascript_semantics -- -- demo\rosetta\n_queens.exw -- ========================= -- sequence co, -- columns occupied -- (ro is implicit) fd, -- forward diagonals bd, -- backward diagonals board atom count procedure solve(integer row, integer N, integer show)...
Give a code snippet in #Phix Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's to...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Run_BASIC
Run BASIC
print "F sequence:"; for i = 0 to 20 print f(i);" "; next i print :print "M sequence:"; for i = 0 to 20 print m(i);" "; next i end   function f(n) f = 1 if n <> 0 then f = n - m(f(n - 1)) end function   function m(n) m = 0 if n <> 0 then m = n - f(m(n - 1)) end function
Give a code snippet in #Run_BASIC Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Fish
Fish
v \0& >l?!v:*&+& >&n;
Give a code snippet in #Fish Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
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 ≤...
#Wee_Basic
Wee Basic
Print 1 "Enter number A:" input a Print 1 "Enter number B:" input b let c=a+b print 1 c end
Give a code snippet in #Wee_Basic 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, sepa...
christopher/rosetta-code
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define MAX 12 char *super = 0; int pos, cnt[MAX];   // 1! + 2! + ... + n! int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; }   int r(int n) { if (!n) return 0;   char c = super[pos - n]; if (!--cnt[n]) { ...
Give a code snippet in #C A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use th...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#NetRexx
NetRexx
class ClassExample   properties private -- class scope foo = int   properties public -- publicly visible bar = boolean   properties indirect -- generates bean patterns baz = String()   method main(args=String[]) static -- main method clsex = ClassExample() -- instantiate clsex.foo = 42 clse...
Give a code snippet in #NetRexx In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the c...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Action.21
Action!
PROC Append(CHAR ARRAY s CHAR c) s(0)==+1 s(s(0))=c RETURN   CHAR FUNC GetCharFromHex(CHAR c1,c2) CHAR ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F] BYTE i,res   res=0 FOR i=0 TO 15 DO IF c1=hex(i) THEN res==+i LSH 4 FI IF c2=hex(i) THEN res==+i FI OD RETURN (res)   PROC Decode(CHA...
Give a code snippet in #Action.21 This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unenco...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Tcl
Tcl
proc leftfact {n} { set s 0 for {set i [set f 1]} {$i <= $n} {incr i} { incr s $f set f [expr {$f * $i}] } return $s }   for {set i 0} {$i <= 110} {incr i [expr {$i>9?10:1}]} { puts "!$i = [leftfact $i]" } for {set i 1000} {$i <= 10000} {incr i 1000} { puts "!$i has [string length [leftfact $i...
Give a code snippet in #Tcl Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Julia
Julia
println("Parent running.") @async(begin sleep(1); println("This is the child process."); sleep(2); println("Child again.") end) sleep(2) println("This is the parent process again.") sleep(2) println("Parent again.")  
Give a code snippet in #Julia Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Nim
Nim
import random, strformat, strutils   randomize()   stdout.write "Player 1 - Enter your name : " let name1 = block: let n = stdin.readLine().strip() if n.len == 0: "PLAYER 1" else: n.toUpper stdout.write "Player 2 - Enter your name : " let name2 = block: let n = stdin.readLine()...
Give a code snippet in #Nim The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to the...
christopher/rosetta-code
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , whic...
#Sidef
Sidef
func scs(u, v) { var ls = lcs(u, v).chars var pat = Regex('(.*)'+ls.join('(.*)')+'(.*)') u.scan!(pat) v.scan!(pat) var ss = (u.shift + v.shift) ls.each { |c| ss += (c + u.shift + v.shift) } return ss }   say scs("abcbdab", "bdcaba")
Give a code snippet in #Sidef The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const proc: main is func begin writeln("positive infinity: " <& Infinity); writeln("negative infinity: " <& -Infinity); writeln("negative zero: " <& -0.0); writeln("not a number: " <& NaN);   # some arithmetic writeln("+Infinity + 2.0 = " <&...
Give a code snippet in #Seed7 The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language ...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Bracmat
Bracmat
(task= ( oracle = (predicate="is made of green cheese") (generateTruth=.str$(!arg " " !(its.predicate) ".")) (generateLie=.str$(!arg " " !(its.predicate) "!")) ) & new$oracle:?SourceOfKnowledge & put $ "You may ask the Source of Eternal Wisdom ONE thing. Enter \"Truth\" or \"Lie\" on the next li...
Give a code snippet in #Bracmat Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#LC3_Assembly
LC3 Assembly
.END
Give a code snippet in #LC3_Assembly Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
GUI/Maximum window dimensions
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations an...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Differences@Transpose@SystemInformation["Devices"][[1, 2, 1, 1, 2]] ->{{1260, 951}}
Give a code snippet in #Mathematica_.2F_Wolfram_Language The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area)...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Sidef
Sidef
func ham_gen { var s = [[1], [1], [1]] var m = [2, 3, 5]   func { var n = [s[0][0], s[1][0], s[2][0]].min { |i| s[i].shift if (s[i][0] == n) s[i].append(n * m[i]) } << ^3 return n } }   var h = ham_gen()   var i = 20; say i.of { h() }.join(' ')   {...
Give a code snippet in #Sidef Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#PL.2FI
PL/I
declare bell character (1); unspec (bell) = '00000111'b; put edit (bell) (a);
Give a code snippet in #PL.2FI Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell w...
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...
#Simula
Simula
BEGIN   BOOLEAN PROCEDURE ISNUMERIC(W); TEXT W; BEGIN BOOLEAN PROCEDURE MORE; MORE := W.MORE; CHARACTER PROCEDURE NEXT; NEXT := IF MORE THEN W.GETCHAR ELSE CHAR(0); CHARACTER PROCEDURE LAST; LAST := IF W.LENGTH = 0 THEN CHAR(0) ...
Give a code snippet in #Simula 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/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Elixir
Elixir
defmodule LucasLehmer do use Bitwise def test do for p <- 2..1300, p==2 or s(bsl(1,p)-1, p-1)==0, do: IO.write "M#{p} " end   defp s(mp, 1), do: rem(4, mp) defp s(mp, n) do x = s(mp, n-1) rem(x*x-2, mp) end end   LucasLehmer.test
Give a code snippet in #Elixir Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Arturo
Arturo
makeList: function [separator][ counter: 1   makeItem: function [item] .export:[counter][ result: ~"|counter||separator||item|" counter: counter+1 return result ]   @[ makeItem "first" makeItem "second" makeItem "third" ] ]   print join.with:"\n" makeL...
Give a code snippet in #Arturo In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of tw...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#COBOL
COBOL
$set REPOSITORY "UPDATE ON"   IDENTIFICATION DIVISION. PROGRAM-ID. perfect-main.   ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION perfect . DATA DIVISION. WORKING-STORAGE SECTION. 01 i PIC 9(8). ...
Give a code snippet in #COBOL Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Phix
Phix
--(1) starting from n characters in and of m length; --(2) starting from n characters in, up to the end of the string; --(3) whole string minus last character; --(4) starting from a known character within the string and of m length; --(5) starting from a known substring within the string and of m length. constan...
Give a code snippet in #Phix Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Retro
Retro
  : bitwise ( ab- ) cr over "a = %d\n" puts dup "b = %d\n" puts 2over and "a and b = %d\n" puts 2over or "a or b = %d\n" puts 2over xor "a xor b = %d\n" puts over not "not a = %d\n" puts 2over << "a << b = %d\n" puts 2over >> "a >> b = %d\n" puts 2drop ;
Give a code snippet in #Retro Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Preserve_screen
Terminal control/Preserve screen
Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved.   If the implement...
#Swift
Swift
  public let CSI = ESC+"[" // Control Sequence Introducer func write(_ text: String...) { for txt in text { write(STDOUT_FILENO, txt, txt.utf8.count) } } write(CSI,"?1049h") // open alternate screen print("Alternate screen buffer\n") for n in (1...5).reversed() { print("Going back in \(n)...") sleep(1) } wr...
Give a code snippet in #Swift Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to b...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Yabasic
Yabasic
lista1$ = "John Serena Bob Mary Serena" lista2$ = "Jim Mary John Jim Bob"   lista1$ = quitadup$(lista1$) lista2$ = quitadup$(lista2$) res$ = quitacomun$(lista1$, lista2$) res$ = res$ + quitacomun$(lista2$, lista1$) print res$     sub quitadup$(l$) l$ = l$ + " " return quitarep$(l$) end sub     sub quitacomun$(l1$, l2...
Give a code snippet in #Yabasic Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
  Class Utils.Phonetic [ Abstract ] {   ClassMethod ToSoundex(String As %String) As %String [ Language = mvbasic ] { Return Soundex(String) }   }  
Give a code snippet in #Cach.C3.A9_ObjectScript Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article)....
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Python
Python
tutor = True   def halve(x): return x // 2   def double(x): return x * 2   def even(x): return not x % 2   def ethiopian(multiplier, multiplicand): if tutor: print("Ethiopian multiplication of %i and %i" % (multiplier, multiplicand)) result = 0 while multiplier >= 1: ...
Give a code snippet in #Python Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Pascal
Pascal
program complexDemo(output);   const { I experienced some hiccups with -1.0 using GPC (GNU Pascal Compiler) } negativeOne = -1.0;   type line = string(80);   { as per task requirements wrap arithmetic operations into separate functions } function sum(protected x, y: complex): complex; begin sum := x + y end;   func...
Give a code snippet in #Pascal A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displays...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Set_lang
Set lang
 
Give a code snippet in #Set_lang Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Ursala
Ursala
#import std   mon =   ~&*~ sep` mat` -[ audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon l...
Give a code snippet in #Ursala A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the c...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Python
Python
s1 = "hello" print s1 + " world"   s2 = s1 + " world" print s2
Give a code snippet in #Python String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string li...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Groovy
Groovy
def top = { it.size() > 1 ? it[0..-2] : '' } def tail = { it.size() > 1 ? it[1..-1] : '' }
Give a code snippet in #Groovy The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Tiny_BASIC
Tiny BASIC
LET N = 0 10 LET N = N + 1 IF N < 3 THEN GOTO 100 LET T = 2 LET A = 1 20 LET A = A + 1 IF (N/A)*A = N THEN LET T = T + 1 IF A<(N+1)/2 THEN GOTO 20 30 PRINT "Tau(",N,") = ",T IF N<100 THEN GOTO 10 END 100 LET T = N GOTO 30
Give a code snippet in #Tiny_BASIC Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#XPL0
XPL0
include c:\cxpl\codes; real K, C, F, R; [ChOut(0, ^K); K:= RlIn(0); C:= K - 273.15; ChOut(0, ^C); RlOut(0, C); CrLf(0); F:= 1.8*C + 32.0; ChOut(0, ^F); RlOut(0, F); CrLf(0); R:= F + 459.67; ChOut(0, ^R); RlOut(0, R); CrLf(0); ]
Give a code snippet in #XPL0 There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 k...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#JavaScript
JavaScript
var array = []; array.push('abc'); array.push(123); array.push(new MyClass); console.log( array[2] );
Give a code snippet in #JavaScript This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET level=12: LET LONG=45 20 LET x=127: LET y=0 30 LET rotation=PI/2 40 LET a1=PI/9: LET a2=PI/9 50 LET c1=0.75: LET c2=0.75 60 DIM x(level): DIM y(level) 70 BORDER 0: PAPER 0: INK 4: CLS 80 GO SUB 100 90 STOP 100 REM Tree 110 LET x(level)=x: LET y(level)=y 120 GO SUB 1000 130 IF level=1 THEN GO TO 240 140 LET lev...
Give a code snippet in #ZX_Spectrum_Basic Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Maple
Maple
queens:=proc(n) local a,u,v,m,aux; a:=[$1..n]; u:=[true$2*n-1]; v:=[true$2*n-1]; m:=[]; aux:=proc(i) local j,k,p,q; if i>n then m:=[op(m),copy(a)]; else for j from i to n do k:=a[j]; p:=i-k+n; q:=i+k-1; if u[p] and v[q] then u[p]:=false; ...
Give a code snippet in #Maple Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's t...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#XPL0
XPL0
  int A(5,4,3,2); [A(3,1,0,1):= 3100; A(3,1,0,1):= A(3,1,0,1)+1; IntOut(0, A(3,1,0,1)); ]
Give a code snippet in #XPL0 For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Tcl
Tcl
package require Tcl 8.5   # Create our little language proc pins args { # Just declaration... foreach p $args {upvar 1 $p v} } proc gate {name pins body} { foreach p $pins { lappend args _$p append v " \$_$p $p" } proc $name $args "upvar 1 $v;$body" }   # Fundamental gates; these are the only ones...
Give a code snippet in #Tcl Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made us...
christopher/rosetta-code