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/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Neko
Neko
/* Repeat a string, in Neko */ var srep = function(s, n) { var str = "" while n > 0 { str += s n -= 1 } return str }   $print(srep("ha", 5), "\n")
Give a code snippet in #Neko Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#OCaml
OCaml
# [? 2 * x | x <- 0 -- max_int ; x * x > 3];; - : int Enum.t = <abstr>
Give a code snippet in #OCaml A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and th...
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.
#jq
jq
$ jq -n -M --arg x 1 '$x|type' # (*) "string"
Give a code snippet in #jq 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/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { println("Police Sanitation Fire") println("------ ---------- ----") var count = 0 for (i in 2..6 step 2) { for (j in 1..7) { if (j == i) continue for (k in 1..7) { if (k == i || k == j) continue ...
Give a code snippet in #Kotlin There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (d...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#Raku
Raku
sub r2cf(Rat $x is copy) { gather loop { $x -= take $x.floor; last unless $x > 0; $x = 1 / $x; } }   say r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>;
Give a code snippet in #Raku Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c...
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...
#x86-64_Assembly
x86-64 Assembly
  evenOdd: mov rax,1 and rax,rdi ret  
Give a code snippet in #x86-64_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#D
D
void main() { import std.stdio;   enum width = 512, height = 512;   auto f = File("xor_pattern.ppm", "wb"); f.writefln("P6\n%d %d\n255", width, height); foreach (immutable y; 0 .. height) foreach (immutable x; 0 .. width) { immutable c = (x ^ y) & ubyte.max; immutable...
Give a code snippet in #D Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Raku
Raku
use File::Temp;   # Generate a temp file in a temp dir my ($filename0,$filehandle0) = tempfile;   # specify a template for the filename # * are replaced with random characters my ($filename1,$filehandle1) = tempfile("******");   # Automatically unlink files at DESTROY (this is the default) my ($filename2,$filehandle2)...
Give a code snippet in #Raku Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions"...
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 ...
#XLISP
XLISP
(DISPLAY "Goodbye, World!" *ERROR-OUTPUT*)
Give a code snippet in #XLISP 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/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Maple
Maple
> use StringTools in Ord( "A" ); Char( 65 ) end; 65   "A"  
Give a code snippet in #Maple Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Ada
Ada
with Ada.Text_IO; with Ada.Strings.Unbounded;   procedure Knapsack_01 is package US renames Ada.Strings.Unbounded;   type Item is record Name  : US.Unbounded_String; Weight : Positive; Value  : Positive; Taken  : Boolean; end record;   type Item_Array is array (Positive range <>) of...
Give a code snippet in #Ada A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have t...
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 ...
#Haskell
Haskell
import Data.Time (fromGregorian) import Data.Time.Calendar.WeekDate (toWeekDate)   --------------------- DAY OF THE WEEK --------------------   isXmasSunday :: Integer -> Bool isXmasSunday year = 7 == weekDay where (_, _, weekDay) = toWeekDate $ fromGregorian year 12 25     --------------------------- TEST ------...
Give a code snippet in #Haskell 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 betwee...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Preserve_screen
Terminal control/Preserve screen
Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved.   If the implement...
#Befunge
Befunge
"h9401?["39*>:#,_"...erotser ot >retnE< sserPH["39*>:#,_~$"l9401?["39*>:#,_@
Give a code snippet in #Befunge Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Smalltalk
Smalltalk
handle := ExternalBytes new:size ... handle free
Give a code snippet in #Smalltalk Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
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.)
#KonsolScript
KonsolScript
//This is a comment. //This is another comment.   /* This is a comment too. */   /* This is a multi-line comment */
Give a code snippet in #KonsolScript 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/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Run_BASIC
Run BASIC
' formats array im() of size ims for ims = 4 to 6   print :print "--- Size: ";ims;" ---" Dim im(ims,ims)   For i = 1 To ims im(i,i) = 1 next   For row = 1 To ims print "["; cma$ = "" For col = 1 To ims print cma$;im(row, col); cma$ = ", " next print "]" next next ims
Give a code snippet in #Run_BASIC Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Wren
Wren
import "/fmt" for Conv   var urlDecode = Fn.new { |enc| var res = "" var i = 0 while (i < enc.count) { var c = enc[i] if (c == "\%") { var b = Conv.atoi(enc[i+1..i+2], 16) res = res + String.fromByte(b) i = i + 3 } else { res = res + c ...
Give a code snippet in #Wren This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded f...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int   var binomial = Fn.new { |n, k| if (n < 0 || k < 0) Fiber.abort("Arguments must be non-negative integers") if (n < k) Fiber.abort("The second argument cannot be more than the first.") if (n == k) return 1 var prod = 1 var i = n - k + 1 while (i <= n)...
Give a code snippet in #Wren This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#PowerShell
PowerShell
Function Test-MTF { [CmdletBinding()] Param ( [Parameter(Mandatory=$true,Position=0)] [string]$word,   [Parameter(Mandatory=$false)] [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz' ) Begin { Function Encode { Param ( ...
Give a code snippet in #PowerShell Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is u...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Nim
Nim
var t = open("/dev/tape", fmWrite) t.writeln "Hi Tape!" t.close
Give a code snippet in #Nim The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#JavaScript
JavaScript
/* create new Point in one of these ways: * var p = new Point(x,y); * var p = new Point(a_point); * default value for x,y is 0 */ function Point() { var arg1 = arguments[0]; var arg2 = arguments[1];   if (arg1 instanceof Point) { this.x = arg1.x; this.y = arg1.y; } else { ...
Give a code snippet in #JavaScript Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#C.2B.2B
C++
#include <QApplication> #include <QMainWindow>   int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow window; window.show(); return app.exec(); }
Give a code snippet in #C.2B.2B Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#PL.2FI
PL/I
Carmichael: procedure options (main, reorder); /* 24 January 2014 */ declare (Prime1, Prime2, Prime3, h3, d) fixed binary (31);   put ('Carmichael numbers are:');   do Prime1 = 1 to 61;   do h3 = 2 to Prime1;   d_loop: do d = 1 to h3+Prime1-1; if (mod((h3+Prime1)*(Prime1-1), d) = 0) & ...
Give a code snippet in #PL.2FI A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to inve...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Processing
Processing
float l = 3; int ints = 13;   void setup() { size(700, 600); background(0, 0, 255); translate(150, 100); stroke(255); turn_left(l, ints); turn_right(l, ints); }   void turn_right(float l, int ints) { if (ints == 0) { line(0, 0, 0, -l); translate(0, -l); } else { turn_left(l, ints-1); rot...
Give a code snippet in #Processing Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon follow...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#Phix
Phix
with javascript_semantics --string s = ".........#.........", --(original) string s = "...............................#"& "................................", --string s = "#"&repeat('.',100), -- [2] t=s, r = "........" integer rule = 30, k, l = length(s), w = 0 for i=1 to 8 do r[i] = iff(mod(ru...
Give a code snippet in #Phix Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting suc...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#C.2B.2B
C++
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); ...
Give a code snippet in #C.2B.2B Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions     -- isCusip :: String -> Bool on isCusip(s) set cs to "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*&#" set ns to mapMaybe(elemIndex(cs), s)   script go on |λ|(f, x) set fx to apply(f, x) (fx div 10) ...
Give a code snippet in #AppleScript This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphan...
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 |...
#Aikido
Aikido
  const str = "abcdefg" var n = 2 var m = 3   println (str[n:n+m-1]) // pos 2 length 3 println (str[n:]) // pos 2 to end println (str >> 1) // remove last character var p = find (str, 'c') println (str[p:p+m-1]) // from pos of p length 3   var s = find (str, "bc") println (str[s, s+m-1]) // pos ...
Give a code snippet in #Aikido Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Axe
Axe
99→B While B Disp B▶Dec," BOTTLES OF","BEER ON THE WALL" Disp B▶Dec," BOTTLES OF","BEER",i,i getKeyʳ Disp "TAKE ONE DOWN",i,"PASS IT AROUND",i B-- Disp B▶Dec," BOTTLES OF","BEER ON THE WALL",i getKeyʳ End
Give a code snippet in #Axe 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/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Perl
Perl
use 5.014; use Math::Algebra::Symbols;   sub bernoulli_number { my ($n) = @_;   return 0 if $n > 1 && $n % 2;   my @A; for my $m (0 .. $n) { $A[$m] = symbols(1) / ($m + 1);   for (my $j = $m ; $j > 0 ; $j--) { $A[$j - 1] = $j * ($A[$j - 1] - $A[$j]); } }   ret...
Give a code snippet in #Perl In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressi...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#MATLAB_.2F_Octave
MATLAB / Octave
stuff = {'apple', [1 2 3], 'cherry',1+2i}   stuff =   'apple' [1x3 double] 'cherry' [1.000000000000000 + 2.000000000000000i]
Give a code snippet in #MATLAB_.2F_Octave Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#Elixir
Elixir
defmodule Rock_paper_scissors do def play, do: loop([1,1,1])   defp loop([r,p,s]=odds) do IO.gets("What is your move? (R,P,S,Q) ") |> String.upcase |> String.first |> case do "Q" -> IO.puts "Good bye!" human when human in ["R","P","S"] -> IO.puts "Your move is #{play_to_s...
Give a code snippet in #Elixir Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winne...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. 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, Euler's identity is the equality: ...
#F.23
F#
  printfn "-1 + 1 = %d" (-1+1)  
Give a code snippet in #F.23 This page uses content from Wikipedia. The original article was at Euler's_identity. 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, Euler's identity i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Picat
Picat
s(N) = sum([1.0/K**2 : K in 1..N]).
Give a code snippet in #Picat Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Action.21
Action!
PROC ToBinaryStr(BYTE n CHAR ARRAY s) BYTE i   s(0)=8 i=8 SetBlock(s+1,8,'0) WHILE n DO s(i)=(n&1)+'0 n==RSH 1 i==-1 OD RETURN   PROC PrintB2(BYTE n) IF n<10 THEN Put(32) FI PrintB(n) RETURN   PROC PrintBin5(BYTE n) CHAR ARRAY s(9),sub(6)   ToBinaryStr(n,s) SCopyS(sub,s,4,s(0)) Print...
Give a code snippet in #Action.21 Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are m...
christopher/rosetta-code
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#AWK
AWK
  # syntax: GAWK -f DESCENDING_PRIMES.AWK BEGIN { start = 1 stop = 99999999 for (i=start; i<=stop; i++) { leng = length(i) flag = 1 for (j=1; j<leng; j++) { if (substr(i,j,1) <= substr(i,j+1,1)) { flag = 0 break } } if (flag) { if (is...
Give a code snippet in #AWK Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#langur
langur
val .isCusip = f(.s) { if not isString(.s) or len(.s) != 9 { return false }   val .basechars = cp2s('0'..'9') ~ cp2s('A'..'Z') ~ "*@#"   val .sum = for[=0] .i of 8 { var .v = index(s2s(.s, .i), .basechars) if not .v: return false .v = .v[1]-1 if .i div 2: .v x= 2 ...
Give a code snippet in #langur This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeri...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Swift
Swift
class Node<T>{ var data:T?=nil var next:Node?=nil init(input:T){ data=input next=nil } }  
Give a code snippet in #Swift singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element def...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Smalltalk
Smalltalk
|i|   i := 1. [:exit | Transcript showCR:i. i == 5 ifTrue:[ exit value:'stopped' ]. i := i + 1. ] loopWithExit
Give a code snippet in #Smalltalk Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} i...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Forth
Forth
\ gfb.fs - generalized fizz buzz : times ( xt n -- ) BEGIN dup WHILE 1- over swap 2>r execute 2r> REPEAT 2drop ; \ 'Domain Specific Language' compiling words \ -- First comment: stack-effect at compile-time \ -- Second comment: stack efect of compiled sequence : ]+[ ( u ca u -- ) ( u f -- u f' ) 2>r >r ] ]]...
Give a code snippet in #Forth Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#BASIC
BASIC
100 DEF PROC callstack 110 ON ERROR GOTO 1000 120 FOR i=1 TO 100 130 POP lnum 140 LIST lnum TO lnum 150 NEXT i 190 END PROC 1000 PRINT "End of stack" 1010 STOP
Give a code snippet in #BASIC Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the pl...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Bracmat
Bracmat
( LCS = A a ta B b tb prefix .  !arg:(?prefix.@(?A:%?a ?ta).@(?B:%?b ?tb)) & ( !a:!b&LCS$(!prefix !a.!ta.!tb) | LCS$(!prefix.!A.!tb)&LCS$(!prefix.!ta.!B) ) | !prefix:? ([>!max:[?max):?lcs | ) & 0:?max & :?lcs & LCS$(.thisisatest.testing123testing) & out$(max !max ...
Give a code snippet in #Bracmat Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be str...
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, ...
#HolyC
HolyC
F64 a = 0 ` 0; Print("0 ` 0 = %5.3f\n", a);
Give a code snippet in #HolyC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Nim
Nim
import strformat, tables   type Data1 = tuple[value: int; key: string] Data2 = tuple[key: string; value: string]   proc `$`(d: Data1 | Data2): string = &"({d[0]}, {d[1]})"   iterator hashJoin(table1: openArray[Data1]; table2: openArray[Data2]): tuple[a: Data1; b: Data2] = # Hash phase. var h: Table[string, seq[...
Give a code snippet in #Nim An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" a...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#ALGOL_68
ALGOL 68
BEGIN # find the last Friday in each month of a year # # returns true if year is a leap year, false otherwise # # assumes year is in the Gregorian Calendar # PROC is leap year = ( INT year )BOOL: year MOD 400 = 0 OR ( year MOD 4 = 0 AND year MOD 100 /= 0 ); # ...
Give a code snippet in #ALGOL_68 Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Yorick
Yorick
for(i = 1; i <= 100; i++) { if(i % 3 == 0) write, format="%s", "Fizz"; if(i % 5 == 0) write, format="%s", "Buzz"; if(i % 3 && i % 5) write, format="%d", i; write, ""; }
Give a code snippet in #Yorick Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Kronecker_product_based_fractals
Kronecker product based fractals
This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matrix   (filled with 0/1)   we ...
#C
C
  #include<graphics.h> #include<stdlib.h> #include<stdio.h>   typedef struct{ int row, col; }cell;   int ROW,COL,SUM=0;   unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); }   cell* kroneckerProduct(char* inputFile,int power){ FILE*...
Give a code snippet in #C This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matri...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#BBC_BASIC
BBC BASIC
Width% = 200 Height% = 200   REM Set window size: VDU 23,22,Width%;Height%;8,16,16,128   REM Draw circles: PROCcircle(100,100,40, 0,0,0) PROCcircle(100,100,80, 255,0,0) END   DEF PROCcircle(cx%,cy%,r%,R%,G%,B%) LOCAL f%, x%, y%, ddx%, ddy% f% = 1 - r% : ...
Give a code snippet in #BBC_BASIC Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#ERRE
ERRE
  PROGRAM ULAM   !$DOUBLE   PROCEDURE HAILSTONE(X,PRT%->COUNT) COUNT=1 IF PRT% THEN PRINT(X,) END IF REPEAT IF X/2<>INT(X/2) THEN X=X*3+1 ELSE X=X/2 END IF IF PRT% THEN PRINT(X,) END IF COUNT=COUNT+1 UNTIL X=1 IF PRT% THEN PRINT END IF END PROCEDURE   B...
Give a code snippet in #ERRE The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#C.23
C#
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width);   static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; // build input table and calculate columns count string[][] table = new string[line...
Give a code snippet in #C.23 Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#J
J
maxlen=: [: >./ #&> maxnum=: (0 ". ;)@(\: maxlen $&> ])@(8!:0)
Give a code snippet in #J Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#Raku
Raku
enum Color (red => 0o1000, green => 0o2000, purple => 0o4000); enum Count (one => 0o100, two => 0o200, three => 0o400); enum Shape (oval => 0o10, squiggle => 0o20, diamond => 0o40); enum Style (solid => 0o1, open => 0o2, striped => 0o4);   my @deck = Color.enums X Count.enums X Shape.enums X Style.enu...
Give a code snippet in #Raku Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, n...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Ada
Ada
with Ada.Text_IO; with Ada.Integer_Text_IO;   procedure Totient is   function Totient (N : in Integer) return Integer is Tot : Integer := N; I  : Integer; N2  : Integer := N; begin I := 2; while I * I <= N2 loop if N2 mod I = 0 then while N2 mod I = 0 loop ...
Give a code snippet in #Ada The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the i...
christopher/rosetta-code
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Julia
Julia
using LightGraphs   edge_list=[(1,2),(3,1),(6,3),(6,7),(7,6),(2,3),(4,2),(4,3),(4,5),(5,6),(5,4),(8,5),(8,8),(8,7)]   grph = SimpleDiGraph(Edge.(edge_list))   tarj = strongly_connected_components(grph)   inzerobase(arrarr) = map(x -> sort(x .- 1, rev=true), arrarr)   println("Results in the zero-base scheme: $(inzeroba...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
sum[term_, i_, lo_, hi_] := Block[{temp = 0}, Do[temp = temp + term, {i, lo, hi}]; temp]; SetAttributes[sum, HoldFirst];
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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 Je...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Inverse_video
Terminal control/Inverse video
Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
#BaCon
BaCon
COLOR INVERSE PRINT "a word" COLOR RESET PRINT "a word"
Give a code snippet in #BaCon Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Ursala
Ursala
#import int   dot = sum:-0+ product*p   #cast %z   test = dot(<1,3,-5>,<4,-2,-1>)
Give a code snippet in #Ursala Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -...
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      ...
#C.2B.2B
C++
#include<cstdio> int main(){char n[]=R"(#include<cstdio> int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}
Give a code snippet in #C.2B.2B 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/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...
#AWK
AWK
  # syntax: GAWK -f SEXY_PRIMES.AWK BEGIN { cutoff = 1000034 for (i=1; i<=cutoff; i++) { n1 = i if (is_prime(n1)) { total_primes++ if ((n2 = n1 + 6) > cutoff) { continue } if (is_prime(n2)) { save(2,5,n1 FS n2) if ((n3 = n2 + 6) > cutoff) { continue } ...
Give a code snippet in #AWK 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 num...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#C.2B.2B
C++
#include <iostream>   bool a(bool in) { std::cout << "a" << std::endl; return in; }   bool b(bool in) { std::cout << "b" << std::endl; return in; }   void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha ...
Give a code snippet in #C.2B.2B Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable r...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#CLU
CLU
series_sum = proc (from, to: int, fn: proctype (real) returns (real)) returns (real) sum: real := 0.0 for i: int in int$from_to(from, to) do sum := sum + fn(real$i2r(i)) end return(sum) end series_sum   one_over_k_squared = proc (k: real) returns (real) retur...
Give a code snippet in #CLU Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
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
#Vedit_macro_language
Vedit macro language
Statline_Message("Goodbye, World!")
Give a code snippet in #Vedit_macro_language 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/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Wren
Wren
var func2 = Fn.new { Fiber.abort("Forced error.") }   var func1 = Fn.new { func2.call() }   func1.call()
Give a code snippet in #Wren Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the pla...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#Perl
Perl
use strict; use 5.10.0;   use threads 'yield'; use threads::shared;   my @a :shared = (100) x 10; my $stop :shared = 0;   sub pick2 { my $i = int(rand(10)); my $j; $j = int(rand(10)) until $j != $i; ($i, $j) }   sub even { lock @a; my ($i, $j) = pick2; my $sum = $a[$i] + $a[$j]; $a[$i] = int($sum / 2); $a[$j] ...
Give a code snippet in #Perl Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all buc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Nanoquery
Nanoquery
import Nanoquery.Net   p = new(Port) p.connect("localhost", 256) p.write("hello socket world") p.close()
Give a code snippet in #Nanoquery For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#jq
jq
add/length
Give a code snippet in #jq Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an establi...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#BASIC256
BASIC256
# Begin Case / Case / End Case, Do / Until, If Then, While / End While begin case case boolean_expr statement(s) case boolean_expr statement(s) else statement(s) end case do statement(s) until boolean_expr if booleanexpr then statement(s) end if if booleanexpr then statem...
Give a code snippet in #BASIC256 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Comm...
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 ...
#min
min
(dup string "" split (int dup pow) (+) map-reduce ==) :munchausen? 1 :i (i 5000 <=) ((i munchausen?) (i puts!) when i succ @i) while
Give a code snippet in #min 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 T...
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...
#Clojure
Clojure
(apply str (interpose "." (.split #"," "Hello,How,Are,You,Today")))
Give a code snippet in #Clojure 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_n-step_number_sequences
Padovan n-step number sequences
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n ==...
#Phix
Phix
with javascript_semantics function padovann(integer n,t) if n<2 or t<3 then return repeat(1,t) end if sequence p = padovann(n-1, t) for i=n+2 to t do p[i] = sum(p[i-n-1..i-2]) end for return p end function constant t = 15, fmt = "%d: %d %d %d %d %d %d %d %2d %2d %2d %2d %2d %3d %3d %3d\n"...
Give a code snippet in #Phix As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R...
christopher/rosetta-code
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, Sylvester's sequence is an integer sequenc...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]] N[Total[1/%], 250]
Give a code snippet in #Mathematica.2FWolfram_Language This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In n...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Fantom
Fantom
  class Compose { static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2) { return |Obj x -> Obj| { fn2 (fn1 (x)) } }   public static Void main () { double := |Int x -> Int| { 2 * x } |Int -> Int| quad := compose(double, double) echo ("Double 3 = ${double(3)}") echo ("Quadruple 3 ...
Give a code snippet in #Fantom Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g ...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#FreeBASIC
FreeBASIC
Dim Shared As String B64 B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _ "abcdefghijklmnopqrstuvwxyz" & _ "0123456789+/"   Function MIMEDecode(s As String ) As Integer If Len(s) Then MIMEdecode = Instr(B64,s) - 1 Else MIMEdecode = -1 End If End Function   Function Decode64(s As String) As String ...
Give a code snippet in #FreeBASIC See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed outpu...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT -- size of file input.txt file="input.txt" ERROR/STOP OPEN (file,READ,-std-) file_size=BYTES ("input.txt") ERROR/STOP CLOSE (file)   -- size of file x:/input.txt ERROR/STOP OPEN (file,READ,x) file_size=BYTES (file) ERROR/STOP CLOSE (file)  
Give a code snippet in #TUSCRIPT Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Delphi
Delphi
proc nonrec main() void: byte DOORS = 100; [DOORS+1] bool door_open; unsigned DOORS i, j;   /* make sure all doors are closed */ for i from 1 upto DOORS do door_open[i] := false od;   /* pass through the doors */ for i from 1 upto DOORS do for j from i by i upto DOORS do ...
Give a code snippet in #Delphi 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/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Arturo
Arturo
evolve: function [arr][ ary: [0] ++ arr ++ [0] ret: new [] loop 1..(size ary)-2 'i [ a: ary\[i-1] b: ary\[i] c: ary\[i+1]   if? 2 = a+b+c -> 'ret ++ 1 else -> 'ret ++ 0 ] ret ]   printIt: function [arr][ print replace replace join map arr => [to :...
Give a code snippet in #Arturo Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the curren...
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....
#Action.21
Action!
BYTE Func Equals(CHAR ARRAY a,b) BYTE i   IF a(0)#b(0) THEN RETURN (0) FI   FOR i=1 TO a(0) DO IF a(i)#b(i) THEN RETURN (0) FI OD RETURN (1)   PROC Lcs(CHAR ARRAY a,b,res) CHAR ARRAY t(100) BYTE i,j,len   IF a(0)<b(0) THEN len=a(0) ELSE len=b(0) FI   WHILE len>0 DO ...
Give a code snippet in #Action.21 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 cons...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Liberty_BASIC
Liberty BASIC
' RC Constrained Random Points on a Circle   nomainwin   WindowWidth =400 WindowHeight =430   open "Constrained Random Points on a Circle" for graphics_nsb as #w   #w "trapclose [quit]" #w "down ; size 7 ; color red ; fill black"   for i =1 to 1000 do x =int( 30 *rnd( 1)) -15 y =int( 30 *rnd( 1)) -15 l...
Give a code snippet in #Liberty_BASIC Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Bracmat
Bracmat
fruits=apple+banana+cherry;
Give a code snippet in #Bracmat Task Create an enumeration of constants with and without explicit values.
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...
#Factor
Factor
USE: io.directories : empty-directory? ( path -- ? ) directory-entries empty? ;
Give a code snippet in #Factor 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Phix
Phix
-- demo/rosettacode/QRdecomposition.exw with javascript_semantics function matrix_mul(sequence a, b) integer arows = ~a, acols = ~a[1], brows = ~b, bcols = ~b[1] if acols!=brows then return 0 end if sequence c = repeat(repeat(0,bcols),arows) for i=1 to arows do for j=1 to bcols do ...
Give a code snippet in #Phix Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Lua
Lua
function ack(M,N) if M == 0 then return N + 1 end if N == 0 then return ack(M-1,1) end return ack(M-1,ack(M, N-1)) end
Give a code snippet in #Lua The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#NS-HUBASIC
NS-HUBASIC
10 COMPUTER=RND(3)+1 20 COMPUTER$="ROCK" 30 IF COMPUTER=2 THEN COMPUTER$="PAPER" 40 IF COMPUTER=3 THEN COMPUTER$="SCISSORS" 50 INPUT "ROCK, PAPER OR SCISSORS? ",HUMAN$ 60 IF HUMAN$="ROCK" THEN GOTO 100 70 IF HUMAN$="PAPER" THEN GOTO 100 80 IF HUMAN$="SCISSORS" THEN GOTO 100 90 PRINT "INVALID GUESS. TRY AGAIN.": GOTO 50...
Give a code snippet in #NS-HUBASIC Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The w...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#SequenceL
SequenceL
main() := babbage(0);   babbage(current) := current when current * current mod 1000000 = 269696 else babbage(current + 1);
Give a code snippet in #SequenceL Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic ...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Sidef
Sidef
var primes = (^Inf -> lazy.grep{.is_prime})   var upto = 1e6 var conspiracy = Hash()   primes.first(upto+1).reduce { |a,b| var d = b%10 conspiracy{"#{a} → #{d}"} := 0 ++ d }   for k,v in (conspiracy.sort_by{|k,_v| k }) { printf("%s count: %6s\tfrequency: %2.2f %\n", k, v.commify, v / upto * 100) }
Give a code snippet in #Sidef A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferen...
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...
#BaCon
BaCon
FUNCTION check$(dir$)   IF FILEEXISTS(dir$) THEN RETURN IIF$(LEN(WALK$(dir$, 127, ".+", FALSE)), " is NOT empty.", " is empty." ) ELSE RETURN " doesn't exist." ENDIF   ENDFUNCTION   dir$ = "bla" PRINT "Directory '", dir$, "'", check$(dir$)   dir$ = "/mnt" PRINT "Directory '", dir$, "'", chec...
Give a code snippet in #BaCon 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 em...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i";   const integer: delta is 8;   const proc: drawDown (inout integer: x, inout integer: y, in integer: n) is forward; const proc: drawUp (inout integer: x, inout integer: y, in integer: n) is forward;   const proc: drawRight (inout integer: x, inout i...
Give a code snippet in #Seed7 Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Yabasic
Yabasic
list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"   dim item$(1)   n = token(list$, item$(), ",")   line input "Enter string to search: " line$ for i = 1 to n if line$ = item$(i) then if not t print "First index for ", line$, ": ", i t = i j = j + 1 ...
Give a code snippet in #Yabasic Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle ...
christopher/rosetta-code
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Ruby
Ruby
require "prime"   smarandache = Enumerator.new do|y| prime_digits = [2,3,5,7] prime_digits.each{|pr| y << pr} # yield the below-tens (1..).each do |n| prime_digits.repeated_permutation(n).each do |perm| c = perm.join.to_i * 10 y << c + 3 if (c+3).prime? y << c + 7 if (c+7).prime? end ...
Give a code snippet in #Ruby The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundr...
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...
#Prolog
Prolog
splitup(Sep,[token(B)|BL]) --> splitup(Sep,B,BL). splitup(Sep,[A|AL],B) --> [A], {\+ [A] = Sep }, splitup(Sep,AL,B). splitup(Sep,[],[B|BL]) --> Sep, splitup(Sep,B,BL). splitup(_Sep,[],[]) --> []. start :- phrase(splitup(",",Tokens),"Hello,How,Are,You,Today"), phrase(splitup(".",Tokens),Backtoget...
Give a code snippet in #Prolog 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 r...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#REXX
REXX
/*REXX program computes and displays the Isqrt (integer square root) of some integers.*/ numeric digits 200 /*insure 'nuff decimal digs for results*/ parse arg range power base . /*obtain optional arguments from the CL*/ if range=='' | range=="," then range= 0..65 ...
Give a code snippet in #REXX Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Prolog
Prolog
  % Find the square root as a continued fraction   cf_sqrt(N, Sz, [A0, Frac]) :- A0 is floor(sqrt(N)), (A0*A0 =:= N -> Sz = 0, Frac = [] ; cf_sqrt(N, A0, A0, 0, 1, 0, [], Sz, Frac)).   cf_sqrt(N, A, A0, M0, D0, Sz0, L, Sz, R) :- M1 is D0*A0 - M0, D1 is (N - M1*M1) div D0, A1 is (...
Give a code snippet in #Prolog Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive...
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <pthread.h>   #include <SDL.h>   // defaults #define PROB_TREE 0.55 #define PROB_F 0.00001 #define PROB_P 0.001   #define TIMERFREQ 100   #ifndef WIDTH # define WIDTH 640 #endif #ifndef HEIGHT # define HEIGHT ...
Give a code snippet in #C This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schw...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#M4
M4
define(`V',`123')dnl define(`VN',`-123')dnl eval(V+1) eval(VN+1)
Give a code snippet in #M4 Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#R
R
intersect_point <- function(ray_vec, ray_point, plane_normal, plane_point) {   pdiff <- ray_point - plane_point prod1 <- pdiff %*% plane_normal prod2 <- ray_vec %*% plane_normal prod3 <- prod1 / prod2 point <- ray_point - ray_vec * as.numeric(prod3)   return(point) }
Give a code snippet in #R Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0...
christopher/rosetta-code
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). 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...
#Julia
Julia
using LibCURL   function callSOAP(url, infilename, outfilename) rfp = open(infilename, "r") wfp = open(outfilename, "w+")   header = curl_slist_append(header, "Content-Type:text/xml") header = curl_slist_append(header, "SOAPAction: rsc"); header = curl_slist_append(header, "Transfer-Encoding: chunke...
Give a code snippet in #Julia In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect on...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked # END CO   MODE OBJNEXTLINK = STRUCT( REF OBJNEXTLINK next, OBJVALUE value # ... etc. required # );   PROC obj nextlink new = REF OBJNEXTLINK: HEAP OBJNEXTLINK;   PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:...
Give a code snippet in #ALGOL_68 Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Haskell
Haskell
module Bitmap(module Bitmap) where   import Control.Monad import Control.Monad.ST import Data.Array.ST   newtype Pixel = Pixel (Int, Int) deriving Eq   instance Ord Pixel where compare (Pixel (x1, y1)) (Pixel (x2, y2)) = case compare y1 y2 of EQ -> compare x1 x2 v -> v   instance Ix...
Give a code snippet in #Haskell Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Arc
Arc
(point break (while t (let x (rand 20) (prn "a: " x) (if (is x 10) (break))) (prn "b: " (rand 20))))
Give a code snippet in #Arc Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Wart
Wart
def (qsort (pivot ... ns)) (+ (qsort+keep (fn(_) (_ < pivot)) ns) list.pivot (qsort+keep (fn(_) (_ > pivot)) ns))   def (qsort x) :case x=nil nil
Give a code snippet in #Wart 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