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/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data = ImportString["{ \"foo\": 1, \"bar\": [10, \"apples\"] }","JSON"] ExportString[data, "JSON"]
Give a code snippet in #Mathematica.2FWolfram_Language Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Lambdatalk
Lambdatalk
  {def A {A.new {S.map {lambda {:x} {* :x :x}} {S.serie 0 10} }}}   {A.get 3 {A}} // equivalent to A[3] -> 9 {A.get 4 {A}} -> 16  
Give a code snippet in #Lambdatalk Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Julia
Julia
  collect(-2:1:2) # → [-2, -1, 0, 1, 2] collect(-2:0:2) # fails collect(-2:-1:2) # → [] collect(-2:10:2) # → [-2] collect(2:1:-2) # → [] collect(2:1:2) # → [2] collect(2:-1:2) # → [2] collect(2:0:2) # fails collect(0:0:0) # fails  
Give a code snippet in #Julia Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Erlang
Erlang
io:put_chars(standard_error, "Goodbye, World!\n").
Give a code snippet in #Erlang Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Pascal
Pascal
Program PythagoreanTriples (output);   var total, prim, maxPeri: int64;   procedure newTri(s0, s1, s2: int64); var p: int64; begin p := s0 + s1 + s2; if p <= maxPeri then begin inc(prim); total := total + maxPeri div p; newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + ...
Give a code snippet in #Pascal A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#AutoHotkey
AutoHotkey
AutoTrim,Off ;Allows for whitespace at end of variable to separate converted characters   MessageText := ;The text to display in the final message box. CurrentASCII := 32 ;Current ASCII number to convert and add to MessageText ConvertedCharacter := ;Stores the currently converted ASCII code RowLength := 0 ;Keeps track...
Give a code snippet in #AutoHotkey Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and ston...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 stoogesort( @L, $i = 0, $j = @L.end ) { @L[$j,$i] = @L[$i,$j] if @L[$i] > @L[$j];   my $interval = $j - $i;   if $interval > 1 { my $t = ( $interval + 1 ) div 3; stoogesort( @L, $i , $j-$t ); stoogesort( @L, $i+$t, $j ); stoogesort( @L, $i , $j-$t ); } ...
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/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#PARI.2FGP
PARI/GP
rep(v)=for(i=1,#v\2,for(j=i+1,#v,if(v[j]!=v[j-i],next(2)));return(i));0; v=["1001110011","1110111011","0010010010","1010101010","1111111111","0100101101","0100100","101","11","00","1"]; for(i=1,#v,print(v[i]" "rep(Vec(v[i]))))
Give a code snippet in #PARI.2FGP Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also trivalent, ternary, or trinary...
#Nim
Nim
type Trit* = enum ttrue, tmaybe, tfalse   proc `$`*(a: Trit): string = case a of ttrue: "T" of tmaybe: "?" of tfalse: "F"   proc `not`*(a: Trit): Trit = case a of ttrue: tfalse of tmaybe: tmaybe of tfalse: ttrue   proc `and`*(a, b: Trit): Trit = const t: array[Trit, array[Trit, Trit]] = [ [ttrue, ...
Give a code snippet in #Nim This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also t...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#CLU
CLU
bottles = proc (n: int) returns (string) if n<0 then return("99 bottles") elseif n=0 then return("No more bottles") elseif n=1 then return("1 bottle") else return(int$unparse(n) || " bottles") end end bottles   thirdline = proc (n: int) returns (string) if n=0 then return("Go to the stor...
Give a code snippet in #CLU Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Axe
Axe
'A'
Give a code snippet in #Axe Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   H...
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 ...
#Ada
Ada
package Wumpus is procedure Start_Game; end Wumpus;  
Give a code snippet in #Ada 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Prolog
Prolog
common_sublist(A, B, M) :- append(_, Ma, A), append(M, _, Ma), append(_, Mb, B), append(M, _, Mb).   longest_list([], L, _, L). longest_list([L|Ls], LongestList, LongestLength, Result) :- length(L, Len), Len >= LongestLength -> longest_list(Ls, L, Len, Result) ; longest_list(Ls, LongestList, LongestLength, Re...
Give a code snippet in #Prolog Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecu...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#BBC_BASIC
BBC BASIC
DIM bearing(32) bearing() = 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, \ \ 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, \ \ 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, \ \ 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38   ...
Give a code snippet in #BBC_BASIC There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print an...
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...
#jq
jq
# Solution for n doors: def doors(n):   def print: . as $doors | range(1; length+1) | if $doors[.] then "Door \(.) is open" else empty end;   [range(n+1)|null] as $doors | reduce range(1; n+1) as $run ( $doors; reduce range($run; n+1; $run ) as $door ( .; .[$door] = (.[$door]...
Give a code snippet in #jq 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/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#jq
jq
# For streams of strings or of arrays or of numbers: def add(s): reduce s as $x (null; .+$x);   # Primes less than . // infinite def primes: (. // infinite) as $n | if $n < 3 then empty else 2, (range(3; $n) | select(is_prime)) end;  
Give a code snippet in #jq Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Vlang
Vlang
fn p_fac_sum(i int) int { mut sum := 0 for p := 1; p <= i/2; p++ { if i%p == 0 { sum += p } } return sum }   fn main() { mut d := 0 mut a := 0 mut p := 0 for i := 1; i <= 20000; i++ { j := p_fac_sum(i) if j < i { d++ } else ...
Give a code snippet in #Vlang These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient...
christopher/rosetta-code
http://rosettacode.org/wiki/Curzon_numbers
Curzon numbers
A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imply the radix of the counting sys...
#Wren
Wren
/* curzon_numbers.wren */   import "./gmp" for Mpz import "./seq" for Lst import "./fmt" for Fmt   for (k in [2, 4, 6, 8, 10]) { System.print("The first 50 Curzon numbers using a base of %(k):") var count = 0 var n = 1 var pow = Mpz.from(k) var curzon50 = [] while (true) { var z = pow + ...
Give a code snippet in #Wren A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imply...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#PostScript
PostScript
  1 {succ dup =} loop  
Give a code snippet in #PostScript Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#Scala
Scala
import java.awt.image._ import java.io.File import javax.imageio._   object HoughTransform extends App { override def main(args: Array[String]) { val inputData = readDataFromImage(args(0)) val minContrast = if (args.length >= 4) 64 else args(4).toInt inputData(args(2).toInt, args(3).toInt, m...
Give a code snippet in #Scala Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Nanoquery
Nanoquery
println 0^0
Give a code snippet in #Nanoquery Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0    ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Maple
Maple
count_jewel := proc(stones, jewels) local count, j, letter: j := convert(jewels,set): count := 0: for letter in stones do if (member(letter, j)) then count++: end if: end do: return count: end proc: count_jewel("aAAbbbb", "aA")
Give a code snippet in #Maple Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case...
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...
#Scheme
Scheme
  (define count (lambda (str1 str2) (let ((len (string-length str1))) (let loop ((index 0) (result 0)) (if (= index len) result (loop (+ index 1) (if (eq? (string-ref str1 index) (string-ref str2 index)) ...
Give a code snippet in #Scheme 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Rascal
Rascal
public num Jenssen(int lo, int hi, num (int i) term){ temp = 0; while (lo <= hi){ temp += term(lo); lo += 1;} return temp; }
Give a code snippet in #Rascal Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the AL...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Picat
Picat
Picat> cl f(X,Y,Sep) = X ++ [Sep,Sep] ++ Y. <Ctrl-D> Picat> print(f("Rosetta","Code",':')) Rosetta::Code yes
Give a code snippet in #Picat Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#AutoHotkey
AutoHotkey
Loop %0% ; number of parameters params .= %A_Index% . A_Space If params != MsgBox, %0% parameters were passed:`n`n %params% Else Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\""
Give a code snippet in #AutoHotkey Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Retro
Retro
1024 [ cr &putn sip 2 / dup ] while
Give a code snippet in #Retro Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwar...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Babel
Babel
-- beer.sp   {b " bottles of beer" < bi { itoa << } < bb { bi ! b << w << "\n" << } < w " on the wall" < beer {<- { iter 1 + dup <- bb ! -> bi ! b << "\n" << "Take one down, pass it around\n" << iter bb ! "\n" << } -> ...
Give a code snippet in #Babel Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Lua
Lua
  i=0 repeat i=i+1 print(i) until i%6 == 0  
Give a code snippet in #Lua Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Dow...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Applesoft_BASIC
Applesoft BASIC
? LEN("HELLO, WORLD!")
Give a code snippet in #Applesoft_BASIC Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible gra...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#EchoLisp
EchoLisp
  (define-syntax-rule (inc x v) (set! x (+ x v))) (define (accumulator (sum 0)) (lambda(x) (inc sum x) sum))   (define x (accumulator 1)) → x (x 5) → 6   ;; another closure (accumulator 3) → (🔒 λ (_x) (📝 #set! sum (#+ sum _x)) sum)   (x 2.3) → 8.3  
Give a code snippet in #EchoLisp A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values ...
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 ...
#EchoLisp
EchoLisp
  ;; sorts a vector of objects in place ;; proc is an user defined comparison procedure   (define (bubble-sort V proc) (define length (vector-length V)) (for* ((i (in-range 0 (1- length))) (j (in-range (1+ i) length))) (unless (proc (vector-ref V i) (vector-ref V j)) (vector-swap! V i j))) V)     (define V ...
Give a code snippet in #EchoLisp 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/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation ...
#Prolog
Prolog
  ?- use_module(library(primality)).   circular(N) :- member(N, [2, 3, 5, 7]). circular(N) :- limit(15, ( candidate(N), N > 9, circular_prime(N))). circular(r(K)) :- between(6, inf, K), N is (10**K - 1) div 9, prime(N).   candidate(0). candidate(N) :- candidate(M), member...
Give a code snippet in #Prolog Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; procedure StripDemo is str : String := " Jabberwocky "; begin Put_Line ("'" & Trim (str, Left) & "'"); Put_Line ("'" & Trim (str, Right) & "'"); Put_Line ("'" & Trim (str, Both) & "'"...
Give a code snippet in #Ada Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace remo...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # convert number to base 20 sub base20(n: uint32, out: [uint8]): (n_digits: uint8) is n_digits := 0; loop [out] := (n % 20) as uint8; n := n / 20; out := @next out; n_digits := n_digits + 1; if n == 0 then break; end if; end...
Give a code snippet in #Cowgol Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left...
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...
#Ada
Ada
with Ada.Text_IO; procedure Combinations is   generic type Set is (<>); function Combinations (Count  : Positive; Output : Boolean := False) return Natural;   function Combinations (Count  : Positive; Output : Boolean := False) return Natural is package Set_...
Give a code snippet in #Ada 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#C
C
#include <stdio.h> #include <stdlib.h>   int main() { char *buffer; FILE *fh = fopen("readentirefile.c", "rb"); if ( fh != NULL ) { fseek(fh, 0L, SEEK_END); long s = ftell(fh); rewind(fh); buffer = malloc(s); if ( buffer != NULL ) { fread(buffer, s, 1, fh); // we can now clos...
Give a code snippet in #C Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished increment...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Logtalk
Logtalk
  :- initialization(main).  
Give a code snippet in #Logtalk Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages...
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...
#0815
0815
  }:s:|=<:2:x~#:e:=/~%~<:20:~$=<:73:x<:69:~$~$~<:20:~$=^:o:<:65: x<:76:=$=$~$<:6E:~$<:a:~$^:s:}:o:<:6F:x<:64:x~$~$$<:a:~$^:s:  
Give a code snippet in #0815 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. Divid...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Go
Go
package main   import "fmt"   func main() { for _, s := range []string{ "The quick brown fox jumps over the lazy dog.", `Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`, "Not a pangram.", } { if pangram(s) { fmt.Println("Yes:", s) } else { fmt....
Give a code snippet in #Go Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write ...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#VBScript
VBScript
  Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0)   cei = 0 : cie = 0 : ei = 0 : ie = 0   Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf...
Give a code snippet in #VBScript The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individu...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#COBOL
COBOL
identification division. program-id. hostname.   data division. working-storage section. 01 hostname pic x(256). 01 nullpos pic 999 value 1.   procedure division. call "gethostname" using hostname by value length of hostname string hostname delimited by lo...
Give a code snippet in #COBOL Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#F.23
F#
  let rec gcd a b = if b = 0 then abs a else gcd b (a % b)   >gcd 400 600 val it : int = 200
Give a code snippet in #F.23 Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest ...
christopher/rosetta-code
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#Raku
Raku
grammar S-Exp { rule TOP {^ <s-list> $};   token s-list { '(' ~ ')' [ <in_list>+ % [\s+] | '' ] } token in_list { <s-token> | <s-list> }   proto token s-token {*} token s-token:sym<Num> {\d*\.?\d+} token s-token:sym<String> {'"' ['\"' |<-[\\"]>]*? '"'} #' token s-token:sym<Atom> {<-[()\s]>+}   } ...
Give a code snippet in #Raku S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datas...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#CLU
CLU
taijitu = cluster is make rep = null   circle = proc (x,y,c,r: int) returns (bool) return (r**2 >= (x/2)**2 + (y-c)**2) end circle   pixel = proc (x,y,r: int) returns (char) if circle(x,y,-r/2,r/6) then return('#') elseif circle(x,y, r/2,r/6) then return('.') elseif c...
Give a code snippet in #CLU One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#D
D
void main() { import std.stdio, std.ascii, std.algorithm, std.range;   uint[26] frequency;   foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15)) foreach (immutable c; buffer.filter!isAlpha) frequency[c.toLower - 'a']++;   writefln("%(%(%s, %),\n%)", frequency[].chunks(10)); ...
Give a code snippet in #D Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignm...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Julia
Julia
module SpatialVectors   export SpatialVector   struct SpatialVector{N, T} coord::NTuple{N, T} end   SpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} = SpatialVector{N, T}(e .- s) function SpatialVector(∠::T, val::T) where T θ = atan(∠) x = val * cos(θ) y = val * sin(θ) return SpatialVec...
Give a code snippet in #Julia Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (l...
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 |...
#SAS
SAS
data _null_; a="abracadabra"; b=substr(a,2,3); /* first number is position, starting at 1, second number is length */ put _all_; run;
Give a code snippet in #SAS 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/The_ISAAC_Cipher
The ISAAC Cipher
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming...
#C.23
C#
  using System;   namespace cipher {   static class Cipher {   // external results static uint[] randrsl = new uint[256]; static uint randcnt; // internal state static uint[] mm = new uint[256]; static uint aa=0, bb=0, cc=0;     static void isaac() { uint i,x,y; cc++; // cc just gets incremented once per 256...
Give a code snippet in #C.23 ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architect...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <gmp.h>   typedef struct frac_s *frac; struct frac_s { int n, d; frac next; };   frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h;   while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = ...
Give a code snippet in #C FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial po...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#Java
Java
import javax.xml.bind.DatatypeConverter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;   /** * "Main Program" that does the parallel processing */ public class ParallelBrut...
Give a code snippet in #Java Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56...
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 ...
#Neko
Neko
/** Check that file/dir exists, in Neko */   var sys_exists = $loader.loadprim("std@sys_exists", 1) var sys_file_type = $loader.loadprim("std@sys_file_type", 1) var sys_command = $loader.loadprim("std@sys_command", 1)   var name = "input.txt" $print(name, " exists as file: ", sys_exists(name), "\n")   $print(name = "d...
Give a code snippet in #Neko 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/Sort_three_variables
Sort three variables
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 ...
#Nim
Nim
proc sortThree[T](a, b, c: var T) = # Bubble sort, why not? while not (a <= b and b <= c): if a > b: swap a, b if b > c: swap b, c   proc testWith[T](a, b, c: T) = var (x, y, z) = (a, b, c) echo "Before: ", x, ", ", y, ", ", z sortThree(x, y, z) echo "After: ", x, ", ", y, ", ", z   testWith(6, 4, 2...
Give a code snippet in #Nim 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/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#Java
Java
public interface Camera{ //functions here with no definition... //ex: //public void takePicture(); }
Give a code snippet in #Java Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePho...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Smalltalk
Smalltalk
perimeter := [:triangle | triangle reduce: #+].   squaredArea := [:triangle | | s | s := (perimeter value: triangle) / 2. triangle inject: s into: [:a2 :edge | s - edge * a2]].   isPrimitive := [:triangle | (triangle reduce: #gcd:) = 1].   isHeronian := [:triangle | (squaredArea value: triangle) sqrt isInteger].  ...
Give a code snippet in #Smalltalk Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Vlang
Vlang
struct Item { item string weight f64 price f64 }   fn main(){ mut left := 15.0 mut items := [ Item{'beef', 3.8, 36}, Item{'pork', 5.4, 43}, Item{'ham', 3.6, 90}, Item{'greaves', 2.4, 45}, Item{'flitch', 4.0, 30}, Item{'brawn', 2.5, 56}, Item{'w...
Give a code snippet in #Vlang A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the...
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...
#Bracmat
Bracmat
( 1:?number & 0:?lines & whl ' ( 1+!lines:~>10:?lines & :?say { This will accumulate all that has to be said after one iteration. } & 0:?begin & ( @( !number { Pattern matching. The '@' indicates we're looking in a string rather than a tree structure. } ...
Give a code snippet in #Bracmat 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 sequen...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Groovy
Groovy
new File('.').eachFileRecurse { if (it.name =~ /.*\.txt/) println it; }
Give a code snippet in #Groovy Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Wal...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Wren
Wren
var powers = List.filled(10, 0) for (i in 1..9) powers[i] = i.pow(i).round // cache powers   var munchausen = Fn.new {|n| if (n <= 0) Fiber.abort("Argument must be a positive integer.") var nn = n var sum = 0 while (n > 0) { var digit = n % 10 sum = sum + powers[digit] n = (n/10)...
Give a code snippet in #Wren A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Vlang
Vlang
fn repeat(n int, f fn()) { for _ in 0.. n { f() } }   fn func() { println("Example") }   fn main() { repeat(4, func) }
Give a code snippet in #Vlang Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
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. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigrat.s7i";   const proc: main is func begin writeln(bigRational parse "0.9(054)"); writeln(bigRational parse "0.(518)"); writeln(bigRational parse "0.75"); writeln(bigRational parse "3.(142857)"); writeln(bigRational parse "0.(8867924528301)"); writeln(bi...
Give a code snippet in #Seed7 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. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is...
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.
#PL.2FI
PL/I
(subscriptrange): filter_values: procedure options (main); /* 15 November 2013 */ declare a(20) fixed, b(*) fixed controlled; declare (i, j, n) fixed binary;   a = random()*99999; /* fill the array with random elements from 0-99998 */ put list ('Unfiltered values:'); put skip edit (a) (f(6)); /* Loop ...
Give a code snippet in #PL.2FI 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/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Delphi
Delphi
  program Number_names;   {$APPTYPE CONSOLE}   const smallies: array[1..19] of string = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'); tens: array[2..9] of string = ('twen...
Give a code snippet in #Delphi Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If th...
#Raku
Raku
use Lingua::EN::Numbers;   sub next-greatest-index ($str, &op = &infix:«<» ) { my @i = $str.comb; (1..^@i).first: { &op(@i[$_ - 1], @i[$_]) }, :end, :k; }   multi next-greatest-integer (Int $num where * >= 0) { return 0 if $num.chars < 2; return $num.flip > $num ?? $num.flip !! 0 if $num.chars == 2; ...
Give a code snippet in #Raku Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear ...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#D
D
import std.stdio, std.file;   void main() { auto dir = "somedir"; writeln(dir ~ " is empty: ", dirEmpty(dir)); }   bool dirEmpty(string dirname) { if (!exists(dirname) || !isDir(dirname)) throw new Exception("dir not found: " ~ dirname); return dirEntries(dirname, SpanMode.shallow).empty; }
Give a code snippet in #D Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#Delphi
Delphi
  program Read_a_file_character_by_character_UTF8;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Classes;   function GetNextCharacter(StreamReader: TStreamReader): char; begin Result := chr(StreamReader.Read); end;   const FileName: TFileName = 'input.txt';   begin if not FileExists(FileName) then r...
Give a code snippet in #Delphi Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should supp...
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.)
#M4
M4
eval(2*3) # eval(2*3) "#" and text after it aren't processed but passed along   dnl this text completely disappears, including the new line   divert(-1) Everything diverted to -1 is processed but the output is discarded. A comment could take this form as long as no macro names are used. divert
Give a code snippet in #M4 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/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)=(...
#Pascal
Pascal
Program LucasLehmer(output); var s, n: int64; i, exponent: integer; begin n := 1; for exponent := 2 to 31 do begin if exponent = 2 then s := 0 else s := 4; n := (n + 1)*2 - 1; // This saves from needing the math unit for exponentiation for i := 1 to exponent-2 do s := (s*s -...
Give a code snippet in #Pascal 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/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...
#Nim
Nim
import algorithm, sequtils, strutils, tables   const C = 0x2545F4914F6CDD1Du64   type XorShift = object state: uint64   func seed(gen: var XorShift; num: uint64) = gen.state = num   func nextInt(gen: var XorShift): uint32 = var x = gen.state x = x xor x shr 12 x = x xor x shl 25 x = x xor x shr 27 gen.sta...
Give a code snippet in #Nim 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 bit...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Python
Python
from fractions import Fraction   def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' '13 / 11, 15 / 14, 15 / 2, 55 / 1'): flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]   n = Frac...
Give a code snippet in #Python FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initi...
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 ) ) , ...
#x86_Assembly
x86 Assembly
global main extern printf   section .text   func_f mov eax, [esp+4] cmp eax, 0 jz f_ret dec eax push eax call func_f mov [esp+0], eax call func_m add esp, 4 mov ebx, [esp+4] sub ebx, eax mov eax, ebx ret f_ret mov eax, 1 ret   func_m mov eax, [esp+4] cmp eax, 0 jz m_ret dec eax push eax call fun...
Give a code snippet in #x86_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Clojure
Clojure
((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x)))))
Give a code snippet in #Clojure A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   class RCSpecialVariables   method RCSpecialVariables() x = super.toString y = this.toString say '<super>'x'</super>' say '<this>'y'</this>' say '<class>'RCSpecialVariables.class'</class>' say '<digits>'digits'</digits>' s...
Give a code snippet in #NetRexx Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#ooRexx
ooRexx
-- This assumes you've already downloaded the following file and placed it -- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt   -- There are several different ways of reading the file. I chose the -- supplier method just because I haven't used it yet in any other examples. source = .stream...
Give a code snippet in #ooRexx Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Tas...
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...
#OCaml
OCaml
for i = 10 downto 0 do Printf.printf "%d\n" i done
Give a code snippet in #OCaml 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/Increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind
Stirling numbers of the second kind
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 ...
#Java
Java
  import java.math.BigInteger; import java.util.HashMap; import java.util.Map;   public class SterlingNumbersSecondKind {   public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n...
Give a code snippet in #Java Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: ...
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :(copy-action) {}   (copy-action)!list obj cache: local :new [] set-to cache obj new for i range 0 -- len obj: push-to new (deepcopy) @obj! i cache return new   (copy-action)!dict obj cache: local :new {} set-to cache obj new for key in keys obj: set-to new (deepcopy) @key cache (deepcopy) @obj! @key c...
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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....
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Action.21
Action!
PROC Main() BYTE i, CH=$02FC, ;Internal hardware value for last key pressed PALNTSC=$D014, ;To check if PAL or NTSC system is used PCOLR0=$02C0,PCOLR1=$02C1, PCOLR2=$02C2,PCOLR3=$02C3, COLOR0=$02C4,COLOR1=$02C5, COLOR2=$02C6,COLOR3=$02C7, COLOR4=$02C8   Graphics(10) PCOLR0=$04 ;gra...
Give a code snippet in #Action.21 Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#zkl
zkl
const C=7, INFINITY=(0.0).inf;   fcn zero{ T(INFINITY, INFINITY) }   // should be INFINITY, but numeric precision is very much in the way fcn is_zero(p){ x,_:=p; (x < -1e20 or x > 1e20) }   fcn neg(p){ return(p[0], -p[1]) } fcn dbl(p){ if(is_zero(p)) return(p);   px,py := p; L:=(3.0 * px * px) / (2.0 * py); ...
Give a code snippet in #zkl Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nut...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#C.23
C#
using System; using System.IO;   namespace DirectoryWalk { class Program { static void Main(string[] args) { string[] filePaths = Directory.GetFiles(@"c:\MyDir", "a*"); foreach (string filename in filePaths) Console.WriteLine(filename); ...
Give a code snippet in #C.23 Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, n...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#ALGOL_68
ALGOL 68
  # operator to return the sum of the digits of an integer value in the # # specified base # PRIO SUMDIGITS = 1; OP SUMDIGITS = ( INT value, INT base )INT: IF base < 2 THEN # invalid base # print( ( "Base for digit sum must be at least 2...
Give a code snippet in #ALGOL_68 Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
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...
#Dyalect
Dyalect
var s = "hello" print(s + " literal") var s1 = s + " literal" print(s1)
Give a code snippet in #Dyalect 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 l...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_digital_rain
Matrix digital rain
Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia. Provided is a reference implementation in Common Lisp to be run in a terminal.
#Locomotive_Basic
Locomotive Basic
10 mode 0:defint a-z:randomize time:ink 0,0:ink 1,26:ink 2,19:border 0 20 dim p(20):mm=5:dim act(mm):for i=1 to mm:act(i)=rnd*19+1:next 30 md=mm-2:dim del(md):for i=1 to md:del(i)=rnd*19+1:next 40 for i=1 to mm:x=act(i):locate x,p(x)+1:pen 1:print chr$(rnd*55+145); 50 if p(x)>0 then locate x,p(x):pen 2:print chr$(rnd*5...
Give a code snippet in #Locomotive_Basic Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia. Provided is a reference implementation in Common Lisp to be run in a terminal.
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...
#AWK
AWK
BEGIN { s = "Hello,How,Are,You,Today" split(s, arr, ",") for(i=1; i < length(arr); i++) { printf arr[i] "." } print }
Give a code snippet in #AWK 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 rela...
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...
#Yabasic
Yabasic
sub wordsOK(string1$, string2$) return right$(string1$, 1) == left$(string2$, 1) End sub   sub Amb$(A$(), B$(), C$(), D$()) local a2, b2, c2, d2   For a2 = 1 To arraysize(A$(), 1) For b2 = 1 To arraysize(B$(), 1) For c2 = 1 To arraysize(C$(), 1) For d2 = 1 To arraysize(D$...
Give a code snippet in #Yabasic 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/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Ruby
Ruby
def rescale_price_fraction(value) raise ArgumentError, "value=#{value}, must have: 0 <= value < 1.01" if value < 0 || value >= 1.01 if value < 0.06 then 0.10 elsif value < 0.11 then 0.18 elsif value < 0.16 then 0.26 elsif value < 0.21 then 0.32 elsif value < 0.26 then 0.38 elsif value <...
Give a code snippet in #Ruby A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. 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, sexy primes are prime numbers that differ from each ot...
#Python
Python
LIMIT = 1_000_035 def primes2(limit=LIMIT): if limit < 2: return [] if limit < 3: return [2] lmtbf = (limit - 3) // 2 buf = [True] * (lmtbf + 1) for i in range((int(limit ** 0.5) - 3) // 2 + 1): if buf[i]: p = i + i + 3 s = p * (i + 1) + i buf[s::p] = [Fal...
Give a code snippet in #Python This page uses content from Wikipedia. The original article was at Sexy_prime. 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, sexy primes are prime ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Oz
Oz
declare %% helpers fun {Sum Xs} {FoldL Xs Number.'+' 0.0} end fun {Product Xs} {FoldL Xs Number.'*' 1.0} end fun {Len Xs} {Int.toFloat {Length Xs}} end   fun {AMean Xs} {Sum Xs} / {Len Xs} end   fun {GMean Xs} {Pow {Product Xs} 1.0/{Len Xs}} end   fun {HMean Xs} {L...
Give a code snippet in #Oz Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ...
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 ...
#JavaScript
JavaScript
function hamming() { var queues = {2: [], 3: [], 5: []}; var base; var next_ham = 1; while (true) { yield next_ham;   for (base in queues) {queues[base].push(next_ham * base)}   next_ham = [ queue[0] for each (queue in queues) ].reduce(function(min, val) { return Math...
Give a code snippet in #JavaScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#JavaScript
JavaScript
const determinant = arr => arr.length === 1 ? ( arr[0][0] ) : arr[0].reduce( (sum, v, i) => sum + v * (-1) ** i * determinant( arr.slice(1) .map(x => x.filter((_, j) => i !== j)) ), 0 );   const permanent = arr => arr.length === 1 ? ( arr[0][0] ...
Give a code snippet in #JavaScript For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Racket
Racket
#lang racket   (require racket/generator)   (define (memoize f) (define table (make-hash)) (λ args (hash-ref! table args (thunk (apply f args)))))   (define fusc (memoize (λ (n) (cond [(<= n 1) n] [(even? n) (fusc (/ n 2))] [else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))   ...
Give a code snippet in #Racket Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition s...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Objeck
Objeck
class CRC32 { function : Main(args : String[]) ~ Nil { "The quick brown fox jumps over the lazy dog"->ToByteArray()->CRC32()->PrintLine(); } }  
Give a code snippet in #Objeck Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets th...
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...
#C.2B.2B
C++
#include <iostream>   int main() { std::cout << "\a"; return 0; }
Give a code snippet in #C.2B.2B 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Isabelle
Isabelle
theory Brazilian imports Main begin   function (sequential) base :: "nat ⇒ nat ⇒ nat list" where "base n 0 = undefined" | "base n (Suc 0) = replicate n 1" | "base n b = (if n < b then [n] else (base (n div b) b) @ [n mod b] )" by pat_completeness auto termination base apply(relation "...
Give a code snippet in #Isabelle Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Elixir
Elixir
defmodule Heronian do def triangle?(a,b,c) when a+b <= c, do: false def triangle?(a,b,c) do area = area(a,b,c) area == round(area) and primitive?(a,b,c) end   def area(a,b,c) do s = (a + b + c) / 2  :math.sqrt(s * (s-a) * (s-b) * (s-c)) end   defp primitive?(a,b,c), do: gcd(gcd(a,b),c) == 1  ...
Give a code snippet in #Elixir Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a +...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#AutoHotkey
AutoHotkey
DllCall("AllocConsole") FileAppend, please type something`n, CONOUT$ FileReadLine, line, CONIN$, 1 msgbox % line FileAppend, please type '75000'`n, CONOUT$ FileReadLine, line, CONIN$, 1 msgbox % line
Give a code snippet in #AutoHotkey 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/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Maple
Maple
five_weekends:= proc() local i, month, count; #Only months with 31 days can possibly satisfy the condition local long_months := [1,3,5,7,8,10,12]; local months := ["January","February","March","April","May","June","July","August","September","October","November","December"]; count := 0; for i from 1900 to 2100 by...
Give a code snippet in #Maple The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (ther...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Lingo
Lingo
put "December 25 is a Sunday in:" refDateObj = date(1905,1,2) repeat with year = 2008 to 2121 dateObj = date(year, 12, 25) dayOfWeek = ((dateObj - refDateObj) mod 7)+1 -- 1=Monday..7=Sunday if dayOfWeek=7 then put year end repeat
Give a code snippet in #Lingo A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Robotic
Robotic
require 'gtk2'   window = Gtk::Window.new window.title = 'Goodbye, World' window.signal_connect(:delete-event) { Gtk.main_quit } window.show_all   Gtk.main
Give a code snippet in #Robotic Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Java
Java
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.m...
Give a code snippet in #Java Make sure you Connect to Active Directory
christopher/rosetta-code