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/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#AmigaBASIC
AmigaBASIC
SCREEN 1,320,200,5,1
Give a code snippet in #AmigaBASIC The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#jq
jq
def linearCombo: reduce to_entries[] as {key: $k,value: $v} (""; if $v == 0 then . else (if $v < 0 and length==0 then "-" elif $v < 0 then " - " elif $v > 0 and length==0 then "" else " + " end) as $sign | ($v|fabs...
Give a code snippet in #jq Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Objeck
Objeck
  use Structure;   bundle Default { class Evens { function : Main(args : String[]) ~ Nil { values := IntVector->New([1, 2, 3, 4, 5]); f := Filter(Int) ~ Bool; evens := values->Filter(f);   each(i : evens) { evens->Get(i)->PrintLine(); }; }   function : Filter(v : Int)...
Give a code snippet in #Objeck Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static   do pb = ProcessBuilder([String '']) env = pb.environment() currentuser = String env.g...
Give a code snippet in #NetRexx Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
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 |...
#PureBasic
PureBasic
Define varA.i = 5, varB.i = 0, *myInteger.Integer   *myInteger = @varA ;set pointer to address of an integer variable varB = *myInteger\i + 3 ;set variable to the 3 + value of dereferenced pointer, i.e varB = 8
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/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Lua
Lua
function identical(t_str) _, fst = next(t_str) if fst then for _, i in pairs(t_str) do if i ~= fst then return false end end end return true end   function ascending(t_str) prev = false for _, i in ipairs(t_str) do if prev and prev >= i then return false end ...
Give a code snippet in #Lua Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false va...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Phix
Phix
-- demo/rosetta/AKSprimes.exw -- Does not work for primes above 53, which is actually beyond the original task anyway. -- Translated from the C version, just about everything is (working) out-by-1, what fun. sequence c = repeat(0,100) procedure coef(integer n) -- out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 e...
Give a code snippet in #Phix The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the c...
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
#Agena
Agena
io.write( "Goodbye, World!" )
Give a code snippet in #Agena 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/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...
#BBC_BASIC
BBC BASIC
DIM Deck{ncards%, card&(51)}, Suit$(3), Rank$(12) Suit$() = "Clubs", "Diamonds", "Hearts", "Spades" Rank$() = "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", \ \ "Eight", "Nine", "Ten", "Jack", "Queen", "King"   PRINT "Creating a new deck..." PROCnewdeck(deck1{}) ...
Give a code snippet in #BBC_BASIC 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 curre...
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#Java
Java
import java.util.Arrays;   public class Deconvolution1D { public static int[] deconv(int[] g, int[] f) { int[] h = new int[g.length - f.length + 1]; for (int n = 0; n < h.length; n++) { h[n] = g[n]; int lower = Math.max(n - f.length + 1, 0); for (int i = lower; i ...
Give a code snippet in #Java The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program inputWin64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
Give a code snippet in #AArch64_Assembly In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#COBOL
COBOL
  identification division. program-id. Levenshtein.   environment division. configuration section. repository. function all intrinsic.   data division. working-storage section. 77 string-a pic x(255). 77 string-b pic...
Give a code snippet in #COBOL This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and com...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Julia
Julia
f(x) = √abs(x) + 5x^3 for i in reverse(split(readline())) v = f(parse(Int, i)) println("$(i): ", v > 400 ? "TOO LARGE" : v) end
Give a code snippet in #Julia The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s,...
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...
#Action.21
Action!
PROC Main() BYTE n,min=[1],max=[100] CHAR c   PrintF("Think a number in range %B-%B%E",min,max) DO n=(max+min) RSH 1 PrintF("My guess is %B%E",n) PrintF("Is it (E)qual, (L)ower or (H)igher?") c=GetD(7) Put(c) PutE() IF c='E THEN Print("I guessed!") EXIT ELSEIF c='L THEN ...
Give a code snippet in #Action.21 Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Pascal
Pascal
program LookAndSayDemo(input, output);   {$IFDEF FPC} {$MODE DELPHI} {$ENDIF}   uses SysUtils;   function LookAndSay(s: string): string; var item: char; index: integer; count: integer; begin Result := ''; item := s[1]; count := 1; for index := 2 to length(s) do if item = s[index] then inc(co...
Give a code snippet in #Pascal 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 sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Swift
Swift
func perfectShuffle<T>(_ arr: [T]) -> [T]? { guard arr.count & 1 == 0 else { return nil }   let half = arr.count / 2 var res = [T]()   for i in 0..<half { res.append(arr[i]) res.append(arr[i + half]) }   return res }   let decks = [ Array(1...8), Array(1...24), Array(1...52), Array(1.....
Give a code snippet in #Swift A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#11l
11l
F det(mm) V m = copy(mm) V result = 1.0   L(j) 0 .< m.len V imax = j L(i) j + 1 .< m.len I m[i][j] > m[imax][j] imax = i   I imax != j swap(&m[imax], &m[j]) result = -result   I abs(m[j][j]) < 1e-12 R Float.infinity   L(i) j + 1 .< m...
Give a code snippet in #11l linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#PicoLisp
PicoLisp
(get Lst (rand 1 (length Lst)))
Give a code snippet in #PicoLisp Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#GeneXus
GeneXus
&string = &string.ReplaceRegEx("^\s+|\s+$", "") // it's a trim! &string = &string.ReplaceRegEx("Another (Match)", "Replacing $1") // Using replace groups
Give a code snippet in #GeneXus Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#MiniScript
MiniScript
num = ceil(rnd*10) while true x = val(input("Your guess?")) if x == num then print "Well guessed!" break end if end while
Give a code snippet in #MiniScript Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issu...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#Crystal
Crystal
n = 2200 l_add, l = Hash(Int32, Bool).new(false), Hash(Int32, Bool).new(false) (1..n).each do |x| x2 = x * x (x..n).each { |y| l_add[x2 + y * y] = true } end   s = 3 (1..n).each do |x| s1 = s s += 2 s2 = s ((x+1)..n).each do |y| l[y] = true if l_add[s1] s1 += s2 s2 += 2 end end   puts (1..n)...
Give a code snippet in #Crystal One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
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 ...
#Python
Python
  """   Python example of   http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds   based on   http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort#Python   """   def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1   while beginIdx <= endIdx: newBegin...
Give a code snippet in #Python 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/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#PureBasic
PureBasic
#Def_p=0.001   Procedure.d Nth_root(n.i, A.d, p.d=#Def_p) Protected Dim x.d(1) x(0)=A: x(1)=A/n While Abs(x(1)-x(0))>p x(0)=x(1) x(1)=((n-1.0)*x(1)+A/Pow(x(1),n-1.0))/n Wend ProcedureReturn x(1) EndProcedure   ;////////////////////////////// Debug "125'th root of 5642 is" Debug Pow(5642,1/125) Debug ...
Give a code snippet in #PureBasic Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
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...
#Delphi
Delphi
program PascalsTriangle;   procedure Pascal(r:Integer); var i, c, k:Integer; begin for i := 0 to r - 1 do begin c := 1; for k := 0 to i do begin Write(c:3); c := c * (i - k) div (k + 1); end; Writeln; end; end;   begin Pascal(9); end.
Give a code snippet in #Delphi Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eithe...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#HicEst
HicEst
READ(FILE="input.txt", LENgth=bytes) ! bytes = -1 if not existent READ(FILE="C:\input.txt", LENgth=bytes) ! bytes = -1 if not existent
Give a code snippet in #HicEst Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Fortran
Fortran
  integer function lcm(a,b) integer:: a,b lcm = a*b / gcd(a,b) end function lcm   integer function gcd(a,b) integer :: a,b,t do while (b/=0) t = b b = mod(a,b) a = t end do gcd = abs(a) end function gcd  
Give a code snippet in #Fortran Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that h...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#D
D
import std.stdio, std.algorithm, std.random, std.range, std.conv, std.typecons, std.typetuple;   int[N][N] knightTour(size_t N=8)(in string start) in { assert(start.length >= 2); } body { static struct P { int x, y; }   immutable P[8] moves = [P(2,1), P(1,2), P(-1,2), P(-2,1), ...
Give a code snippet in #D Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw...
#Haskell
Haskell
{-# LANGUAGE DeriveFunctor #-} import Data.Numbers.Primes (isPrime) import Data.List   ------------------------------------------------------------ -- memoization utilities   type Memo2 a = Memo (Memo a)   data Memo a = Node a (Memo a) (Memo a) deriving Functor   memo :: Integral a => Memo p -> a -> p memo (Node a l ...
Give a code snippet in #Haskell The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition int...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Bracmat
Bracmat
( ( Amb = first last list words word solution .  !arg:(?first.?list) & ( !list: |  !list:(.?words) ?list &  !words  :  ?  %( @(?word:!first ? @?last) & Amb$(!last.!list):?solution & !word !solution:?solution ...
Give a code snippet in #Bracmat Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automat...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#C.2B.2B
C++
void number_reversal_game() { cout << "Number Reversal Game. Type a number to flip the first n numbers."; cout << "You win by sorting the numbers in ascending order."; cout << "Anything besides numbers are ignored.\n"; cout << "\t |1__2__3__4__5__6__7__8__9|\n"; int list[9] = {1,2,3,4,5,6,7,8,9}; do ...
Give a code snippet in #C.2B.2B Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Sidef
Sidef
define TRIALS = 1e4;   func prob_choice_picker(options) { var n = 0; var a = []; options.each { |k,v| n += v; a << [n, k]; } func { var r = 1.rand; a.first{|e| r <= e[0] }[1]; } }   var ps = Hash( aleph => 1/5, beth => 1/6, gimel => 1/7, daleth => ...
Give a code snippet in #Sidef Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because flo...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Picat
Picat
go ?=> println("\nEnd terms with '.'.\n'quit.' ends the session.\n"), Prev = findall(P,beats(P,_)), ChoiceMap = new_map([P=0 : P in Prev]), ResultMap = new_map([computer_wins=0,user_wins=0,draw=0]), play(Prev,ChoiceMap,ResultMap), nl, println("Summary:"), println(choiceMap=ChoiceMap), println(resultMa...
Give a code snippet in #Picat Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Oz
Oz
declare [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} [StringX] = {Module.link ['x-oz://system/String.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   AllTasksUrl = "http://rosettacode.org/mw/api.php?action=query&lis...
Give a code snippet in #Oz task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll n...
christopher/rosetta-code
http://rosettacode.org/wiki/Playfair_cipher
Playfair cipher
Playfair cipher You are encouraged to solve this task according to the task description, using any language you may know. Task Implement a Playfair cipher for encryption and decryption. The user must be able to choose   J  =  I     or   no   Q   in the alphabet. The output of the encrypted and decrypted message ...
#Phix
Phix
with javascript_semantics constant keyword = "Playfair example", option = 'Q' -- ignore Q -- option = 'J' -- replace J with I sequence table, findchar procedure build_table() table = repeat(repeat(' ',5),5) findchar = repeat(0,26) findchar[option-'A'+1] = {0,0} -- (note any (J...
Give a code snippet in #Phix Playfair cipher You are encouraged to solve this task according to the task description, using any language you may know. Task Implement a Playfair cipher for encryption and decryption. The user must be able to choose   J  =  I     or   no   Q   in the alphabet. The output of the en...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Red
Red
  Red [] print "Evaluation from left to right with no precedence, unless you use parenthesis." print "" a: "123456789" guess: "" valid: "" sucess: false random/seed now/time loop 4 [append valid last random a] print ["The numbers are: " valid/1 ", " valid/2 ", " valid/3 " and " valid/4] sort valid insert valid " "   ex...
Give a code snippet in #Red The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digi...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Haskell
Haskell
import Data.List   -- Return the common prefix of two lists. commonPrefix2 (x:xs) (y:ys) | x == y = x : commonPrefix2 xs ys commonPrefix2 _ _ = []   -- Return the common prefix of zero or more lists. commonPrefix (xs:xss) = foldr commonPrefix2 xs xss commonPrefix _ = []   -- Split a string into path components. splitPa...
Give a code snippet in #Haskell Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the...
christopher/rosetta-code
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
KaprekaQ[1] = True; KaprekaQ[n_Integer] := Block[{data = IntegerDigits[n^2], last = False, i = 1}, While[i < Length[data] && FromDigits[data[[i + 1 ;;]]] =!= 0 && Not[last], last = FromDigits[data[[;; i]]] + FromDigits[data[[i + 1 ;;]]] == n; i++]; last]; Select[Range[10000], KaprekaQ] Length[Select[Range[100...
Give a code snippet in #Mathematica.2FWolfram_Language A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting pure...
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...
#REXX
REXX
/*REXX program classifies various positive integers for types of aliquot sequences. */ parse arg low high $L /*obtain optional arguments from the CL*/ high= word(high low 10,1); low= word(low 1,1) /*obtain the LOW and HIGH (range). */ if $L='' then $L=11 12 28 496 220 1184 12496 1...
Give a code snippet in #REXX 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#OCaml
OCaml
let () = Array.iter print_endline ( Sys.readdir Sys.argv.(1) )
Give a code snippet in #OCaml Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/Harmonic_series
Harmonic series
This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, the n-th harmonic number is the sum of the recipr...
#BASIC
BASIC
h = 0.0   print "The first twenty harmonic numbers are:" for n = 1 to 20 h += 1.0 / n print n, h next n print   h = 1 : n = 2 for i = 2 to 10 while h < i h += 1.0 / n n += 1 end while print "The first harmonic number greater than "; i; " is "; h; ", at position "; n-1 next i end
Give a code snippet in #BASIC This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, the n-th harmonic ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Mercury
Mercury
:- module comb. :- interface. :- import_module list, int, bag.   :- pred choose(list(T)::in, int::in, bag(T)::out) is nondet. :- pred choose_all(list(T)::in, int::in, list(list(T))::out) is det. :- pred count_choices(list(T)::in, int::in, int::out) is det.   :- implementation. :- import_module solutions.   choose(L, N,...
Give a code snippet in #Mercury The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member o...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Fortran
Fortran
PROGRAM TOWER   CALL Move(4, 1, 2, 3)   CONTAINS   RECURSIVE SUBROUTINE Move(ndisks, from, to, via) INTEGER, INTENT (IN) :: ndisks, from, to, via   IF (ndisks == 1) THEN WRITE(*, "(A,I1,A,I1)") "Move disk from pole ", from, " to pole ", to ELSE CALL Move(ndisks-1, from, via, to) CAL...
Give a code snippet in #Fortran Task Solve the   Towers of Hanoi   problem with recursion.
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_68
ALGOL 68
#!/usr/local/bin/a68g --script #   # Demonstrate toupper and tolower for standard ALGOL 68 strings. This does not work for multibyte character sets. #   INT l2u = ABS "A" - ABS "a";   PROC to upper = (CHAR c)CHAR: (ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u ));   PROC to lower = (CHAR c)CHAR: ...
Give a code snippet in #ALGOL_68 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 no...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#AutoHotkey
AutoHotkey
InputBox, Dynamic, Variable Name %Dynamic% = hello ListVars MsgBox % %dynamic% ; says hello
Give a code snippet in #AutoHotkey Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#MATLAB
MATLAB
function [varargout] = emptyprogram(varargin)
Give a code snippet in #MATLAB Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Aime
Aime
real mean(list l) { integer i; real x, y;   x = y = 0;   i = 0; while (i < l_length(l)) { x += Gcos(l[i]); y += Gsin(l[i]); i += 1; }   return Gatan2(y / l_length(l), x / l_length(l)); }   integer main(void) { o_form("mean of 1st set: /d6/\n", mean(l_effect(350, 1...
Give a code snippet in #Aime When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first readi...
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.
#SETL
SETL
A := [1, 2, 3]; B := [3, 4, 5]; print(A + B); -- [1 2 3 3 4 5]
Give a code snippet in #SETL 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/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 ...
#AutoHotkey
AutoHotkey
REM The names (only used for printing the results): DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4) Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water" Nation$() = "Denmark", "England", "Germany", "Norway", "Sweden" Colr$() = "Blue", "Green", "Red", "White", "Yellow" Sm...
Give a code snippet in #AutoHotkey 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 fi...
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...
#Erlang
Erlang
  -module( pig_dice ).   -export( [game/1, goal/0, hold/2, player_name/1, players_totals/1, quit/2, roll/2, score/1, task/0] ).   -record( player, {name, score=0, total=0} ).   game( [_Player | _T]=Players ) -> My_pid = erlang:self(), erlang:spawn_link( fun() -> random:seed(os:timestamp()), game_loop( [#player{...
Give a code snippet in #Erlang 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#Visual_Basic_.NET
Visual Basic .NET
Imports System, System.Console   Module Module1   Dim np As Boolean()   Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n ...
Give a code snippet in #Visual_Basic_.NET A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 whic...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Groovy
Groovy
import static Man.* import static Woman.*   Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) { Map<Woman,Man> engagedTo = new TreeMap() List<Man> freeGuys = (Man.values()).clone() while(freeGuys) { Man thisGuy = freeGuys[0] freeGuys...
Give a code snippet in #Groovy Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Sidef
Sidef
var raw = <<'TABLE' map, 9, 150 compass, 13, 35 water, 153, 200 sandwich, 50, 160 glucose, 15, 60 tin, 68, 45 banana, 27, 60 apple, 39, 40 cheese, 23, 30 bee...
Give a code snippet in #Sidef A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#Aime
Aime
ordl(list a, b) { integer i, l, o;   l = min(~a, ~b); i = 0; while (i < l) { if (a[i] != b[i]) { o = a[i] < b[i]; break; }   i += 1; }   i < l ? o : ~a <= ~b; }   main(void) { o_(ordl(list(1, 2), list(1, 2)), "\n"); o_(ordl(list(1e2, 2), li...
Give a code snippet in #Aime sorting 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Forth
Forth
include lib/interprt.4th include lib/istype.4th include lib/argopen.4th   \ --------------------- \ Variables \ ---------------------   81 string sudokugrid 9 array sudoku_row 9 array sudoku_col 9 array sudoku_box   \ ------------- \ 4tH interface \ -------------   : >grid ( n2 a1 n...
Give a code snippet in #Forth Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Raku
Raku
sub propdivsum (\x) { my @l = x > 1; (2 .. x.sqrt.floor).map: -> \d { unless x % d { my \y = x div d; y == d ?? @l.push: d !! @l.append: d,y } } sum @l; }   multi quality (0,1) { 'perfect ' } multi quality (0,2) { 'amicable' } multi quality (0,$n) { "sociable-$n" } multi quality ($,1) { 'aspi...
Give a code snippet in #Raku 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Oberon-2
Oberon-2
  MODULE Stacks; IMPORT Object, Object:Boxed, Out := NPCT:Console;   TYPE Pool(E: Object.Object) = POINTER TO ARRAY OF E; Stack*(E: Object.Object) = POINTER TO StackDesc(E); StackDesc*(E: Object.Object) = RECORD pool: Pool(E); cap-,top: LONGINT; END;   PROCEDURE (s: Stack(E)) INIT*(cap: LONGINT...
Give a code snippet in #Oberon-2 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#ProDOS
ProDOS
:a editvar /modify /value=-random-= <10 editvar /newvar /value=-random- /title=a editvar /newvar /value=b /userinput=1 /title=Guess a number: if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a
Give a code snippet in #ProDOS Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Tcl
Tcl
package require Tcl 8.5 package require csv package require html package require struct::queue   set csvData "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians m...
Give a code snippet in #Tcl Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Aime
Aime
record r, s; integer c; file f; list l; text an, d, k;   an = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";   f.affix("tmp/config");   while ((c = f.peek) ^ -1) { integer removed;   f.side(" \t\r"); c = f.peek; removed = c == ';'; if (removed) { f.pick; f.side(" \...
Give a code snippet in #Aime The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are i...
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...
#Perl
Perl
sub partition { my($all, $div) = @_; my @marks = 0; push @marks, $_/$div * $all for 1..$div; my @copy = @marks; $marks[$_] -= $copy[$_-1] for 1..$#marks; @marks[1..$#marks]; }   sub bars { my($h,$w,$p,$rev) = @_; my (@nums,@vals,$line,$d);   $d = 2**$p; push @nums, int $_/($d-1)...
Give a code snippet in #Perl 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 ha...
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...
#Scala
Scala
def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = { val sum = properDivisors(n).sum if (sum == 0) ("terminate", list ::: List(sum)) else if (step >= 16 || sum > 140737488355328L) ("non-term", list) else { list.indexOf(sum) match { case -1 => createAli...
Give a code snippet in #Scala 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...
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
#Crystal
Crystal
keys = ('a'..'z').to_a # => a, b, c ... z vals = (1..26).to_a # => 1, 2, 3 ... 26   hash = Hash.zip(keys, vals) p hash
Give a code snippet in #Crystal 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/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Factor
Factor
: multiply ( a b -- a*b ) * ;
Give a code snippet in #Factor A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#OCaml
OCaml
let sqr x = x *. x   let stddev l = let n, sx, sx2 = List.fold_left (fun (n, sx, sx2) x -> succ n, sx +. x, sx2 +. sqr x) (0, 0., 0.) l in sqrt ((sx2 -. sqr sx /. float n) /. float n)   let _ = let l = [ 2.;4.;4.;4.;5.;5.;7.;9. ] in Printf.printf "List: "; List.iter (Printf.printf "%g ") l;...
Give a code snippet in #OCaml Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the funct...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#PL.2FI
PL/I
  declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);   put (sum(A**2));  
Give a code snippet in #PL.2FI 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/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#GAP
GAP
# Built-in LcmInt(12, 18); # 36
Give a code snippet in #GAP Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has b...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#True_BASIC
True BASIC
FUNCTION min(a, b) IF a < b THEN LET min = a ELSE LET min = b END FUNCTION   FUNCTION d6 LET d6 = 1 + INT(RND * 6) END FUNCTION   FUNCTION rollstat LET a = d6 LET b = d6 LET c = d6 LET d = d6 LET rollstat = a + b + c + d - min(min(a, b), min(c, d)) END FUNCTION   DIM statnames$(6) DATA "STR"...
Give a code snippet in #True_BASIC RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four,...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. 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 body...
#Harbour
Harbour
FOR i := 10 TO 0 STEP -1 ? i NEXT
Give a code snippet in #Harbour Task Write a   for   loop which writes a countdown from   10   to   0. 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/Incr...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Ceylon
Ceylon
  module knapsack "1.0.0" { }  
Give a code snippet in #Ceylon A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#REXX
REXX
/* REXX */ ml ='1 3 7 8 10 2 4 16 14 4 3 1 9 18 11 12 14 17 18 20 7 1 3 9 5' Do i=1 To 5 Do j=1 To 5 Parse Var ml m.i.j ml End End   l='' Do i=1 To 5 Do j=1 To 5 l=l right(m.i.j,2) End Say l l='' End   sum=0 Do i=2 To 5 Do j=1 To i-1 sum=sum+m.i.j End End Say 'Sum below main diag...
Give a code snippet in #REXX Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
EmptyQ[a_] := If[Length[a] == 0, True, False] SetAttributes[Push, HoldAll];[a_, elem_] := AppendTo[a, elem] SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = Last[a]; Set[a, Most[a]]; b] Peek[a_] := If[EmptyQ[a], False, Last[a]]   Example use: stack = {};Push[stack, 1]; Push[stack, 2]; Push[stac...
Give a code snippet in #Mathematica.2FWolfram_Language 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also call...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#OCaml
OCaml
let rec copy t = if Obj.is_int t then t else let tag = Obj.tag t in if tag = Obj.double_tag then t else if tag = Obj.closure_tag then t else if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else if tag = 0 || tag = Obj.double_array_tag then begin let size = Obj.size t in ...
Give a code snippet in #OCaml Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this fa...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Java
Java
import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*;   public class Game2048 extends JPanel {   enum State { start, won, running, over }   final Color[] colorTable = { new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3), new Color(0xffd...
Give a code snippet in #Java Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some m...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer 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 |...
#Dc
Dc
[Use _ (underscore) as negative sign for numbers.]P []pP [Enter two numbers to compare: ]P ? sbsa [[greater than]]sp lb la >p [ [less than]]sp lb la <p [ [equal to]]sp lb la =p la n [ is ]P P [ ]P lbn []pP  
Give a code snippet in #Dc 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 Con...
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)
#Raku
Raku
say "$year is a {Date.is-leap-year($year) ?? 'leap' !! 'common'} year."
Give a code snippet in #Raku 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/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Raku
Raku
sub merge_sort ( @a ) { return @a if @a <= 1;   my $m = @a.elems div 2; my @l = flat merge_sort @a[ 0 ..^ $m ]; my @r = flat merge_sort @a[ $m ..^ @a ];   return flat @l, @r if @l[*-1] !after @r[0]; return flat gather { take @l[0] before @r[0] ?? @l.shift !! @r.shift while @...
Give a code snippet in #Raku 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/Order_disjoint_list_items
Order disjoint list items
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 ...
#Julia
Julia
  function order_disjoint{T<:AbstractArray}(m::T, n::T) rlen = length(n) rdis = zeros(Int, rlen) for (i, e) in enumerate(n) j = findfirst(m, e) while j in rdis && j != 0 j = findnext(m, e, j+1) end rdis[i] = j end if 0 in rdis throw(DomainError()) ...
Give a code snippet in #Julia 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/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Atari_Basic
Atari Basic
  10 REM DELEGATION CODE AND EXAMPLE . ATARI BASIC 2020 A. KRESS andreas.kress@hood-group.com 14 REM 15 GOTO 100:REM MAINLOOP 16 REM 20 REM DELEGATOR OBJECT 21 REM 30 IF DELEGATE THEN GOSUB DELEGATE:GOTO 56 35 REM 50 REM DELEGATOR HAS TO DO THE JOB 55 PRINT "DEFAULT IMPLEMENTATION - DONE BY DELEGATOR" 56 RETURN 60...
Give a code snippet in #Atari_Basic A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Smalltalk
Smalltalk
someClass class >> isAbstract ^ true   someClass class >> new self isAbstract ifTrue:[ ^ self error:'trying to instantiate an abstract class' ]. ^ super new   someClass >> method1 ^ self subclassResponsibility  
Give a code snippet in #Smalltalk Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#PicoLisp
PicoLisp
(de prime? (N Lst) (let S (sqrt N) (for D Lst (T (> D S) T) (T (=0 (% N D)) NIL) ) ) ) (de primeseq (A B) (let (I 1 R) (nth (make (link 2) (while (> A (inc 'I 2)) (and (prime? I (made)) (link I)) ) (setq R (length (made))) ...
Give a code snippet in #PicoLisp Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or p...
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 ≤...
#Common_Lisp
Common Lisp
(write (+ (read) (read)))
Give a code snippet in #Common_Lisp 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, se...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#AutoHotkey
AutoHotkey
FormatTime, t MsgBox,% t
Give a code snippet in #AutoHotkey Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Smalltalk
Smalltalk
12 lcm: 18
Give a code snippet in #Smalltalk Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Oz
Oz
raise sillyError end raise slightlyLessSilly(data:42 reason:outOfMemory) end
Give a code snippet in #Oz Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Euphoria
Euphoria
function merge(sequence left, sequence right) sequence result result = {} while length(left) > 0 and length(right) > 0 do if compare(left[1], right[1]) <= 0 then result = append(result, left[1]) left = left[2..$] else result = append(result, right[1]) ...
Give a code snippet in #Euphoria 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/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Pascal
Pascal
program fizzbuzz(output); var i: integer; begin for i := 1 to 100 do if i mod 15 = 0 then writeln('FizzBuzz') else if i mod 3 = 0 then writeln('Fizz') else if i mod 5 = 0 then writeln('Buzz') else writeln(i) end.
Give a code snippet in #Pascal Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <ucontext.h>   typedef struct { ucontext_t caller, callee; char stack[8192]; void *in, *out; } co_t;   co_t * co_new(void(*f)(), void *data) { co_t * c = malloc(sizeof(*c)); getcontext(&c->callee); c->in = data;   c->callee.uc_stack.ss_sp = c->stack; c->callee.uc_...
Give a code snippet in #C 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 a...
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...
#Nim
Nim
# Least signficant bit: proc isOdd(i: int): bool = (i and 1) != 0 proc isEven(i: int): bool = (i and 1) == 0   # Modulo: proc isOdd2(i: int): bool = (i mod 2) != 0 proc isEven2(i: int): bool = (i mod 2) == 0   # Bit Shifting: proc isOdd3(n: int): bool = n != ((n shr 1) shl 1) proc isEven3(n: int): bool = n == ((n shr 1...
Give a code snippet in #Nim 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Python
Python
def isqrt ( x ): q = 1 while q <= x : q *= 4 z,r = x,0 while q > 1 : q /= 4 t,r = z-r-q,r/2 if t >= 0 : z,r = t,r+q return r   print ' '.join( '%d'%isqrt( n ) for n in xrange( 66 )) print '\n'.join( '{0:114,} = isqrt( 7^{1:3} )'.format( isqrt( 7**n ),n ...
Give a code snippet in #Python Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your compute...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Lang5
Lang5
do 20 ? int dup . 10 == if break then 20 ? int . loop
Give a code snippet in #Lang5 Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#F.23
F#
open System   let decode uri = Uri.UnescapeDataString(uri)   [<EntryPoint>] let main argv = printfn "%s" (decode "http%3A%2F%2Ffoo%20bar%2F") 0
Give a code snippet in #F.23 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 f...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#C.2B.2B
C++
  #include <iostream> #include <string> #include <vector>   void print_vector(const std::vector<int> &pos, const std::vector<std::string> &str) { for (size_t i = 1; i < pos.size(); ++i) // offset: i:1..N printf("%s\t", str[pos[i]].c_str()); // str: 0..N-1 printf("\n"); }   // idea: custo...
Give a code snippet in #C.2B.2B The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member o...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#ALGOL_68
ALGOL 68
BEGIN # solve the 4 rings or 4 squares puzzle # # we need to find solutions to the equations: a + b = b + c + d = d + e + f = f + g # # where a, b, c, d, e, f, g in lo : hi ( not necessarily unique ) # # depending on show, the solutions will ...
Give a code snippet in #ALGOL_68 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Go
Go
package main   import ( "bytes" "fmt" "math/rand" "time" )   type maze struct { c []byte // cell contents h []byte // horizontal walls above cells v []byte // vertical walls to the left of cells c2 [][]byte // cells by row h2 [][]byte // horizontal walls by row (ignore f...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Scala
Scala
  import scala.util.Random   object AverageLoopLength extends App {   val factorial: LazyList[Double] = 1 #:: factorial.zip(LazyList.from(1)).map(n => n._2 * factorial(n._2 - 1)) val results = for (n <- 1 to 20; avg = tested(n, 1000000); theory = expected(n) ...
Give a code snippet in #Scala Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#K
K
r:m@&a=x:|/a:+\{:[x[8+!3]~"OUT";1;-1]}'m:0:"mlijobs.txt"; `0:,/"Maximum simultaneous license use is ",$x; `0:" at the following times:\n";`0:r[;14+!19]
Give a code snippet in #K A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkou...
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,...
#Yabasic
Yabasic
a = open("passwd", "a") // Open the file for appending, i.e. what you write to the file will be appended after its initial contents. // If the file does not exist, it will be created.   print #a "account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell" print #a "jsmith...
Give a code snippet in #Yabasic 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...
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
#Tcl
Tcl
puts -nonewline "Goodbye, World!"
Give a code snippet in #Tcl 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/Standar...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Erlang
Erlang
  Deg=45. Rad=math:pi()/4.   math:sin(Deg * math:pi() / 180)==math:sin(Rad).  
Give a code snippet in #Erlang Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that eval...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Fortran
Fortran
INTEGER A, B PRINT *, 'Type in two integer numbers separated by white space', + ' and press ENTER' READ *, A, B PRINT *, ' A + B = ', (A + B) PRINT *, ' A - B = ', (A - B) PRINT *, ' A * B = ', (A * B) PRINT *, ' A / B = ', (A / B) PRINT *, 'MOD(A,B) = ', MOD(A,B) PRINT * PRINT *, 'Even though...
Give a code snippet in #Fortran Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code