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/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed)....
#Go
Go
package main   import ( "fmt" "sort" )   func contains(a []int, b int) bool { for _, j := range a { if j == b { return true } } return false }   func gcd(a, b int) int { for a != b { if a > b { a -= b } else { b -= a } ...
Give a code snippet in #Go The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an elec...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#OCaml
OCaml
(* insert x at all positions into li and return the list of results *) let rec insert x = function | [] -> [[x]] | a::m as li -> (x::li) :: (List.map (fun y -> a::y) (insert x m))   (* list of all permutations of li *) let permutations li = List.fold_right (fun a z -> List.concat (List.map (insert a) z)) li [[]]...
Give a code snippet in #OCaml ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#BASIC256
BASIC256
  circle1$ = " 0.000, 0.000, 1.000" circle2$ = " 4.000, 0.000, 1.000" circle3$ = " 2.000, 4.000, 2.000"   subroutine ApolloniusSolver(c1$, c2$, c3$, s1, s2, s3) x1 = int(mid(c1$, 3, 1)): y1 = int(mid(c1$, 11, 1)): r1 = int(mid(c1$, 19, 1)) x2 = int(mid(c2$, 3, 1)): y2 = int(mid(c2$, 11, 1)): r2 = int(mid(c2$...
Give a code snippet in #BASIC256 Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straigh...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Fermat
Fermat
  Array a[3,1] [a]:=[(1,2,3)] [b]:=Trans([a]) [a] [b]  
Give a code snippet in #Fermat Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#AWK
AWK
  # syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK BEGIN { split("1,2,1,5,2",list1,",") split("1,2,1,5,2,2",list2,",") split("1,2,3,4,5",list3,",") split("1,2,3,4,5",list4,",") x = compare_array(list1,list2) ? "<" : ">=" ; printf("list1%slist2\n",x) x = compare_array(list2,list3) ? "<" : ">=" ; p...
Give a code snippet in #AWK sorting 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#C.23
C#
static void Main(string[] args) { Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 })); Console.Read(); }   private static decimal DotProduct(decimal[] vec1, decimal[] vec2) { if (vec1 == null) return 0;   if (vec2 == null) return 0;   if (vec1.Length != vec2.Length) return...
Give a code snippet in #C.23 Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1]...
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.
#min
min
(1 2 3 4 5) (sqrt puts) foreach  ; print each square root (1 2 3 4 5) 'sqrt map  ; collect return values
Give a code snippet in #min Task Take a combined set of elements and apply a function to each element.
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() local lst lst := [10, 20, 30, 40] every callback(write,!lst) end   procedure callback(p,arg) return p(" -> ", arg) end
Give a code snippet in #Icon_and_Unicon Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Maple
Maple
module MyVector() option object; local value := Vector();   export ModuleApply::static := proc( ) Object( MyVector, _passed ); end proc;   export ModuleCopy::static := proc( mv::MyVector, proto::MyVector, v::Vector, $ ) mv:-value := v; end proc;   export ModulePrint::static := proc(mv::...
Give a code snippet in #Maple Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (l...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Fortran
Fortran
module fifo_nodes type fifo_node integer :: datum ! the next part is not variable and must be present type(fifo_node), pointer :: next logical :: valid end type fifo_node end module fifo_nodes   program FIFOTest use fifo implicit none   type(fifo_head) :: thehead type(fifo_node), dimensi...
Give a code snippet in #Fortran Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of q...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#MATLAB
MATLAB
  function r = isnum(a) r = ~isnan(str2double(a)) end   % tests disp(isnum(123)) % 1 disp(isnum("123")) % 1 disp(isnum("foo123")) % 0 disp(isnum("123bar")) % 0 disp(isnum("3.1415")) % 1    
Give a code snippet in #MATLAB Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash declare -A pinyin=( [甲]='jiă' [乙]='yĭ' [丙]='bĭng' [丁]='dīng' [戊]='wù' [己]='jĭ' [庚]='gēng' [辛]='xīn' [壬]='rén' [癸]='gŭi' [子]='zĭ' [丑]='chŏu' [寅]='yín' [卯]='măo' [辰]='chén' [巳]='sì' [午]='wŭ' [未]='wèi' [申]='shén' [酉]='yŏu' [戌]='xū' [亥]='hài' ) celestial=(甲 ...
Give a code snippet in #UNIX_Shell Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities r...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#UNIX_Shell
UNIX Shell
# List of abbreviated compass point labels compass_points=( N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW )   # List of angles to test test_angles=( 0.00 16.87 16.88 33.75 50....
Give a code snippet in #UNIX_Shell There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print a...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#Haskell
Haskell
import Control.Concurrent import Data.List import System.Time   -- Library: ansi-terminal import System.Console.ANSI   number :: (Integral a) => a -> [String] number 0 = ["██████" ,"██ ██" ,"██ ██" ,"██ ██" ,"██████"] number 1 = [" ██" ," ██" ," ██" ," ██" ," ██"] number 2 = ["██...
Give a code snippet in #Haskell Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change eve...
christopher/rosetta-code
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Phix
Phix
with javascript_semantics function revn(atom n, integer nd) atom r = 0 for i=1 to nd do r = r*10+remainder(n,10) n = floor(n/10) end for return r end function integer nd = 2, count = 0 atom lim = 99, n = 9, t0 = time() while true do n += 1 atom r = revn(n,nd) if r<n then ...
Give a code snippet in #Phix Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be pos...
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. ...
#MOO
MOO
for i in [1..5] s = ""; for j in [1..i] s += "*"; endfor player:tell(s); endfor
Give a code snippet in #MOO “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 structure...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#uBasic.2F4tH
uBasic/4tH
PRINT "Insertion sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Insertionsort (n) PROC _ShowArray (n) PRINT   END     _Insertionsort PARAM (1) ' Insertion sort LOCAL (3)   FOR b@ = 1 TO a@-1 c@ = @(b@) d@ = b@ DO WHILE (d@>0) * (c@ < @(ABS(d@-1))) @(d@) = @(d@-1) ...
Give a code snippet in #uBasic.2F4tH Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#PARI.2FGP
PARI/GP
A(m,n)={ if(m, if(n, A(m-1, A(m,n-1)) , A(m-1,1) ) , n+1 ) };
Give a code snippet in #PARI.2FGP 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/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Pascal
Pascal
program appendARecordToTheEndOfATextFile;   var passwd: bindable text; FD: bindingType;   begin { initialize FD } FD := binding(passwd); FD.name := '/tmp/passwd';   { attempt opening file [e.g. effective user has proper privileges?] } bind(passwd, FD);   { query binding state of `passwd` } FD := binding(passwd...
Give a code snippet in #Pascal Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#FreeBASIC
FreeBASIC
' version 17-02-2016 ' compile with: fbc -s console   ' TRUE/FALSE are built-in constants since FreeBASIC 1.04 ' For older versions they have to be defined. #Ifndef TRUE #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function WD(m As Integer, d As Integer, y As Integer) As Integer ' Zellerish '...
Give a code snippet in #FreeBASIC Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display w...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Ring
Ring
  for n = 2008 to 2121 if n < 2100 leap = n - 1900 else leap = n - 1904 ok m = (((n-1900)%7) + floor(leap/4) + 27) % 7 if m = 4 see "25 Dec " + n + nl ok next  
Give a code snippet in #Ring A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#BASIC
BASIC
DIM baseString AS STRING, subString AS STRING, findString AS STRING DIM m AS INTEGER, n AS INTEGER   baseString = "abcdefghijklmnopqrstuvwxyz" n = 12 m = 5   ' starting from n characters in and of m length; subString = MID$(baseString, n, m) PRINT subString   ' starting from n characters in, up to the end of the string...
Give a code snippet in #BASIC 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/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Free_Pascal
Free Pascal
  function randg(mean,stddev: float): float;  
Give a code snippet in #Free_Pascal Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. R...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#TXR
TXR
(defmacro swp (left right) (with-gensyms (tmp) ^(let ((,tmp ,left)) (set ,left ,right ,right ,tmp))))
Give a code snippet in #TXR Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity....
christopher/rosetta-code
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Nim
Nim
import imageman   const Width = 81   proc peano(points: var seq[Point]; x, y, lg, i1, i2: int) =   if lg == 1: points.add ((Width - x) * 10, (Width - y) * 10) return   let lg = lg div 3 points.peano(x + 2 * i1 * lg, y + 2 * i1 * lg, lg, i1, i2) points.peano(x + (i1 - i2 + 1) * lg, y + (i1 + i2) * lg, lg...
Give a code snippet in #Nim Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO;   procedure Main is subtype Block is String (1 .. 80); Infile_Name  : String := "infile.dat"; outfile_Name : String := "outfile.dat"; Infile  : File_Type; outfile  : File_Type;   Line : Block := (Others => ' '); begin Open (File => Infile, Mode => In_Fi...
Give a code snippet in #Ada Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Ruby
Ruby
exit if RUBY_VERSION < '1.8.6' puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)
Give a code snippet in #Ruby Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Red
Red
>>view []  
Give a code snippet in #Red Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Icon_and_Unicon
Icon and Unicon
link matrix procedure main(argv) if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.") matrix1 := identity_matrix(argv[1], argv[1]) write_matrix(&output,matrix1) end  
Give a code snippet in #Icon_and_Unicon Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#8086_Assembly
8086 Assembly
start: mov al, 0x04 mov bl, 0x05 call multiply ;at this point in execution, the AX register contains 0x0900. ;more code goes here, ideally with some sort of guard against "fallthrough" into multiply.   ; somewhere far away from start multiply: mul bl ;outputs 0x0014 to ax ret
Give a code snippet in #8086_Assembly A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to d...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Lang5
Lang5
: flip "" split reverse "" join ; "qwer asdf" flip .
Give a code snippet in #Lang5 Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#newLISP
newLISP
#!/usr/bin/env newlisp   (let ((program (main-args 1))) (println (format "Program: %s" program)) (exit))
Give a code snippet in #newLISP The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the scrip...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#C.23
C#
using System;   namespace Repeat { class Program { static void Repeat(int count, Action<int> fn) { if (null == fn) { throw new ArgumentNullException("fn"); } for (int i = 0; i < count; i++) { fn.Invoke(i + 1); } }   ...
Give a code snippet in #C.23 Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#Julia
Julia
  for i in 1:0x200000 - 1 Symbol("x" * Char(i)) end  
Give a code snippet in #Julia Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#OCaml
OCaml
Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))
Give a code snippet in #OCaml A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Ruby
Ruby
str = `ls` arr = `ls`.lines
Give a code snippet in #Ruby Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Slate
Slate
define: #Singleton &builder: [Oddball clone]
Give a code snippet in #Slate A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Sed
Sed
sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt
Give a code snippet in #Sed Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#SAS
SAS
  options minoperator;   %macro haver(lat1, long1, lat2, long2, type=D, dist=K);   %if %upcase(&type) in (D DEG DEGREE DEGREES) %then %do; %let convert = constant('PI')/180; %end; %else %if %upcase(&type) in (R RAD RADIAN RADIANS) %then %do; %let convert = 1; %end; %else %do; %put ERROR - Enter RADIANS or ...
Give a code snippet in #SAS This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equati...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[CreateVar, ImportConfig]; CreateVar[x_, y_String: "True"] := Module[{}, If[StringFreeQ[y, ","] , ToExpression[x <> "=" <> y] , ToExpression[x <> "={" <> StringJoin@Riffle[StringSplit[y, ","], ","] <> "}"] ] ] ImportConfig[configfile_String] := Module[{data}, (*data = ImportString[configfil...
Give a code snippet in #Mathematica.2FWolfram_Language The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a...
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#VBScript
VBScript
Option Explicit   function dice5 dice5 = int(rnd*5) + 1 end function   function dice7 dim j do j = 5 * dice5 + dice5 - 6 loop until j < 21 dice7 = j mod 7 + 1 end function
Give a code snippet in #VBScript Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using ...
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...
#Picat
Picat
go =>  % Create and print the deck deck(Deck), print_deck(Deck), nl,    % Shuffle the deck print_deck(shuffle(Deck)), nl,    % Deal 3 cards Deck := deal(Deck,Card1), Deck := deal(Deck,Card2), Deck := deal(Deck,Card3),   println(deal1=Card1), println(deal2=Card2), println(deal3=Card3),  % The r...
Give a code snippet in #Picat 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#Logtalk
Logtalk
  :- public(foo/1). % predicate can be called from anywhere   :- protected(bar/2). % predicate can be called from the declaring entity and its descendants   :- private(baz/3). % predicate can only be called from the declaring entity   :- object(object, % predicates declared in the protocol become private fo...
Give a code snippet in #Logtalk Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#AutoIt
AutoIt
$ awk 'BEGIN{system("mv input.txt output.txt")}' $ awk 'BEGIN{system("mv docs mydocs")}' $ awk 'BEGIN{system("mv /input.txt /output.txt")}' $ awk 'BEGIN{system("mv docs mydocs")}'
Give a code snippet in #AutoIt Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the r...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Z80_Assembly
Z80 Assembly
ld hl,RamArea ;a label for an arbitrary section of RAM ld a,(foo) ;load the value of some memory location. "foo" is the label of a 16-bit address. ld b,a ;use this as a loop counter. xor a ;set A to zero   loop: ;creates a list of ascending values starting at zero. Each is stored at a differen...
Give a code snippet in #Z80_Assembly Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are c...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make -- First 10 states of the cellular automata. local r: RANDOM automata: STRING do create r.make create automata.make_empty across 1 |..| 10 as c loop if r.double_item < 0.5 then automata.append ("0") else automata.append...
Give a code snippet in #Eiffel Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the curren...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Java
Java
public static double[][] mult(double a[][], double b[][]){//a[m][n], b[n][p] if(a.length == 0) return new double[0][0]; if(a[0].length != b.length) return null; //invalid dims   int n = a[0].length; int m = a.length; int p = b[0].length;   double ans[][] = new double[m][p];   for(int i = 0;i < m;i+...
Give a code snippet in #Java Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Perl
Perl
my $number = 1 + int rand 10; do { print "Guess a number between 1 and 10: " } until <> == $number; print "You got it!\n";
Give a code snippet in #Perl Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#PARI.2FGP
PARI/GP
reverse(s)=concat(Vecrev(s))
Give a code snippet in #PARI.2FGP Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string E...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#PicoLisp
PicoLisp
(scl 6)   (de cubicBezier (Img N X1 Y1 X2 Y2 X3 Y3 X4 Y4) (let (R (* N N N) X X1 Y Y1 DX 0 DY 0) (for I N (let (J (- N I) A (*/ 1.0 J J J R) B (*/ 3.0 I J J R) C (*/ 3.0 I I J R) D (*/ 1.0 I I I R) ) (brez Img ...
Give a code snippet in #PicoLisp Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Perl
Perl
print "true\n" if ( 727 == 0x2d7 && 727 == 01327 && 727 == 0b1011010111 && 12345 == 12_345 # underscores are ignored; useful for keeping track of places );
Give a code snippet in #Perl Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#sed
sed
y/abcdefghijklmnopqrstuvwxyz/nopqrstuvwxyzabcdefghijklm/ y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/NOPQRSTUVWXYZABCDEFGHIJKLM/
Give a code snippet in #sed Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Bracmat
Bracmat
put$"Goodbye, World!"
Give a code snippet in #Bracmat Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#UNIX_Shell
UNIX Shell
iseven() { [[ $(($1%2)) -eq 0 ]] && return 0 return 1 }
Give a code snippet in #UNIX_Shell Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace LargestNumber { class Program { static bool ChkDec(int num) { HashSet<int> set = new HashSet<int>();   return num.ToString() .Select(c => c - '0') .All(d => (d != 0) && (num...
Give a code snippet in #C.23 Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   ...
christopher/rosetta-code
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#M2000_Interpreter
M2000 Interpreter
  Module BBCtrans { \\ LZW compression plaintext$="TOBEORNOTTOBEORTOBEORNOT" Function encodeLZW$(i$) { Def long c, d, i, l, o$, w$ DIM dict$(0 to 4095) FOR i = 0 TO 255 : dict$(i) = CHR$(i) : NEXT i l = i i = 1 ...
Give a code snippet in #M2000_Interpreter The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
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: * * * * * * * * * * * * * * * ...
#Ursala
Ursala
#import nat   triangle = ~&a^?\<<&>>! ^|RNSiDlrTSPxSxNiCK9xSx4NiCSplrTSPT/~& predecessor
Give a code snippet in #Ursala 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/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#FreeBASIC
FreeBASIC
' version 27-06-2018 ' compile with: fbc -s console ' or: fbc -s gui   Screen 13 ' Screen 18: 320x200, 8bit colordepth 'ScreenRes 320, 200, 24 ' Screenres: 320x200, 24bit colordepth   If ScreenPtr = 0 Then Print "Error setting video mode!" End End If   Dim As UInteger depth, x = 1...
Give a code snippet in #FreeBASIC Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#OCaml
OCaml
let frames = { contents = 0 }   let t_acc = { contents = 0 }   let last_t = { contents = Sdltimer.get_ticks () }   let print_fps () = let t = Sdltimer.get_ticks () in let dt = t - !last_t in t_acc := !t_acc + dt; if !t_acc > 1000 then begin let el_time = !t_acc / 1000 in Printf.printf "- fps...
Give a code snippet in #OCaml Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#uBasic.2F4tH
uBasic/4tH
Proc _Repeat (_HelloWorld, 5) : End   _Repeat Param (2) : Local (1) : For c@ = 1 To b@ : Proc a@ : Next : Return _HelloWorld Print "Hello world!" : Return
Give a code snippet in #uBasic.2F4tH Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#PARI.2FGP
PARI/GP
0^0 0.^0 0^0.
Give a code snippet in #PARI.2FGP Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0    ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#D
D
import std.algorithm : map; import std.bigint; import std.range; import std.stdio;   BigInt factorial(BigInt n) { if (n == 0) return BigInt(1); BigInt res = 1; while (n > 0) { res *= n--; } return res; }   BigInt lah(BigInt n, BigInt k) { if (k == 1) return factorial(n); if (k == n) ...
Give a code snippet in #D Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly orde...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Picat
Picat
multiply(A, B) = A*B.  
Give a code snippet in #Picat A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Ursala
Ursala
#import std #import nat   pascal = choose**ziDS+ iota*t+ iota+ successor
Give a code snippet in #Ursala Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eithe...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#8086_Assembly
8086 Assembly
.model small ;.exe file .stack 1024 ;this value doesn't matter, I chose this arbitrarily .data ;not needed in an empty program .code mov ax,4C00h int 21h ;exit this program and return to MS-DOS
Give a code snippet in #8086_Assembly Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Rust
Rust
use std::fmt::{Display, Formatter};   // We could use std::ops::RangeInclusive, but we would have to extend it to // normalize self (not much trouble) and it would not have to handle pretty // printing for it explicitly. So, let's make rather an own type.   #[derive(Clone, Debug, PartialEq, PartialOrd)] pub struct Clos...
Give a code snippet in #Rust Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Tcl
Tcl
package require Tcl 8.5   proc walk {y x} { global w ww h cnt grid len if {!$y || $y==$h || !$x || $x==$w} { incr cnt 2 return } set t [expr {$y*$ww + $x}] set m [expr {$len - $t}] lset grid $t [expr {[lindex $grid $t] + 1}] lset grid $m [expr {[lindex $grid $m] + 1}] if {![lindex $gri...
Give a code snippet in #Tcl A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths f...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#8086_Assembly
8086 Assembly
bits 16 cpu 8086 segment .text org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Given a number in AX, return string with ordinal suffix ;; in DX. nth: mov cx,10 ; Divisor mov bx,.sfx ; Pointer to end of number .digit: xor dx,dx ; Zero DX div cx ; AX = DX:...
Give a code snippet in #8086_Assembly Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#NS-HUBASIC
NS-HUBASIC
10 LOCATE 6,11 20 PRINT "GOODBYE, WORLD!"
Give a code snippet in #NS-HUBASIC Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#M2000_Interpreter
M2000 Interpreter
  Report "Dutch Flag from Dijkstra" const center=2 enum balls {Red, White, Blue} fillarray=lambda a=(Red, White, Blue) (size as long=10)-> { if size<1 then size=1 randomitem=lambda a->a#val(random(0,2)) dim a(size)<<randomitem() =a() } Display$=lambda$ (s as array) ->{ Document r$=eval$(array(s)) ...
Give a code snippet in #M2000_Interpreter The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the ord...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#AWK
AWK
  # usage: awk -f 5weekends.awk cal.txt   # Filter a file of month-calendars, such as # ... ## January 1901 ## Mo Tu We Th Fr Sa Su ## 1 2 3 4 5 6 ## 7 8 9 10 11 12 13 ## 14 15 16 17 18 19 20 ## 21 22 23 24 25 26 27 ## 28 29 30 31 # ... ## March 1901 ## Mo Tu We Th Fr S...
Give a code snippet in #AWK The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Nim
Nim
import math import bignum import strformat import strutils import tables import times   const Composite = {9: "5529", 10: "6078", 11: "1037", 12: "5488", 13: "2884"}.toTable   const Subscripts = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]   let One = newInt(1)   #-------------------------------------------------...
Give a code snippet in #Nim In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively u...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Objeck
Objeck
class RungeKuttaMethod { function : Main(args : String[]) ~ Nil { x0 := 0.0; x1 := 10.0; dx := .1;   n := 1 + (x1 - x0)/dx; y := Float->New[n->As(Int)];   y[0] := 1; for(i := 1; i < n; i++;) { y[i] := Rk4(Rate(Float, Float) ~ Float, dx, x0 + dx * (i - 1), y[i-1]); };   for(i := 0; ...
Give a code snippet in #Objeck Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This e...
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...
#Run_BASIC
Run BASIC
list$ = "h,e,l,l,o" ' supply list seperated with comma's   while word$(list$,d+1,",") <> "" 'Count how many in the list d = d + 1 wend   dim theList$(d) ' place list in array for i = 1 to d theList$(i) = word$(list$,i,",") next i   for i = 1 to d ' print the Permutations for j = 2 to d perm$ = "" for k =...
Give a code snippet in #Run_BASIC 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#TXR
TXR
$ txr -p '(+ (read) (read))' 1.2 2.3 3.5
Give a code snippet in #TXR A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Ring
Ring
  see "42 %! 2017 = " + multInv(42, 2017) + nl   func multInv a,b b0 = b x0 = 0 multInv = 1 if b = 1 return 0 ok while a > 1 q = floor(a / b) t = b b = a % b a = t t = x0 x0 = multInv - q * x0 multInv = t e...
Give a code snippet in #Ring From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Tcl
Tcl
proc commaQuibble {lst} { return \{[join [lreplace $lst end-1 end [join [lrange $lst end-1 end] " and "]] ", "]\} }   foreach input { {} {"ABC"} {"ABC" "DEF"} {"ABC" "DEF" "G" "H"} } { puts [commaQuibble $input] }
Give a code snippet in #Tcl Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An inpu...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Factor
Factor
USING: assocs combinators.random formatting grouping io kernel macros math math.statistics namespaces prettyprint quotations random sequences sorting ; IN: sequence-mutation   SYMBOL: verbose?  ! Turn on to show mutation details.  ! Off by default.   ! Return a random base as a character. : rand-base (...
Give a code snippet in #Factor Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 INPUT "Enter a string:"; s$ 20 INPUT "Enter a number: "; n
Give a code snippet in #ZX_Spectrum_Basic User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>   void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); }   double calculate_entropy(int ones, int zeros) { double result = 0;   int total = ones + ze...
Give a code snippet in #C The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   c...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#ReScript
ReScript
let map_range = ((a1, a2), (b1, b2), s) => { b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1)) }   Js.log("Mapping [0,10] to [-1,0] at intervals of 1:")   for i in 0 to 10 { Js.log("f(" ++ Js.String.make(i) ++ ") = " ++ Js.String.make(map_range((0.0, 10.0), (-1.0, 0.0), float(i)))) }
Give a code snippet in #ReScript Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearl...
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.)
#GAP
GAP
# Dirty implementation # Only P3 format, an image is a list of 3 matrices (r, g, b) # Max color is always 255 WriteImage := function(name, img) local f, r, g, b, i, j, maxcolor, nrow, ncol, dim; f := OutputTextFile(name, false); r := img[1]; g := img[2]; b := img[3]; dim := DimensionsMat(r); nrow := dim[1...
Give a code snippet in #GAP 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/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#ALGOL_W
ALGOL W
begin  % draw a sphere  %  % returns the next integer larger than x or x if x is an integer  % integer procedure ceil( real value x ) ; begin integer tmp; tmp := truncate( x ); if tmp not =...
Give a code snippet in #ALGOL_W Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#REXX
REXX
SIGNAL {ON|OFF} someCondition {name}
Give a code snippet in #REXX Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the stat...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Haskell
Haskell
import Control.Monad (forM_)   import Data.List (permutations)   -- Compute all derangements of a list derangements :: Eq a => [a] -> [[a]] derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations   -- Compute the number of derangements of n elements subfactorial :: (Eq a, Num a) => a -> a subfacto...
Give a code snippet in #Haskell A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial o...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#C.2B.2B
C++
  #include <algorithm> #include <functional> #include <string> #include <iostream> #include <vector>   //code for a C++11 compliant compiler template <class BidirectionalIterator, class T> void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) { std::reverse(first, last...
Give a code snippet in #C.2B.2B Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by sp...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#PureBasic
PureBasic
If OpenConsole() Structure Persona nombre.s{15} apellido.s{30} edad.w List amigos$() EndStructure   Dim MyFriends.Persona(100)   ; Aquí la posición '1' del array MyFriends() ; contendrá una persona y su propia información MyFriends(1)\nombre = "Carlos" MyFriends(1)\apellido = "Gzlez." ...
Give a code snippet in #PureBasic Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ImportString[ "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo", "Base64" ]
Give a code snippet in #Mathematica.2FWolfram_Language See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himse...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Salmon
Salmon
  standard_error.print("Goodbye, World!\n");  
Give a code snippet in #Salmon Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 org 100h section .text jmp demo ;;; Count jewels. ;;; Input: DS:SI = jewels, DS:DX = stones ;;; Output: CX = how many stones are jewels ;;; Destroyed: AX, BX, SI, DI jewel: xor ax,ax mov cx,128 ; Allocate 256 bytes (128 words) on stack .zloop: push ax ; Set them all to zero loop .zloop mov...
Give a code snippet in #8086_Assembly Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Common_Lisp
Common Lisp
(defun terminate (status) #+sbcl ( sb-ext:quit :unix-status status) ; SBCL #+ccl ( ccl:quit status) ; Clozure CL #+clisp ( ext:quit status) ; GNU CLISP #+cmu ( unix:unix-exit status) ...
Give a code snippet in #Common_Lisp Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object fina...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Wren
Wren
class Animal { // methods }   class Dog is Animal { // methods }   class Cat is Animal { // mwethods }   class Labrador is Dog { // methods }   class Collie is Dog { // methods }
Give a code snippet in #Wren This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types....
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Forth
Forth
\ in Forth, you do many things on your own. This word is used to define 2D arrays : 2D-ARRAY ( height width ) CREATE DUP , * CELLS ALLOT DOES> ( y x baseaddress ) ROT ( x baseaddress y ) OVER @ ( x baseaddress y width ) * ( x baseaddress y*width ) ROT ( baseaddress y*width x ) + 1+ CELLS + ;   r...
Give a code snippet in #Forth Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Wren
Wren
import "io" for File   var name = "input.txt" System.print("'%(name)' has a a size of %(File.size(name)) bytes")
Give a code snippet in #Wren Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Factor
Factor
USING: accessors arrays colors.constants kernel locals math math.ranges opengl sequences ui ui.gadgets ui.render ;   CONSTANT: palette { COLOR: black COLOR: red COLOR: green COLOR: blue COLOR: magenta COLOR: cyan COLOR: yellow COLOR: white }   CONSTANT: bands 4   TUPLE: pinstripe < gadge...
Give a code snippet in #Factor The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Smalltalk
Smalltalk
  a := #('apple' 'orange'). a size
Give a code snippet in #Smalltalk Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter f...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#ALGOL_W
ALGOL W
begin  % Quaternion record type  % record Quaternion ( real a, b, c, d );    % returns the norm of the specified quaternion  % real procedure normQ ( reference(Quaternion) value q ) ; sqrt( (a(q) * a(q)) + (b(q) * b(q)) + (c(q...
Give a code snippet in #ALGOL_W Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Define ThenIf(a, b) If b Then a #Define InvertAssign(a, b) b = a   Dim As Boolean needUmbrella = False, raining = True ThenIf(needUmbrella = True, raining = True) Print "needUmbrella = "; needUmbrella   Dim As Integer b = 0, a = 3 InvertAssign(a, b) Print "b is"; b Sleep
Give a code snippet in #FreeBASIC Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the...
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "Permutat.bas" 110 LET N=4 ! Number of elements 120 NUMERIC T(1 TO N) 130 FOR I=1 TO N 140 LET T(I)=I 150 NEXT 160 LET S=0 170 CALL PERM(N) 180 PRINT "Number of permutations:";S 190 END 200 DEF PERM(I) 210 NUMERIC J,X 220 IF I=1 THEN 230 FOR X=1 TO N 240 PRINT T(X); 250 NEXT 260 PRI...
Give a code snippet in #IS-BASIC 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   g...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#Cowgol
Cowgol
include "cowgol.coh";   typedef Coord is uint16; # floating point types are not supported   record Point is x: Coord; y: Coord; end record;   sub shoelace(p: [Point], length: intptr): (area: Coord) is var left: Coord := 0; var right: Coord := 0;   var y0 := p.y; var x0 := p.x;   while length...
Give a code snippet in #Cowgol Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns t...
christopher/rosetta-code