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/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...
#Raku
Raku
my %x = foo => 0, bar => [0, 1]; my %y = %x.deepmap(*.clone);   %x<bar>[1]++; say %x; say %y;
Give a code snippet in #Raku 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 fac...
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.
#OCaml
OCaml
let () = let top = Tk.openTk() in Wm.title_set top "An Empty Window"; Wm.geometry_set top "240x180"; Tk.mainLoop (); ;;
Give a code snippet in #OCaml 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/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Go
Go
package main   import "fmt"   func main() { fmt.Println(2*3*4*5*6*7*8*9*10) }
Give a code snippet in #Go Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
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      ...
#Applesoft_BASIC
Applesoft BASIC
10 LIST
Give a code snippet in #Applesoft_BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Icon_and_Unicon
Icon and Unicon
procedure main() lim := 13 wid := 5 every writes(right("* |" | (1 to lim) | "\n",wid)|right("\n",wid*(lim+1),"_")) # header row and separator every (i := 1 to lim) & writes(right( i||" |" | (j := 1 to lim, if j < i then "" else i*j) | "\n",wid)) # table content and triangle end
Give a code snippet in #Icon_and_Unicon Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program heapSort64.s */ /* look Pseudocode begin this task */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assem...
Give a code snippet in #AArch64_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Lambdatalk
Lambdatalk
  {def loops_for {lambda {:i :n} {if {>= :i :n} then (end of loop) else {br}{S.map {lambda {} *} {S.serie 0 :i}} {loops_for {+ :i 1} :n}}}} -> loops_for   {loops_for 0 5} -> * * * * * * * * * * * * * * * (end of loop)   a simpler way, using {S.map function {S.serie start end [step]}   {S.map {lamb...
Give a code snippet in #Lambdatalk “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract st...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Emacs_Lisp
Emacs Lisp
(when something (kill-emacs))
Give a code snippet in #Emacs_Lisp Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object final...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Nanoquery
Nanoquery
% println 5^3^2 15625 % println (5^3)^2 15625 % println 5^(3^2) 1953125
Give a code snippet in #Nanoquery This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements S...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#EchoLisp
EchoLisp
  (string-downcase "alphaBETA") → "alphabeta" (string-upcase "alphaBETA") → "ALPHABETA" (string-titlecase "alphaBETA") → "Alphabeta" (string-randcase "alphaBETA") → "alphaBEtA" (string-randcase "alphaBETA") → "AlPHaBeTA"  
Give a code snippet in #EchoLisp Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is no...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#BASIC
BASIC
f = freefile open f, "output.txt" write f, "This string is to be written to the file" close f
Give a code snippet in #BASIC Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#MUMPS
MUMPS
  CACHE>WRITE $DATA(VARI) 0 CACHE>SET VARI="HELLO" WRITE $DATA(VARI) 1 CACHE>NEW VARI WRITE $DATA(VARI) ;Change to a new scope 0 CACHE 1S1>SET VARI(1,2)="DOWN" WRITE $DATA(VARI) 10 CACHE 1S1>WRITE $DATA(VARI(1)) 10 CACHE 1S1>WRITE $D(VARI(1,2)) 1 CACHE 1S1>SET VARI(1)="UP" WRITE $DATA(VARI(1)) 11 <CACHE 1S1>QUIT ;Leave...
Give a code snippet in #MUMPS Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langu...
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.)
#XLISP
XLISP
; this is a comment
Give a code snippet in #XLISP 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/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#Ruby
Ruby
class Array def cocktailsort! begin swapped = false 0.upto(length - 2) do |i| if self[i] > self[i + 1] self[i], self[i + 1] = self[i + 1], self[i] swapped = true end end break unless swapped   swapped = false (length - 2).downto(0) do |i| ...
Give a code snippet in #Ruby 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/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Transd
Transd
#lang transd   MainModule : { _start: (λ (with fs FileStream() words String() (open-r fs "D:\\Temp\\wordlist.txt") (for line in (read-lines fs) do (with days (split line " ") len 0 (for w in days do (for y in days do (if (neq w y)...
Give a code snippet in #Transd The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or de...
christopher/rosetta-code
http://rosettacode.org/wiki/Pinstripe/Display
Pinstripe/Display
Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the display, we can switch to a wider 2 pi...
#Phix
Phix
(let Pbm # Create PBM of 384 x 288 pixels (make (for N 4 (let (C 0 L (make (do (/ 384 N) (do N (link C)) (setq C (x| 1 C)) ) ) ) (do 72 (link L)) ) ) ) (out '(display) # Pipe to ImageMagick (p...
Give a code snippet in #Phix Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the display,...
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Julia
Julia
# v0.6   using Dates   function easter(year::Int)::Date a = rem(year, 19) b, c = divrem(year, 100) d = rem(19a + b - div(b, 4) - div(b - div(b + 8, 25) + 1, 3) + 15, 30) e = rem(32 + 2 * rem(b, 4) + 2 * div(c, 4) - d - rem(c, 4), 7) f = d + e - 7 * div(a + 11d + 22e, 451) + 114 month, day = divr...
Give a code snippet in #Julia Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   year...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#BBC_BASIC
BBC BASIC
MAXRND = 7 FOR r% = 2 TO 5 check% = FNdistcheck(FNdice5, 10^r%, 0.05) PRINT "Over "; 10^r% " runs dice5 "; IF check% THEN PRINT "failed distribution check with "; check% " bin(s) out of range" ELSE PRINT "passed distribution check" ENDIF NEXT...
Give a code snippet in #BBC_BASIC This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing ran...
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 ...
#Python
Python
import os from PIL import Image     def imgsave(path, arr): w, h = len(arr), len(arr[0]) img = Image.new('1', (w, h)) for x in range(w): for y in range(h): img.putpixel((x, y), arr[x][y]) img.save(path)     def get_shape(mat): return len(mat), len(mat[0])     def kron(matrix1, ma...
Give a code snippet in #Python 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#ALGOL_68
ALGOL 68
PR read "uriParser.a68" PR   PROC test uri parser = ( STRING uri )VOID: BEGIN URI result := parse uri( uri ); print( ( uri, ":", newline ) ); IF NOT ok OF result THEN # the parse failed # print( ( " ", error OF result, newline ) ) ELSE ...
Give a code snippet in #ALGOL_68 URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Perl
Perl
use strict; use warnings; use constant True => 1;   sub add_edge { my ($g, $a, $b, $weight) = @_; $g->{$a} ||= {name => $a}; $g->{$b} ||= {name => $b}; push @{$g->{$a}{edges}}, {weight => $weight, vertex => $g->{$b}}; }   sub push_priority { my ($a, $v) = @_; my $i = 0; my $j = $#{$a}; w...
Give a code snippet in #Perl This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#jq
jq
# If the input is a valid representation of a binary string # then pass it along: def check_binary: . as $a | reduce .[] as $x ($a; if $x | (type == "number" and . == floor and 0 <= . and . <= 255) then $a else error("\(.) is an invalid representation of a byte") end );
Give a code snippet in #jq Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accordin...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Nanoquery
Nanoquery
items = {1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"} unique = {}   for item in items if not item in unique unique.append(item) end end
Give a code snippet in #Nanoquery Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64 Print "a - > "; Asc("a") Print "98 -> "; Chr(98) Print Print "Press any key to exit the program" Sleep End  
Give a code snippet in #FreeBASIC 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). ...
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Common_Lisp
Common Lisp
(defun augment-instance-with-slots (instance slots) (change-class instance (make-instance 'standard-class :direct-superclasses (list (class-of instance)) :direct-slots slots)))
Give a code snippet in #Common_Lisp Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Raku
Raku
use Image::PNG::Portable;   my ($w, $h) = (400, 400);   my $png = Image::PNG::Portable.new: :width($w), :height($h);   (0, .025 ... 52*π).race.map: -> \Θ { $png.set: |((cis( Θ / π ) * Θ).reals »+« ($w/2, $h/2))».Int, 255, 0, 255; }   $png.write: 'Archimedean-spiral-perl6.png';
Give a code snippet in #Raku The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#AutoHotkey
AutoHotkey
dice5() { Random, v, 1, 5 Return, v }   dice7() { Loop { v := 5 * dice5() + dice5() - 6 IfLess v, 21, Return, (v // 3) + 1 } }
Give a code snippet in #AutoHotkey Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls usin...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#8th
8th
  {"one": 1, "two": "bad"} ( swap . space . cr ) m:each  
Give a code snippet in #8th Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compo...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Ada
Ada
generic type Number is range <>; package Miller_Rabin is   type Result_Type is (Composite, Probably_Prime);   function Is_Prime (N : Number; K : Positive := 10) return Result_Type;   end Miller_Rabin;
Give a code snippet in #Ada This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primali...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Java
Java
import java.util.LinkedList;   public class Sieve{ public static LinkedList<Integer> sieve(int n){ if(n < 2) return new LinkedList<Integer>(); LinkedList<Integer> primes = new LinkedList<Integer>(); LinkedList<Integer> nums = new LinkedList<Integer>();   ...
Give a code snippet in #Java This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   al...
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.
#Commodore_BASIC
Commodore BASIC
100 FOR I=0 TO 24 110 : Y=INT(I*127/24) 120 : FOR J=0 TO 39 130 : X=INT(J*127/39) 140 : HL = (X OR Y) AND NOT (X AND Y) 150 : H = INT(HL / 8) 160 : L = HL - 8 * H 170 : POKE 2048+I*40+J,L*16+H 180 : POKE 3072+I*40+J,160 190 : NEXT J 210 NEXT I 220 GETKEY K$
Give a code snippet in #Commodore_BASIC 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/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)=(...
#Oz
Oz
%% compile : ozc -x <file.oz> functor import Application System define   fun {Arg Idx Default} Cmd = {Application.getArgs plain} Len = {Length Cmd} in if Len < Idx then Default else {StringToInt {Nth Cmd Idx}} end end   fun {LLtest N} Mp = {Pow 2 N} - 1 fun {S K} ...
Give a code snippet in #Oz 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/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#PicoLisp
PicoLisp
: (max 2 4 1 3) # Return the maximal argument -> 4 : (apply max (2 4 1 3)) # Apply to a list -> 4 : (maxi abs (2 -4 -1 3)) # Maximum according to given function -> -4
Give a code snippet in #PicoLisp Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#Kotlin
Kotlin
// version 1.1.4-3   fun Byte.toUInt() = java.lang.Byte.toUnsignedInt(this)   fun Byte.toULong() = java.lang.Byte.toUnsignedLong(this)   fun Int.toULong() = java.lang.Integer.toUnsignedLong(this)   val s = arrayOf( byteArrayOf( 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3), byteArrayOf(14, 11...
Give a code snippet in #Kotlin GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р a...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#JavaScript
JavaScript
/* * javascript bf interpreter * by wenxichang@163.com */   function execute(code) { var mem = new Array(30000); var sp = 10000; var opcode = new String(code); var oplen = opcode.length; var ip = 0; var loopstack = new Array(); var output = "";   for (var i = 0; i < 30000; ++i) mem[i]...
Give a code snippet in #JavaScript Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly i...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Z80_Assembly
Z80 Assembly
EmptyString: byte 0
Give a code snippet in #Z80_Assembly Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty....
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Hack
Hack
<?hh echo 'Hello world!'; ?>
Give a code snippet in #Hack Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#BBC_BASIC
BBC BASIC
N%=5 @%=LENSTR$(N%*N%-1)+1 BotCol%=0 : TopCol%=N%-1 BotRow%=0 : TopRow%=N%-1 DIM Matrix%(TopCol%,TopRow%)   Dir%=0 : Col%=0 : Row%=0 FOR I%=0 TO N%*N%-1 Matrix%(Col%,Row%)=I% PRINT TAB(Col%*@%,Row%) I% CASE Dir% OF WHEN 0: IF Col% < TopCol% THE...
Give a code snippet in #BBC_BASIC Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#Delphi
Delphi
open System   type Point = double * double type Triangle = Point * Point * Point   let Det2D (t:Triangle) = let (p1, p2, p3) = t let (p1x, p1y) = p1 let (p2x, p2y) = p2 let (p3x, p3y) = p3   p1x * (p2y - p3y) + p2x * (p3y - p1y) + p3x * (p1y - p2y)   let CheckTriWinding allowReversed t = ...
Give a code snippet in #Delphi Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt import "/sort" for Sort   var r = Random.new()   var dice5 = Fn.new { 1 + r.int(5) }   var checkDist = Fn.new { |gen, nRepeats, tolerance| var occurs = {} for (i in 1..nRepeats) { var d = gen.call() occurs[d] = occurs.containsKey(d) ? occurs[d] + ...
Give a code snippet in #Wren This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random i...
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) ...
#Brat
Brat
1.to 100 { n | true? n % 15 == 0 { p "FizzBuzz" } { true? n % 3 == 0 { p "Fizz" } { true? n % 5 == 0 { p "Buzz" } { p n } } } }
Give a code snippet in #Brat 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 ...
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...
#Perl
Perl
  use 5.10.0;   my $w = `tput cols` - 1; my $h = `tput lines` - 1; my $r = "\033[H";   my ($green, $red, $yellow, $norm) = ("\033[32m", "\033[31m", "\033[33m", "\033[m");   my $tree_prob = .05; my $burn_prob = .0002;   my @forest = map([ map((rand(1) < $tree_prob) ? 1 : 0, 1 .. $w) ], 1 .. $h);   sub iterate { my @new...
Give a code snippet in #Perl 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 S...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_literals,_with_continuations
Long literals, with continuations
This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The literal is to be in the form ...
#Python
Python
"""Long string literal. Requires Python 3.6+ for f-strings."""   revision = "October 13th 2020"   # String literal continuation. Notice the trailing space at the end of each # line but the last, and the lack of commas. There is exactly one "blank" # between each item in the list. elements = ( "hydrogen helium lithi...
Give a code snippet in #Python This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). T...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox: 0 0 300 300   /plate { exch 100 mul 50 add exch th mul 10 add moveto dup s mul neg 2 div 0 rmoveto dup s mul 0 rlineto 0 th rlineto s neg mul 0 rlineto closepath gsave .5 setgray fill grestore 0 setgray stroke } def   /drawtower { 0 1...
Give a code snippet in #PostScript Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Lua
Lua
function make(value, modulo) local v = value % modulo local tbl = {value=v, modulo=modulo}   local mt = { __add = function(lhs, rhs) if type(lhs) == "table" then if type(rhs) == "table" then if lhs.modulo ~= rhs.modulo then erro...
Give a code snippet in #Lua Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Emacs_Lisp
Emacs Lisp
(defun sum-3-5 (n) (let ((sum 0)) (dotimes (x n) (when (or (zerop (% x 3)) (zerop (% x 5))) (setq sum (+ sum x)))) sum))
Give a code snippet in #Emacs_Lisp Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
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...
#Go
Go
package main   import "fmt"   func accumulator(sum interface{}) func(interface{}) interface{} { return func(nv interface{}) interface{} { switch s := sum.(type) { case int: switch n := nv.(type) { case int: sum = s + n case float64: ...
Give a code snippet in #Go 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Forth
Forth
: luhn ( addr len -- ? ) 0 >r over + ( R: sum ) begin 1- 2dup <= while \ odd dup c@ [char] 0 - r> + >r 1- 2dup <= while \ even dup c@ [char] 0 - 2* 10 /mod + \ even digits doubled, split, and summed r> + >...
Give a code snippet in #Forth The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of...
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#Java
Java
public class SpinningRod { public static void main(String[] args) throws InterruptedException { String a = "|/-\\"; System.out.print("\033[2J"); // hide the cursor long start = System.currentTimeMillis(); while (true) { for (int i = 0; i < 4; i++) { Syst...
Give a code snippet in #Java Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the p...
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.
#Tcl
Tcl
#include <tcl.h>   /* A data structure used to enforce data safety */ struct block { int size; unsigned char data[4]; };   static int Memalloc( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_HashTable *nameMap = clientData; static int nameCounter = 0; ch...
Give a code snippet in #Tcl 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/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...
#Logtalk
Logtalk
:- object(hailstone).   :- public(generate_sequence/2). :- mode(generate_sequence(+natural, -list(natural)), zero_or_one). :- info(generate_sequence/2, [ comment is 'Generates the Hailstone sequence that starts with its first argument. Fails if the argument is not a natural number.', argnames is ['Start', 'Seque...
Give a code snippet in #Logtalk 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) + ...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Q
Q
r:x%0 ?[1=sum r=(0n;0w;-0w);"division by zero detected";()]
Give a code snippet in #Q Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Frege
Frege
module Happy where   import Prelude.Math -- ugh, since Frege doesn't have Set, use Map instead import Data.Map (member, insertMin, empty emptyMap)   digitToInteger :: Char -> Integer digitToInteger c = fromInt $ (ord c) - (ord '0')   isHappy :: Integer -> Bool isHappy = p emptyMap where p _ 1n = true p s n | ...
Give a code snippet in #Frege From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron tri...
#Factor
Factor
USING: assocs.extras grouping io kernel lists lists.lazy math math.primes.factors prettyprint ranges sequences ;   : pair-same? ( ... n quot: ( ... m -- ... n ) -- ... ? ) [ dup 1 + ] dip same? ; inline   : RA-f? ( n -- ? ) [ factors sum ] pair-same? ; : RA-d? ( n -- ? ) [ group-factors sum-keys ] pair-same? ; : fi...
Give a code snippet in #Factor A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime ...
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...
#PHP
PHP
<?php function compose($f, $g) { return function($x) use ($f, $g) { return $f($g($x)); }; }   $trim_strlen = compose('strlen', 'trim'); echo $result = $trim_strlen(' Test '), "\n"; // prints 4 ?>
Give a code snippet in #PHP 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/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Bracmat
Bracmat
(knapsack= ( things = (map.9.150.1) (compass.13.35.1) (water.153.200.2) (sandwich.50.60.2) (glucose.15.60.2) (tin.68.45.3) (banana.27.60.3) (apple.39.40.3) (cheese.23.30.1) (beer.52.10.3) (suntan cream.11.70.1) (camera.32.30.1) (T-shirt.24.15...
Give a code snippet in #Bracmat 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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg w...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#J
J
luhn=: 0 = 10 (| +/@,) 10 #.inv 1 2 *&|: _2 "."0\ |.
Give a code snippet in #J The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#jq
jq
# zip/0 emits [] if input is [].   def zip: . as $in | [range(0; $in[0]|length) as $i | $in | map( .[$i] ) ];
Give a code snippet in #jq Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Io
Io
Example := Object clone Example foo := method(x, 42+x)   name := "foo" Example clone perform(name,5) println // prints "47"
Give a code snippet in #Io Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#SPL
SPL
width,height = #.scrsize() #.angle(#.degrees) #.scroff() incr = 0 > incr = (incr+0.05)%360 x = width/2 y = height/2 length = 5 angle = incr #.scrclear() #.drawline(x,y,x,y) > i, 1..150 x += length*#.cos(angle) y += length*#.sin(angle) #.drawcolor(#.hsv2rgb(angle,1,1):3) #.drawline(x,y) ...
Give a code snippet in #SPL A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the ang...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. 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: Def...
#Ada
Ada
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_IO;   procedure Traversing is package Char_Lists is new Ada.Containers.Doubly_Linked_Lists (Character);   procedure Print (Position : in Char_Lists.Cursor) is begin Ada.Text_IO.Put (Char_Lists.Element (Position)); end Print;   My_List : Char_Li...
Give a code snippet in #Ada Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Rem...
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"
#Liberty_BASIC
Liberty BASIC
print CommandLine$
Give a code snippet in #Liberty_BASIC 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/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#zkl
zkl
T(1,2).extend(T(4,5,6)) //-->L(1,2,4,5,6) T(1,2).extend(4,5,6) //-->L(1,2,4,5,6)
Give a code snippet in #zkl Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Latitude
Latitude
use 'format importAllSigils.   doors := Object clone. doors missing := { False. }. doors check := { self slot ($1 ordinal). }. doors toggle := { self slot ($1 ordinal) = self slot ($1 ordinal) not. }. 1 upto 101 do { takes '[i]. local 'j = i. while { j <= 100. } do { doors toggle (j). j = j + i. }. ...
Give a code snippet in #Latitude 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/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#Sidef
Sidef
class PalindromeGenerator (digit, base=10) {   has power = base has after = (digit*power - 1) has even = false   method next {   if (++after == power*(digit+1)) { power *= base if even after = digit*power even.not! }   even ? (after*power*base...
Give a code snippet in #Sidef Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful nu...
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 ...
#Julia
Julia
function fizzbuzz(triggers :: Vector{Tuple{Int, ASCIIString}}, upper :: Int) for i = 1 : upper triggered = false   for trigger in triggers if i % trigger[1] == 0 triggered = true print(trigger[2]) end end    !triggered && print(i...
Give a code snippet in #Julia 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/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#SNUSP
SNUSP
$!/?\=false= + =true=# \-/
Give a code snippet in #SNUSP Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Ring
Ring
  system("dir")  
Give a code snippet in #Ring Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#C.23
C#
using System; using MathNet.Numerics.LinearRegression; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double;   class Program { static void Main(string[] args) { var col = DenseVector.OfArray(new double[] { 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.7...
Give a code snippet in #C.23 Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . ....
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...
#Delphi
Delphi
  USES StdCtrls, Classes, SysUtils, StrUtils, Contnrs;   procedure AlignByColumn(Output: TMemo; Align: TAlignment); const TextToAlign = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$'#$D#$A + 'are$delineated$by$a$single$''dollar''$character,$write$a$program'#$D#$A + 'that$aligns$each$colum...
Give a code snippet in #Delphi 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 le...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Phix
Phix
with javascript_semantics ?lcm(12,18) ?lcm({12,18})
Give a code snippet in #Phix Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has ...
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: ...
#Wren
Wren
import "random" for Random import "/str" for Str import "/ioutil" for Input   var choices = "rpsq" var rand = Random.new()   var pWins = 0 // player wins var cWins = 0 // computer wins var draws = 0 // neither wins var games = 0 // games played var pFreqs = [0, 0, 0] // player f...
Give a code snippet in #Wren Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner ...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#R
R
  # based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R ceasar <- function(x, key) { # if key is negative, wrap to be positive if (key < 0) { key <- 26 + key }   old <- paste(letters, LETTERS, collapse="", sep="") new <- paste(substr(old, key * 2 + 1, 52), substr(old, 1, key * 2), sep="") ch...
Give a code snippet in #R Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A)....
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Tcl
Tcl
proc eval_twice {func a b} { set x $a set 1st [expr $func] set x $b set 2nd [expr $func] expr {$2nd - $1st} }   puts [eval_twice {2 ** $x} 3 5] ;# ==> 24
Give a code snippet in #Tcl x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and l...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Nanoquery
Nanoquery
def count_divisors(n) count = 0 for (i = 1) ((i * i) <= n) (i += 1) if (n % i) = 0 if i = (n / i) count += 1 else count += 2 end end ...
Give a code snippet in #Nanoquery Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors...
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...
#ATS
ATS
(*   Compile with "myatscc isqrt.dats", thus obtaining an executable called "isqrt".   ##myatsccdef=\ patscc -O2 \ -I"${PATSHOME}/contrib/atscntrb" \ -IATS "${PATSHOME}/contrib/atscntrb" \ -D_GNU_SOURCE -DATS_MEMALLOC_LIBC \ -o $fname($1) $1 -lgmp   *)   #include "share/atspre_staload.hats"   (* An interface to...
Give a code snippet in #ATS 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 p...
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 ...
#GAP
GAP
IsExistingFile("input.txt"); IsDirectoryPath("docs"); IsExistingFile("/input.txt"); IsDirectoryPath("/docs");
Give a code snippet in #GAP 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/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...
#Emacs_Lisp
Emacs Lisp
;; -*- lexical-binding: t; -*- (mapcar #'funcall (mapcar (lambda (x) (lambda () (* x x))) '(1 2 3 4 5 6 7 8 9 10))) ;; => (1 4 9 16 25 36 49 64 81 100)
Give a code snippet in #Emacs_Lisp 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/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...
#Gambas
Gambas
Public Sub Main()   Print String$(5, "ha")   End
Give a code snippet in #Gambas 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/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Fantom
Fantom
  a := "" // assign an empty string to 'a' a.isEmpty // method on sys::Str to check if string is empty a.size == 0 // what isEmpty actually checks a == "" // alternate check for an empty string !a.isEmpty // check that a string is not empty  
Give a code snippet in #Fantom Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#FOCAL
FOCAL
TYPE "Hello, world" !
Give a code snippet in #FOCAL Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Python
Python
import fileinput   changerow, changecolumn, changevalue = 2, 4, '"Spam"'   with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue l...
Give a code snippet in #Python CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, cha...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#PicoLisp
PicoLisp
(for F (sort (dir)) (prinl F) )
Give a code snippet in #PicoLisp Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exa...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   shared sealed class Rational(numerator, denominator = 1) satisfies Numeric<Rational> {   shared Integer numerator; shared Integer denominator;   Integer gcd(Integer a, Integer b) => if (b == 0) then a else gcd(b, a % b);   shared Rational inverted => Rational(denominator, n...
Give a code snippet in #Ceylon task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Oforth
Oforth
[["Joe",5531], ["Adam",2341], ["Bernie",122], ["David",19]] sortBy(#first) println
Give a code snippet in #Oforth Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#Phix
Phix
with javascript_semantics include builtins\cffi.e constant tGSH = """ HANDLE WINAPI GetStdHandle( _In_ DWORD nStdHandle ); """, tSCOCP = """ BOOL WINAPI SetConsoleOutputCP( _In_ UINT wCodePageID ); """, STD_OUTPUT_HANDLE = -11, CP_UTF8 = 65001, envset = {"LANG","LC_ALL","LC_CTYPE"} atom k32 = NULL, xGetStd...
Give a code snippet in #Phix The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note tha...
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 ...
#EDSAC_order_code
EDSAC order code
  [Bubble sort demo for Rosetta Code website] [EDSAC program. Initial Orders 2]   [Sorts a list of double-word integers. List must be loaded at an even address. First item gives number of items to follow. Address of list is placed in location 49. List can then be referred to with code letter L.] ...
Give a code snippet in #EDSAC_order_code 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Racket
Racket
  #lang racket/gui   (define-values [W H] (get-display-size #t))   (define parts 4) (define colors '("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White"))   (define (paint-pinstripe canvas dc) (send dc set-pen "black" 0 'transparent) (send dc set-brush "black" 'solid) (define H* (round (/ H parts))) ...
Give a code snippet in #Racket The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Forth
Forth
stdin slurp-fid type bye
Give a code snippet in #Forth Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Scala
Scala
val list = List(1,2,3,4,2,3,4,99) val l2 = list.distinct // l2: scala.List[scala.Int] = List(1,2,3,4,99)   val arr = Array(1,2,3,4,2,3,4,99) val arr2 = arr.distinct // arr2: Array[Int] = Array(1, 2, 3, 4, 99)  
Give a code snippet in #Scala Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Raku
Raku
use ntheory:from<Perl5> <is_prime>;   for 3 .. 11 -> $base { say "Starting base $base..."; my @stems = grep { .is-prime }, ^$base; for 1 .. * -> $digits { print ' ', @stems.elems; my @new; my $place = $base ** $digits; for 1 ..^ $base -> $digit { my $left = $digit...
Give a code snippet in #Raku A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis
Vigenère cipher/Cryptanalysis
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS...
#C.2B.2B
C++
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <array> using namespace std;   typedef array<pair<char, double>, 26> FreqArray;   class VigenereAnalyser { private: array<double, 26> targets; array<double, 26> sortedTargets; FreqArray freq;   // Update the fr...
Give a code snippet in #C.2B.2B Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text: MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VU...
christopher/rosetta-code
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#OCaml
OCaml
let permutation = [151;160;137;91;90;15; 131;13;201;95;96;53;194;233;7;225;140;36;103;30;69;142;8;99;37;240;21;10;23; 190; 6;148;247;120;234;75;0;26;197;62;94;252;219;203;117;35;11;32;57;177;33; 88;237;149;56;87;174;20;125;136;171;168; 68;175;74;165;71;134;139;48;27;166; 77;146;158;231;83;111;229;122;60;211;133;230;220...
Give a code snippet in #OCaml The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#BBC_BASIC
BBC BASIC
FIFOSIZE = 1000   FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END   DEF PROCenqueue(n) : LOCAL f% D...
Give a code snippet in #BBC_BASIC Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Suneido
Suneido
Print("Hello world!")
Give a code snippet in #Suneido Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#xTalk
xTalk
  on DecToVLQ Ask "Enter base 10 value:" -- input dialog box if it is not empty then if it is a number then put it into theString if isWholeNumString(theString) is false then -- I think there is built in equivalent for this but I rolled my own! answer "Only Whole Decimal Number...
Give a code snippet in #xTalk Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert ...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#PHP
PHP
<?php class Maze { protected $width; protected $height; protected $grid; protected $path; protected $horWalls; protected $vertWalls; protected $dirs; protected $isDebug;   public function __construct($x, $y, $debug = false) { $this->width = $x; $this->height = $y...
Give a code snippet in #PHP This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Clojure
Clojure
  (defn cfrac [a b n] (letfn [(cfrac-iter [[x k]] [(+ (a k) (/ (b (inc k)) x)) (dec k)])] (ffirst (take 1 (drop (inc n) (iterate cfrac-iter [1 n]))))))   (def sq2 (cfrac #(if (zero? %) 1.0 2.0) (constantly 1.0) 100)) (def e (cfrac #(if (zero? %) 2.0 %) #(if (= 1 %) 1.0 (double (dec %))) 100)) (def pi (cfrac #(i...
Give a code snippet in #Clojure continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to w...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#zkl
zkl
stdin:=File.stdin.read(); thisFileSrc:=File(System.argv[1]).read(); println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match");
Give a code snippet in #zkl Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and prod...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Scheme
Scheme
  >(define gcd (lambda (a b) (if (zero? b) a (gcd b (remainder a b))))) >(define lcm (lambda (a b) (if (or (zero? a) (zero? b)) 0 (abs (* b (floor (/ a (gcd a b)))))))) >(lcm 12 18) 36
Give a code snippet in #Scheme Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that ha...
christopher/rosetta-code