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/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Red
Red
    Create an HTML table   The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The r...
Give a code snippet in #Red Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with ...
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 ...
#AWK
AWK
  # syntax: GAWK -f FASTA_FORMAT.AWK filename # stop processing each file when an error is encountered { if (FNR == 1) { header_found = 0 if ($0 !~ /^[;>]/) { error("record is not valid") nextfile } } if ($0 ~ /^;/) { next } # comment begins with a ";" if ($0 ~ /^>/) { # ...
Give a code snippet in #AWK 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Vlang
Vlang
fn is_leap(year int) bool { return year %400 ==0 || (year%4 ==0 && year%100!=0) }   fn main() { for y in 1950..2012 { if is_leap(y) { println(y) } } }  
Give a code snippet in #Vlang Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Java
Java
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner;   public class CSV {   private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows;   public void open(File file) throws FileNotFoundException, IOException { ...
Give a code snippet in #Java CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, chang...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#C
C
#include <libxml/parser.h> #include <libxml/tree.h>   int main() { xmlDoc *doc = xmlNewDoc("1.0"); xmlNode *root = xmlNewNode(NULL, BAD_CAST "root"); xmlDocSetRootElement(doc, root);   xmlNode *node = xmlNewNode(NULL, BAD_CAST "element"); xmlAddChild(node, xmlNewText(BAD_CAST "some text here")); xmlAddChild...
Give a code snippet in #C Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Julia
Julia
# v0.6   function shellsort!(a::Array{Int})::Array{Int} incr = div(length(a), 2) while incr > 0 for i in incr+1:length(a) j = i tmp = a[i] while j > incr && a[j - incr] > tmp a[j] = a[j-incr] j -= incr end a[j] =...
Give a code snippet in #Julia 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/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#REXX
REXX
/*REXX program that displays a "REXX" 3D "ASCII art" as a logo. */ signal . /* Uses left-hand shadows, slightly raised view. 0=5~2?A?2?A? @)E)3@)B)1)2)8()2)1)2)8()2) @]~")2@]0`)0@)%)6{)%)0@)%)6{)%) #E)1#A@0}2)4;2(1}2)4;2( #3??3@0#2??@1}2)2;2(3}2)2;2( #2@5@)@2@0#2@A}2)0;2(5}2)0;2( #2@?"@)@2@0#2@?7...
Give a code snippet in #REXX Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJVALUE = ~ # Mode/type of actual obj to be queued # END CO   MODE OBJLINK = STRUCT( REF OBJLINK next, REF OBJLINK prev, OBJVALUE value # ... etc. required # );   PROC obj link new = REF OBJLINK: HEAP OBJLINK;   PROC obj link free = (REF OBJLINK free)VOID: prev OF...
Give a code snippet in #ALGOL_68 Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array:...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Raku
Raku
my @list = 1..10; say [+] @list; say [*] @list; say [~] @list; say min @list; say max @list; say [lcm] @list;
Give a code snippet in #Raku Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#K
K
perm:{:[1<x;,/(>:'(x,x)#1,x#0)[;0,'1+_f x-1];,!x]} perm 2 (0 1 1 0)   `0:{1_,/" ",/:x}'r@perm@#r:("some";"random";"text") some random text some text random random some text random text some text some random text random some
Give a code snippet in #K Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generati...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#VBScript
VBScript
  option explicit   function eef( b, r1, r2 ) if b then eef = r1 else eef = r2 end if end function   dim a, b wscript.stdout.write "First integer: " a = cint(wscript.stdin.readline) 'force to integer wscript.stdout.write "Second integer: " b = cint(wscript.stdin.readline) 'force to integer wscript.stdout.write...
Give a code snippet in #VBScript Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#OCaml
OCaml
open CalendarLib   let list_first_five = function | x1 :: x2 :: x3 :: x4 :: x5 :: _ -> [x1; x2; x3; x4; x5] | _ -> invalid_arg "list_first_five"   let () = let months = ref [] in for year = 1900 to 2100 do for month = 1 to 12 do let we = ref 0 in let num_days = Date.days_in_month (Date.make_year...
Give a code snippet in #OCaml The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (ther...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#68000_Assembly
68000 Assembly
ForLoop: MOVE.W #10,D0 loop: JSR Print_D0_As_Ascii ;some routine that converts the digits of D0 into ascii characters and prints them to screen. DBRA D0,loop ;repeat until D0.W = $FFFF rts
Give a code snippet in #68000_Assembly Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#BQN
BQN
•Show +´ 30‿1‿20‿2‿10 •Show +˝ 30‿1‿20‿2‿10 •Show tab ← (2+↕5) |⌜ 9+↕3 •Show +˝ tab
Give a code snippet in #BQN Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. S...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Julia
Julia
function pascal(n) if n<=0 print("n has to have a positive value") end x=0 while x<=n for a=0:x print(binomial(x,a)," ") end println("") x+=1 end end
Give a code snippet in #Julia Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#VBA
VBA
Private Function totient(ByVal n As Long) As Long Dim tot As Long: tot = n Dim i As Long: i = 2 Do While i * i <= n If n Mod i = 0 Then Do While True n = n \ i If n Mod i <> 0 Then Exit Do Loop tot = tot - tot \ i End If ...
Give a code snippet in #VBA The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the i...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. ...
#11l
11l
F nonoblocks([Int] &blocks, Int cells) -> [[(Int, Int)]] [[(Int, Int)]] r I blocks.empty | blocks[0] == 0 r [+]= [(0, 0)] E assert(sum(blocks) + blocks.len - 1 <= cells, ‘Those blocks will not fit in those cells’) V (blength, brest) = (blocks[0], blocks[1..]) V minspace4rest = sum(brest...
Give a code snippet in #11l Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Rust
Rust
use std::fmt;   const SIZE: usize = 8; const MOVES: [(i32, i32); 8] = [ (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), ];   #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] struct Point { x: i32, y: i32, }   impl Point { fn mov(&self, &(dx, dy):...
Give a code snippet in #Rust Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#BQN
BQN
Knuth ← { 𝕊 arr: l ← ≠arr { arr ↩ ⌽⌾(⟨•rand.Range l, 𝕩⟩⊸⊏)arr }¨↕l arr } P ← •Show Knuth   P ⟨⟩ P ⟨10⟩ P ⟨10, 20⟩ P ⟨10, 20, 30⟩
Give a code snippet in #BQN The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to...
christopher/rosetta-code
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#Wren
Wren
import "/fmt" for Conv, Fmt import "/math" for Int   var isMagnanimous = Fn.new { |n| if (n < 10) return true var p = 10 while (true) { var q = (n/p).floor var r = n % p if (!Int.isPrime(q + r)) return false if (q < 10) break p = p * 10 } return true }   var l...
Give a code snippet in #Wren A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Sidef
Sidef
say sum(1..1000, {|n| 1 / n**2 })
Give a code snippet in #Sidef Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64 Dim a As Integer = 3 Dim p As Integer Ptr = @a Print a, p
Give a code snippet in #FreeBASIC 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Kotlin
Kotlin
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13) Type :help for help, :quit for quit >>> println("Look no main!") Look no main! >>> :quit
Give a code snippet in #Kotlin Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Tcl
Tcl
pack [label .l -text "Goodbye, World"]
Give a code snippet in #Tcl Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#APL
APL
- 1 2 3 ¯1 ¯2 ¯3 2 * 1 2 3 4 2 4 8 16 2 × ⍳4 2 4 6 8 3 * 3 3 ⍴ ⍳9 3 9 27 81 243 729 2187 6561 19683  
Give a code snippet in #APL Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Hoon
Hoon
|= n=@ud =+ m=0 =+ o=(reap 1 '*') |^  ?: =(m n) o $(m +(m), o (weld top bot)) ++ gap (fil 3 (pow 2 m) ' ') ++ top (turn o |=(l=@t (rap 3 gap l gap ~))) ++ bot (turn o |=(l=@t (rap 3 l ' ' l ~))) --
Give a code snippet in #Hoon Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#ColdFusion
ColdFusion
  <cfoutput> <cfset str = "Hello World"> <cfset j = createObject("java","java.lang.String").init(str)> <cfset t = j.getBytes()> <p>#arrayLen(t)#</p> </cfoutput>  
Give a code snippet in #ColdFusion Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Perl
Perl
sub shell_sort { my (@a, $h, $i, $j, $k) = @_; for ($h = @a; $h = int $h / 2;) { for $i ($h .. $#a) { $k = $a[$i]; for ($j = $i; $j >= $h && $k < $a[$j - $h]; $j -= $h) { $a[$j] = $a[$j - $h]; } $a[$j] = $k; } } @a; }   my @...
Give a code snippet in #Perl Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Python
Python
>>> def duration(seconds): t= [] for dm in (60, 60, 24, 7): seconds, m = divmod(seconds, dm) t.append(m) t.append(seconds) return ', '.join('%d %s' % (num, unit) for num, unit in zip(t[::-1], 'wk d hr min sec'.split()) if num)   >>> for seconds in [7259, 86400, 6000000]: print("%7d sec = %s" % (seconds...
Give a code snippet in #Python Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g....
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Action.21
Action!
DEFINE DIGNUM="4"   TYPE Score=[BYTE bulls,cows,err]   PROC Generate(CHAR ARRAY secret) DEFINE DIGCOUNT="9" CHAR ARRAY digits(DIGCOUNT) BYTE i,j,d,tmp,count   FOR i=0 TO DIGCOUNT-1 DO digits(i)=i+'1 OD   secret(0)=DIGNUM count=DIGCOUNT FOR i=1 TO DIGNUM DO d=Rand(count) secret(i)=digits(...
Give a code snippet in #Action.21 Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if ...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Fortran
Fortran
  module Miller_Rabin use PrimeDecompose implicit none   integer, parameter :: max_decompose = 100   private :: int_rrand, max_decompose   contains   function int_rrand(from, to) integer(huge) :: int_rrand integer(huge), intent(in) :: from, to   real :: o call random_number(o) int_rrand ...
Give a code snippet in #Fortran This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin pri...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Oforth
Oforth
StringBuffer new "Hello, " << "World!" << println
Give a code snippet in #Oforth Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Elena
Elena
import system'routines; import extensions;   public program() { var haystack := new string[]{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"};   new string[]{"Washington", "Bush"}.forEach:(needle) { var index := haystack.indexOfElement:needle;   if (index == -1) ...
Give a code snippet in #Elena Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle th...
christopher/rosetta-code
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "ftp.s7i";   const proc: main is func local var ftpFileSys: ftp is fileSys.value; var string: line is ""; begin ftp := openFtp("kernel.org"); setActiveMode(ftp, FALSE); # Passive is the default. chdir(ftp, "/pub/linux/kernel"); for line range listDir(ftp,...
Give a code snippet in #Seed7 Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#Crystal
Crystal
def merge_sort(a : Array(Int32)) : Array(Int32) return a if a.size <= 1 m = a.size // 2 lt = merge_sort(a[0 ... m]) rt = merge_sort(a[m .. -1]) return merge(lt, rt) end   def merge(lt : Array(Int32), rt : Array(Int32)) : Array(Int32) result = Array(Int32).new until lt.empty? || rt.empty? result << (lt...
Give a code snippet in #Crystal 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/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Delphi
Delphi
  program Chinese_zodiac;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils, System.Math;   type TElements = array of array of char;   TChineseZodiac = record Year: Integer; Yyear: string; Animal: string; Element: string; AnimalChar: char; ElementChar: char; procedure Ass...
Give a code snippet in #Delphi Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities resul...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new()   var biased = Fn.new { |n| rand.float() < 1 / n }   var unbiased = Fn.new { |n| while (true) { var a = biased.call(n) var b = biased.call(n) if (a != b) return a } }   var m = 50000 var f = "$d: $2.2f\% $2.2f\%"...
Give a code snippet in #Wren P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator t...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Maxima
Maxima
/* Two solutions */ plot3d(1, [theta, 0, %pi], [phi, 0, 2 * %pi], [transform_xy, spherical_to_xyz], [grid, 30, 60], [box, false], [legend, false])$   load(draw)$ draw3d(xu_grid=30, yv_grid=60, surface_hide=true, parametric_surface(cos(phi)*sin(theta), sin(phi)*sin(theta), ...
Give a code snippet in #Maxima Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a D...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Swift
Swift
struct SimpleMovingAverage { var period: Int var numbers = [Double]()   mutating func addNumber(_ n: Double) -> Double { numbers.append(n)   if numbers.count > period { numbers.removeFirst() }   guard !numbers.isEmpty else { return 0 }   return numbers.reduce(0, +) / Double(num...
Give a code snippet in #Swift Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#360_Assembly
360 Assembly
* Perfect numbers 15/05/2016 PERFECTN CSECT USING PERFECTN,R13 prolog SAVEAREA B STM-SAVEAREA(R15) " DC 17F'0' " STM STM R14,R12,12(R13) " ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 ...
Give a code snippet in #360_Assembly Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#JavaScript
JavaScript
(() => { 'use strict'; const main = () => {   // abundantTuple :: Int -> [(Int, Int)] const abundantTuple = n => { // Either a list containing the tuple of N // and its divisor sum (if n is abundant), // or otherwise an empty list. const x = diviso...
Give a code snippet in #JavaScript An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Perl
Perl
my @bond; my $grid = 10; my $water = '▒'; $D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;   sub percolate { generate(shift || 0.6); fill(my $x = 1,my $y = 0); my @stack;   while () { if (my $dir = direction($x,$y)) { push @stack, [$x,$y]; ($x,$y) = move($dir, $x, $y) ...
Give a code snippet in #Perl Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean clust...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#ALGOL_68
ALGOL 68
BEGIN # returns the area of the polygon defined by the points p using the Shoelace formula # OP AREA = ( [,]REAL p )REAL: BEGIN [,]REAL points = p[ AT 1, AT 1 ]; # normalise array bounds to start at 1 # IF 2 UPB points /= 2 THEN # the points do not have 2 coordin...
Give a code snippet in #ALGOL_68 Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Sidef
Sidef
func simple_moving_average(period) {   var list = [] var sum = 0   func (number) { list.append(number) sum += number if (list.len > period) { sum -= list.shift } (sum / list.length) } }   var ma3 = simple_moving_average(3) var ma5 = simple_moving_avera...
Give a code snippet in #Sidef Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#C.2B.2B
C++
#include <algorithm> #include <iomanip> #include <iostream> #include <vector>   const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 3...
Give a code snippet in #C.2B.2B Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Raku
Raku
use MONKEY-SEE-NO-EVAL; sub eval_with_x($code, *@x) { [R-] @x.map: -> \x { EVAL $code } }   say eval_with_x('3 * x', 5, 10); # Says "15". say eval_with_x('3 * x', 5, 10, 50); # Says "105".
Give a code snippet in #Raku x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Oforth
Oforth
Object Class new: MyClass(att) MyClass method: initialize(v) v := att ;
Give a code snippet in #Oforth In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cl...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#PHP
PHP
<?php   if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOB...
Give a code snippet in #PHP Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(b...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#J
J
2+3 5
Give a code snippet in #J A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#zonnon
zonnon
  var a: array 10 of integer; da: array * of cardinal;  
Give a code snippet in #zonnon This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retr...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Aime
Aime
void read_stream(file f) { text s;   while (f_line(f, s) != -1) { # the read line available as -s- } }
Give a code snippet in #Aime Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
c = Compile[{{k, _Integer}}, Module[{out = {0}, start = 0, stop = 0, rlist = {0}, r = 0, sum = 0.0, diff = 0.0, imax = 8, step = 10}, Do[ If[j == k, imax = 2, imax = 8]; Do[ If[i == 2, start = i 10^j + 2; stop = (i + 1) 10^j - 1; step = 10; , start = i 10^j; s...
Give a code snippet in #Mathematica.2FWolfram_Language Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   di...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Ring
Ring
  See "Mathematical Functions" + nl See "Sin(0) = " + sin(0) + nl See "Sin(90) radians = " + sin(90) + nl See "Sin(90) degree = " + sin(90*3.14/180) + nl   See "Cos(0) = " + cos(0) + nl See "Cos(90) radians = " + cos(90) + nl See "Cos(90) degree = " + cos(90*3.14/180) + nl   See "Tan(0) = " + tan(0) + nl See "Tan(90) r...
Give a code snippet in #Ring Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Groovy
Groovy
def make2d = { nrows, ncols -> (0..<nrows).collect { [0]*ncols } }
Give a code snippet in #Groovy Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those num...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_properties
Reflection/List properties
Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
#JavaScript
JavaScript
var obj = Object.create({ name: 'proto', proto: true, doNothing: function() {} }, { name: {value: 'obj', writable: true, configurable: true, enumerable: true}, obj: {value: true, writable: true, configurable: true, enumerable: true}, 'non-enum': {value: 'non-enumerable', writable: true, enumer...
Give a code snippet in #JavaScript Task The goal is to get the properties of an object, as names, values or both. Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (let (Data (in "wire.data" (make (while (line) (link @)))) Grid (grid (length (car Data)) (length Data)) ) (mapc '((G D) (mapc put G '(val .) D)) Grid (apply mapcar (flip Data) list) ) (loop (disp Grid T '((This) (pack " " (: val) " ")) ) (wa...
Give a code snippet in #PicoLisp Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All ce...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#PowerShell
PowerShell
  :myLabel while (<condition>) { <statement list>}  
Give a code snippet in #PowerShell Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the free...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#C
C
  #include<windows.h> #include<string.h> #include<stdio.h>   #define MAXORDER 25   int main(int argC, char* argV[]) { char str[MAXORDER],commandString[1000],*startPath; long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max; int i,j,len; double scale; FILE* fp;   if(argC==1) printf("Usage : %s...
Give a code snippet in #C Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a fac...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#C
C
#include <stdio.h> #include <stdbool.h> #include <time.h>   #define n 100 #define nn ((n * (n + 1)) >> 1)   bool Contains(int lst[], int item, int size) { for (int i = size - 1; i >= 0; i--) if (item == lst[i]) return true; return false; }   int * MianChowla() { static int mc[n]; mc[0] = 1; int sums[nn]; sums[0]...
Give a code snippet in #C The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise su...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Wren
Wren
import "/seq" for Lst import "/math" for Nums   var limit = 1e6   var selfRefSeq = Fn.new { |s| var sb = "" for (d in "9876543210") { if (s.contains(d)) { var count = s.count { |c| c == d } sb = sb + "%(count)%(d)" } } return sb }   var permute // recursive permut...
Give a code snippet in #Wren There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 31131...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Inverse_video
Terminal control/Inverse video
Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
#Ring
Ring
  nverse = char(17)+char(128)+char(17)+char(15) normal = char(17)+char(128+15)+char(17)+char(0) see inverse + " inverse " + normal + " video"  
Give a code snippet in #Ring Task Display a word in inverse video   (or reverse video)   followed by a word in normal video.
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Console.WriteLine("Stdout is tty: {0}", Console.IsOutputRedirected) End Sub   End Module
Give a code snippet in #Visual_Basic_.NET Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/2
Text processing/2
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters...
#D
D
void main() { import std.stdio, std.array, std.string, std.regex, std.conv, std.algorithm;   auto rxDate = `^\d\d\d\d-\d\d-\d\d$`.regex; // Works but eats lot of RAM in DMD 2.064. // auto rxDate = ctRegex!(`^\d\d\d\d-\d\d-\d\d$`);   int[string] repeatedDates; int goodReadings; for...
Give a code snippet in #D The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or m...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#AWK
AWK
  # syntax: GAWK -f HUMBLE_NUMBERS.AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { PROCINFO["sorted_in"] = "@ind_num_asc" ; SORTTYPE = 1 n = 1 for (; count<5193; n++) { if (is_humble(n)) { arr[length(n)]++ if (coun...
Give a code snippet in #AWK Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above i...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Amazing_Hopper
Amazing Hopper
  #!/usr/bin/hopper   #include <hopper.h>   main:   hxres = 500 // horizontal resolution hyres = 500 // vertical resolution   itermax = 100 // maximum iters to do   brk_out = 64 // |z|^2 greater than this is a breakout magnify = 1 // 10 is standard magn...
Give a code snippet in #Amazing_Hopper Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
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...
#OASYS_Assembler
OASYS Assembler
; Comment (to end of line) - Introduces a negative number (not used for subtraction) = Load an include file or define a macro & Prefix for a method % Prefix for a global variable ! Prefix for an object . Prefix for a property ' Prefix for a vocabulary word ? Prefix for a class; check if an object is o...
Give a code snippet in #OASYS_Assembler 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, e...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Picat
Picat
go ?=> member(N,1..11), Farey = farey(N), println(N=Farey), fail, nl. go => true.   farey(N) = M => M1 = [0=$(0/1)] ++ [I2/J2=$(I2/J2) : I in 1..N, J in I..N, GCD=gcd(I,J),I2 =I//GCD,J2=J//GCD].sort_remove_dups(), M = [ E: _=E in M1]. % extract the rational representation    
Give a code snippet in #Picat The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Go
Go
package main   import ( "fmt" "math/big" )   var one = big.NewInt(1)   func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q)...
Give a code snippet in #Go Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyl...
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 ...
#PARI.2FGP
PARI/GP
fibonocci(n)
Give a code snippet in #PARI.2FGP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Icon_and_Unicon
Icon and Unicon
procedure main() X := [1,2,3,-5,6,9] every x := !L do write(x) end
Give a code snippet in #Icon_and_Unicon Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continu...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Ruby
Ruby
require 'prime'   def mersenne_factor(p) limit = Math.sqrt(2**p - 1) k = 1 while (2*k*p - 1) < limit q = 2*k*p + 1 if q.prime? and (q % 8 == 1 or q % 8 == 7) and trial_factor(2,p,q) # q is a factor of 2**p-1 return q end k += 1 end nil end   def trial_factor(base, exp, mod) squar...
Give a code snippet in #Ruby A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before st...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Emacs_Lisp
Emacs Lisp
123 ;; decimal all Emacs #b101 ;; binary Emacs 21 up, XEmacs 21 #o77 ;; octal Emacs 21 up, XEmacs 21 #xFF ;; hex Emacs 21 up, XEmacs 21 #3r210 ;; any radix 2-36 Emacs 21 up (but not XEmacs 21.4)
Give a code snippet in #Emacs_Lisp Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but shou...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Lasso
Lasso
local(mydata = 'I am data one')   split_thread => { loop(2) => { sleep(2000) stdoutnl(#mydata) #mydata = 'Oh, looks like I am in a new thread' } }   loop(2) => { sleep(3000) stdoutnl(#mydata) #mydata = 'Aha, I am still in the original thread' }
Give a code snippet in #Lasso Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#PicoLisp
PicoLisp
(unless (=0 (setq Ldap (native "libldap.so" "ldap_open" 'N "example.com" 389))) (quit "Can't open LDAP") )   (native "libldap.so" "ldap_simple_bind_s" 'I Ldap "user" "password")
Give a code snippet in #PicoLisp The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Cowgol
Cowgol
include "cowgol.coh";   typedef QueueData is uint8; # the queue will contain bytes include "queue.coh"; # from the Queue/Definition task   var queue := MakeQueue();   # enqueue bytes 0 to 20 print("Enqueueing: "); var n: uint8 := 0; while n < 20 loop print_i8(n); print_char(' '); Enqueue(queue, n); n :...
Give a code snippet in #Cowgol Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clean
Clean
import StdEnv   sortArray :: (a e) -> a e | Array a e & Ord e sortArray array = {y \\ y <- sort [x \\ x <-: array]}   Start :: {#Int} Start = sortArray {2, 4, 3, 1, 2}
Give a code snippet in #Clean 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/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Dylan
Dylan
  define method factorial (n) if (n < 1) error("invalid argument"); else reduce1(\*, range(from: 1, to: n)) end end method;  
Give a code snippet in #Dylan Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a n...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#EchoLisp
EchoLisp
  (define a #(1 3 -5)) (define b #(4 -2 -1))   ;; function definition (define ( ⊗ a b) (for/sum ((x a)(y b)) (* x y))) (⊗ a b) → 3   ;; library (lib 'math) (dot-product a b) → 3  
Give a code snippet in #EchoLisp 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#Delphi
Delphi
  program Bitwise_IO;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Classes;   type TBitReader = class private readData: Cardinal; startPosition: Integer; endPosition: Integer; Stream: TStream; procedure Align; function BaseStream: TStream; procedure EnsureData(bitCount: Intege...
Give a code snippet in #Delphi The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Lambdatalk
Lambdatalk
  {script LAMBDATALK.DICT["W.unicodeLength"] = function() { function countCodePoints(str) { var point, index, width = 0, len = 0; for (index = 0; index < str.length;) { point = str.codePointAt(index); width = 0; while (point) { width += 1; point =...
Give a code snippet in #Lambdatalk Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme...
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) ...
#PARI.2FGP
PARI/GP
{for(n=1,100, print(if(n%3, if(n%5, n , "Buzz" ) , if(n%5, "Fizz" , "FizzBuzz" ) )) )}
Give a code snippet in #PARI.2FGP 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   Fizz...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#SAS
SAS
  options mprint mlogic symbolgen source source2;   %macro SubSets (FieldCount = ); data _NULL_; Fields = &FieldCount; SubSets = 2**Fields; call symput ("NumSubSets", SubSets); run;   %put &NumSubSets;   data inital; %do j = 1 %to &FieldCount; F&j. = 1; %end; run;   data SubSets; set inital; RowCount =_n_; ca...
Give a code snippet in #SAS A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Scala
Scala
while (true) println("SPAM")
Give a code snippet in #Scala Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const func float: frand is func # Uniform distribution, (0..1] result var float: frand is 0.0; begin repeat frand := rand(0.0, 1.0); until frand <> 0.0; end func;   const func float: randomNormal is # Normal distribution,...
Give a code snippet in #Seed7 Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related...
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...
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Common_Path is function "rem" (A, B : String) return String is Slash : Integer := A'First; -- At the last slash seen in A At_A  : Integer := A'first; At_B  : Integer := B'first; begin loop if At_A > A'Last then if ...
Give a code snippet in #Ada 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 dir...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Ol
Ol
  (define i 24)   (assert i ===> 42)  
Give a code snippet in #Ol Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type Animal Extends Object Declare Abstract Sub MakeNoise() End Type   Type Bear Extends Animal name As String Declare Constructor(name As String) Declare Sub MakeNoise() End Type   Constructor Bear(name As String) This.name = name End Constructor   Sub Bear.MakeNoise() Print name; " is...
Give a code snippet in #FreeBASIC Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Tcl
Tcl
proc countSubstrings {haystack needle} { regexp -all ***=$needle $haystack } puts [countSubstrings "the three truths" "th"] puts [countSubstrings "ababababab" "abab"] puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]
Give a code snippet in #Tcl Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It...
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#Icon_and_Unicon
Icon and Unicon
procedure main() aTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] write("aTree and bTree ",(sameFringe(aTree,bTree),"have")|"don't have", " the same leaves.") cTree := [1, [2, [4, [7]], [5]], [3, [6, [8]]]] dTree := [1, [2, [4, [7]],...
Give a code snippet in #Icon_and_Unicon Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any...
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...
#Hy
Hy
(defn arithmetic-mean [xs] (if xs (/ (sum xs) (len xs))))
Give a code snippet in #Hy 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 establi...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Ruby
Ruby
notes = 'NOTES.TXT' if ARGV.empty? File.copy_stream(notes, $stdout) rescue nil else File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]} end
Give a code snippet in #Ruby Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT ...
christopher/rosetta-code
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#GUISS
GUISS
Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.yahoo.co.uk, Button:Go,Area:browser window,Inputbox:searchbox>elephants,Button:Search
Give a code snippet in #GUISS Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
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 ...
#PL.2FI
PL/I
if condition_exp then unique_statement; else unique_statement;   if condition_exp then unique_statement; else unique_statement;   if condition_exp then do; list_of_statements; end; else do; list_of_statements; end;
Give a code snippet in #PL.2FI 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Chapel
Chapel
// arr is an array of string to int. any type can be used in both places. var keys: domain(string); var arr: [keys] int;   // keys can be added to a domain using +, new values will be initialized to the default value (0 for int) keys += "foo"; keys += "bar"; keys += "baz";   // array access via [] or () arr["foo"] = 1;...
Give a code snippet in #Chapel Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition,...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Logo
Logo
make "cell_list [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0] make "generations 9   to evolve :n ifelse :n=1 [make "nminus1 item :cell_count :cell_list][make "nminus1 item :n-1 :cell_list] ifelse :n=:cell_count[make "nplus1 item 1 :cell_list][make "nplus1 item :n+1 :cell_list] ifelse ((item :n :cell_list)=0) [ ifelse (and...
Give a code snippet in #Logo Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current ...
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 ...
#Scheme
Scheme
(import (rnrs base (6)) (srfi :27 random-bits))   (define (shuffle lst) (define (swap! vec i j) (let ((tmp (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j tmp))) (define vec (list->vector lst)) (let loop ((i (sub1 (vector-length vec)))) (unless (zero? i) ...
Give a code snippet in #Scheme 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/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Sidef
Sidef
var sum = [0]   ARGF.each { |line| var x = line.words.map{.to_n} sum = [ x.first + sum.first, 1 ..^ x.end -> map{|i| x[i] + [sum[i-1, i]].max}..., x.last + sum.last, ] }   say sum.max
Give a code snippet in #Sidef Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#Sidef
Sidef
func dist_squared(a, b) { sqr(a[0] - b[0]) + sqr(a[1] - b[1]) }   func closest_pair_simple(arr) { arr.len < 2 && return Inf var (a, b, d) = (arr[0, 1], dist_squared(arr[0,1])) arr.clone! while (arr) { var p = arr.pop for l in arr { var t = dist_squared(p, l) i...
Give a code snippet in #Sidef This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a fun...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Visual_Basic
Visual Basic
Sub pascaltriangle() 'Pascal's triangle Const m = 11 Dim t(40) As Integer, u(40) As Integer Dim i As Integer, n As Integer, s As String, ss As String ss = "" For n = 1 To m u(1) = 1 s = "" For i = 1 To n u(i + 1) = t(i) + t(i + 1) s = s & u(i) & " ...
Give a code snippet in #Visual_Basic Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#PureBasic
PureBasic
If OpenConsole() Define.d a, b b = 0   ;positive infinity PrintN(StrD(Infinity())) ;returns the value for positive infinity from builtin function   a = 1.0 PrintN(StrD(a / b)) ;calculation results in the value of positive infinity   ;negative infinity PrintN(StrD(-Infinity())) ;returns the value for neg...
Give a code snippet in #PureBasic Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherw...
christopher/rosetta-code