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/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...
#Yabasic
Yabasic
  REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***   text$ = "You are encouraged to solve this task according to the task description, using any language you may know." key$ = "desoxirribonucleic acid" // With a single character you get a Caesar encryption. W...
Give a code snippet in #Yabasic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Powershell
Powershell
Function Truncate-File(fname) { $null | Set-Content -Path "$fname" }  
Give a code snippet in #Powershell Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by cr...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings   func StrLen(A); \Return number of characters in an ASCIIZ string char A; int I; for I:= 0 to -1>>1-1 do if A(I) = 0 then return I;   func StrFind(A, B); \Search ...
Give a code snippet in #XPL0 Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Ukkonen%E2%80%99s_suffix_tree_construction
Ukkonen’s suffix tree construction
Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calculate Pi generate the first 1...
#Wren
Wren
import "/big" for BigRat import "/dynamic" for Struct import "/trait" for ByRef import "io" for File   var maxChar = 128   var Node = Struct.create("Node", ["children", "suffixLink", "start", "pEnd", "suffixIndex"])   var text = "" var root = null var lastNewNode = null var acti...
Give a code snippet in #Wren Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Cal...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0)   DIM a(6), b(5) a() = 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 b() = 4.1, 7.2, 1.7, 9.3, 4.4, 3.2   PRINT "Median of a() is " ; FNmedian(a()) PRINT "Median of b() is " ; FNmedian(b()) END   DEF FNmedian(a()) LOCAL C% ...
Give a code snippet in #BBC_BASIC Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle val...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Elixir
Elixir
iex(1)> list = Enum.to_list(1..20) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] iex(2)> Enum.random(list) 19 iex(3)> Enum.take_random(list,4) [19, 20, 7, 15]
Give a code snippet in #Elixir Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#Scala
Scala
object Main extends App { print("\u001Bc") // clear screen first println("\u001B[6;3HHello") }
Give a code snippet in #Scala Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Tcl
Tcl
package require Tcl 8.5 namespace eval subrand { variable mod 1000000000 state [lrepeat 55 0] si 0 sj 0   proc seed p1 { global subrand::mod subrand::state subrand::si subrand::sj set p2 1 lset state 0 [expr {$p1 % $mod}] for {set i 1; set j 21} {$i < 55} {incr i; incr j 21} { if {$j >= 55} {incr j -55...
Give a code snippet in #Tcl A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#PowerShell
PowerShell
  [string[]]$volume = cmd /c vol   $volume  
Give a code snippet in #PowerShell Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function x = hailstone(n) x = n; while n > 1 % faster than mod(n, 2) if n ~= floor(n / 2) * 2 n = n * 3 + 1; else n = n / 2; end x(end + 1) = n; %#ok end
Give a code snippet in #MATLAB_.2F_Octave 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   = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Common_Lisp
Common Lisp
  (defun integer-to-list (n) (map 'list #'digit-char-p (prin1-to-string n)))   (defun narcissisticp (n) (let* ((lst (integer-to-list n)) (e (length lst))) (= n (reduce #'+ (mapcar (lambda (x) (expt x e)) lst)))))   (defun start () (loop for c from 0 while (< narcissistic 25) c...
Give a code snippet in #Common_Lisp A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displayst...
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...
#uBasic.2F4tH
uBasic/4tH
if set (a, open ("yourcsv.csv", "r")) < 0 then print "Cannot open \qyourcsv.csv\q" ' open file a for reading end ' abort on file opening errors endif   if set (b, open ("mycsv.csv", "w")) < 0 then print "Cannot open \qmycsv.csv\q" ' open file a for writing end ...
Give a code snippet in #uBasic.2F4tH 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 fil...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#J
J
(pred;succ;<data) conew 'DoublyLinkedListElement'
Give a code snippet in #J Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Eleme...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Scala
Scala
  object StringLength extends App { val s1 = "møøse" val s3 = List("\uD835\uDD18", "\uD835\uDD2B", "\uD835\uDD26", "\uD835\uDD20", "\uD835\uDD2C", "\uD835\uDD21", "\uD835\uDD22").mkString val s4 = "J\u0332o\u0332s\u0332e\u0301\u0332"   List(s1, s3, s4).foreach(s => println( s"The string: $s, chara...
Give a code snippet in #Scala Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme cont...
christopher/rosetta-code
http://rosettacode.org/wiki/Twelve_statements
Twelve statements
This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. If statement 5 is true, then statemen...
#Common_Lisp
Common Lisp
  (defparameter *state* (make-list 12))   (defparameter *statements* '(t ; 1 (= (count-true '(7 8 9 10 11 12)) 3) ; 2 (= (count-true '(2 4 6 8 10 12)) 2) ; 3 ...
Give a code snippet in #Common_Lisp This puzzle is borrowed from   math-frolic.blogspot. Given the following twelve statements, which of them are true? 1. This is a numbered list of twelve statements. 2. Exactly 3 of the last 6 statements are true. 3. Exactly 2 of the even-numbered statements are true. 4. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Phix
Phix
with javascript_semantics include mpfr.e procedure multi_order(mpz res, a, sequence p_and_k) mpz {pk,t,x,q,pz} = mpz_inits(5) mpz_set_si(res,1) if length(p_and_k)=1 then string {ps} = p_and_k mpz_set_str(pk,ps) mpz_sub_ui(t,pk,1) else atom {p, k} = p_and_k mpz_s...
Give a code snippet in #Phix The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is effici...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Factor
Factor
USING: kernel sequences splitting math accessors io.encodings.ascii io.files math.parser io ; IN: maxlicenses   TUPLE: maxlicense max-count current-count times ;   <PRIVATE   : <maxlicense> ( -- max ) -1 0 V{ } clone \ maxlicense boa ; inline   : out? ( line -- ? ) [ "OUT" ] dip subseq? ; inline   : line-time ( line --...
Give a code snippet in #Factor A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a ch...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE REALPTR="CARD" TYPE PointR=[REALPTR x,y]   INT ARRAY SinTab=[ 0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83 88 92 96 100 104 108 112 116 120 124 128 132 136 139 143 147 150 154 158 161 165 168 171 175 178 181 184 187 190 193 196 199 202 204 20...
Give a code snippet in #Action.21 A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or to...
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...
#Malbolge
Malbolge
b'`;$9!=IlXFiVwwvtPO0)pon%IHGFDV|dd@Q=+^:('&Y$#m!1S|.QOO=v('98$65aCB}0i.Tw+QPU'7qK#I20jiDVgG S(bt<%@#!7~|4{y1xv.us+rp(om%lj"ig}fd"cx``uz]rwvYnslkTonPfOjiKgJeG]\EC_X]@[Z<R;VU7S6QP2N1LK-I ,GF(D'BA#?>7~;:9y16w43s10)p-,l*#(i&%e#d!~``{tyxZpuXsrTTongOkdMhg`Hd]ba`_^W@[ZYXW9UNSRQPOHMLK J-++FE''<A$?>=<;:387xw43s10/(-&m*)('&}${d...
Give a code snippet in #Malbolge 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 ...
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...
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" )   func main() { empty, err := IsEmptyDir("/tmp") if err != nil { log.Fatalln(err) } if empty { fmt.Printf("/tmp is empty\n") } else { fmt.Printf("/tmp is not empty\n") } }   func IsEmptyDir(name string) (bool, error) { entries, err := ioutil.ReadDir(name...
Give a code snippet in #Go Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Smalltalk
Smalltalk
Integer extend [ millerRabinTest: kl [ |k| k := kl. self <= 3 ifTrue: [ ^true ] ifFalse: [ (self even) ifTrue: [ ^false ] ifFalse: [ |d s| d := self - 1. s := 0. [ (d rem: 2) == 0 ] whileTrue: [ ...
Give a code snippet in #Smalltalk 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 p...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Icon_and_Unicon
Icon and Unicon
# strip_comments: # return part of string up to first character in 'markers', # or else the whole string if no comment marker is present procedure strip_comments (str, markers) return str ? tab(upto(markers) | 0) end   procedure main () write (strip_comments ("apples, pears and bananas", cset ("#;"))) write (...
Give a code snippet in #Icon_and_Unicon Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 ...
#Commodore_BASIC
Commodore BASIC
100 REM SORT BY COMPARISON 110 DIM IN$(6), OU$(6) 120 FOR I=0 TO 6:READ IN$(I): NEXT I 130 DATA VIOLET,RED,GREEN,INDIGO,BLUE,YELLOW,ORANGE 140 OU$(0)=IN$(0):N=1 150 FOR I=1 TO 6 160 : IN$=IN$(I) 180 : GOSUB 390 190 : FOR J=0 TO N-1 200 : OU$ = OU$(J) 210 : GOSUB 340 220 : IF R>=0 THEN 280 230 : FOR K=N TO J+1 STEP ...
Give a code snippet in #Commodore_BASIC 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/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#ChucK
ChucK
  "Hello" => string A; A + " World!" => string B; <<< B >>>;  
Give a code snippet in #ChucK String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string lit...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#PureBasic
PureBasic
Procedure factorial(n) Protected i, f = 1 For i = 2 To n f = f * i Next ProcedureReturn f EndProcedure
Give a code snippet in #PureBasic Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of...
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...
#Tcl
Tcl
package require Tcl 8.5   proc miller_rabin {n k} { if {$n <= 3} {return true} if {$n % 2 == 0} {return false}   # write n - 1 as 2^s·d with d odd by factoring powers of 2 from n − 1 set d [expr {$n - 1}] set s 0 while {$d % 2 == 0} { set d [expr {$d / 2}] incr s }   whil...
Give a code snippet in #Tcl 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/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Perl
Perl
perl -n -0777 -e 'print "file len: ".length' stuff.txt
Give a code snippet in #Perl Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Sidef
Sidef
func fib(n) { return NaN if (n < 0)   func (n) { n < 2 ? n  : (__FUNC__(n-1) + __FUNC__(n-2)) }(n) }
Give a code snippet in #Sidef While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwant...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#AutoHotkey
AutoHotkey
set1 := "the that a" set2 := "frog elephant thing" set3 := "walked treaded grows" set4 := "slowly quickly"   MsgBox % amb( "", set1, set2, set3, set4 ) ; this takes a total of 17 iterations to complete   amb( char = "", set1 = "", set2 = "", set3 = "", set4 = "" ) { ; original call to amb must leave char param b...
Give a code snippet in #AutoHotkey Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite auto...
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...
#Action.21
Action!
PROC CheckIsEmpty(CHAR ARRAY s) PrintF("'%S' is empty? ",s) IF s(0)=0 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC Main() CHAR ARRAY str1,str2   str1="" str2="text"   CheckIsEmpty(str1) CheckIsEmpty(str2) RETURN
Give a code snippet in #Action.21 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/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#VBA
VBA
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean 'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level. Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, Degr...
Give a code snippet in #VBA Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT e(3,2): REM 3 ^ 2 20 PRINT e(1.5,2.7): REM 1.5 ^ 2.7 30 STOP 9950 DEF FN e(a,b)=a^b
Give a code snippet in #ZX_Spectrum_Basic Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclops_numbers
Cyclops numbers
A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10. There are many different ...
#Raku
Raku
use Lingua::EN::Numbers;   my @cyclops = 0, |flat lazy ^∞ .map: -> $exp { my @oom = (exp($exp, 10) ..^ exp($exp + 1, 10)).grep: { !.contains: 0 } |@oom.hyper.map: { $_ ~ 0 «~« @oom } }   my @prime-cyclops = @cyclops.grep: { .is-prime };   for '', @cyclops, 'prime ', @prime-...
Give a code snippet in #Raku A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base ...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Slate
Slate
PositiveInfinity
Give a code snippet in #Slate Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise,...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#ACL2
ACL2
:set-state-ok t   (defun array-swap (name array i j) (let ((ai (aref1 name array i)) (aj (aref1 name array j))) (aset1 name (aset1 name array j ai) i aj)))   (defun shuffle-r (name array m state) (if (zp m) (mv array state) (mv-let (i state) (r...
Give a code snippet in #ACL2 The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of   precedence   and   associativity...
#PicoLisp
PicoLisp
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
Give a code snippet in #PicoLisp This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a function to find the closest two p...
#Java
Java
import java.util.*;   public class ClosestPair { public static class Point { public final double x; public final double y;   public Point(double x, double y) { this.x = x; this.y = y; }   public String toString() { return "(" + x + ", " + y + ")"; } }   public static cl...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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 Provide a func...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Scala
Scala
def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8   val primitives: List[(Any, Long)] = List((Byte, Byte.MaxValue), (Short, Short.MaxValue), (Int, Int.MaxValue), (Long, Long.MaxValue))   primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${n...
Give a code snippet in #Scala Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols nobinary   parse arg nbr rangeBegin rangeEnd .   if nbr = '' | nbr = '.' then do if rangeBegin = '' | rangeBegin = '.' then rangeBegin = 1 if rangeEnd = '' | rangeEnd = '.' then rangeEnd = 100 if rangeEnd > rangeBegin then directi...
Give a code snippet in #NetRexx Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#uBasic.2F4tH
uBasic/4tH
print "Degree | Multifactorials 1 to 10" for x = 1 to 53 : print "-"; : next : print for d = 1 to 5 print d;" ";"| "; for n = 1 to 10 print FUNC(_multiFact(n, d));" "; next print next   end   _multiFact param (2) local (2) c@ = 1 for d@ = a@ to 2 step -b@ c@ = c@ * d@ next retur...
Give a code snippet in #uBasic.2F4tH The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Lambdatalk
Lambdatalk
  {feigenbaum 11} // on my computer stackoverflow for values greater than 11 -> [3.2185114220380866,4.3856775985683365,4.600949276538056,4.6551304953919646,4.666111947822846, 4.668548581451485,4.66906066077106,4.669171554514976,4.669195154039278,4.669200256503637]   with:   {def feigenbaum {lambda {:maxi} {f3 :maxi...
Give a code snippet in #Lambdatalk Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Common_Lisp
Common Lisp
(defun coloured-text () (with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil) (dolist (i '(:red :green :yellow :blue :magenta :cyan :white)) (add-string scr (format nil "~A~%" i) :fgcolor i)) (refresh scr) ;; wait for keypress (get-char scr)))
Give a code snippet in #Common_Lisp Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour H...
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Ruby
Ruby
def cut_it(h, w) if h.odd? return 0 if w.odd? h, w = w, h end return 1 if w == 1   nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] # [next,dy,dx] blen = (h + 1) * (w + 1) - 1 grid = [false] * (blen + 1)   walk = lambda do |y, x, count=0| return count+1 if y==0 or y==h or x==0 or...
Give a code snippet in #Ruby A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths ...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#zkl
zkl
fcn bind(a,type,b){ if(type.isType(a)) b else Void } fcn just(x){ if(Deferred.isType(x)) x() else x } // force lazy evaluation fcn rtn(x) { just(x) }
Give a code snippet in #zkl Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and retur...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#11l
11l
V template = ‘<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.’   F madlibs(template) print("The story template is:\n"template) V fields = sorted(Array(Set(re:‘<[^>]+>’.find_strings(template)))) V values = input("\nInput a comma-separated list of words to replace ...
Give a code snippet in #11l This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Julia
Julia
#declaration/assignment, declaration is optional x::Int32 = 1 #datatypes are inferred dynamically, but can also be set thru convert functions and datatype literals x = 1 #x is inferred as Int, which is Int32 for 32-bit machines, Int64 for 64-bit machines #variable reference julia>x 1   x = int8(1) #x is of type Int8 x ...
Give a code snippet in #Julia Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#min
min
(1 2 3 4) 0 '+ reduce puts! ; sum (1 2 3 4) 1 '* reduce puts! ; product
Give a code snippet in #min Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. S...
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 ...
#APL
APL
  h ← ⎕fio['fopen'] 'input.txt' h 7 ⎕fio['fstat'] h 66311 803134 33188 1 1000 1000 0 11634 4096 24 1642047105 1642047105 1642047105 ⎕fio['fclose'] h 0 h ← ⎕fio['fopen'] 'docs/' h 7 ⎕fio['fstat'] h 66311 3296858 16877 2 1000 1000 0 4096 4096 8 1642047108 1642047108 164204710...
Give a code snippet in #APL 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/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.
#Pascal
Pascal
my @arr1 = (1, 2, 3); my @arr2 = (4, 5, 6); my @arr3 = (@arr1, @arr2);
Give a code snippet in #Pascal 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/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Fantom
Fantom
  class Palindrome { // Function to test if given string is a palindrome public static Bool isPalindrome (Str str) { str == str.reverse }   // Give it a test run public static Void main () { echo (isPalindrome("")) echo (isPalindrome("a")) echo (isPalindrome("aa")) echo (isPalindrome(...
Give a code snippet in #Fantom A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly a...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Racket
Racket
  #lang racket   (define input (for/list ([i 11]) (printf "Enter a number (~a of 11): " (+ 1 i)) (read)))   (for ([x (reverse input)]) (define res (+ (sqrt (abs x)) (* 5 (expt x 3)))) (if (> res 400) (displayln "Overflow!") (printf "f(~a) = ~a\n" x res)))  
Give a code snippet in #Racket The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#ALGOL_68
ALGOL 68
# Find Munchausen Numbers between 1 and 5000 # # note that 6^6 is 46 656 so we only need to consider numbers consisting of 0 to 5 #   # table of Nth powers - note 0^0 is 0 for Munchausen numbers, not 1 # []INT nth power = ([]INT( 0, 1, 2 * 2, 3 * 3 * 3, 4 * 4 * 4...
Give a code snippet in #ALGOL_68 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 se...
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.)
#NATURAL
NATURAL
* This is a comment and extends to the end of the line
Give a code snippet in #NATURAL 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/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # Sum of squares sub sumsquare(vec: [int32], len: intptr): (out: uint32) is out := 0; while len > 0 loop var cur := [vec]; # make positive first so we can use extra range of uint32 if cur < 0 then cur := -cur; end if; out := out +...
Give a code snippet in #Cowgol Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on thi...
#Julia
Julia
using Primes   function wilsonprimes(limit = 11000) sgn, facts = 1, accumulate(*, 1:limit, init = big"1") println(" n: Wilson primes\n--------------------") for n in 1:11 print(lpad(n, 2), ": ") sgn = -sgn for p in primes(limit) if p > n && (facts[n < 2 ? 1 : n - 1] * f...
Give a code snippet in #Julia Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. ...
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
accum n: labda i: set :n + n i n   local :x accum 1 drop x 5 drop accum 3 !print x 2.3
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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 numeri...
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: ...
#Ruby
Ruby
class RockPaperScissorsGame CHOICES = %w[rock paper scissors quit] BEATS = { 'rock' => 'paper', 'paper' => 'scissors', 'scissors' => 'rock', }   def initialize() @plays = { 'rock' => 1, 'paper' => 1, 'scissors' => 1, } @score = [0, 0, 0] # [0]:Hum...
Give a code snippet in #Ruby 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/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Ela
Ela
fib n | n < 0 = fail "Negative n" | else = fix (\f n -> if n < 2 then n else f (n - 1) + f (n - 2)) n
Give a code snippet in #Ela While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
stripchars[a_,b_]:=StringReplace[a,(#->"")&/@Characters[b]] stripchars["She was a soul stripper. She took my heart!","aei"] ->Sh ws soul strppr. Sh took my hrt!
Give a code snippet in #Mathematica.2FWolfram_Language Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripp...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#Ruby
Ruby
def partition(mask) return [[]] if mask.empty? [*1..mask.inject(:+)].permutation.map {|perm| mask.map {|num_elts| perm.shift(num_elts).sort } }.uniq end
Give a code snippet in #Ruby In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Nim
Nim
import random   import rapid/gfx   var window = initRWindow() .title("Rosetta Code - Chaos Game") .open() surface = window.openGfx() sierpinski = window.newRCanvas() points: array[3, Vec2[float]]   for i in 0..<3: points[i] = vec2(cos(PI * 2 / 3 * i.float), sin(PI * 2 / 3 * i.float)) * 300   var point...
Give a code snippet in #Nim The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as t...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#D
D
import std.stdio;   void vanEck(int firstIndex, int lastIndex) { int[int] vanEckMap; int last = 0; if (firstIndex == 1) { writefln("VanEck[%d] = %d", 1, 0); } for (int n = 2; n <= lastIndex; n++) { int vanEck = last in vanEckMap ? n - vanEckMap[last] : 0; vanEckMap[last] = n;...
Give a code snippet in #D The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured pre...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Racket
Racket
  #lang racket   (define (truncate file size) (unless (file-exists? file) (error 'truncat "missing file: ~a" file)) (when (> size (file-size file)) (printf "Warning: extending file size.\n")) (call-with-output-file* file #:exists 'update (λ(o) (file-truncate o size))))  
Give a code snippet in #Racket Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creati...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#q
q
  pascal:{(x-1){0+':x,0}\1} pascal 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1  
Give a code snippet in #q Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 o...
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 ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program quickSort.s */ /* look pseudo code in wikipedia quicksort */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, ...
Give a code snippet in #ARM_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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#C
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdint.h> #include <ctype.h>   typedef unsigned char uchar;   typedef enum { nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd...
Give a code snippet in #C A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#NetRexx
NetRexx
s_ = 'Hello' s_ = s_', world!' say s_
Give a code snippet in #NetRexx Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
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...
#Go
Go
// Go doesn't have generics, but sometimes a type definition helps // readability and maintainability. This example is written to // the following function type, which uses float64. type ffType func(float64) float64   // compose function requested by task func compose(f, g ffType) ffType { return func(x float64) ...
Give a code snippet in #Go 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   t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Nanoquery
Nanoquery
import sort   // sorting string literals x = "lion, tigers, and" y = "bears, oh my!" z = "(from the \"Wizard of OZ\")"   varlist = sort({x,y,z})   x = varlist[0] y = varlist[1] z = varlist[2] println x; println y; println z   // sorting integers x = 77444 y = -12 z = 0   varlist = sort({x, y, z})   x = varlist[0] y = v...
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/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Rust
Rust
fn fib(n: i64) -> Option<i64> { // A function declared inside another function does not pollute the outer namespace. fn actual_fib(n: i64) -> i64 { if n < 2 { n } else { actual_fib(n - 1) + actual_fib(n - 2) } }   if n < 0 { None } else { ...
Give a code snippet in #Rust While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwante...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Phix
Phix
constant s = "(test)" ?s[2..-1] ?s[1..-2] ?s[2..-2]
Give a code snippet in #Phix The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Rust
Rust
// Part 1: Inverted index structure   use std::{ borrow::Borrow, collections::{BTreeMap, BTreeSet}, };   #[derive(Debug, Default)] pub struct InvertedIndex<T> { indexed: BTreeMap<String, BTreeSet<usize>>, sources: Vec<T>, }   impl<T> InvertedIndex<T> { pub fn add<I, V>(&mut self, source: T, tokens: ...
Give a code snippet in #Rust An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ter...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#MACRO-10
MACRO-10
  title Host Introspection subttl PDP-10 assembly (MACRO-10 on TOPS-20). KJX 2022. search monsym,macsym   comment \ The wordsize is detected by putting 1 into a re- gister, counting the leading zeros (resulting in wordsize-1) and adding 1 to the result.   Endianness doesn't really apply...
Give a code snippet in #MACRO-10 Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#PHP
PHP
echo "Goodbye, World !";
Give a code snippet in #PHP Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standar...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#TI-89_BASIC
TI-89 BASIC
Define doors(fast) = Func Local doors,i,j seq(false,x,1,100) ? doors If fast Then For i,1,10,1 true ? doors[i^2] EndFor Else For i,1,100,1 For j,i,100,i not doors[j] ? doors[j] EndFor EndFor EndIf Return doors EndFunc
Give a code snippet in #TI-89_BASIC 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, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Java
Java
import java.util.*;   public class PasswordGenerator { final static Random rand = new Random();   public static void main(String[] args) { int num, len;   try { if (args.length != 2) throw new IllegalArgumentException();   len = Integer.parseInt(args[0]); ...
Give a code snippet in #Java Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:...
christopher/rosetta-code
http://rosettacode.org/wiki/Leonardo_numbers
Leonardo numbers
Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = L(n-1) + L(n-2) + 1 ...
#Python
Python
def Leonardo(L_Zero, L_One, Add, Amount): terms = [L_Zero,L_One] while len(terms) < Amount: new = terms[-1] + terms[-2] new += Add terms.append(new) return terms   out = "" print "First 25 Leonardo numbers:" for term in Leonardo(1,1,1,25): out += str(term) + " " print out   out =...
Give a code snippet in #Python Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#Python
Python
import re   # Optional Python 2.x compatibility #try: input = raw_input #except: pass   template = '''<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.'''   def madlibs(template): print('The story template is:\n' + template) fields = sorted(set( re.findall('<[^>]+>'...
Give a code snippet in #Python This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#8086_Assembly
8086 Assembly
call foo
Give a code snippet in #8086_Assembly Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function w...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Visual_Basic
Visual Basic
import "graphics" for Canvas, Color import "input" for Keyboard, Clipboard import "dome" for Window, Process   var X = 10 var Y = 28   class Main { construct new() {}   init() { _text = "" _enterNum = false Keyboard.handleText = true Keyboard.textRegion(X, Y, 8, 8) }   up...
Give a code snippet in #Visual_Basic In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Wren
Wren
import "/big" for BigInt, BigRat   var sylvester = [BigInt.two] var prod = BigInt.two var count = 1 while (true) { var next = prod + 1 sylvester.add(next) count = count + 1 if (count == 10) break prod = prod * next } System.print("The first 10 terms in the Sylvester sequence are:") System.print(sylv...
Give a code snippet in #Wren 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 ...
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 ...
#Batch_File
Batch File
1>&2 echo Goodbye, World!
Give a code snippet in #Batch_File 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#jq
jq
def stoogesort: def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;   # for efficiency, define an auxiliary function # that takes as input [L, i, j] def ss: .[1] as $i | .[2] as $j | .[0] | if .[$j] < .[$i] then swap($i;$j) else . end | if $j - $i > 1 then (($j - $i + 1) / 3 | floor) a...
Give a code snippet in #jq Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#ReScript
ReScript
let my_compare = (a, b) => { if a < b { "A is less than B" } else if a > b { "A is greater than B" } else if a == b { "A equals B" } else { "cannot compare NANs" } }   let a = int_of_string(Sys.argv[2]) let b = int_of_string(Sys.argv[3])   Js.log(my_compare(a, b))
Give a code snippet in #ReScript 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#ActionScript
ActionScript
var arr:Array = new Array(1, 2, 3, 4, 5); var evens:Array = new Array(); for (var i:int = 0; i < arr.length(); i++) { if (arr[i] % 2 == 0) evens.push(arr[i]); }
Give a code snippet in #ActionScript Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#SNOBOL4
SNOBOL4
* # Create sample table t = table() t<'cat'> = 'meow' t<'dog'> = 'woof' t<'pig'> = 'oink'   * # Convert table to key/value array a = convert(t,'array')   * # Iterate pairs ploop i = i + 1; output = a<i,1> ' -> ' a<i,2> :s(ploop) * # Iterate keys kloop ...
Give a code snippet in #SNOBOL4 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#PHP
PHP
$seconds = 42; echo "Sleeping...\n"; sleep($seconds); # number is integer in seconds echo "Awake!\n";
Give a code snippet in #PHP Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread f...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Unprotect[Mean]; Mean[{}] := 0
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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 progr...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
VanDerCorput[n_,base_:2]:=Table[ FromDigits[{Reverse[IntegerDigits[k,base]],0},base], {k,n}] VanDerCorput[10,2] VanDerCorput[10,3] VanDerCorput[10,4] VanDerCorput[10,5]  
Give a code snippet in #Mathematica.2FWolfram_Language When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multi...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Haskell
Haskell
factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ] -- [2..n] >>= (\p-> [p|isPrime p]) >>= divs n where divs n p | rem n p == 0 = p : divs (quot n p) p | otherwise = []
Give a code snippet in #Haskell The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains th...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#UNIX_Shell
UNIX Shell
#!/bin/bash array=("orange" "apple") echo "${#array[@]}"
Give a code snippet in #UNIX_Shell Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#RLaB
RLaB
  >> x = rand(10,1); y = rand(10,1); >> writem("mytextfile.txt", [x,y]);  
Give a code snippet in #RLaB Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Logtalk
Logtalk
sum(List, Sum) :- sum(List, 0, Sum).   sum([], Sum, Sum). sum([X| Xs], Acc, Sum) :- Acc2 is Acc + X, sum(Xs, Acc2, Sum).
Give a code snippet in #Logtalk Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#GAP
GAP
for i in [10, 9 .. 0] do Print(i, "\n"); od;
Give a code snippet in #GAP Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incremen...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#J
J
NB. Temp conversions are all linear polynomials K2K =: 0 1 NB. K = (1 *k) + 0 K2C =: _273 1 NB. C = (1 *k) - 273 K2F =: _459.67 1.8 NB. F = (1.8*k) - 459.67 K2R =: 0 1.8 NB. R = (1.8*k) + 0   NB. Do all conversions at once (eval NB. polynomials in pa...
Give a code snippet in #J There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelv...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Nim
Nim
import random, sequtils, strformat, strutils   type Grid = seq[string] # Row first, i.e. [y][x].   const Full = '.' Used = '#' Empty = ' '     proc newGrid(p: float; xsize, ysize: Positive): Grid =   result = newSeqWith(ysize, newString(xsize)) for row in result.mitems: for cell in row.mitems: cel...
Give a code snippet in #Nim Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluste...
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...
#bc
bc
scale = 0 /* to use integer division */   /* encode Gray code */ define e(i) { auto h, r   if (i <= 0) return 0 h = i / 2 r = e(h) * 2 /* recurse */ if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */ return r }   /* decode Gray code */ define d(i) { auto h, r   if (i <= 0) return 0 h = d(i ...
Give a code snippet in #bc 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 pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Unlambda
Unlambda
```ci``s``s`ks``s`k`s``s`kc``s``s``si`kr`k. `k.*k `k``s``s``s``s`s`k`s``s`ksk`k``s``si`kk`k``s`kkk `k``s`k`s``si`kk``s`kk``s``s``s``si`kk`k`s`k`s``s`ksk`k`s`k`s`k`si``si`k`ki `k``s`k`s``si`k`ki``s`kk``s``s``s``si`kk`k`s`k`s`k`si`k`s`k`s``s`ksk``si`k`ki `k`ki``s`k`s`k`si``s`kkk
Give a code snippet in #Unlambda Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Liberty_BASIC
Liberty BASIC
  call sample 100 call sample 1000 call sample 10000   end   sub sample n dim dat( n) for i =1 to n dat( i) =rnd( 1) next i   '// show mean, standard deviation sum =0 sSq =0 for i =1 to n sum =sum +dat( i) sSq =sSq +dat( i)^2 next i print n; " data terms...
Give a code snippet in #Liberty_BASIC Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Perl
Perl
my $levels = 6; my $side = 512; my $height = get_height($side);   sub get_height { my($side) = @_; $side * sqrt(3) / 2 }   sub triangle { my($x1, $y1, $x2, $y2, $x3, $y3, $fill, $animate) = @_; my $svg; $svg .= qq{<polygon points="$x1,$y1 $x2,$y2 $x3,$y3"}; $svg .= qq{ style="fill: $fill; stroke-width...
Give a code snippet in #Perl Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code