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/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
function list = countingSort(list)   minElem = min(list); maxElem = max(list);   count = zeros((maxElem-minElem+1),1);   for number = list count(number - minElem + 1) = count(number - minElem + 1) + 1; end   z = 1;   for i = (minElem:maxElem) while( count(i-minElem +1) >...
Give a code snippet in #MATLAB_.2F_Octave 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Modula-2
Modula-2
MODULE Faulhaber; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   VAR TextWinExSrc : ExceptionSource;   (* Helper Functions *) PROCEDURE Abs(n : INTEGER) : INTEGER; BEGIN IF n < 0 THEN RETURN ...
Give a code snippet in #Modula-2 In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expr...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT common="" dir1="/home/user1/tmp/coverage/test" dir2="/home/user1/tmp/covert/operator" dir3="/home/user1/tmp/coven/members" dir1=SPLIT (dir1,":/:"),dir2=SPLIT (dir2,":/:"), dir3=SPLIT (dir3,":/:") LOOP d1=dir1,d2=dir2,d3=dir3 IF (d1==d2,d3) THEN common=APPEND(common,d1,"/") ELSE PRINT common E...
Give a code snippet in #TUSCRIPT Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as th...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#MAXScript
MAXScript
str1 = "Hello" str2 = copy str1
Give a code snippet in #MAXScript This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Nanoquery
Nanoquery
def first(function) return function() end   def second() return "second" end   result = first(second) println result
Give a code snippet in #Nanoquery Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#ALGOL_68
ALGOL 68
# returns the sum of the multiples of 3 and 5 below n # PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT: BEGIN # calculate the sum of the multiples of 3 below n # LONG LONG INT multiples of 3 = ( n - 1 ) OVER 3; LONG LONG INT multiples of 5 = ( n - 1 ) OVER 5; ...
Give a code snippet in #ALGOL_68 Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#HicEst
HicEst
READ(Text="123459 ", Format="i10") dec ! 123459 READ(Text=" abcf123 ", Format="Z10") hex ! 180154659 READ(Text=" 7651 ", Format="o10") oct ! 4009 READ(Text=" 101011001", Format="B10.10") bin ! 345
Give a code snippet in #HicEst It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#FreeBASIC
FreeBASIC
Dim As Integer m1(1 To 3) = {3,4,5} Dim As String m2 = "[" Dim As Integer x, y ,z For x = 1 To Ubound(m1) y = m1(x) + 1 z = y * 2 m2 &= Str(z) & ", " Next x m2 = Left(m2, Len(m2) -2) m2 &= "]" Print m2 Sleep
Give a code snippet in #FreeBASIC A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematical...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#APL
APL
sd←+/⊥⍣¯1
Give a code snippet in #APL Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Julia
Julia
function bernoulli(n) A = Vector{Rational{BigInt}}(undef, n + 1) for m = 0 : n A[m + 1] = 1 // (m + 1) for j = m : -1 : 1 A[j] = j * (A[j] - A[j + 1]) end end return A[1] end   function display(n) B = map(bernoulli, 0 : n) pad = mapreduce(x -> ndigits(numerato...
Give a code snippet in #Julia Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as pe...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o...
#Nim
Nim
import strutils     func step(cells: string; rule: int): string = for i in 0..(cells.len - 3): var bin = 0 var b = 2 for n in i..(i + 2): inc bin, ord(cells[n] == '*') shl b b = b shr 1 let a = if (rule and 1 shl bin) != 0: '*' else: '.' result.add(a)     func addNoCells(cells: var str...
Give a code snippet in #Nim The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other w...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Simula
Simula
BEGIN   CLASS COMPARABLE;;   COMPARABLE CLASS PAIR(N,V); TEXT N,V;;   CLASS COMPARATOR; VIRTUAL: PROCEDURE COMPARE IS INTEGER PROCEDURE COMPARE(A, B); REF(COMPARABLE) A, B;; BEGIN END**OF**COMPARATOR;   COMPARATOR CLASS PAIRBYNAME; BEGIN INTEGER PROCEDURE COMP...
Give a code snippet in #Simula Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to e...
#Phix
Phix
constant template = { { { 1, 2 }, { 3, 4, 1, }, 5 } }, template2 = { { { 1, 2 }, { 10, 4, 1 }, 5 } }, payload = {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"} sequence unused = repeat(true,length(payload)), missing = {} function fill(object t, s...
Give a code snippet in #Phix A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#PARI.2FGP
PARI/GP
  M=vector(41) M[1]=1 M[2]=2 for(n=3, 41, M[n]=(M[n-1]*(2*n+1) + M[n-2]*(3*n-3))/(n+2)) M=concat([1], M) for(n=1, 42, print(M[n]," ",isprime(M[n])))  
Give a code snippet in #PARI.2FGP Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#Clojure
Clojure
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cit...
Give a code snippet in #Clojure 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/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#TI-83_BASIC
TI-83 BASIC
seq(0,X,1,100 For(X,1,100 0 or Ans-not(fPart(cumSum(1 or Ans)/A End Pause Ans
Give a code snippet in #TI-83_BASIC There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Befunge
Befunge
1>:5`#@_:>"*",v | :-1< ^+1,+5+5<
Give a code snippet in #Befunge “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract struc...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#REXX
REXX
/*REXX pgm finds if words can be spelt from a pool of toy blocks (each having 2 letters)*/ list= 'A bark bOOk treat common squaD conFuse' /*words can be: upper/lower/mixed case*/ blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' do k=1 for words(list) ...
Give a code snippet in #REXX ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#MATLAB_.2F_Octave
MATLAB / Octave
dec2base(26,16) base2dec('1a', 16)
Give a code snippet in #MATLAB_.2F_Octave Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer ...
christopher/rosetta-code
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Factor
Factor
USING: arrays ascii io kernel math prettyprint random sequences strings ; IN: rosetta-code.penneys-game   ! Generate a random boolean. : t|f ( -- t/f ) 1 random-bits 0 = ;   ! Checks whether the sequence chosen by the human is valid. : valid-input? ( seq -- ? ) [ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter lengt...
Give a code snippet in #Factor Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#Ada
Ada
function noargs return Integer; function twoargs (a, b : Integer) return Integer; -- varargs do not exist function optionalargs (a, b : Integer := 0) return Integer; -- all parameters are always named, only calling by name differs procedure dostuff (a : Integer);
Give a code snippet in #Ada Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#Raku
Raku
# sboxes from http://en.wikipedia.org/wiki/GOST_(block_cipher) constant sbox = [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3], [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9], [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11], [7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3], ...
Give a code snippet in #Raku GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_wheel
Color wheel
Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and ...
#FreeBASIC
FreeBASIC
#include "fbgfx.bi"   Sub HSVtoRGB(h As Single, s As Integer, v As Integer, Byref r As Integer, Byref g As Integer, Byref b As Integer) If s = 0 Then r = v g = v b = v Return End If   h = h Mod 360 Dim As Single hue = h   Select Case h Case 0f To 51.5f hue...
Give a code snippet in #FreeBASIC Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you un...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#LabVIEW
LabVIEW
  {if true then yes else no} -> yes   {def switch {lambda {:n} {if {< :n 0} then :n is negative else {if {> :n 0} then :n is positive else :n is zero}}}}   {switch -12} -> -12 is negative {switch 12} -> 12 is positive {switch 0} -> 0 is zero  
Give a code snippet in #LabVIEW Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Commo...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#OCaml
OCaml
# int_of_string "123459";; - : int = 123459 # int_of_string "0xabcf123";; - : int = 180154659 # int_of_string "0o7651";; - : int = 4009 # int_of_string "0b101011001";; - : int = 345
Give a code snippet in #OCaml It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#D
D
import std.stdio;   void hanoi(in int n, in char from, in char to, in char via) { if (n > 0) { hanoi(n - 1, from, via, to); writefln("Move disk %d from %s to %s", n, from, to); hanoi(n - 1, via, to, from); } }   void main() { hanoi(3, 'L', 'M', 'R'); }
Give a code snippet in #D Task Solve the   Towers of Hanoi   problem with recursion.
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...
#Wart
Wart
i <- 1024 while (i > 0) prn i i <- (int i/2)
Give a code snippet in #Wart 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#8th
8th
  : pass-me "I was passed\n" . ; : passer w:exec ; \ pass 'pass-me' to 'passer' ' pass-me passer  
Give a code snippet in #8th Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
Factorial base numbers indexing permutations of a collection
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0....
#AppleScript
AppleScript
-- Permutate a list according to a given factorial base number. on FBNShuffle(|Ω|, fbn) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to "." set fbnDigits to fbn's text items set AppleScript's text item delimiters to astid   repeat with m from 1 to (count fbn...
Give a code snippet in #AppleScript You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#Factor
Factor
USING: grouping kernel math random sequences ;   : sorted? ( seq -- ? ) 2 <clumps> [ first2 <= ] all? ; : bogosort ( seq -- newseq ) [ dup sorted? ] [ randomize ] until ;
Give a code snippet in #Factor Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#PowerShell
PowerShell
  $url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'   (New-Object System.Net.WebClient).DownloadFile($url, "$env:TEMP\unixdict.txt")   $ordered = Get-Content -Path "$env:TEMP\unixdict.txt" | ForEach-Object {if (($_.ToCharArray() | Sort-Object) -join '' -eq $_) {$_}} | Group-Object -Property Length | ...
Give a code snippet in #PowerShell An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file l...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Julia
Julia
  type PigPlayer name::String score::Int strat::Function end   function PigPlayer(a::String) PigPlayer(a, 0, pig_manual) end   function scoreboard(pps::Array{PigPlayer,1}) join(map(x->@sprintf("%s has %d", x.name, x.score), pps), " | ") end   function pig_manual(pps::Array{PigPlayer,1}, pdex::Intege...
Give a code snippet in #Julia The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to t...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Astro
Astro
mean([1, 2, 3]) mean(1..10) mean([])  
Give a code snippet in #Astro Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an esta...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#GlovePIE
GlovePIE
if var.end=0 then // Without the code being in this if statement, the code would keep executing until it were to stop. var.end=1 // These variables, respectively, refer to an integer, a boolean, and a string. var.variable1=3 var.variable2=True var.variable3="Hi!" // var.example1 now refers to a string object instead. v...
Give a code snippet in #GlovePIE Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/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      ...
#C1R
C1R
Quine
Give a code snippet in #C1R 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   s...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#BQN
BQN
(1⌈´↕×0=↕|⊢)¨ ∘‿10⥊1+↕100
Give a code snippet in #BQN Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Red
Red
Red[]   repeat i 5 [ loop i [prin "*"] prin newline ]
Give a code snippet in #Red “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structure...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#BBC_BASIC
BBC BASIC
REM >split PRINT FN_split( "gHHH5YY++///\" ) END   DEF FN_split( s$ ) LOCAL c$, split$, d$, i% c$ = LEFT$( s$, 1 ) split$ = "" FOR i% = 1 TO LEN s$ LET d$ = MID$( s$, i%, 1 ) IF d$ <> c$ THEN split$ += ", " c$ = d$ ENDIF split$ += d$ NEXT = split$
Give a code snippet in #BBC_BASIC Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly). ...
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...
#Scheme
Scheme
#\a #\A #\? #\space #\newline
Give a code snippet in #Scheme 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Visual_Basic_.NET
Visual Basic .NET
Public Class Board Inherits System.Windows.Forms.Form   Const XbyX = 4 Const XSize = 60   Private Empty As New Panel Private Tiles As New List(Of Tile) Private Moves As Integer   Public Sub New() Me.Text = XbyX ^ 2 - 1 & " Puzzle Game" Me.ClientSize = New Size(XbyX * XSize, X...
Give a code snippet in #Visual_Basic_.NET Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Ol
Ol
  #include <extensions/embed.h>   #define min(x,y) (x < y ? x : y)   extern unsigned char repl[]; int Query(char *Data, size_t *Length) { ol_t ol; embed_new(&ol, repl, 0);   word s = embed_eval(&ol, new_string(&ol, "(define sample \"Here am I\")" "sample" ), 0); if (!is_string(s)) goto fail;   int i = *Leng...
Give a code snippet in #Ol This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, siz...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Pascal
Pascal
  Program FileTruncate;   uses SysUtils;   var myfile: file of byte; filename: string; position: integer;   begin write('File for truncation: '); readln(filename); if not FileExists(filename) then begin writeln('Error: File does not exist.'); exit; end;   write('Truncate position: '); re...
Give a code snippet in #Pascal Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creati...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#CLU
CLU
sum_squares = proc (ns: sequence[int]) returns (int) sum: int := 0 for n: int in sequence[int]$elements(ns) do sum := sum + n ** 2 end return(sum) end sum_squares   start_up = proc () po: stream := stream$primary_output()   stream$putl(po, int$unparse(sum_squares(sequence[int]$[]))) ...
Give a code snippet in #CLU Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#APL
APL
  ∇r ← digitsOf n;digitList digitList ← ⍬ loop:→((⌊n)=0)/done digitList ← digitList,(⌊n|⍨10) n ← n÷10 →loop done: r ← ⊖digitList ∇   ∇r ← getASN n;idx;list idx ← 0 list ← 0⍴0 loop: →(n=⍴list)/done →(isArmstrongNumber idx)/add →next add: list ← list,idx next: idx ← idx+1 →loop done: r ← list ∇ ...
Give a code snippet in #APL A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m} ...
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...
#AppleScript
AppleScript
AST URL decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1"
Give a code snippet in #AppleScript 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 unen...
christopher/rosetta-code
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics th...
#R
R
  magictrick<-function(){ deck=c(rep("B",26),rep("R",26)) deck=sample(deck,52) blackpile=character(0) redpile=character(0) discardpile=character(0) while(length(deck)>0){ if(deck[1]=="B"){ blackpile=c(blackpile,deck[2]) deck=deck[-2] }else{ redpile=c(redpile,deck[2]) deck=dec...
Give a code snippet in #R Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the tr...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   32 var space   def bksp /# -- backspace #/ 8 tochar print enddef   def floor .5 + int enddef   def center tostr align enddef   def startday /# year -- day of the week of january 1 #/ 1 - >ps tps 365 * tps 4 / floor + tps 100 / floor - ps> 400 / floor + 7 mod enddef   ...
Give a code snippet in #Phixmonti Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display w...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Lingo
Lingo
sx = xtra("Shell").new() if the platform contains "win" then put sx.shell_cmd("dir") else put sx.shell_cmd("ls") end if
Give a code snippet in #Lingo Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Retro
Retro
$c 'hello,_world! 'This_is_'a_string'  
Give a code snippet in #Retro 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#Julia
Julia
using Printf   # Total circles area: https://rosettacode.org/wiki/Total_circles_area   xc = [1.6417233788, -1.4944608174, 0.6110294452, 0.3844862411, -0.2495892950, 1.7813504266, -0.1985249206, -1.7011985145, -0.4319462812, 0.2178372997, -0.6294854565, 1.7952608455, 1.4168575317, 1.4637371396, -0.5263668798,...
Give a code snippet in #Julia Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#Tcl
Tcl
set max_invalid_run 0 set max_invalid_run_end "" set tot_file 0 set num_file 0   set linefmt "Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f"   set filename readings.txt set fh [open $filename] while {[gets $fh line] != -1} { set tot_line [set count [set num_line 0]] set fields [regexp...
Give a code snippet in #Tcl This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. I...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#C.23
C#
  using System; using System.Net;   class Program { static void Main(string[] args) { var client = new WebClient(); var data = client.DownloadString("https://www.google.com");   Console.WriteLine(data); } }  
Give a code snippet in #C.23 Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request ...
christopher/rosetta-code
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat...
#Wren
Wren
import "/fmt" for Conv, Fmt import "/sort" for Sort   var games = ["12", "13", "14", "23", "24", "34"] var results = "000000"   var nextResult = Fn.new { if (results == "222222") return false var res = Conv.atoi(results, 3) + 1 results = Fmt.swrite("$06t", res) return true }   var points = List.filled(4...
Give a code snippet in #Wren It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their...
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: ...
#Sidef
Sidef
[%w(a b c),%w(A B C),%w(1 2 3)].zip { |i,j,k| say (i, j, k) }
Give a code snippet in #Sidef 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 exam...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#F.23
F#
// No arguments noArgs()   // Fixed number of arguments oneArg x   // Optional arguments // In a normal function: optionalArgs <| Some(5) <| None // In a function taking a tuple: optionalArgsInTuple(Some(5), None) // In a function in a type: foo.optionalArgs 5;; // However, if you want to pass more than one paramter, t...
Give a code snippet in #F.23 Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#Maple
Maple
with(ImageTools): img := Read("pentagon.png")[..,..,1]: img_x := Convolution (img, Matrix ([[1,2,1], [0,0,0],[-1,-2,-1]])): img_y := Convolution (img, Matrix ([[-1,0,1],[-2,0,2],[-1,0,1]])): img := Array (abs (img_x) + abs (img_y), datatype=float[8]): countPixels := proc(M) local r,c,i,j,row,col: row := Array([]); c...
Give a code snippet in #Maple Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\di...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module dot_product { A=(1,3,-5) B=(4,-2,-1) Function Dot(a, b) { if len(a)<>len(b) Then Error "not same length" if len(a)=0 then Error "empty vectors" Let a1=each(a), b1=each(b), sum=0 While a1, b1 {sum+=array(a1)*array(b1)} =sum } ...
Give a code snippet in #M2000_Interpreter 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#C.2B.2B
C++
#include <ctime> #include <iostream> using namespace std;   int identity(int x) { return x; } int sum(int num) { for (int i = 0; i < 1000000; i++) num += i; return num; }   double time_it(int (*action)(int), int arg) { clock_t start_time = clock(); action(arg); clock_t finis_time = clock(); return ((dou...
Give a code snippet in #C.2B.2B Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time betwe...
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...
#Seed7
Seed7
var char: ch is 'z';
Give a code snippet in #Seed7 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  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#MiniScript
MiniScript
f = function(n) if n > 0 then return n - m(f(n - 1)) return 1 end function   m = function(n) if n > 0 then return n - f(m(n - 1)) return 0 end function   print f(12) print m(12)
Give a code snippet in #MiniScript Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#M2000_Interpreter
M2000 Interpreter
  \\ this is global, but call as local in events, which means with local visibility for identifiers \\ so thispos and this$ has to exist in caller 's context   Function Global Local1(new Feed$) { \\ this function can be used from other Integer \\ this$ and thispos, exist just before the call of...
Give a code snippet in #M2000_Interpreter In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Cowgol
Cowgol
include "cowgol.coh";   sub fibonacci(n: uint32): (a: uint32) is a := 0; var b: uint32 := 1; while n > 0 loop var c := a + b; a := b; b := c; n := n - 1; end loop; end sub;   # test var i: uint32 := 0; while i < 20 loop print_i32(fibonacci(i)); print_char(' '); ...
Give a code snippet in #Cowgol The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#PARI.2FGP
PARI/GP
is square(9)
Give a code snippet in #PARI.2FGP Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enablin...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Run_BASIC
Run BASIC
[loop] cls ' Clear screen html "Click Y or N" ' no other options button #y, "Y", [Y] ' they either click [Y] button #n, "N", [N] ' or they click [N] html "<br>";msg$ ' print message showing what they entered wait [...
Give a code snippet in #Run_BASIC Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pre...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/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 |...
#BQN
BQN
•Out "Enter number 1: " a ← •BQN •GetLine @ •Out "Enter number 2: " b ← •BQN •GetLine @ •Show a + b •Show a - b •Show a × b •Show a ÷ b •Show b | a •Show a ⋆ b
Give a code snippet in #BQN 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/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 ...
#JavaScript
JavaScript
var myhash = {}; //a new, empty object myhash["hello"] = 3; myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name myhash["!"] = 9;   //iterate using for..in loop for (var key in myhash) { //ensure key is in object and not in prototype if (myhash.hasOwnProperty(key)) { console.log(...
Give a code snippet in #JavaScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#ooRexx
ooRexx
  #!/usr/bin/rexx /*.----------------------------------------------------------------------.*/ /*|bashcolours: Display a table showing all of the possible colours that |*/ /*| can be generated using ANSI escapes in bash in an xterm |*/ /*| terminal session. ...
Give a code snippet in #ooRexx Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#REXX
REXX
┌─ ─┐ ┌─ ─┐ π │ 1 │ │ 1 │ John ─── = 4 ∙ arctan│ ─── │ - arctan│ ───── │ Machin's 4 │ 5 │ │ 239 │ formula └─ ─┘ └─ ...
Give a code snippet in #REXX Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal seque...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#REXX
REXX
/*REXX pgm displays if a filename has a known extension (as per a list of extensions). */ $= 'zip rar 7z gz archive A## tar.bz2'; upper $ /*a list of "allowable" file extensions*/ parse arg fn /*obtain optional argument from the CL.*/ @.= ...
Give a code snippet in #REXX File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensi...
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...
#UNIX_Shell
UNIX Shell
#! /bin/bash   declare -a doors for((i=1; i <= 100; i++)); do doors[$i]=0 done   for((i=1; i <= 100; i++)); do for((j=i; j <= 100; j += i)); do echo $i $j doors[$j]=$(( doors[j] ^ 1 )) done done   for((i=1; i <= 100; i++)); do if [[ ${doors[$i]} -eq 0 ]]; then op="closed" else op="open" fi ...
Give a code snippet in #UNIX_Shell 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/Order_disjoint_list_items
Order disjoint list items
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 ...
#Swift
Swift
func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] { let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 }) let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in cur.0.append(cur.2[el, default: 0] > 0 ? cur.1.removeFirst() : el) cur.2[el]? -= 1 })   return reduced....
Give a code snippet in #Swift 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/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Wren
Wren
/* window_management.wren */   var GTK_WINDOW_TOPLEVEL = 0 var GTK_ORIENTATION_VERTICAL = 1 var GTK_BUTTONBOX_CENTER = 5   foreign class GtkWindow { construct new(type) {}   foreign title=(title) foreign setDefaultSize(width, height)   foreign add(widget) foreign connectDestroy()   foreign showA...
Give a code snippet in #Wren Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of ...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Red
Red
  Red [Needs: 'view] system/view/screens/1/pane/-1/visible?: false ;; suppress console window ;; because this code is heavily influenced / (copied from ... ) ;; by the rebol version ( which actually works with red as well with ;; some minimal changes ) i added some comments to make the ;; code more readable...   ;;----...
Give a code snippet in #Red Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
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...
#Retro
Retro
'abcdefghijklmnopqrstuvwxyz 'FULL s:const '__________________________ 'TEST s:const :s:pangram? (s-f) '__________________________ &TEST #26 copy s:to-lower [ c:letter? ] s:filter [ dup $a - &TEST + store ] s:for-each &TEST &FULL s:eq? ;  
Give a code snippet in #Retro 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/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#Tcl
Tcl
# Check if we're using one of the UTF or "unicode" encodings if {[string match utf-* [encoding system]] || [string match *unicode* [encoding system]]} { puts "\u25b3" } else { error "terminal does not support unicode (probably)" }
Give a code snippet in #Tcl The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that...
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...
#FreeBASIC
FreeBASIC
' version 10-07-2018 ' compile with: fbc -s console   Type ext_euclid Dim As Integer a, b End Type   ' "Table method" aka "The Magic Box" Function magic_box(x As Integer, y As Integer) As ext_euclid   Dim As Integer a(1 To 128), b(1 To 128), d(1 To 128), k(1 To 128)   a(1) = 1 : b(1) = 0 : d(1) = x a(2)...
Give a code snippet in #FreeBASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Vala
Vala
void main() { string s = "Hello,How,Are,You,Today"; print(@"$(string.joinv(".", s.split(",")))"); }
Give a code snippet in #Vala Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw(say);   sub fangs { my $vampire = shift; my $length = length 0 + $vampire; return if $length % 2; my $fang_length = $length / 2; my $from = '1' . '0' x ($fang_length - 1); my $to = '9' x $fang_length; my $sorted =...
Give a code snippet in #Perl A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#F.23
F#
  // Sum below leading diagnal. Nigel Galloway: July 21st., 2021 let _,n=[[ 1; 3; 7; 8;10]; [ 2; 4;16;14; 4]; [ 3; 1; 9;18;11]; [12;14;17;18;20]; [ 7; 1; 3; 9; 5]]|>List.fold(fun(n,g) i->let i,_=i|>List.splitAt n in (n+1,g+(i|>List.sum)))(0,0) in printfn "%d" n  
Give a code snippet in #F.23 Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "socket.s7i";   const proc: main is func begin writeln(numericAddress(inetSocketAddress("www.kame.net", 1024))); end func;
Give a code snippet in #Seed7 DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#min
min
42 :my-var 42 "my-var" define
Give a code snippet in #min This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   pre...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#Haskell
Haskell
{-# LANGUAGE DeriveGeneric #-}   module Main (main) where   import qualified Data.ByteString.Lazy as ByteString (readFile, writeFile) import Data.Binary (Binary) import qualified Data.Binary as Binary (decode, encode) import GHC.Generics (Generic)   data Employee = Manager String String | In...
Give a code snippet in #Haskell Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Befunge
Befunge
for i = 0; i <= 100; i++ out = "" if i % 3 == 0 out = "Fizz" end if i % 5 == 0 out = out + "Buzz" end if out == "" out = i end print(out) end
Give a code snippet in #Befunge Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Run_BASIC
Run BASIC
s$ = "Run BASIC" print mid$(s$,2) 'strip first print left$(s$,len(s$) -1) 'strip last print mid$(s$,2,len(s$) -2) 'strip first and last
Give a code snippet in #Run_BASIC The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Arturo
Arturo
stripComments: function [str][ strip replace str {/[#;].+/} "" ]   loop ["apples, pears # and bananas", "apples, pears ; and bananas"] 'str [ print [str "->" stripComments str] ]
Give a code snippet in #Arturo Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#J
J
sternbrocot=:1 :0 ind=. 0 seq=. 1 1 while. -. u seq do. ind=. ind+1 seq=. seq, +/\. seq {~ _1 0 +ind end. )
Give a code snippet in #J For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Haskell
Haskell
module RosettaSelect where   import Data.Maybe (listToMaybe) import Control.Monad (guard)   select :: [String] -> IO String select [] = return "" select menu = do putStr $ showMenu menu putStr "Choose an item: " choice <- getLine maybe (select menu) return $ choose menu choice   showMenu :: [String] -> String...
Give a code snippet in #Haskell Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the st...
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,...
#Rust
Rust
  use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Result; use std::io::Write; use std::path::Path;   /// Password record with all fields #[derive(Eq, PartialEq, Debug)] pub struct PasswordRecord { pub account: String, pub password: ...
Give a code snippet in #Rust 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 us...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#PL.2FI
PL/I
  /* To push a node onto the end of the queue. */ push: procedure (tail); declare tail handle (node), t handle (node); t = new(:node:); get (t => value); if tail ^= bind(:null, node:) then tail => link = t; /* If the queue was non-empty, points the tail of the queue */ /* to the new node. ...
Give a code snippet in #PL.2FI Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#CLU
CLU
sieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1,max,true) prime[1] := false for p: int in int$from_to(2, max/2) do if prime[p] then for c: int in int$from_to_by(p*p, max, p) do prime[c] := false end end end ...
Give a code snippet in #CLU A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Self_numbers
Self numbers
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or d...
#Nim
Nim
import bitops, strutils, std/monotimes, times   const MaxCount = 2 * 1_000_000_000 + 9 * 9   # Bit string used to represent an array of booleans. type BitString = object len: Natural # length in bits. values: seq[byte] # Sequence containing the bits.     proc newBitString(n: Natural): BitString = ## Retu...
Give a code snippet in #Nim A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. Y...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#Icon_and_Unicon
Icon and Unicon
procedure main() every process(!&input) end   procedure process(s) s ? (s1 := tab(upto(' \t')), s2 := (tab(many(' \t')), tab(0))) | fail write("'",s1,"' -> '",s2,"' = ", levenshtein(s1,s2)) end   procedure levenshtein(s, t) if (n := *s+1) = 1 then return *t if (m := *t+1) = 1 then return *s   ev...
Give a code snippet in #Icon_and_Unicon This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theo...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Sidef
Sidef
func fasta_format(strings) { var out = [] var text = '' for line in (strings.lines) { if (line.begins_with('>')) { text.len && (out << text) text = line.substr(1)+': ' } else { text += line } } text.len && (out << text) return o...
Give a code snippet in #Sidef In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Roset...
christopher/rosetta-code
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Go
Go
package main   import ( "fmt" "math/big" )   var big1 = new(big.Int).SetUint64(1)   func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1)   ...
Give a code snippet in #Go Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive int...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Golfscript
Golfscript
"Hello world!"
Give a code snippet in #Golfscript Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard er...
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Cowgol
Cowgol
include "cowgol.coh";   # print uint32 right-aligned in column, with # thousands separators sub print_col(num: uint32, width: uint8) is # maximum integer is 4,294,967,296 for length 13, # plus one extra for the zero terminator var buf: uint8[14]; var start := &buf[0]; var last := UIToA(num, 10, &buf...
Give a code snippet in #Cowgol Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#D
D
void main() @safe { import std.stdio, std.algorithm, std.range, std.random;   enum uint w = 14, h = 10; auto vis = new bool[][](h, w), hor = iota(h + 1).map!(_ => ["+---"].replicate(w)).array, ver = h.iota.map!(_ => ["| "].replicate(w) ~ "|").array;   void walk(in uint x, in uint y) ...
Give a code snippet in #D This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a m...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Ada
Ada
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;   function Get_PPM (File : File_Type) return Image is use Ada.Characters.Latin_1; use Ada.Integer_Text_IO;   function Get_Line return String ...
Give a code snippet in #Ada Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscal...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Octave
Octave
varname = input ("Enter variable name: ", "s"); value = input ("Enter value: ", "s"); eval([varname,"=",value]);
Give a code snippet in #Octave Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#AutoHotkey
AutoHotkey
FileRead, Contents, unixdict.txt Loop, Parse, Contents, % "`n", % "`r" { ; parsing each line of the file we just read Loop, Parse, A_LoopField ; parsing each letter/character of the current word Dummy .= "," A_LoopField Sort, Dummy, % "D," ; sorting those letters before removing the delimiters (comma) ...
Give a code snippet in #AutoHotkey When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words...
christopher/rosetta-code