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/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Forth
Forth
: pangram? ( addr len -- ? ) 0 -rot bounds do i c@ 32 or [char] a - dup 0 26 within if 1 swap lshift or else drop then loop 1 26 lshift 1- = ;   s" The five boxing wizards jump quickly." pangram? . \ -1
Give a code snippet in #Forth Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#Swift
Swift
import Foundation   func textCharacter(_ ch: Character) -> Character? { switch (ch) { case "a", "b", "c": return "2" case "d", "e", "f": return "3" case "g", "h", "i": return "4" case "j", "k", "l": return "5" case "m", "n", "o": return "6" case "p", "...
Give a code snippet in #Swift When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO ...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance/Alignment
Levenshtein distance/Alignment
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used t...
#11l
11l
F levenshteinAlign(aa, bb) V a = aa.lowercase() V b = bb.lowercase() V costs = [[0] * (b.len + 1)] * (a.len + 1) L(j) 0 .. b.len costs[0][j] = j L(i) 1 .. a.len costs[i][0] = i L(j) 1 .. b.len V tmp = costs[i - 1][j - 1] + Int(a[i - 1] != b[j - 1]) costs[i][j] = min(1 ...
Give a code snippet in #11l The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to d...
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...
#ALGOL_68
ALGOL 68
$ a68g -e 'print(("Hello",new line))'
Give a code snippet in #ALGOL_68 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 implement...
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 ...
#BASIC
BASIC
10 READ N% 20 FOR A%=1 TO N% 30 READ J$,S$ 40 GOSUB 100 50 PRINT S$;" in ";J$;":";J% 60 NEXT 70 END   100 REM Count how many stones (S$) are jewels (J$). 110 DIM J%(127) 120 J%=0 130 FOR I%=1 TO LEN(J$): J%(ASC(MID$(J$,I%,1)))=1: NEXT 140 FOR I%=1 TO LEN(S$): J%=J%+J%(ASC(MID$(S$,I%,1))): NEXT 150 ERASE J% 160 RETURN ...
Give a code snippet in #BASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
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 |...
#D
D
import std.stdio, std.math, std.algorithm;   T[] factors(T)(in T n) pure nothrow { if (n == 1) return [n];   T[] res = [1, n]; T limit = cast(T)real(n).sqrt + 1; for (T i = 2; i < limit; i++) { if (n % i == 0) { res ~= i; immutable q = n / i; if (q > i...
Give a code snippet in #D 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Ursala
Ursala
#import flo   le = <0.06,.11,.16,.21,.26,.31,.36,.41,.46,.51,.56,.61,.66,.71,.76,.81,.86,.91,.96,1.01> out = <0.10,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.90,.94,.98,1.>   price_fraction = fleq@rlPlX*|rhr\~&p(le,out)
Give a code snippet in #Ursala A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#EasyLang
EasyLang
rom_digs$[] = [ "M" "D" "C" "L" "X" "V" "I" ] rom_vals[] = [ 1000 500 100 50 10 5 1 ] # func rom2int rom_numb$ . val . val = 0 for dig$ in strchars rom_numb$ for i range len rom_digs$[] if rom_digs$[i] = dig$ v = rom_vals[i] . . val += v if old_v < v val -= 2 * old_v ....
Give a code snippet in #EasyLang Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Nim
Nim
import osproc, strutils   var name = "" while name.len == 0: stdout.write "Enter output file name (without extension): " name = stdin.readLine().strip() name.add ".wav"   var rate = 0 while rate notin 2000..19_200: stdout.write "Enter sampling rate in Hz (2000 to 192000): " try: rate = parseInt(stdin.readLine()...
Give a code snippet in #Nim Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Swift
Swift
let ranges = [ (0.00..<0.06, 0.10), (0.06..<0.11, 0.18), (0.11..<0.16, 0.26), (0.16..<0.21, 0.32), (0.21..<0.26, 0.38), (0.26..<0.31, 0.44), (0.31..<0.36, 0.50), (0.36..<0.41, 0.54), (0.41..<0.46, 0.58), (0.46..<0.51, 0.62), (0.51..<0.56, 0.66), (0.56..<0.61, 0.70), (0.61..<0.66, 0.74), (0.6...
Give a code snippet in #Swift A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Groovy
Groovy
println new File('input.txt').exists() println new File('/input.txt').exists() println new File('docs').exists() println new File('/docs').exists()
Give a code snippet in #Groovy Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Ada
Ada
generic type Element_Type is private; package Container is type Tree is tagged private; procedure Replace_All(The_Tree : in out Tree; New_Value : Element_Type); private type Node; type Node_Access is access Node; type Tree tagged record Value : Element_type; Left  : Node_Access := null; ...
Give a code snippet in #Ada Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some funct...
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...
#Python
Python
import random   colours_in_order = 'Red White Blue'.split()   def dutch_flag_sort(items, order=colours_in_order): 'return sort of items using the given order' reverse_index = dict((x,i) for i,x in enumerate(order)) return sorted(items, key=lambda x: reverse_index[x])   def dutch_flag_check(items, order=colo...
Give a code snippet in #Python 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 c...
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,...
#J
J
require'strings ~system/packages/misc/xenos.ijs' record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0'   passfields=: <;._1':username:password:gid:uid:gecos:home:shell'   passrec=: LF,~ [: }.@;@ , ':';"0 (passfields i. {. ) { a:,~ {:   R1=: passrec record'' username: jsmith password: x gid: 1001 uid: 1000 g...
Give a code snippet in #J 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 usefu...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#BBC_BASIC
BBC BASIC
VDU 23,22,212;40;16,32,16,128 txt$ = "Hello World! " direction% = TRUE ON MOUSE direction% = NOT direction% : RETURN OFF REPEAT CLS PRINT txt$; IF direction% THEN txt$ = RIGHT$(txt$) + LEFT$(txt$) ELSE txt$ = MID$(txt$,2) + LEFT$(tx...
Give a code snippet in #BBC_BASIC Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#R
R
d <- 5/0 if ( !is.finite(d) ) { # it is Inf, -Inf, or NaN }
Give a code snippet in #R Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#R
R
compose <- function(f,g) function(x) { f(g(x)) } r <- compose(sin, cos) print(r(.5))
Give a code snippet in #R Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#360_Assembly
360 Assembly
* Octal 04/07/2016 OCTAL CSECT USING OCTAL,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " ...
Give a code snippet in #360_Assembly Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#J
J
thru=: <. + i.@(+*)@-~ chr=: a.&i.   lower=: 'a' thru&.chr 'z' upper=: 'A' thru&.chr 'Z' digit=: '0' thru&.chr '9' other=: ('!' thru&.chr '~')-.lower,upper,digit,'`\' all=: lower,upper,digit,other   pwgen =:verb define"0 :: pwhelp NB. pick one of each, remainder from all, then shuffle (?~y) { (?@# { ])every lower;u...
Give a code snippet in #J Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Go
Go
package main   import ( "fmt" "os" )   func printStat(p string) { switch i, err := os.Stat(p); { case err != nil: fmt.Println(err) case i.IsDir(): fmt.Println(p, "is a directory") default: fmt.Println(p, "is a file") } }   func main() { printStat("input.txt") ...
Give a code snippet in #Go Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Glee
Glee
'*' %% 5
Give a code snippet in #Glee Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Lua
Lua
vector = {mt = {}}   function vector.new (x, y) local new = {x = x or 0, y = y or 0} setmetatable(new, vector.mt) return new end   function vector.mt.__add (v1, v2) return vector.new(v1.x + v2.x, v1.y + v2.y) end   function vector.mt.__sub (v1, v2) return vector.new(v1.x - v2.x, v1.y - v2.y) end   ...
Give a code snippet in #Lua 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 (len...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Phix
Phix
-- -- demo\rosetta\Munching_squares.exw -- ================================= -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbu...
Give a code snippet in #Phix Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#VBA
VBA
'RosettaCode Hamming numbers 'This is a well known hard problem in number theory: 'counting the number of lattice points in a 'n-dimensional tetrahedron, here n=3. Public a As Double, b As Double, c As Double, d As Double Public p As Double, q As Double, r As Double Public cnt() As Integer 'stores the number of lattice...
Give a code snippet in #VBA Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming number...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Bracmat
Bracmat
fil$("test.txt",r) { r opens a text file, rb opens a binary file for reading } & fil$(,STR,\n) { first argument empty: same as before (i.e. "test.txt") } { if \n were replaced by e.g. "\n\t " we would read word-wise instead } & 0:?lineno & whl ' ( fil$:(?line.?sep) { "sep" conta...
Give a code snippet in #Bracmat Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Z80_Assembly
Z80 Assembly
; Spiral matrix in Z80 assembly (for CP/M OS - you can use `tnylpo` or `z88dk-ticks` on PC) OPT --syntax=abf : OUTPUT "spiralmt.com" ; asm syntax for z00m's variant of sjasmplus ORG $100 spiral_matrix: ld a,5 ; N matrix size (argument for the code) (valid range: 1..150) ; setup phase ...
Give a code snippet in #Z80_Assembly Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Ruby
Ruby
open(fname, 'w'){|f| f.write(str) }
Give a code snippet in #Ruby Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Racket
Racket
#lang racket   (require racklog)   (define %select (%rel (x xs S S1) [(x (cons x xs) xs)] [(x (cons S xs) (cons S S1)) (%select x xs S1)] [((cons x xs) S) (%select x S S1) (%select xs S1)] [('() (_))]))   (define %next-to (%rel (A B C) [(A B C) (%or (%left-of A B C) (%le...
Give a code snippet in #Racket Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five h...
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...
#BQN
BQN
•Show "" •Show 0 = ≠ "" •Show 0 ≠ ≠ "" •Show "" ≡ ⟨⟩
Give a code snippet in #BQN 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Nim
Nim
import strformat   func isPrime(n: int): bool = if n < 2: return false if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 var d = 5 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 true   var count = 1 write(stdout, " 2") for i in ...
Give a code snippet in #Nim Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation....
#PL.2FI
PL/I
  /* Uses a push-down pop-up stack for the stack (instead of array) */ cvt: procedure options (main); /* 10 Sept. 2012 */ declare (true initial ('1'b), false initial ('0'b) ) bit (1); declare list character (1) controlled, written bit (1) controlled; declare (RPN, out) character (100) varying; ...
Give a code snippet in #PL.2FI Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivale...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Picat
Picat
main => _ = random2(), A = [random(-10,10) : _ in 1..30], println(A), heapSort(A), println(A).   heapSort(A) => heapify(A), End = A.len, while (End > 1) swap(A, End, 1), End := End - 1, siftDown(A, 1, End) end.   heapify(A) => Count = A.len, Start = Count // 2, while (Start >= 1) ...
Give a code snippet in #Picat Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#AWK
AWK
  BEGIN { nrcolors = 8 direction = 1   for (quarter=0; quarter<4; quarter++) { for (height=0; height<5; height++) { for (width=0; width<nrcolors; width++) { # gradient goes white-to-black or black-to-white depending on direction if (direction % 2) color = width * (255 / (nrcolo...
Give a code snippet in #AWK The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Gambas
Gambas
Public Sub Main() Dim cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"] Dim siCount As Short Dim sTemp As String   For Each sTemp In cList Print cList.key & "=" & sTemp;; Next   Print   For siCount = 1 To cList.Count Print cL...
Give a code snippet in #Gambas Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Nim
Nim
for x in countdown(10,0): echo(x)
Give a code snippet in #Nim Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incremen...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function %maxsubs (v,n) ... $if n==1 then $ if (v[1]<0) then return {zeros(1,0),zeros(1,0)} $ else return {v,v}; $ endif; $endif; ${v1,v2}=%maxsubs(v[1:n-1],n-1); $m1=sum(v1); m2=sum(v2); m3=m2+v[n]; $if m3>0 then v3=v2|v[n]; else v3=zeros(1,0); endif; $if m3>m1 then return {v2|v[n],v3}; $else return {v1,v3}; ...
Give a code snippet in #Euler_Math_Toolbox Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all ...
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 |...
#DCL
DCL
$ inquire a "Please provide an integer" $ inquire b "Please provide another" $ if a .lt. b then $ write sys$output "the first integer is less" $ if a .eq. b then $ write sys$output "the integers have the same value" $ if a .gt. b then $ write sys$output "the first integer is greater"
Give a code snippet in #DCL 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/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Elixir
Elixir
defmodule RC do def lastSunday(year) do Enum.map(1..12, fn month -> lastday = :calendar.last_day_of_the_month(year, month) daynum = :calendar.day_of_the_week(year, month, lastday) sunday = lastday - rem(daynum, 7) {year, month, sunday} end) end end   y = String.to_integer(hd(System...
Give a code snippet in #Elixir Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 20...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
longmonth = [1 3 5 7 8 10 12];   i = 1;   for y = 1900:2100 for m = 1:numel(longmonth) [num,name] = weekday(datenum(y,longmonth(m),1)); if num == 6 x(i,:) = datestr(datenum(y,longmonth(m),1),'mmm yyyy'); %#ok<SAGROW> i = i+1; end end end   fprintf('There are %i mo...
Give a code snippet in #MATLAB_.2F_Octave 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 pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Pascal
Pascal
program convertSecondsToCompoundDuration(output);   const suffixUnitWeek = 'wk'; suffixUnitDay = 'd'; suffixUnitHour = 'hr'; { Use `'h'` to be SI-compatible. } suffixUnitMinute = 'min'; suffixUnitSecond = 'sec'; { NB: Only `'s'` is SI-approved. }   suffixSeparator = ' '; { A non-breaking space wou...
Give a code snippet in #Pascal Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g....
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#R
R
i <- 1024L while(i > 0) { print(i) i <- i %/% 2 }
Give a code snippet in #R Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Visual_Basic_.NET
Visual Basic .NET
Class BinaryTree(Of T) ReadOnly Property Left As BinaryTree(Of T) ReadOnly Property Right As BinaryTree(Of T) ReadOnly Property Value As T   Sub New(value As T, Optional left As BinaryTree(Of T) = Nothing, Optional right As BinaryTree(Of T) = Nothing) Me.Value = value Me.Left = left ...
Give a code snippet in #Visual_Basic_.NET Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together w...
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...
#Julia
Julia
function lookandsay(s::String) rst = IOBuffer() c = 1 for i in 1:length(s) if i != length(s) && s[i] == s[i+1] c += 1 else print(rst, c, s[i]) c = 1 end end String(take!(rst)) end     function lookandsayseq(n::Integer) rst = Vector{Stri...
Give a code snippet in #Julia 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...
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...
#Run_BASIC
Run BASIC
for i = 1000 to 1016 print i;" = "; factorial$(i) next wait function factorial$(num) if num = 1 then factorial$ = "1" fct = 2 while fct <= num if (num mod fct) = 0 then factorial$ = factorial$ ; x$ ; fct x$ = " x " num = num / fct else fct = fct + 1 end if wend end function
Give a code snippet in #Run_BASIC 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 w...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#UNIX_Shell
UNIX Shell
#!/bin/sh   getopprec() { case "$1" in '+') echo 2;; '-') echo 2;; '*') echo 3;; '/') echo 4;; '%') echo 4;; '^') echo 4;; '(') echo 5;; esac }   getopassoc() { case "$1" in '^') echo r;; *) echo l;; esac }   showstacks() { [ ...
Give a code snippet in #UNIX_Shell Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens rep...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#ooRexx
ooRexx
  x = .array~of("a", "b", "c") y = .array~of("A", "B", "C") z = .array~of(1, 2, 3)   loop i = 1 to x~size say x[i]y[i]z[i] end  
Give a code snippet in #ooRexx Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exa...
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...
#tsql
tsql
;WITH Iterate(N,A,B,X0,X1) AS ( SELECT 1 ,CASE WHEN @a < 0 THEN @b-(-@a % @b) ELSE @a END ,CASE WHEN @b < 0 THEN -@b ELSE @b END ,0 ,1 UNION ALL SELECT N+1 ,B ,A%B ,X1-((A/B)*X0) ,X0 FROM Iterate WHERE A != 1 AND B != 0 ), ModularInverse(Result) AS ( SELECT -1 FROM ...
Give a code snippet in #tsql 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/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Plain_TeX
Plain TeX
\long\def\antefi#1#2\fi{#2\fi#1} \def\fornum#1=#2to#3(#4){% \edef#1{\number\numexpr#2}\edef\fornumtemp{\noexpand\fornumi\expandafter\noexpand\csname fornum\string#1\endcsname {\number\numexpr#3}{\ifnum\numexpr#4<0 <\else>\fi}{\number\numexpr#4}\noexpand#1}\fornumtemp } \long\def\fornumi#1#2#3#4#5#6{\def#1{\unless\if...
Give a code snippet in #Plain_TeX Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
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 |...
#Befunge
Befunge
10:p&v: >:0:g%#v_0:g\:0:g/\v >:0:g:*`| > >0:g1+0:p >:0:g:*-#v_0:g\>$>:!#@_.v > ^ ^ ," "<
Give a code snippet in #Befunge Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Go_2
Go
package main   import "fmt"   type rangeBounds struct { b1, b2 float64 }   func mapRange(x, y rangeBounds, n float64) float64 { return y.b1 + (n - x.b1) * (y.b2 - y.b1) / (x.b2 - x.b1) }   func main() { r1 := rangeBounds{0, 10} r2 := rangeBounds{-1, 0} for n := float64(0); n <= 10; n += 2 { ...
Give a code snippet in #Go_2 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 ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#JavaScript
JavaScript
  var ctx, wid, hei, cols, rows, maze, stack = [], start = {x:-1, y:-1}, end = {x:-1, y:-1}, grid = 8; function drawMaze() { for( var i = 0; i < cols; i++ ) { for( var j = 0; j < rows; j++ ) { switch( maze[i][j] ) { case 0: ctx.fillStyle = "black"; break; case 1: ...
Give a code snippet in #JavaScript Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be use...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   placesList = [String - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - ] sortedList = shellSort(String[] Arrays.copyOf(placesList...
Give a code snippet in #NetRexx 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#jq
jq
# The range of codepoints is from m up to but excluding n; # "class" should be a character class, e.g. Ll or Lu for lower/upper case respectively. def generate(class; m; n): reduce (range(m;n) | [.] | implode | select( test( "\\p{" + class + "}" ))) as $c (""; . + $c);
Give a code snippet in #jq Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task req...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Nim
Nim
import strformat   func totient(n: int): int = var tot = n var nn = n var i = 2 while i * i <= nn: if nn mod i == 0: while nn mod i == 0: nn = nn div i dec tot, tot div i if i == 2: i = 1 inc i, 2 if nn > 1: dec tot,...
Give a code snippet in #Nim The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the i...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Processing
Processing
String txt = "Hello, world! "; boolean dir = true;   void draw(){ background(128); text(txt, 10, height/2); if(frameCount%10==0){ if(dir) { txt = rotate(txt, 1); } else { txt = rotate(txt, txt.length()-1); } } }   void mouseReleased(){ dir = !dir; }   String rotate(String text, int sta...
Give a code snippet in #Processing Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This ta...
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 ...
#Io
Io
  List do( insertionSortInPlace := method( for(j, 1, size - 1, key := at(j) i := j - 1   while(i >= 0 and at(i) > key, atPut(i + 1, at(i)) i = i - 1 ) atPut(i + 1, key) ) ) )   lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) lst insertionSortInPlace println # ==> list...
Give a code snippet in #Io 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/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
#SPL
SPL
$include.txt
Give a code snippet in #SPL 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/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Ring
Ring
  # Project : Color of a screen pixel   Load "gamelib.ring" r = 0 g = 0 b = 0 al_init() al_init_image_addon() display = al_create_display(1000,800) al_set_target_bitmap(al_get_backbuffer(display)) al_clear_to_color(al_map_rgb(255,255,255)) image = al_load_bitmap("stock.jpg") al_draw_rotated_bitmap(image,0,0,250,250,150...
Give a code snippet in #Ring Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
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...
#Kotlin
Kotlin
// version 1.0.6   import java.util.*   fun main(args: Array<String>) { val calendar = GregorianCalendar(1900, 0, 1) val months31 = arrayOf(1, 3, 5, 7, 8, 10, 12) val monthsWithFive = mutableListOf<String>() val yearsWithNone = mutableListOf<Int>() for (year in 1900..2100) { var countInYear...
Give a code snippet in #Kotlin 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 (the...
christopher/rosetta-code
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#Common_Lisp
Common Lisp
(ql:quickload 'ironclad) (defun md4 (str) (ironclad:byte-array-to-hex-string (ironclad:digest-sequence :md4 (ironclad:ascii-string-to-byte-array str))))   (md4 "Rosetta Code")
Give a code snippet in #Common_Lisp Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace LatinSquares { using matrix = List<List<int>>;   class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; }   static matrix DList(int n, int start) {...
Give a code snippet in #C.23 A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element wit...
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...
#PicoLisp
PicoLisp
(scl 28)   (de *A ~(flip (1.00000000000000000000 0.57721566490153286061 -0.65587807152025388108 -0.04200263503409523553 0.16653861138229148950 -0.04219773455554433675 -0.00962197152787697356 0.00721894324666309954 -0.00116516759185906511 -0.00021524167411495097 0.00012805028238811619 -0.0...
Give a code snippet in #PicoLisp 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/...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Elixir
Elixir
defmodule Munchausen do @pow for i <- 0..9, into: %{}, do: {i, :math.pow(i,i) |> round}   def number?(n) do n == Integer.digits(n) |> Enum.reduce(0, fn d,acc -> @pow[d] + acc end) end end   Enum.each(1..5000, fn i -> if Munchausen.number?(i), do: IO.puts i end)
Give a code snippet in #Elixir A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Common_Lisp
Common Lisp
(require :lispbuilder-sdl) (require :simple-rgb)   (defparameter *palette* (let ((palette-aux (make-array 256 :element-type 'fixnum))) (dotimes (i 256) (let ((color_i (simple-rgb:hsv->rgb (simple-rgb:hsv (/ i 255.0) 1.0 1.0)))) (setf (aref palette-aux i) (loop :for component :across color_i ...
Give a code snippet in #Common_Lisp The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#11l
11l
F quad(top = 2200) V r = [0B] * top V ab = [0B] * (top * 2)^2 L(a) 1 .< top L(b) a .< top ab[a * a + b * b] = 1B V s = 3 L(c) 1 .< top (V s1, s, V s2) = (s, s + 2, s + 2) L(d) c + 1 .< top I ab[s1] r[d] = 1B s1 += s2 s2 += 2 R enumerate...
Give a code snippet in #11l One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclu...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Scala
Scala
object MaximumTrianglePathSum extends App { // Solution: def sum(triangle: Array[Array[Int]]) = triangle.reduceRight((upper, lower) => upper zip (lower zip lower.tail) map {case (above, (left, right)) => above + Math.max(left, right)} ).head   // Tests: def triang...
Give a code snippet in #Scala Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Prolog
Prolog
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% The Rosetta Code Virtual Machine, for GNU Prolog. %%% %%% The following code uses GNU Prolog's extensions for global %%% variables. %%% %%% Usage: vm [INPUTFILE [OUTPUTFILE]] %%% The notation "-" means to use standard input or standard outpu...
Give a code snippet in #Prolog A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read in...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Raku
Raku
my $host = '127.0.0.1'; my $port = 256;   my $client = IO::Socket::INET.new(:$host, :$port); $client.print( 'hello socket world' ); $client.close;
Give a code snippet in #Raku For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#MUMPS
MUMPS
NESTLOOP  ;.../loops/nested  ;set up the 2D array with random values NEW A,I,J,K,FLAG,TRIGGER SET K=15 ;Magic - just to give us a size to work with SET TRIGGER=20 ;Magic - the max value, and the end value FOR I=1:1:K FOR J=1:1:K SET A(I,J)=$RANDOM(TRIGGER)+1  ;Now, search through the array, halting when the value o...
Give a code snippet in #MUMPS 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 me...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#PicoLisp
PicoLisp
('((X) (list (lit X) (lit X))) '((X) (list (lit X) (lit X))))
Give a code snippet in #PicoLisp A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#SequenceL
SequenceL
evens(x(1))[i] := x[i] when x[i] mod 2 = 0;
Give a code snippet in #SequenceL Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#PowerShell
PowerShell
$frequencies = 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 foreach($tone in $frequencies){ [Console]::beep($tone, 500) }
Give a code snippet in #PowerShell Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, R...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Z80_Assembly
Z80 Assembly
org &8000
Give a code snippet in #Z80_Assembly Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven lang...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Go
Go
package main   import "fmt"   func pfacSum(i int) int { sum := 0 for p := 1; p <= i/2; p++ { if i%p == 0 { sum += p } } return sum }   func main() { var d, a, p = 0, 0, 0 for i := 1; i <= 20000; i++ { j := pfacSum(i) if j < i { d++ ...
Give a code snippet in #Go These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#C.2B.2B
C++
  #include <math.h> #include <iostream> #include <iomanip>   bool isPrime( unsigned u ) { if( u < 4 ) return u > 1; if( /*!( u % 2 ) ||*/ !( u % 3 ) ) return false;   unsigned q = static_cast<unsigned>( sqrt( static_cast<long double>( u ) ) ), c = 5; while( c <= q ) { if( !( u % c )...
Give a code snippet in #C.2B.2B Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Haskell
Haskell
-- as a translation from imperative code, this is probably not a "good" implementation import Data.List   type Var = (Int, Int, Int, Int) -- sx sy sz c   magicSum :: Int -> Int magicSum x = ((x * x + 1) `div` 2) * x   wrapInc :: Int -> Int -> Int wrapInc max x | x + 1 == max = 0 | otherwise = x + 1   wra...
Give a code snippet in #Haskell A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbe...
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...
#PHP
PHP
#!/usr/bin/env php The 24 Game   Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24.   An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
Give a code snippet in #PHP 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/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Ring
Ring
  # Project : Carmichael 3 strong pseudoprimes   see "The following are Carmichael munbers for p1 <= 61:" + nl see "p1 p2 p3 product" + nl   for p = 2 to 61 carmichael3(p) next   func carmichael3(p1) if isprime(p1) = 0 return ok for h3 = 1 to p1 -1 t1 = (h3 + p1) * (p1 -1) ...
Give a code snippet in #Ring A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to invest...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Golfscript
Golfscript
# end of line comment
Give a code snippet in #Golfscript Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Julia
Julia
msg = "Rosetta code"   using Nettle digest = hexdigest("sha256", msg)   # native using SHA digest1 = join(num2hex.(sha256(msg)))   @assert digest == digest1
Give a code snippet in #Julia SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b78...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#R
R
str1 <- "the quick brown fox, etc." str2 <- 'the quick brown fox, etc.' identical(str1, str2) #returns TRUE
Give a code snippet in #R Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Her...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Klong
Klong
  cf::{[f g i];f::x;g::y;i::z; f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0} cf({:[0=x;1;2]};{x;1};1000) cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000) cf({:[0=x;3;6]};{((2*x)-1)^2};1000)  
Give a code snippet in #Klong continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wri...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#VAX_Assembly
VAX Assembly
  00000064 0000 1 n = 100 0000 0000 2 .entry doors, ^m<> 26'AF 9F 0002 3 pushab b^arr ; offset signed byte 50 64 8F 9A 0005 4 movzbl #n, r0 50 DD 0009 ...
Give a code snippet in #VAX_Assembly There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Home_primes
Home primes
This page uses content from Wikipedia. The original article was at Home 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 number theory, the home prime HP(n) of an integer n greater than 1 is...
#Raku
Raku
use Prime::Factor;   my $start = now;   (flat 2..20, 65).map: -> $m { my ($now, @steps, @factors) = now, $m;   @steps.push: @factors.join('_') while (@factors = prime-factors @steps[*-1].Int) > 1;   say (my $step = +@steps) > 1 ?? (@steps[0..*-2].map( { "HP$_\({--$step})" } ).join: ' = ') !! ("HP$m"), ...
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Home 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 number theory, the home prime HP(n) of ...
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...
#LiveCode
LiveCode
function lookAndSay S put 0 into C put char 1 of S into lastChar repeat with i = 2 to length(S) add 1 to C if char i of S is lastChar then next repeat put C & lastChar after R put 0 into C put char i of S into lastChar end repeat return R & C + 1 & lastChar end lookAndSay   ...
Give a code snippet in #LiveCode 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 seque...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
small = "zero"["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; tens = # <> "-" & /@ {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; big = Pr...
Give a code snippet in #Mathematica.2FWolfram_Language Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support f...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Tcl
Tcl
% package require Tcl 8.5 8.5.2 % expr inf+1 Inf % set inf_val [expr {1.0 / 0.0}] Inf % set neginf_val [expr {-1.0 / 0.0}] -Inf % set negzero_val [expr {1.0 / $neginf_val}] -0.0 % expr {0.0 / 0.0} domain error: argument not in valid range % expr nan domain error: argument not in valid range % expr {1/-inf} -0.0
Give a code snippet in #Tcl The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to...
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#FreeBASIC
FreeBASIC
' version 23-10-2016 ' compile with: fbc -s console   Const scr_x = 800 ' screen 800 x 800 Const scr_y = 600 Const m_x = scr_x \ 2 ' middle of screen Const m_y = scr_y \ 2     Sub superellipse(a As Long, b As Long, n As Double)   ReDim As Long y(0 To a) Dim As Long x   y(0) = b ' value for x = 0 ...
Give a code snippet in #FreeBASIC A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw...
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#11l
11l
F rev(n) R BigInt(reversed(String(n)))   [BigInt = (Bool, BigInt)] cache   F lychrel(BigInt =n) I n C :cache R :cache[n]   V r = rev(n) V res = (1B, n) [BigInt] seen L(i) 1000 n += r r = rev(n) I n == r res = (0B, BigInt(0)) L.break I n C :cache ...
Give a code snippet in #11l   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most st...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#ALGOL_68
ALGOL 68
'PR' QUOTE 'PR'   'PROC' PRINT CALENDAR = ('INT' YEAR, PAGE WIDTH)'VOID': 'BEGIN'   ()'STRING' MONTH NAMES = ( "JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE", "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"), WEEKDAY NAMES = ("SU","MO","TU","WE","TH","FR","SA"); 'FORMAT' WEEKDAY FMT =...
Give a code snippet in #ALGOL_68 Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the...
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.
#J
J
"_1
Give a code snippet in #J Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Fortran
Fortran
C This would be some kind of comment C Usually one would avoid columns 2-6 even in a comment.
Give a code snippet in #Fortran Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#ALGOL_68
ALGOL 68
PROC raise exception= ([]STRING args)VOID: ( put(stand error, ("Exception: ",args, newline)); stop );   PROC raise zero division error := VOID: raise exception("integer division or modulo by zero");   PROC int div = (INT a,b)REAL: a/b; PROC int over = (INT a,b)INT: a%b; PROC int mod = (INT a,b)INT: a%*b;   BE...
Give a code snippet in #ALGOL_68 Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Golo
Golo
#!/usr/bin/env golosh ---- This module demonstrates variadic functions. ---- module Variadic   import gololang.Functions   ---- Varargs have the three dots after them just like Java. ---- function varargsFunc = |args...| { foreach arg in args { println(arg) } }   function main = |args| {   varargsFunc(1, 2, 3...
Give a code snippet in #Golo Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Re...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task   Declare_Queue(String) '' expand Queue type for Strings   Dim stringQueue As Queue(String) With stringQueue '' push some strings into the Queue .push("first") .push("second") .push("third") .push("f...
Give a code snippet in #FreeBASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#D
D
import std.stdio, std.uri;   void main() { writeln(decodeComponent("http%3A%2F%2Ffoo%20bar%2F")); }
Give a code snippet in #D This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read in...
#Phix
Phix
-- -- demo\rosetta\Compiler\parse.e -- ============================= -- -- The reusable part of parse.exw -- with javascript_semantics include lex.e sequence tok procedure errd(sequence msg, sequence args={}) {tok_line,tok_col} = tok error(msg,args) end procedure global sequence toks integer next_tok = 1 f...
Give a code snippet in #Phix A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened forma...
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 ...
#RLaB
RLaB
x = rand(1,10); y = rand(1,10); s = sum( x .* y );
Give a code snippet in #RLaB 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/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#Tcl
Tcl
package require Thread   foreach name {Aristotle Kant Spinoza Marx Russel} { lappend forks [thread::mutex create] lappend tasks [set t [thread::create -preserved { # Implement each task as a coroutine internally for simplicity of presentation # This is because we want to remain able to receive m...
Give a code snippet in #Tcl The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie";   if dog == Dog & Dog == DOG & dog == DOG then do say 'There is just one dog named' dog'.' end else do say 'The three dogs are named' dog',' Dog 'and' DOG'.' end   return  
Give a code snippet in #NetRexx Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, ...
christopher/rosetta-code