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/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Python
Python
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Give a code snippet in #Python Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Ruby
Ruby
for i in collection do puts i end
Give a code snippet in #Ruby Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Self
Self
traits point = (| parent* = traits clonable. printString = ('Point(', x asString, ':', y asString, ')'). |)   point = (| parent* = traits point. x <- 0. y <- 0 |)   traits circle = (| parent* = traits clonable. printString = ('Circle(', center asString, ',', r asString, ')'). |)   circle = (| ...
Give a code snippet in #Self Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#8080_Assembly
8080 Assembly
bdos: equ 5 ; CP/M calls puts: equ 9   nmemb: equ 15 ; Change this to print more or fewer members   org 100h     ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Generate and output members of the sequence mvi b,nmemb ; Counter   outloop: push b ; Preserve counter across calls   mvi c,puts ; Out...
Give a code snippet in #8080_Assembly The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Ada
Ada
with Ada.Strings.Fixed; with Ada.Text_IO; with Templates_Parser;   procedure Csv2Html is use type Templates_Parser.Vector_Tag;   Chars : Templates_Parser.Vector_Tag; Speeches : Templates_Parser.Vector_Tag;   CSV_File : Ada.Text_IO.File_Type; begin -- read the csv data Ada.Text_IO.Open (File => CSV_Fil...
Give a code snippet in #Ada Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#PowerBASIC
PowerBASIC
FUNCTION PBMAIN () AS LONG DIM haystack(54) AS STRING ARRAY ASSIGN haystack() = "foo", "bar", "baz", "quux", "quuux", "quuuux", _ "bazola", "ztesch", "foo", "bar", "thud", "grunt", "foo", _ "bar", "bletch", "foo", "bar", "fum", "fred", "jim", _ "sheila", "barne...
Give a code snippet in #PowerBASIC Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a need...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String 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 |...
#zkl
zkl
"foo" == "foo" //True "foo" == "FOO" //False "foo" == "foobar" //False Op("==")("foo","foo") //True Op("==","foo")("foo") //True   "abc"<"cde" //True "abc">"cde" //False   "foo" == "FOO" //False "abc".toUpper()=="ABC" //True   123=="123" //False 123=="123".toInt() //True   ...
Give a code snippet in #zkl Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Kotlin
Kotlin
// version 1.1.3   val encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNW...
Give a code snippet in #Kotlin 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 VUX...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#C
C
#include <stdlib.h> /* qsort() */ #include <stdio.h> /* printf() */   int intcmp(const void *aa, const void *bb) { const int *a = aa, *b = bb; return (*a < *b) ? -1 : (*a > *b); }   int main() { int nums[5] = {2,4,3,1,2}; qsort(nums, 5, sizeof(int), intcmp); printf("result: %d %d %d %d %d\n", ...
Give a code snippet in #C 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#jsish
jsish
/* Environment variables, in Jsi */ puts(Util.getenv("HOME")); var environment = Util.getenv(); puts(environment.PATH);
Give a code snippet in #jsish Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Symsyn
Symsyn
    a : 1 : 2 : 27 : 44 : 46 : 57 : 77 : 154 : 212   binary_search param item index size index saveindex index L (index + size - 1) H if L <= H ((L + H) shr 1) M if base.M > item - 1 M H else if base.M < item + 1 M L else - saveindex M return M ...
Give a code snippet in #Symsyn A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret ...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Fortran
Fortran
MODULE Cards   IMPLICIT NONE   TYPE Card CHARACTER(5) :: value CHARACTER(8) :: suit END TYPE Card   TYPE(Card) :: deck(52), hand(52) TYPE(Card) :: temp   CHARACTER(5) :: pip(13) = (/"Two ", "Three", "Four ", "Five ", "Six ", "Seven", "Eight", "Nine ", "Ten ", & "Jack "...
Give a code snippet in #Fortran Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current...
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Go
Go
package main   import "fmt"   func main() { coconuts := 11 outer: for ns := 2; ns < 10; ns++ { hidden := make([]int, ns) coconuts = (coconuts/ns)*ns + 1 for { nc := coconuts for s := 1; s <= ns; s++ { if nc%ns == 1 { hidden[s-1]...
Give a code snippet in #Go Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he ...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Common_Lisp
Common Lisp
(defun make-round () (let ((array (make-array 3 :element-type 'bit :initial-element 0))) (setf (bit array (random 3)) 1) array))   (defun show-goat (initial-choice array) (loop for i = (random 3) when (and (/= initial-choice i) ...
Give a code snippet in #Common_Lisp Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed f...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Racket
Racket
#lang racket   ;; suits: (define suits '(club heart diamond spade))   ;; ranks (define ranks '(1 2 3 4 5 6 7 8 9 10 jack queen king))   ;; cards (define cards (for*/list ([suit suits] [rank ranks]) (list suit rank)))   ;; a deck is a box containing a list of cards. (define (new-deck) (box cards))   ;; shuffle ...
Give a code snippet in #Racket Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current ...
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 ...
#F.23
F#
  // Order by pair comparisons. Nigel Galloway: April 23rd., 2021 let clrs=let n=System.Random() in lN2p [|for g in 7..-1..2->n.Next(g)|] [|"Red";"Orange";"Yellow";"Green";"Blue";"Indigo";"Violet"|] let rec fG n g=printfn "Is %s less than %s" n g; match System.Console.ReadLine() with "Yes"-> -1|"No"->1 |_->printfn "Ent...
Give a code snippet in #F.23 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/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#C.23
C#
using System; class Program { public static long Ackermann(long m, long n) { if(m > 0) { if (n > 0) return Ackermann(m - 1, Ackermann(m, n - 1)); else if (n == 0) return Ackermann(m - 1, 1); } else if(m == 0) { ...
Give a code snippet in #C.23 The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Java
Java
public class Binomial {   // precise, but may overflow and then produce completely incorrect results private static long binomialInt(int n, int k) { if (k > n - k) k = n - k;   long binom = 1; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; r...
Give a code snippet in #Java This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Dart
Dart
int M(int n) => n==0?1:n-F(M(n-1)); int F(int n) => n==0?0:n-M(F(n-1));   main() { String f="",m=""; for(int i=0;i<20;i++) { m+="${M(i)} "; f+="${F(i)} "; } print("M: $m"); print("F: $f"); }
Give a code snippet in #Dart Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n )...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Fortran
Fortran
DIMENSION A(5,4,3,2) !Declares a (real) array A of four dimensions, storage permitting. X = 3*A(2,I,1,K) !Extracts a certain element, multiplies its value by three, result to X. A(1,2,3,4) = X + 1 !Places a value (the result of the expression X + ...
Give a code snippet in #Fortran For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new va...
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Racket
Racket
  #lang racket   ;; A quick `amb' implementation (define fails '()) (define (fail) (if (pair? fails) ((car fails)) (error "no more choices!"))) (define (amb xs) (let/cc k (set! fails (cons k fails))) (if (pair? xs) (begin0 (car xs) (set! xs (cdr xs))) (begin (set! fails (cdr fails)) (fail)))) (define (assert ...
Give a code snippet in #Racket Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#D
D
void main() { import std.stdio;   immutable input = "Character,Speech\n" ~ "The multitude,The messiah! Show us the messiah!\n" ~ "Brians mother,<angry>Now you listen here! He's not the messiah; " ~ "he's a very naughty boy! Now go away!</angry>\n" ~ "The multitude,Who...
Give a code snippet in #D Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Frink
Frink
d = parseDate[ARGS@0] for m = 1 to 12 { d = beginningOfNextMonth[d] n = d - (((parseInt[d -> ### u ###] + 1) mod 7) + 1) days println[n -> ### yyyy-MM-dd ###] }
Give a code snippet in #Frink Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#AutoHotkey
AutoHotkey
PRAGMA INCLUDE <sys/file.h> OPTION DEVICE O_NONBLOCK   OPEN ME$ FOR DEVICE AS me   IF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN PRINT "I am already running, exiting..." END ENDIF   PRINT "Running this program, doing things..." SLEEP 5000   CLOSE DEVICE me
Give a code snippet in #AutoHotkey This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Sparkling
Sparkling
let numbers = { 1, 2, 3, 4 }; foreach(numbers, function(idx, num) { print(num); });
Give a code snippet in #Sparkling Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Factor
Factor
USING: assocs combinators.short-circuit formatting io.encodings.utf8 io.files kernel literals locals make prettyprint random sequences ; IN: rosetta-code.semordnilap   CONSTANT: words $[ "unixdict.txt" utf8 file-lines ]   : semordnilap? ( str1 str2 -- ? ) { [ = not ] [ nip words member? ] } 2&& ;   [ [let ...
Give a code snippet in #Factor A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the tot...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#R
R
mat <- rbind(c(1,3,7,8,10), c(2,4,16,14,4), c(3,1,9,18,11), c(12,14,17,18,20), c(7,1,3,9,5)) print(sum(mat[lower.tri(mat)]))
Give a code snippet in #R Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/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"
#MMIX
MMIX
argv IS $1 argc IS $0 i IS $2   LOC #100 Main LOC @ SETL i,1 % i = 1 Loop CMP $3,argc,2 % argc < 2 ? BN $3,1F % then jump to end XOR $255,$255,$255 % clear $255 8ADDU $255,i,argv % i*8 + argv LDOU $25...
Give a code snippet in #MMIX 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/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#Julia
Julia
struct Anode node_type::String left::Union{Nothing, Anode} right::Union{Nothing, Anode} value::Union{Nothing, String} end   make_leaf(t, v) = Anode(t, nothing, nothing, v) make_node(t, l, r) = Anode(t, l, r, nothing)   const OP2 = Dict("Multiply" => "*", "Divide" => "/", "Mod" => "%", "Add" => "+", "Sub...
Give a code snippet in #Julia An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Java
Java
public class GammaFunction {   public double st_gamma(double x){ return Math.sqrt(2*Math.PI/x)*Math.pow((x/Math.E), x); }   public double la_gamma(double x){ double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, ...
Give a code snippet in #Java Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/libr...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#E
E
def stringToInteger := __makeInt def integerToString(i :int, base :int) { return i.toString(base) }
Give a code snippet in #E Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, bu...
christopher/rosetta-code
http://rosettacode.org/wiki/Next_highest_int_from_digits
Next highest int from digits
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).   If th...
#Nim
Nim
import algorithm   type Digit = range[0..9]   func digits(n: Natural): seq[Digit] = ## Return the list of digits of "n" in reverse order. if n == 0: return @[Digit 0] var n = n while n != 0: result.add n mod 10 n = n div 10   func nextHighest(n: Natural): Natural = ## Find the next highest integer of ...
Give a code snippet in #Nim Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.   Numbers will not be padded to the left with zeroes.   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear t...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#PHP
PHP
  define('src_name', 'input.jpg'); // source image define('dest_name', 'output.jpg'); // destination image   $img = imagecreatefromjpeg(src_name); // read image   if(empty($img)){ echo 'Image could not be loaded!'; exit; }   $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255...
Give a code snippet in #PHP Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#11l
11l
F divisors(n) V divs = [1] L(ii) 2 .< Int(n ^ 0.5) + 3 I n % ii == 0 divs.append(ii) divs.append(Int(n / ii)) divs.append(n) R Array(Set(divs))   F sequence(max_n) V previous = 0 V n = 0 [Int] r L n++ V ii = previous I n > max_n L.break L ...
Give a code snippet in #11l Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exact...
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...
#Maude
Maude
  fmod FACTORIAL is   protecting INT .   op undefined : -> Int . op _! : Int -> Int .   var n : Int .   eq 0 ! = 1 . eq n ! = if n < 0 then undefined else n * (sd(n, 1) !) fi .   endfm   red 11 ! .  
Give a code snippet in #Maude 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#M4
M4
define(`randSeed',141592653)dnl define(`setRand', `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnl define(`rand_t',`eval(randSeed^(randSeed>>13))')dnl define(`random', `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')dnl define(`for', `ifelse($#,0,``$0'', `ifelse(ev...
Give a code snippet in #M4 Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current cont...
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#Perl
Perl
#!/usr/bin/perl   use strict; # see https://rosettacode.org/wiki/Hunt_the_Wumpus use warnings; use List::Util qw( shuffle ); $| = 1;   my %tunnels = qw(A BKT B ACL C BDM D CEN E DFO F EGP G FHQ H GIR I HJS J IKT K AJL L BKM M CLN N DMO O ENP P FOQ Q GPR R HQS S IRT T AJS); my ($you, $wumpus, $bat1, $bat2, $pit1, $pit...
Give a code snippet in #Perl This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game i...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE PTR="CARD" DEFINE UNIT_COUNT="10"   PTR ARRAY names(UNIT_COUNT), values(UNIT_COUNT) BYTE count=[0]   PROC Append(CHAR ARRAY name REAL POINTER value) names(count)=name values(count)=value count==+1 RETURN   PROC Init() REAL arshin,centimeter,kilom...
Give a code snippet in #Action.21 Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#D
D
void main() { import std.stdio;   enum uint N = 15; uint[N + 2] t; t[1] = 1;   foreach (immutable i; 1 .. N + 1) { foreach_reverse (immutable j; 2 .. i + 1) t[j] += t[j - 1]; t[i + 1] = t[i]; foreach_reverse (immutable j; 2 .. i + 2) t[j] += t[j - 1]; ...
Give a code snippet in #D Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generate...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#PureBasic
PureBasic
Dim numbers(20) For i = 0 To 20 numbers(i) = Random(1000) Next   SortArray(numbers(), #PB_Sort_Ascending)
Give a code snippet in #PureBasic 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/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Fortran
Fortran
  !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Thu Jun 6 23:29:06 ! !a=./f && make $a && echo -2 | OMP_NUM_THREADS=2 $a !gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f ! assert 1 = */ 1 ! assert 2 = */ ...
Give a code snippet in #Fortran Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it wou...
christopher/rosetta-code
http://rosettacode.org/wiki/P-Adic_numbers,_basic
P-Adic numbers, basic
Conversion and addition of p-adic Numbers. Task. Convert two rationals to p-adic numbers and add them up. Rational reconstruction is needed to interpret the result. p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions (a series of digits 0 ≤ d < p times p-power weights) are finite-tailed and tend ...
#Wren
Wren
import "/dynamic" for Struct   // constants var EMX = 64 // exponent maximum (if indexing starts at -EMX) var DMX = 1e5 // approximation loop maximum var AMX = 1048576 // argument maximum var PMAX = 32749 // prime maximum   // global variables var P1 = 0 var P = 7 // default prime var K = 11 //...
Give a code snippet in #Wren Conversion and addition of p-adic Numbers. Task. Convert two rationals to p-adic numbers and add them up. Rational reconstruction is needed to interpret the result. p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions (a series of digits 0 ≤ d < p times p-power weight...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of...
#Julia
Julia
const a1 = [0, 1403580, -810728] const m1 = 2^32 - 209 const a2 = [527612, 0, -1370589] const m2 = 2^32 - 22853 const d = m1 + 1   mutable struct MRG32k3a x1::Tuple{Int64, Int64, Int64} x2::Tuple{Int64, Int64, Int64} MRG32k3a() = new((0, 0, 0), (0, 0, 0)) MRG32k3a(seed_state) = new((seed_state, 0, 0), (...
Give a code snippet in #Julia MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#AppleScript
AppleScript
--------------- COMBINATIONS WITH REPETITION -------------   -- combinationsWithRepetition :: Int -> [a] -> [kTuple a] on combinationsWithRepetition(k, xs) -- A list of lists, representing -- sets of cardinality k, with -- members drawn from xs.   script combinationsBySize script f ...
Give a code snippet in #AppleScript The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each memb...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#ALGOL_60
ALGOL 60
begin procedure movedisk(n, f, t); integer n, f, t; begin outstring (1, "Move disk from"); outinteger(1, f); outstring (1, "to"); outinteger(1, t); outstring (1, "\n"); end;   procedure dohanoi(n, f, t, u); integer n, f, t, u; begin if n < 2 then movedisk(1, f, t) else ...
Give a code snippet in #ALGOL_60 Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#AWK
AWK
  # syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ... BEGIN { for (i=1; i<=ARGC-1; i++) { path = ARGV[i] msg = (make_dir_path(path) == 0) ? "created" : "exists" printf("'%s' %s\n",path,msg) } exit(0) } function make_dir_path(path, cmd) { # cmd = sprintf("mkdir -p '%s'",path) # Unix c...
Give a code snippet in #AWK Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory...
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
#BCPL
BCPL
get "libhdr"   let sumsquares(v, len) = len=0 -> 0,  !v * !v + sumsquares(v+1, len-1)   let start() be $( let vector = table 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 writef("%N*N", sumsquares(vector, 10)) $)
Give a code snippet in #BCPL 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/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 |...
#langur
langur
var .s = "no more " .s ~= "foo bars" writeln .s
Give a code snippet in #langur Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Nim
Nim
import times   let t0 = cpuTime()   #################################################################################################### # Build list of primes.   const NPrimes = 1_000_000 N = 16 * NPrimes   var sieve: array[(N - 1) div 2 + 1, bool] # False (default) means prime.   for i, composite in sieve: if...
Give a code snippet in #Nim Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primori...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Raku
Raku
my @arr;   push @arr, 1; push @arr, 3;   @arr[0] = 2;   say @arr[0];
Give a code snippet in #Raku This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrie...
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 |...
#EasyLang
EasyLang
a = number input b = number input if a < b print "less" . if a = b print "equal" . if a > b print "greater" .
Give a code snippet in #EasyLang 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/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Pike
Pike
string input = "a!===b=!=c"; array sep = ({"==", "!=", "=" });   array result = replace(input, sep, `+("\0", sep[*], "\0"))/"\0"; result; Result: ({ "a", "!=", "", "==", "b", "=", "", "!=", "c" })   int pos = 0; foreach(result; int index; string data) { if ((<"==", "!=", "=">)[data]) result[index] = ({ da...
Give a code snippet in #Pike It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is...
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: * * * * * * * * * * * * * * * ...
#Phix
Phix
procedure sierpinski(integer n) integer lim = power(2,n)-1 for y=lim to 0 by -1 do puts(1,repeat(' ',y)) for x=0 to lim-y do puts(1,iff(and_bits(x,y)?" ":"* ")) end for puts(1,"\n") end for end procedure for i=1 to 5 do sierpinski(i) end for
Give a code snippet in #Phix 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/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Lambdatalk
Lambdatalk
  1) the A.find function gets a value and a unidimensional array, then retuns the item matching the value else -1   {def A.find {def A.find.r {lambda {:val :arr :n :i :acc} {if {> :i :n} then -1 else {if {= :val {A.get :i :arr}} then :i else {A.find.r :val :arr :n {+ :i 1} {A.addlast! :i :ac...
Give a code snippet in #Lambdatalk Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Delphi
Delphi
  program Cantor_set;   {$APPTYPE CONSOLE}   const WIDTH: Integer = 81; HEIGHT: Integer = 5;   var Lines: TArray<TArray<Char>>;   procedure Init; var i, j: Integer; begin SetLength(lines, HEIGHT, WIDTH); for i := 0 to HEIGHT - 1 do for j := 0 to WIDTH - 1 do lines[i, j] := '*'; end;   procedure Ca...
Give a code snippet in #Delphi Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. 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 l...
#Tcl
Tcl
while true { puts SPAM } # or for {} 1 {} { puts SPAM }
Give a code snippet in #Tcl Task Print out       SPAM       followed by a   newline   in an infinite loop. 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/...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#FunL
FunL
for i <- 1.. do println( i )
Give a code snippet in #FunL Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations lim...
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.
#zkl
zkl
fcn archimedeanSpiral(a,b,circles){ w,h:=640,640; centerX,centerY:=w/2,h/2; bitmap:=PPM(w+1,h+1,0xFF|FF|FF); // White background   foreach deg in ([0.0 .. 360*circles]){ rad:=deg.toRad(); r:=rad*b + a; x,y:=r.toRectangular(rad); bitmap[centerX + x, centerY + y] = 0x00|FF|00; // Green ...
Give a code snippet in #zkl 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/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SetDirectory@NotebookDirectory[]; If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ]; CopyFile["input.txt", "output.txt"]
Give a code snippet in #Mathematica.2FWolfram_Language File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#zkl
zkl
while(1){ digits := [1..4].pump(String,(0).random.fpM("11-",1,9)); exp := ask("Enter an expression using the digits ",digits, " that evals to 24: ") - " \n"; expf:=exp.apply(fcn(c){if ("1"<=c<="9") "(%s).toFloat()".fmt(c) else c}); reg r; try { Compiler.Compiler.compileText(expf).__constructor(); ...
Give a code snippet in #zkl The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digi...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Visual_Basic
Visual Basic
Option Explicit Const Pi As Double = 3.14159265358979 Dim angle As Double Dim nDepth As Integer Dim nColor As Long   Private Sub Form_Load() nColor = vbBlack nDepth = 12 DragonCurve End Sub   Sub DragonProc(size As Double, ByVal split As Integer, d As Integer) If split = 0 Then xForm.Line -Step(-Co...
Give a code snippet in #Visual_Basic Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon foll...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Factor
Factor
  USING: vocaba vocabb... ;  
Give a code snippet in #Factor Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
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...
#Lua
Lua
local function encrypt(text, key) return text:gsub("%a", function(t) local base = (t:lower() == t and string.byte('a') or string.byte('A'))   local r = t:byte() - base r = r + key r = r%26 -- works correctly even if r is negative r = r + base return string.char(r) end) end   local function decrypt(...
Give a code snippet in #Lua 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/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Maxima
Maxima
printf(true, "in the following terminate every number with semicolon `;'")$ n: readonly("Input x-size: ")$ m: readonly("Input y-size: ")$ a: make_array(fixnum, n, m)$ fillarray(a, makelist(i, i, 1, m*n))$   /* indexing starts from 0 */ print(a[0,0]); print(a[n-1,m-1]);
Give a code snippet in #Maxima 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. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those num...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#PARI.2FGP
PARI/GP
aliquot(x) = { my (L = List(x), M = Map(Mat([x,1])), k, m = "non-term.", n = x);   for (i = 2, 16, n = vecsum(divisors(n)) - n; if (n > 2^47, break, n == 0, m = "terminates"; break, mapisdefined(M, n, &k), m = if (k == 1, if (i == 2, "perfect", i == 3, "am...
Give a code snippet in #PARI.2FGP An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classificat...
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: ...
#BASIC
BASIC
arraybase 1 global n dim n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}   print " +: "; " "; cat(10, "+") print " -: "; " "; cat(10, "-") print " *: "; " "; cat(10, "*") print " /: "; " "; cat(10, "/") print " ^: "; " "; cat(10, "^") print "max: "; " "; cat(10, "max") print "min: "; " "; cat(10, "min") print "avg: "; " "; ca...
Give a code snippet in #BASIC 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#PicoLisp
PicoLisp
(de rpnCalculator (Str) (let (^ ** Stack) # Define '^' from the built-in '**' (prinl "Token Stack") (for Token (str Str "*+-/\^") (if (num? Token) (push 'Stack @) (set (cdr Stack) ((intern Token) (cadr Stack) (pop 'Stack)) ) ) (prin Token) ...
Give a code snippet in #PicoLisp Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#FreeBASIC
FreeBASIC
Function isPrime(Byval ValorEval As Uinteger) As Boolean If ValorEval < 2 Then Return False If ValorEval Mod 2 = 0 Then Return ValorEval = 2 If ValorEval Mod 3 = 0 Then Return ValorEval = 3 Dim d As Integer = 5 While d * d <= ValorEval If ValorEval Mod d = 0 Then Return False Else d += 2 ...
Give a code snippet in #FreeBASIC This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Fortran
Fortran
program main   use rgbimage_m   implicit none   integer :: nx, ny, i, j, k   type(rgbimage) :: im   ! init image of height nx, width ny nx = 400 ny = 300 call im%init(nx, ny)   ! set some random pixel data do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) e...
Give a code snippet in #Fortran Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Wren
Wren
var permute // recursive permute = Fn.new { |input| if (input.count == 1) return [input] var perms = [] var toInsert = input[0] for (perm in permute.call(input[1..-1])) { for (i in 0..perm.count) { var newPerm = perm.toList newPerm.insert(i, toInsert) perms.ad...
Give a code snippet in #Wren Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   gener...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#TypeScript
TypeScript
function josephus(n: number, k: number): number { if (!n) { return 1; }   return ((josephus(n - 1, k) + k - 1) % n) + 1; }
Give a code snippet in #TypeScript Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#zonnon
zonnon
  module Main; type Callback = procedure (integer): integer; Vector = array {math} * of integer;   procedure Power(i:integer):integer; begin return i*i; end Power;   procedure Map(x: Vector;p: Callback): Vector; var i: integer; r: Vector; begin r := new Vector(len(x)); for i := 0 to len(x) - 1 do r[i] := p(i)...
Give a code snippet in #zonnon Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt import "/ioutil" for Input import "/str" for Str   var cave = { 1: [ 2, 3, 4], 2: [ 1, 5, 6], 3: [ 1, 7, 8], 4: [ 1, 9, 10], 5: [ 2, 9, 11], 6: [ 2, 7, 12], 7: [ 3, 6, 13], 8: [ 3, 10, 14], 9: [ 4, 5, 15], 10: [ 4, 8, 16], 11: [ 5, 12...
Give a code snippet in #Wren This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game i...
christopher/rosetta-code
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Julia
Julia
# Run from Julia REPL to see the plots. using Statistics, Distributions, Plots   const racket_xdata = [-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, ...
Give a code snippet in #Julia W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#EchoLisp
EchoLisp
  (define ∆-🍒 1) → ∆-🍒 (set! ∆-🍒 (1+ ∆-🍒)) → 2 (printf "🔦 Look at ∆-🍒 : %d" ∆-🍒) 🔦 Look at ∆-🍒 : 2  
Give a code snippet in #EchoLisp Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Kotlin
Kotlin
// version 1.1.0   fun main(args: Array<String>) { val names = arrayOf("Jimmy", "Bill", "Barack", "Donald") val ages = arrayOf(92, 70, 55, 70) val hash = mapOf(*names.zip(ages).toTypedArray()) hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") } }
Give a code snippet in #Kotlin Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Perl
Perl
#!/usr/bin/perl   use strict; use 5.10.0;   package Integrator; use threads; use threads::shared;   sub new { my $cls = shift; my $obj = bless { t => 0, sum => 0, ref $cls ? %$cls : (), stop => 0, tid => 0, func => shift, }, ref $cls || $cls;   share($obj->{sum}); share($obj->{stop});   $obj...
Give a code snippet in #Perl In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such me...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Asymptote
Asymptote
unitsize(1 inch);   fill(scale(6)*unitsquare, invisible);   picture yinyang(pair center, real radius) { picture p; fill(p, unitcircle, white); fill(p, arc(0, S, N) -- cycle, black); fill(p, circle(N/2, 1/2), white); fill(p, circle(S/2, 1/2), black); fill(p, circle(N/2, 1/5), black); fill(p, ...
Give a code snippet in #Asymptote One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/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"
#Smalltalk
Smalltalk
(1 to: Smalltalk getArgc) do: [ :i | (Smalltalk getArgv: i) displayNl ]
Give a code snippet in #Smalltalk 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/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.
#WDTE
WDTE
let s => import 'stream'; let a => import 'arrays';   let max list => a.stream list -> s.extent 1 > -> at 0  ;
Give a code snippet in #WDTE 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/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#CoffeeScript
CoffeeScript
  is_contigous_binary = (n) -> # return true if binary representation of n is # of the form 1+0+ # examples: # 0 true # 1 true # 100 true # 110 true # 1001 false # 1010 false   # special case zero, or you'll get an infinite loop later return true if n == 0   # first remove 0s from ...
Give a code snippet in #CoffeeScript Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the f...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() every i := 2097152 | 2097151 | 1 | 127 | 128 | 589723405834 | 165 | 256 do write(image(i)," = ",string2hex(v := uint2vlq(i))," = ",vlq2uint(v)) end   procedure vlq2uint(s) #: decode a variable length quantity if *s > 0 then { i := 0 s ? while h := ord(move(1)) do { if (p...
Give a code snippet in #Icon_and_Unicon 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,...
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...
#FutureBasic
FutureBasic
window 1, @"Empty string", (0,0,480,270)   CFStringRef s   s = @"" if ( fn StringIsEqual( s, @"" ) ) then print @"string is empty" if ( fn StringLength( s ) == 0 ) then print @"string is empty" if ( len(s) == 0 ) then print @"string is empty"   print   s = @"Hello" if ( fn StringIsEqual( s, @"" ) == NO ) then print @"s...
Give a code snippet in #FutureBasic 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/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Lua
Lua
io.write(" /$$\n") io.write("| $$\n") io.write("| $$ /$$ /$$ /$$$$$$\n") io.write("| $$ | $$ | $$ |____ $$\n") io.write("| $$ | $$ | $$ /$$$$$$$\n") io.write("| $$ | $$ | $$ /$$__ $$\n") io.write("| $$$$$$$$| $$$$$$/| $$$$$$$\n") io.write("|________/ \______/ \_______/\n")
Give a code snippet in #Lua Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#BBC_BASIC
BBC BASIC
ntreated% = 9 nplacebo% = 10 DIM results%(ntreated% + nplacebo% - 1) results%() = 85, 88, 75, 66, 25, 29, 83, 39, 97, \ REM treated group \ 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 : REM placebo group   greater% = 0 FOR comb% = 0 TO 2^(ntreated%+nplacebo%)-1 ...
Give a code snippet in #BBC_BASIC Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example of Currying in a specific la...
#D
D
void main() { import std.stdio, std.functional;   int add(int a, int b) { return a + b; }   alias add2 = partial!(add, 2); writeln("Add 2 to 3: ", add(2, 3)); writeln("Add 2 to 3 (curried): ", add2(3)); }
Give a code snippet in #D This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example o...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Common_Lisp
Common Lisp
;; * The input file as a parameter (defparameter *input* #p"fasta.txt" "The input file name.")   ;; * Reading the data (with-open-file (data *input*) (loop :for line = (read-line data nil nil) :while line ;; Check if we have a comment using a simple test instead of a RegEx :if (char=...
Give a code snippet in #Common_Lisp In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Yabasic
Yabasic
n = 1000 long = 10 * int(n / 4) needdecimal = 1 //true dim a(long) nines = 0 predigit = 0 // {First predigit is a 0}   for j = 1 to long a(j-1) = 2 // {Start with 2s} next j   for j = 1 to n q = 0 for i = long to 1 step -1 // {Work backwards} x = 10*a(i-1) + q*i a(i-1) = mod(x, (2*i - 1)) q ...
Give a code snippet in #Yabasic Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal se...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Ra
Ra
  class SelectionSort **Sort a list with the Selection Sort algorithm**   on start   args := program arguments .sort(args) print args   define sort(list) is shared **Sort the list**   test list := [4, 2, 7, 3] .sort(list) assert list = [2, 3, 4, 7]   body count := list.count last := count ...
Give a code snippet in #Ra 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/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Sidef
Sidef
func getNthLine(filename, n) { var file = File.new(filename); file.open_r.each { |line| Num($.) == n && return line; } warn "file #{file} does not have #{n} lines, only #{$.}\n"; return nil; }   var line = getNthLine("/etc/passwd", 7); print line if defined line;
Give a code snippet in #Sidef Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it i...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Perl
Perl
use Imager;   my $w = 640; my $h = 640;   my $img = Imager->new(xsize => $w, ysize => $h, channels => 3); my $green = Imager::Color->new('#00FF00');   my ($x, $y) = (0, 0);   foreach (1 .. 2e5) { my $r = rand(100); ($x, $y) = do { if ($r <= 1) { ( 0.00 * $x - 0.00 * $y, 0.00 * $x + 0.16 * $y + 0.00) } ...
Give a code snippet in #Perl A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Run_BASIC
Run BASIC
a = lftFct(0,10,1) a = lftFct(20,110,10) a = lftFct(1000,10000,1000)   function lftFct(f,t,s) print :print "------ From ";f;" --To-> ";t;" Step ";s;" -------" for i = f to t step s lftFct = 1 fct = 1 for j = 1 to i-1 fct = fct * j lftFct = lftFct + fct next j if i >= 1000 then print i;" ";len(str$(lftFct));"...
Give a code snippet in #Run_BASIC Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   ...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#Go
Go
  package main   import ( "io" "log" "net/http" "os" )   func main() { r, err := http.Get("https://sourceforge.net/") if err != nil { log.Fatalln(err) } io.Copy(os.Stdout, r.Body) }  
Give a code snippet in #Go Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Sidef
Sidef
say 0.75.as_frac #=> 3/4 say 0.518518.as_frac #=> 259259/500000 say 0.9054054.as_frac #=> 4527027/5000000
Give a code snippet in #Sidef This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Retro
Retro
echo '\'hello s:put nl bye' | retro
Give a code snippet in #Retro Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementati...
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...
#Perl
Perl
use Math::ModInt qw(mod); sub f { my $x = shift; $x**100 + $x + 1 }; print f mod(10, 13);
Give a code snippet in #Perl 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, tw...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Ursa
Ursa
# outputs time in milliseconds import "time" out (time.getcurrent) endl console
Give a code snippet in #Ursa Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   D...
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...
#Frege
Frege
module Hailstone where   import Data.List (maximumBy)   hailstone :: Int -> [Int] hailstone 1 = [1] hailstone n | even n = n : hailstone (n `div` 2) | otherwise = n : hailstone (n * 3 + 1)   withResult :: (t -> t1) -> t -> (t1, t) withResult f x = (f x, x)   main :: IO () main = do let h27 =...
Give a code snippet in #Frege The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#F.23
F#
let inline bresenham fill (x0, y0) (x1, y1) = let steep = abs(y1 - y0) > abs(x1 - x0) let x0, y0, x1, y1 = if steep then y0, x0, y1, x1 else x0, y0, x1, y1 let x0, y0, x1, y1 = if x0 > x1 then x1, y1, x0, y0 else x0, y0, x1, y1 let dx, dy = x1 - x0, abs(y1 - y0) let s = if y0 < y1 then 1 else -1 let...
Give a code snippet in #F.23 Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
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. ...
#Swift
Swift
for i in 1...5 { for _ in 1...i { print("*", terminator: "") } print() }
Give a code snippet in #Swift “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 structu...
christopher/rosetta-code