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
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Fortran
Fortran
module Q_mod implicit none   type quaternion real :: a, b, c, d end type   public :: norm, neg, conj public :: operator (+) public :: operator (*)   private :: q_plus_q, q_plus_r, r_plus_q, & q_mult_q, q_mult_r, r_mult_q, & norm_q, neg_q, conj_q   interface norm module procedure norm_q end interface   interface neg module procedure neg_q end interface   interface conj module procedure conj_q end interface   interface operator (+) module procedure q_plus_q, q_plus_r, r_plus_q end interface   interface operator (*) module procedure q_mult_q, q_mult_r, r_mult_q end interface   contains   function norm_q(x) result(res) real :: res type (quaternion), intent (in) :: x   res = sqrt(x%a*x%a + x%b*x%b + x%c*x%c + x%d*x%d)   end function norm_q   function neg_q(x) result(res) type (quaternion) :: res type (quaternion), intent (in) :: x   res%a = -x%a res%b = -x%b res%c = -x%c res%d = -x%d   end function neg_q   function conj_q(x) result(res) type (quaternion) :: res type (quaternion), intent (in) :: x   res%a = x%a res%b = -x%b res%c = -x%c res%d = -x%d   end function conj_q   function q_plus_q(x, y) result (res) type (quaternion) :: res type (quaternion), intent (in) :: x, y   res%a = x%a + y%a res%b = x%b + y%b res%c = x%c + y%c res%d = x%d + y%d   end function q_plus_q   function q_plus_r(x, r) result (res) type (quaternion) :: res type (quaternion), intent (in) :: x real, intent(in) :: r   res = x res%a = x%a + r   end function q_plus_r   function r_plus_q(r, x) result (res) type (quaternion) :: res type (quaternion), intent (in) :: x real, intent(in) :: r   res = x res%a = x%a + r   end function r_plus_q   function q_mult_q(x, y) result (res) type (quaternion) :: res type (quaternion), intent (in) :: x, y   res%a = x%a*y%a - x%b*y%b - x%c*y%c - x%d*y%d res%b = x%a*y%b + x%b*y%a + x%c*y%d - x%d*y%c res%c = x%a*y%c - x%b*y%d + x%c*y%a + x%d*y%b res%d = x%a*y%d + x%b*y%c - x%c*y%b + x%d*y%a   end function q_mult_q   function q_mult_r(x, r) result (res) type (quaternion) :: res type (quaternion), intent (in) :: x real, intent(in) :: r   res%a = x%a*r res%b = x%b*r res%c = x%c*r res%d = x%d*r   end function q_mult_r   function r_mult_q(r, x) result (res) type (quaternion) :: res type (quaternion), intent (in) :: x real, intent(in) :: r   res%a = x%a*r res%b = x%b*r res%c = x%c*r res%d = x%d*r   end function r_mult_q end module Q_mod   program Quaternions use Q_mod implicit none   real :: r = 7.0 type(quaternion) :: q, q1, q2   q = quaternion(1, 2, 3, 4) q1 = quaternion(2, 3, 4, 5) q2 = quaternion(3, 4, 5, 6)   write(*, "(a, 4f8.3)") " q = ", q write(*, "(a, 4f8.3)") " q1 = ", q1 write(*, "(a, 4f8.3)") " q2 = ", q2 write(*, "(a, f8.3)") " r = ", r write(*, "(a, f8.3)") " Norm of q = ", norm(q) write(*, "(a, 4f8.3)") " Negative of q = ", neg(q) write(*, "(a, 4f8.3)") "Conjugate of q = ", conj(q) write(*, "(a, 4f8.3)") " q + r = ", q + r write(*, "(a, 4f8.3)") " r + q = ", r + q write(*, "(a, 4f8.3)") " q1 + q2 = ", q1 + q2 write(*, "(a, 4f8.3)") " q * r = ", q * r write(*, "(a, 4f8.3)") " r * q = ", r * q write(*, "(a, 4f8.3)") " q1 * q2 = ", q1 * q2 write(*, "(a, 4f8.3)") " q2 * q1 = ", q2 * q1   end program
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#C1R
C1R
Quine
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oz
Oz
declare [Queue] = {Link ['x-oz://system/adt/Queue.ozf']} MyQueue = {Queue.new} in {MyQueue.isEmpty} = true {MyQueue.put foo} {MyQueue.put bar} {MyQueue.put baz} {MyQueue.isEmpty} = false {Show {MyQueue.get}} %% foo {Show {MyQueue.get}} %% bar {Show {MyQueue.get}} %% baz
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
@queue = (); # we will simulate a queue in a array   push @queue, (1..5); # enqueue numbers from 1 to 5   print shift @queue,"\n"; # dequeue   print "array is empty\n" unless @queue; # is empty ?   print $n while($n = shift @queue); # dequeue all print "\n"; print "array is empty\n" unless @queue; # is empty ?
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#OCaml
OCaml
let rec quickselect k = function [] -> failwith "empty" | x :: xs -> let ys, zs = List.partition ((>) x) xs in let l = List.length ys in if k < l then quickselect k ys else if k > l then quickselect (k-l-1) zs else x
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#PARI.2FGP
PARI/GP
part(list, left, right, pivotIndex)={ my(pivotValue=list[pivotIndex],storeIndex=left,t); t=list[pivotIndex]; list[pivotIndex]=list[right]; list[right]=t; for(i=left,right-1, if(list[i] <= pivotValue, t=list[storeIndex]; list[storeIndex]=list[i]; list[i]=t; storeIndex++ ) ); t=list[right]; list[right]=list[storeIndex]; list[storeIndex]=t; storeIndex }; quickselect(list, left, right, n)={ if(left==right,return(list[left])); my(pivotIndex=part(list, left, right, random(right-left)+left)); if(pivotIndex==n,return(list[n])); if(n < pivotIndex, quickselect(list, left, pivotIndex - 1, n) , quickselect(list, pivotIndex + 1, right, n) ) };
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Java
Java
public class RangeExtraction {   public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39};   int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
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
#NewLISP
NewLISP
(normal 1 .5 1000)
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
#Nim
Nim
import random, stats, strformat   var rs: RunningStat   randomize()   for _ in 1..5: for _ in 1..1000: rs.push gauss(1.0, 0.5) echo &"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation:.5f}"  
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#Phix
Phix
integer fn = open("RCTEST.INI","r") sequence lines = get_text(fn,GT_LF_STRIPPED) close(fn) constant dini = new_dict() for i=1 to length(lines) do string li = trim(lines[i]) if length(li) and not find(li[1],"#;") then integer k = find(' ',li) if k!=0 then string rest = li[k+1..$] li = li[1..k-1] -- (may want upper()) if find(',',rest) then sequence a = split(rest,',') for j=1 to length(a) do a[j]=trim(a[j]) end for putd(li,a,dini) else putd(li,rest,dini) end if else putd(li,1,dini) -- "" end if end if end for function visitor(object key, object data, object /*user_data*/) ?{key,data} return 1 end function traverse_dict(routine_id("visitor"),0,dini) ?getd("FAVOURITEFRUIT",dini)
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#MiniScript
MiniScript
pullInt = function(chars) numstr = chars.pull while chars and chars[0] != "," and chars[0] != "-" numstr = numstr + chars.pull end while return val(numstr) end function   expandRange = function(s) result = [] chars = s.split("") while chars num = pullInt(chars) if not chars or chars.pull == "," then result.push num else result = result + range(num, pullInt(chars)) chars.pull // skip "," after range end if end while return result end function   print expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#MUMPS
MUMPS
RANGEXP(X) ;Integer range expansion NEW Y,I,J,X1,H SET Y="" FOR I=1:1:$LENGTH(X,",") DO .S X1=$PIECE(X,",",I) FOR Q:$EXTRACT(X1)'=" " S X1=$EXTRACT(X1,2,$LENGTH(X1)) ;clean up leading spaces .SET H=$FIND(X1,"-")-1 .IF H=1 SET H=$FIND(X1,"-",(H+1))-1 ;If the first value is negative ignore that "-" .IF H<0 SET Y=$SELECT($LENGTH(Y)=0:Y_X1,1:Y_","_X1) .IF '(H<0) FOR J=+$EXTRACT(X1,1,(H-1)):1:+$EXTRACT(X1,(H+1),$LENGTH(X1)) SET Y=$SELECT($LENGTH(Y)=0:J,1:Y_","_J) KILL I,J,X1,H QUIT Y
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   parse arg inFileName .   if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json' lines = scanFile(inFileName) loop l_ = 1 to lines[0] say l_.right(4)':' lines[l_] end l_   return   -- Read a file and return contents as a Rexx indexed string method scanFile(inFileName) public static returns Rexx   fileLines = '' do inFile = File(inFileName) inFileScanner = Scanner(inFile) loop l_ = 1 while inFileScanner.hasNext() fileLines[0] = l_ fileLines[l_] = inFileScanner.nextLine() end l_ inFileScanner.close()   catch ex = FileNotFoundException ex.printStackTrace end   return fileLines  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#NewLISP
NewLISP
  (set 'in-file (open "filename" "read")) (while (read-line in-file) (write-line)) (close in-file)
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#RapidQ
RapidQ
  print reverse$("This is a test")  
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#EchoLisp
EchoLisp
  ;; put info string in permanent storage for later use (info 'make-Q "usage: (define q (make-Q)) ; (q '[top | empty? | pop | push value | to-list | from-list list])")   ;; make-Q (define (make-Q) (let ((q (make-vector 0))) (lambda (message . args) (case message ((empty?) (vector-empty? q)) ((top) (if (vector-empty? q) (error 'Q:top:empty q) (vector-ref q 0))) ((push) (vector-push q (car args))) ((pop) (if (vector-empty? q) (error 'Q:pop:empty q) (vector-shift q))) ((to-list) (vector->list q)) ((from-list) (set! q (list->vector (car args))) q ) (else (info 'make-Q) (error "Q:bad message:" message )))))) ; display info if unknown message   ;; (define q (make-Q)) (q 'empty?) → #t (q 'push 'first) → first (q 'push 'second) → second (q 'pop) → first (q 'pop) → second (q 'top) "💬 error: Q:top:empty #()" (q 'from-list '( 6 7 8)) → #( 6 7 8) (q 'top) → 6 (q 'pop) → 6 (q 'to-list)→ (7 8) (q 'delete) "💭 error: Q:bad message: delete"   ;; save make-Q (local-put 'make-Q)  
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#FreeBASIC
FreeBASIC
  Dim Shared As Integer q(3) = {1, 2, 3, 4} Dim Shared As Integer q1(3) = {2, 3, 4, 5} Dim Shared As Integer q2(3) = {3, 4, 5, 6} Dim Shared As Integer i, r = 7, t(3)   Function q_norm(q() As Integer) As Double ' medida o valor absoluto de un cuaternión Dim As Double a = 0 For i = 0 To 3 a += q(i)^2 Next i Return Sqr(a) End Function   Sub q_neg(q() As Integer) For i = 0 To 3 q(i) *= -1 Next i End Sub   Sub q_conj(q() As Integer) ' conjugado de un cuaternión For i = 1 To 3 q(i) *= -1 Next i End Sub   Sub q_addreal(q() As Integer, r As Integer) q(0) += r End Sub   Sub q_add(q() As Integer, r() As Integer) ' adición entre cuaternios For i = 0 To 3 q(i) += r(i) Next i End Sub   Sub q_mulreal(q() As Integer, r As Integer) For i = 0 To 3 q(i) *= r Next i End Sub   Sub q_mul(q() As Integer, r() As Integer) ' producto entre cuaternios Dim As Integer m(3) m(0) = q(0)*r(0) - q(1)*r(1) - q(2)*r(2) - q(3)*r(3) m(1) = q(0)*r(1) + q(1)*r(0) + q(2)*r(3) - q(3)*r(2) m(2) = q(0)*r(2) - q(1)*r(3) + q(2)*r(0) + q(3)*r(1) m(3) = q(0)*r(3) + q(1)*r(2) - q(2)*r(1) + q(3)*r(0) For i = 0 To 3 : q(i) = m(i) : Next i End Sub   Function q_show(q() As Integer) As String Dim As String a = "(" For i = 0 To 3 a += Str(q(i)) + ", " Next i Return Mid(a,1,Len(a)-2) + ")" End Function   '--- Programa Principal --- Print " q = "; q_show(q()) Print "q1 = "; q_show(q1()) Print "q2 = "; q_show(q2()) Print " r = "; r Print "norm(q) ="; q_norm(q()) For i = 0 To 3 : t(i) = q(i) : Next i : q_neg(t())  : Print " neg(q) = "; q_show(t()) For i = 0 To 3 : t(i) = q(i) : Next i : q_conj(t()) : Print "conj(q) = "; q_show(t()) For i = 0 To 3 : t(i) = q(i) : Next i : q_addreal(t(),r) : Print " r + q = "; q_show(t()) For i = 0 To 3 : t(i) = q1(i) : Next i : q_add(t(),q2()) : Print "q1 + q2 = "; q_show(t()) For i = 0 To 3 : t(i) = q2(i) : Next i : q_add(t(),q1()) : Print "q2 + q1 = "; q_show(t()) For i = 0 To 3 : t(i) = q(i) : Next i : q_mulreal(t(),r) : Print " r * q = "; q_show(t()) For i = 0 To 3 : t(i) = q1(i) : Next i : q_mul(t(),q2()) : Print "q1 * q2 = "; q_show(t()) For i = 0 To 3 : t(i) = q2(i) : Next i : q_mul(t(),q1()) : Print "q2 * q1 = "; q_show(t()) End  
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Ceylon
Ceylon
shared void run() {print(let (x = """shared void run() {print(let (x = $) x.replaceFirst("$", "\"\"\"" + x + "\"\"\""));}""") x.replaceFirst("$", "\"\"\"" + x + "\"\"\""));}
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
with javascript_semantics printf(1,"empty:%t\n",empty()) -- true push_item(5) printf(1,"empty:%t\n",empty()) -- false push_item(6) printf(1,"pop_item:%v\n",pop_item()) -- 5 printf(1,"pop_item:%v\n",pop_item()) -- 6 printf(1,"empty:%t\n",empty()) -- true
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PHP
PHP
<?php $queue = new SplQueue; echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true // $queue->dequeue(); // would raise RuntimeException $queue->enqueue(1); $queue->enqueue(2); $queue->enqueue(3); echo $queue->dequeue(), "\n"; // returns 1 echo $queue->isEmpty() ? 'true' : 'false', "\n"; // returns false ?>
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#Perl
Perl
my @list = qw(9 8 7 6 5 0 1 2 3 4); print join ' ', map { qselect(\@list, $_) } 1 .. 10 and print "\n";   sub qselect { my ($list, $k) = @_; my $pivot = @$list[int rand @{ $list } - 1]; my @left = grep { $_ < $pivot } @$list; my @right = grep { $_ > $pivot } @$list; if ($k <= @left) { return qselect(\@left, $k); } elsif ($k > @left + 1) { return qselect(\@right, $k - @left - 1); } else { $pivot } }
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#JavaScript
JavaScript
function rangeExtraction(list) { var len = list.length; var out = []; var i, j;   for (i = 0; i < len; i = j + 1) { // beginning of range or single out.push(list[i]);   // find end of range for (var j = i + 1; j < len && list[j] == list[j-1] + 1; j++); j--;   if (i == j) { // single number out.push(","); } else if (i + 1 == j) { // two numbers out.push(",", list[j], ","); } else { // range out.push("-", list[j], ","); } } out.pop(); // remove trailing comma return out.join(""); }   // using print function as supplied by Rhino standalone print(rangeExtraction([ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ]));
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
#Objeck
Objeck
bundle Default { class RandomNumbers { function : Main(args : String[]) ~ Nil { rands := Float->New[1000]; for(i := 0; i < rands->Size(); i += 1;) { rands[i] := 1.0 + 0.5 * RandomNormal(); };   each(i : rands) { rands[i]->PrintLine(); }; }   function : native : RandomNormal() ~ Float { return (2 * Float->Pi() * Float->Random())->Cos() * (-2 * (Float->Random()->Log()))->SquareRoot(); } } }
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#Phixmonti
Phixmonti
def optionValue 2 get "," find if " " "-" subst "," " " subst split len for var i i get "-" " " subst rot 1 get "(" chain print i print ") = " print swap trim print nl swap endfor drop drop else swap 1 get print " = " print swap print nl endif enddef   0 tolist   "rosetta_read.cfg" "r" fopen var file   file 0 > if true while file fgets dup -1 != if trim len 0 > if 1 get '#' != if " " find var pos pos if 1 pos 1 - slice swap len pos - pos 1 + swap slice nip 2 tolist else "" 2 tolist endif 0 put else drop endif else drop endif true else drop file fclose false endif endwhile   len for get 1 get ";" == if 2 get print " = false" print nl else 2 get "" == if 1 get print " = true" print nl else optionValue endif endif drop endfor endif
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#NetRexx
NetRexx
/*NetRexx program to expand a range of integers into a list. ************* * 09.08.2012 Walter Pachl derived from my Rexx version * Changes: translate(old,' ',',') -> old.translate(' ',',') * dashpos=pos('-',x,2) -> dashpos=x.pos('-',2) * Do -> Loop * Parse Var a x a -> Parse a x a * Parse Var x ... -> Parse x ... **********************************************************************/   parse arg old if old = '' then old='-6,-3--1,3-5,7-11,14,15,17-20' /*original list of nums/ranges */   Say 'old='old /*show old list of nums/ranges. */ a=old.translate(' ',',') /*translate commas to blanks */ new='' /*new list of numbers (so far). */   comma='' Loop While a<>'' /* as long as there is input */ Parse a x a /* get one element */ dashpos=x.pos('-',2) /* find position of dash, if any */ If dashpos>0 Then Do /* element is low-high */ Parse x low =(dashpos) +1 high /* split the element */ Loop j=low To high /* output all numbers in range */ new=new||comma||j /* with separating commas */ comma=',' /* from now on use comma */ End End Else Do /* element is a number */ new=new||comma||x /* append (with comma) */ comma=',' /* from now on use comma */ End End Say 'new='new /*show the expanded list */  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Nim
Nim
for line in lines "input.txt": echo line
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rascal
Rascal
import String; reverse("string")
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Elena
Elena
import extensions;   template queue<T> { T[] theArray; int theTop; int theTale;   constructor() { theArray := new T[](8); theTop := 0; theTale := 0; }   bool empty() = theTop == theTale;   push(T object) { if (theTale > theArray.Length) { theArray := theArray.reallocate(theTale) };   theArray[theTale] := object;   theTale += 1 }   T pop() { if (theTale == theTop) { InvalidOperationException.new:"Queue is empty".raise() };   T item := theArray[theTop];   theTop += 1;   ^ item } }   public program() { queue<int> q := new queue<int>(); q.push(1); q.push(2); q.push(3); console.printLine(q.pop()); console.printLine(q.pop()); console.printLine(q.pop()); console.printLine("a queue is ", q.empty().iif("empty","not empty")); console.print("Trying to pop:"); try { q.pop() } catch(Exception e) { console.printLine(e.Message) } }
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#GAP
GAP
# GAP has built-in support for quaternions   A := QuaternionAlgebra(Rationals); # <algebra-with-one of dimension 4 over Rationals>   b := BasisVectors(Basis(A)); # [ e, i, j, k ]   q := [1, 2, 3, 4]*b; # e+(2)*i+(3)*j+(4)*k   # Conjugate ComplexConjugate(q); # e+(-2)*i+(-3)*j+(-4)*k   # Division 1/q; # (1/30)*e+(-1/15)*i+(-1/10)*j+(-2/15)*k   # Computing norm may be difficult, since the result would be in a quadratic field. # Sqrt exists in GAP, but it is quite unusual: see ?E in GAP documentation, and the following example Sqrt(5/3); # 1/3*E(60)^7+1/3*E(60)^11-1/3*E(60)^19-1/3*E(60)^23-1/3*E(60)^31+1/3*E(60)^43-1/3*E(60)^47+1/3*E(60)^59   # However, the square of the norm is easy to compute q*ComplexConjugate(q); # (30)*e   q1 := [2, 3, 4, 5]*b; # (2)*e+(3)*i+(4)*j+(5)*k   q2 := [3, 4, 5, 6]*b; # (3)*e+(4)*i+(5)*j+(6)*k   q1*q2 - q2*q1; # (-2)*i+(4)*j+(-2)*k   # Can't add directly to a rational, one must make a quaternion of it r := 5/3*b[1]; # (5/3)*e r + q; # (8/3)*e+(2)*i+(3)*j+(4)*k   # For multiplication, no problem (we are in an algebra over rationals !) r*q; # (5/3)*e+(10/3)*i+(5)*j+(20/3)*k 5/3*q; # (5/3)*e+(10/3)*i+(5)*j+(20/3)*k   # Negative -q; (-1)*e+(-2)*i+(-3)*j+(-4)*k     # While quaternions are built-in, you can define an algebra in GAP by specifying it's multiplication table. # See tutorial, p. 60, and reference of the functions used below.   # A multiplication table of dimension 4.   T := EmptySCTable(4, 0); SetEntrySCTable(T, 1, 1, [1, 1]); SetEntrySCTable(T, 1, 2, [1, 2]); SetEntrySCTable(T, 1, 3, [1, 3]); SetEntrySCTable(T, 1, 4, [1, 4]); SetEntrySCTable(T, 2, 1, [1, 2]); SetEntrySCTable(T, 2, 2, [-1, 1]); SetEntrySCTable(T, 2, 3, [1, 4]); SetEntrySCTable(T, 2, 4, [-1, 3]); SetEntrySCTable(T, 3, 1, [1, 3]); SetEntrySCTable(T, 3, 2, [-1, 4]); SetEntrySCTable(T, 3, 3, [-1, 1]); SetEntrySCTable(T, 3, 4, [1, 2]); SetEntrySCTable(T, 4, 1, [1, 4]); SetEntrySCTable(T, 4, 2, [1, 3]); SetEntrySCTable(T, 4, 3, [-1, 2]); SetEntrySCTable(T, 4, 4, [-1, 1]);   A := AlgebraByStructureConstants(Rationals, T, ["e", "i", "j", "k"]); b := GeneratorsOfAlgebra(A);   IsAssociative(A); # true   IsCommutative(A); # false   # Then, like above   q := [1, 2, 3, 4]*b; # e+(2)*i+(3)*j+(4)*k   # However, as is, GAP does not know division or conjugate on this algebra. # QuaternionAlgebra is useful as well for extensions of rationals, # and this one _has_ conjugate and division, as seen previously.   # Try this on Q[z] where z is the square root of 5 (in GAP it's ER(5)) F := FieldByGenerators([ER(5)]); A := QuaternionAlgebra(F); b := GeneratorsOfAlgebra(A);   q := [1, 2, 3, 4]*b; # e+(2)*i+(3)*j+(4)*k   # Conjugate and division   ComplexConjugate(q); # e+(-2)*i+(-3)*j+(-4)*k   1/q; # (1/30)*e+(-1/15)*i+(-1/10)*j+(-2/15)*k
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Clojure
Clojure
((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x)))))
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
(println (fifo 'Queue)) # Retrieve the number '1' (println (fifo 'Queue)) # Retrieve an internal symbol 'abc' (println (fifo 'Queue)) # Retrieve a transient symbol "abc" (println (fifo 'Queue)) # and a list (abc) (println (fifo 'Queue)) # Queue is empty -> NIL
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FI
PL/I
  test: proc options (main);     /* To implement a queue. */ define structure 1 node, 2 value fixed, 2 link handle(node); declare (head, tail, t) handle (node); declare null builtin; declare i fixed binary;   head, tail = bind(:node, null:);   do i = 1 to 10; /* Add ten items to the tail of the queue. */ if head = bind(:node, null:) then do; head,tail = new(:node:); get list (head => value); put skip list (head => value); head => link = bind(:node, null:); /* A NULL link */ end; else do; t = new(:node:); tail => link = t; /* Point the tail to the new node. */ tail = t; tail => link = bind(:node, null:); /* Set the tail link to NULL */ get list (tail => value) copy; put skip list (tail => value); end; end;   /* Pop all the items in the queue. */ put skip list ('The queue has:'); do while (head ^= bind(:node, null:)); put skip list (head => value); head = head => link; end; end test;  
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PostScript
PostScript
  [1 2 3 4 5] 6 exch tadd = [1 2 3 4 5 6] uncons = 1 [2 3 4 5 6] [] empty? =true  
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#Phix
Phix
sequence s = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4} function quick_select(integer k) integer left = 1, right = length(s) while left<right do object pivotv = s[k]; {s[k], s[right]} = {s[right], s[k]} integer pos = left for i=left to right do if s[i]<pivotv then {s[i], s[pos]} = {s[pos], s[i]} pos += 1 end if end for {s[right], s[pos]} = {s[pos], s[right]} if pos==k then exit end if if pos<k then left = pos + 1 else right = pos - 1 end if end while return s[k] end function for i=1 to 10 do integer r = quick_select(i) printf(1," %d",r) end for {} = wait_key()
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#jq
jq
# Input should be an array def extract: reduce .[] as $i # state is an array with integers or [start, end] ranges ([]; if length == 0 then [ $i ] else ( .[-1]) as $last | if ($last|type) == "array" then if ($last[1] + 1) == $i then setpath([-1,1]; $i) else . + [ $i ] end elif ($last + 1) == $i then setpath([-1]; [$last, $i]) else . + [ $i ] end end) | map( if type == "number" then tostring elif .[0] == .[1] -1 then "\(.[0]),\(.[1])" # satisfy special requirement else "\(.[0])-\(.[1])" end ) | join(",") ;
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
#OCaml
OCaml
let pi = 4. *. atan 1.;; let random_gaussian () = 1. +. sqrt (-2. *. log (Random.float 1.)) *. cos (2. *. pi *. Random.float 1.);; let a = Array.init 1000 (fun _ -> random_gaussian ());;
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#PHP
PHP
<?php   $conf = file_get_contents('parse-conf-file.txt');   // Add an "=" after entry name $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);   // Replace multiple parameters separated by commas : // name = value1, value2 // by multiple lines : // name[] = value1 // name[] = value2 $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL; } return $r; }, $conf );   // Replace empty values by "true" $conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);   // Parse configuration file $ini = parse_ini_string($conf);   echo 'Full name = ', $ini['FULLNAME'], PHP_EOL; echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL; echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL; echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL; echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Nim
Nim
import parseutils, strutils   proc expandRange(input: string): string = var output: seq[string] for range in input.split(','): var sep = range.find('-', 1) if sep > 0: # parse range var first = -1 if range.substr(0, sep-1).parseInt(first) == 0: break var last = -1 if range.substr(sep+1).parseInt(last) == 0: break for i in first..last: output.add($i) else: # parse single number var n = -1 if range.parseInt(n) > 0: output.add($n) else: break return output.join(",")   echo("-6,-3--1,3-5,7-11,14,15,17-20".expandRange)
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Oberon-2
Oberon-2
  MODULE LIVector; IMPORT SYSTEM; TYPE LIPool = POINTER TO ARRAY OF LONGINT; LIVector*= POINTER TO LIVectorDesc; LIVectorDesc = RECORD cap-: INTEGER; len-: INTEGER; LIPool: LIPool; END;   PROCEDURE (v: LIVector) Init*(cap: INTEGER); BEGIN v.cap := cap; v.len := 0; NEW(v.LIPool,cap); END Init;   PROCEDURE (v: LIVector) Add*(x: LONGINT); VAR newLIPool: LIPool; BEGIN IF v.len = LEN(v.LIPool^) THEN (* run out of space *) v.cap := v.cap + (v.cap DIV 2); NEW(newLIPool,v.cap); SYSTEM.MOVE(SYSTEM.ADR(v.LIPool^),SYSTEM.ADR(newLIPool^),v.cap * SIZE(LONGINT)); v.LIPool := newLIPool END; v.LIPool[v.len] := x; INC(v.len) END Add;   PROCEDURE (v: LIVector) At*(idx: INTEGER): LONGINT; BEGIN RETURN v.LIPool[idx]; END At; END LIVector.   MODULE LIRange; IMPORT Out, LIV := LIVector;   TYPE Range* = POINTER TO RangeDesc; RangeDesc = RECORD l,r: POINTER TO ARRAY 1 OF LONGINT; END;   PROCEDURE (r: Range) Init*(); BEGIN r.l := NIL; r.r := NIL; END Init;   PROCEDURE (r: Range) IsEmpty*(): BOOLEAN; BEGIN RETURN (r.l = NIL) & (r.l = NIL); END IsEmpty;   PROCEDURE (r: Range) SetLeft*(v: LONGINT); BEGIN IF r.l = NIL THEN NEW(r.l) END; r.l[0] := v; END SetLeft;   PROCEDURE (r: Range) SetRight*(v : LONGINT); BEGIN IF r.r = NIL THEN NEW(r.r) END; r.r[0] := v; END SetRight;   PROCEDURE (r: Range) LeftPart*(): BOOLEAN; BEGIN RETURN r.l # NIL; END LeftPart;   PROCEDURE (r: Range) GetLeft(): LONGINT; BEGIN RETURN r.l[0]; END GetLeft;   PROCEDURE (r: Range) RightPart*(): BOOLEAN; BEGIN RETURN r.l # NIL; END RightPart;   PROCEDURE (r: Range) GetRight*(): LONGINT; BEGIN RETURN r.r[0]; END GetRight;   PROCEDURE (r: Range) Show*(); BEGIN Out.Char('('); IF r.l # NIL THEN Out.LongInt(r.l[0],10) END; Out.String(" - "); IF r.r # NIL THEN Out.LongInt(r.r[0],10); END; Out.Char(')');Out.Ln END Show;   PROCEDURE (r: Range) Expand*(VAR liv: LIV.LIVector); VAR from, to : LONGINT; BEGIN IF r.l # NIL THEN from := r.l[0] ELSE from := 0 END; IF r.r # NIL THEN to := r.r[0] ELSE to := from END; WHILE (from <= to) DO liv.Add(from);INC(from) END END Expand; END LIRange.   MODULE Splitter; TYPE Splitter* = POINTER TO SplitterDesc; SplitterDesc = RECORD from: INTEGER; c: CHAR; s: POINTER TO ARRAY OF CHAR; END;   PROCEDURE (s: Splitter) Init*; BEGIN s.c := ','; s.from := 0; s.s := NIL; END Init;   PROCEDURE (s: Splitter) On*(str: ARRAY OF CHAR); BEGIN s.from := 0; NEW(s.s,LEN(str)); COPY(str,s.s^) END On;   PROCEDURE (s: Splitter) OnWithChar*(str: ARRAY OF CHAR;c: CHAR); BEGIN s.from := 0; s.c := c; NEW(s.s,LEN(str)); COPY(str,s.s^) END OnWithChar;   PROCEDURE (s: Splitter) Next*(VAR str: ARRAY OF CHAR); VAR k : INTEGER; BEGIN k := 0; IF (s.from < LEN(s.s^) - 1) & (s.s[s.from] = 0X) THEN str[0] := 0X END; WHILE (k < LEN(str) - 1) & (s.from < LEN(s.s^) - 1) & (s.s[s.from] # s.c) DO str[k] := s.s[s.from]; INC(k);INC(s.from) END; IF k < LEN(str) - 1 THEN str[k] := 0X ELSE str[LEN(str) - 1] := 0X END; WHILE (s.from < LEN(s.s^) - 1) & (s.s[s.from] # s.c) DO INC(s.from) END; INC(s.from) END Next; END Splitter.   MODULE ExpandRange; IMPORT Out, LIV := LIVector, LIR := LIRange, S := Splitter;   PROCEDURE GetNumberFrom(s: ARRAY OF CHAR; VAR from: INTEGER; VAR done: BOOLEAN): LONGINT; VAR d,i: INTEGER; num,sign: LONGINT; BEGIN i := from; num := 0;sign := 1; CASE s[i] OF '-': sign := -1;INC(i) |'+': INC(i); ELSE END; WHILE (i < LEN(s) - 1) & (s[i] >= '0') & (s[i] <= '9') DO d := ORD(s[i]) - ORD('0'); num := d + num * 10; INC(i); END; IF i = from THEN done := FALSE ELSE done := TRUE; from := i END; RETURN sign * num END GetNumberFrom;   PROCEDURE GetRange(s: ARRAY OF CHAR): LIR.Range; VAR r: LIR.Range; i: INTEGER; num: LONGINT; done: BOOLEAN; BEGIN i := 0;NEW(r);r.Init(); WHILE (i < LEN(s) - 1) & (s[i] = 20X) DO INC(i) END; (* Left value *) done := FALSE; num := GetNumberFrom(s,i,done); IF ~done THEN RETURN r END; r.SetLeft(num);   WHILE (i < LEN(s) - 1) & (s[i] = 20X) DO INC(i) END; CASE s[i] OF '-' : INC(i); | 0X : RETURN r; ELSE END; WHILE (i < LEN(s) - 1) & (s[i] = 20X) DO INC(i) END;   (* Right Value *) done := FALSE; num := GetNumberFrom(s,i,done); IF ~done THEN RETURN r END; r.SetRight(num); RETURN r; END GetRange;   VAR i: INTEGER; r: LIR.Range; sp: S.Splitter; p : ARRAY 128 OF CHAR; liv: LIV.LIVector; BEGIN NEW(sp);sp.Init(); NEW(liv);liv.Init(128);   sp.On("-6,-3--1,3-5,7-11,14,15,17-20"); sp.Next(p); WHILE (p[0] # 0X) DO r := GetRange(p); r.Expand(liv); sp.Next(p); END; FOR i := 0 TO liv.len - 2 DO Out.LongInt(liv.At(i),3);Out.Char(','); END; Out.LongInt(liv.At(liv.len - 1),3);Out.Ln; END ExpandRange.    
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Objeck
Objeck
  bundle Default { class ReadFile { function : Main(args : String[]) ~ Nil { f := IO.FileReader->New("in.txt"); if(f->IsOpen()) { string := f->ReadString(); while(f->IsEOF() = false) { string->PrintLine(); string := f->ReadString(); }; f->Close(); }; } } }  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raven
Raven
"asdf" reverse
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Elisa
Elisa
  component GenericQueue ( Queue, Element ); type Queue; Queue (MaxLength = integer) -> Queue; Length( Queue ) -> integer; Empty ( Queue ) -> boolean; Full ( Queue ) -> boolean; Push ( Queue, Element) -> nothing; Pull ( Queue ) -> Element; begin Queue (MaxLength) = Queue:[ MaxLength; length:=0; list=alist(Element) ]; Length ( queue ) = queue.length; Empty ( queue ) = (queue.length <= 0); Full ( queue ) = (queue.length >= queue.MaxLength);   Push ( queue, element ) = [ exception (Full(queue), "Queue Overflow"); queue.length:= queue.length + 1; add (queue.list, element)]; Pull ( queue ) = [ exception (Empty(queue), "Queue Underflow"); queue.length:= queue.length - 1; remove(first(queue.list))]; end component GenericQueue;  
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Elixir
Elixir
defmodule Queue do def new, do: {Queue, [], []}   def push({Queue, input, output}, x), do: {Queue, [x|input], output}   def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}}   def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false end
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Go
Go
package main   import ( "fmt" "math" )   type qtn struct { r, i, j, k float64 }   var ( q = &qtn{1, 2, 3, 4} q1 = &qtn{2, 3, 4, 5} q2 = &qtn{3, 4, 5, 6}   r float64 = 7 )   func main() { fmt.Println("Inputs") fmt.Println("q:", q) fmt.Println("q1:", q1) fmt.Println("q2:", q2) fmt.Println("r:", r)   var qr qtn fmt.Println("\nFunctions") fmt.Println("q.norm():", q.norm()) fmt.Println("neg(q):", qr.neg(q)) fmt.Println("conj(q):", qr.conj(q)) fmt.Println("addF(q, r):", qr.addF(q, r)) fmt.Println("addQ(q1, q2):", qr.addQ(q1, q2)) fmt.Println("mulF(q, r):", qr.mulF(q, r)) fmt.Println("mulQ(q1, q2):", qr.mulQ(q1, q2)) fmt.Println("mulQ(q2, q1):", qr.mulQ(q2, q1)) }   func (q *qtn) String() string { return fmt.Sprintf("(%g, %g, %g, %g)", q.r, q.i, q.j, q.k) }   func (q *qtn) norm() float64 { return math.Sqrt(q.r*q.r + q.i*q.i + q.j*q.j + q.k*q.k) }   func (z *qtn) neg(q *qtn) *qtn { z.r, z.i, z.j, z.k = -q.r, -q.i, -q.j, -q.k return z }   func (z *qtn) conj(q *qtn) *qtn { z.r, z.i, z.j, z.k = q.r, -q.i, -q.j, -q.k return z }   func (z *qtn) addF(q *qtn, r float64) *qtn { z.r, z.i, z.j, z.k = q.r+r, q.i, q.j, q.k return z }   func (z *qtn) addQ(q1, q2 *qtn) *qtn { z.r, z.i, z.j, z.k = q1.r+q2.r, q1.i+q2.i, q1.j+q2.j, q1.k+q2.k return z }   func (z *qtn) mulF(q *qtn, r float64) *qtn { z.r, z.i, z.j, z.k = q.r*r, q.i*r, q.j*r, q.k*r return z }   func (z *qtn) mulQ(q1, q2 *qtn) *qtn { z.r, z.i, z.j, z.k = q1.r*q2.r-q1.i*q2.i-q1.j*q2.j-q1.k*q2.k, q1.r*q2.i+q1.i*q2.r+q1.j*q2.k-q1.k*q2.j, q1.r*q2.j-q1.i*q2.k+q1.j*q2.r+q1.k*q2.i, q1.r*q2.k+q1.i*q2.j-q1.j*q2.i+q1.k*q2.r return z }
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#CLU
CLU
q="start_up=proc()\n"|| " po:stream:=stream$primary_output()\n"|| " stream$puts(po,\"q=\\\"\")\n"|| " for c:char in string$chars(q) do\n"|| " if c='\\n' then stream$puts(po,\"\\\\n\\\"||\\n\\\"\")\n"|| " elseif c='\\\\' then stream$puts(po,\"\\\\\\\\\")\n"|| " elseif c='\\\"' then stream$puts(po,\"\\\\\\\"\")\n"|| " else stream$putc(po,c)\n"|| " end\n"|| " end\n"|| " stream$puts(po,\"\\\"\\n\"||q)\n"|| "end start_up\n"|| "" start_up=proc() po:stream:=stream$primary_output() stream$puts(po,"q=\"") for c:char in string$chars(q) do if c='\n' then stream$puts(po,"\\n\"||\n\"") elseif c='\\' then stream$puts(po,"\\\\") elseif c='\"' then stream$puts(po,"\\\"") else stream$putc(po,c) end end stream$puts(po,"\"\n"||q) end start_up
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PowerShell
PowerShell
  [System.Collections.ArrayList]$queue = @() # isEmpty? if ($queue.Count -eq 0) { "isEmpty? result : the queue is empty" } else { "isEmpty? result : the queue is not empty" } "the queue contains : $queue" $queue += 1 # push "push result : $queue" $queue += 2 # push $queue += 3 # push "push result : $queue"   $queue.RemoveAt(0) # pop "pop result : $queue"   $queue.RemoveAt(0) # pop "pop result : $queue"   if ($queue.Count -eq 0) { "isEmpty? result : the queue is empty" } else { "isEmpty? result : the queue is not empty" } "the queue contains : $queue"  
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Prolog
Prolog
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% definitions of queue empty(U-V) :- unify_with_occurs_check(U, V).   push(Queue, Value, NewQueue) :- append_dl(Queue, [Value|X]-X, NewQueue).     pop([X|V]-U, X, V-U) :- \+empty([X|V]-U).       append_dl(X-Y, Y-Z, X-Z).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% use of queue queue :- % create an empty queue empty(Q), format('Create queue ~w~n~n', [Q]),   % add numbers 1 and 2 write('Add numbers 1 and 2 : '), push(Q, 1, Q1), push(Q1, 2, Q2),   % display queue format('~w~n~n', [Q2]),   % pop element pop(Q2, V, Q3),   % display results format('Pop : Value ~w Queue : ~w~n~n', [V, Q3]),   % test the queue write('Test of the queue : '), ( empty(Q3) -> writeln('Queue empy'); writeln('Queue not empty')), nl,   % pop the elements write('Pop the queue : '), pop(Q3, V1, Q4), format('Value ~w Queue : ~w~n~n', [V1, Q4]),   write('Pop the queue : '), pop(Q4, _V, _Q5).  
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#Picat
Picat
main => L = [9,8,7,6,5,0,1,2,3,4], Len = L.len, println([select(L,1,Len,I) : I in 1..Len]), nl.   select(List, Left, Right, K) = Select => if Left = Right then Select = List[Left] else PivotIndex = partition(List, Left, Right, random(Left,Right)), if K == PivotIndex then Select = List[K] elseif K < PivotIndex then Select = select(List, Left, PivotIndex-1, K) else Select = select(List, PivotIndex+1, Right, K) end end.   partition(List, Left, Right, PivotIndex) = StoreIndex => PivotValue = List[PivotIndex], swap(List,PivotIndex,Right), StoreIndex = Left, foreach(I in Left..Right-1) if List[I] @< PivotValue then swap(List,StoreIndex,I), StoreIndex := StoreIndex+1 end end, swap(List,Right,StoreIndex).   % swap L[I] <=> L[J] swap(L,I,J) => T = L[I], L[I] := L[J], L[J] := T.
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8))) (de swapL (Lst X Y) (let L (nth Lst Y) (swap L (swap (nth Lst X) (car L)) ) ) ) (de partition (Lst L R P) (let V (get Lst P) (swapL Lst R P) (for I (range L R) (and (> V (get Lst I)) (swapL Lst L I) (inc 'L) ) ) (swapL Lst L R) L ) ) (de quick (Lst N L R) (default L (inc N) R (length Lst)) (if (= L R) (get Lst L) (let P (partition Lst L R (rand L R)) (cond ((= N P) (get Lst N)) ((> P N) (quick Lst N L P)) (T (quick Lst N P R)) ) ) ) ) (let Lst (9 8 7 6 5 0 1 2 3 4) (println (mapcar '((N) (quick Lst N)) (range 0 9) ) ) )
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Jsish
Jsish
/* Range Extraction, in Jsish */ function rangeExtraction(list) { var len = list.length; var out = []; var i, j;   for (i = 0; i < len; i = j + 1) { // beginning of range or single out.push(list[i]);   // find end of range for (j = i + 1; j < len && list[j] == list[j-1] + 1; j++); j--;   if (i == j) { // single number out.push(","); } else if (i + 1 == j) { // two numbers out.push(",", list[j], ","); } else { // range out.push("-", list[j], ","); } } out.pop(); // remove trailing comma return out.join(""); }   var arr = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ];   puts(arr); puts(rangeExtraction(arr));
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
#Octave
Octave
p = normrnd(1.0, 0.5, 1000, 1); disp(mean(p)); disp(sqrt(sum((p - mean(p)).^2)/numel(p)));
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
#ooRexx
ooRexx
/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/ pi=RxCalcPi() /* get value of pi */ Parse Arg n seed . /* allow specification of N & seed*/ If n==''|n==',' Then n=1000 /* N is the size of the array. */ If seed\=='' Then Call random,,seed /* use seed for repeatable RANDOM#*/ mean=1 /* desired new mean (arith. avg.) */ sd=1/2 /* desired new standard deviation.*/ Do g=1 For n /* generate N uniform random nums.*/ n.g=random(0,1e5)/1e5 /* REXX gens uniform rand integers*/ End   Say ' old mean=' mean() Say 'old standard deviation=' stddev() Say Do j=1 To n-1 By 2 m=j+1 /*use Box-Muller method */ _=sd*RxCalcPower(-2*RxCalcLog(n.j),.5)*RxCalcCos(2*pi*n.m,,'R')+mean n.m=sd*RxCalcpower(-2*RxCalcLog(n.j),.5)*RxCalcSin(2*pi*n.m,,'R')+, mean /* rand # must be 0???1. */ n.j=_ End /* j */ Say ' new mean=' mean() Say 'new standard deviation=' stddev() Exit mean: _=0 Do k=1 For n _=_+n.k End Return _/n stddev: _avg=mean() _=0 Do k=1 For n _=_+(n.k-_avg)**2 End Return RxCalcPower(_/n,.5)   :: requires rxmath library
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#Picat
Picat
go => Vars = ["fullname","favouritefruit","needspeeling","seedsremoved","otherfamily"], Config = read_config("read_a_configuration_file_config.cfg"), foreach(Key in Vars) printf("%w = %w\n", Key, Config.get(Key,false)) end, nl.   % Read configuration file read_config(File) = Config => Config = new_map(), Lines = [Line : Line in read_file_lines(File), Line != [], not membchk(Line[1],"#;")], foreach(Line in Lines) Line := strip(Line), once( append(Key,[' '|Value],Line) ; Key = Line, Value = true), if find(Value,",",_,_) then Value := [strip(Val) : Val in split(Value,",")] end, Key := strip(to_lowercase(Key)), Config.put(Key,Value) end.
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#OCaml
OCaml
#load "str.cma"   let range a b = if b < a then invalid_arg "range"; let rec aux i acc = if i = b then List.rev (i::acc) else aux (succ i) (i::acc) in aux a []   let parse_piece s = try Scanf.sscanf s "%d-%d" (fun a b -> range a b) with _ -> [int_of_string s]   let range_expand rng = let ps = Str.split (Str.regexp_string ",") rng in List.flatten (List.map parse_piece ps)   let () = let rng = "-6,-3--1,3-5,7-11,14,15,17-20" in let exp = range_expand rng in List.iter (Printf.printf " %d") exp; print_newline ()
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Objective-C
Objective-C
NSString *path = [NSString stringWithString:@"/usr/share/dict/words"]; NSError *error = nil; NSString *words = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REBOL
REBOL
print reverse "asdf"
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Erlang
Erlang
-module(fifo). -export([new/0, push/2, pop/1, empty/1]).   new() -> {fifo, [], []}.   push({fifo, In, Out}, X) -> {fifo, [X|In], Out}.   pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}.   empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Haskell
Haskell
import Control.Monad (join)   data Quaternion a = Q a a a a deriving (Show, Eq)   realQ :: Quaternion a -> a realQ (Q r _ _ _) = r   imagQ :: Quaternion a -> [a] imagQ (Q _ i j k) = [i, j, k]   quaternionFromScalar :: (Num a) => a -> Quaternion a quaternionFromScalar s = Q s 0 0 0   listFromQ :: Quaternion a -> [a] listFromQ (Q a b c d) = [a, b, c, d]   quaternionFromList :: [a] -> Quaternion a quaternionFromList [a, b, c, d] = Q a b c d   normQ :: (RealFloat a) => Quaternion a -> a normQ = sqrt . sum . join (zipWith (*)) . listFromQ   conjQ :: (Num a) => Quaternion a -> Quaternion a conjQ (Q a b c d) = Q a (-b) (-c) (-d)   instance (RealFloat a) => Num (Quaternion a) where (Q a b c d) + (Q p q r s) = Q (a + p) (b + q) (c + r) (d + s) (Q a b c d) - (Q p q r s) = Q (a - p) (b - q) (c - r) (d - s) (Q a b c d) * (Q p q r s) = Q (a * p - b * q - c * r - d * s) (a * q + b * p + c * s - d * r) (a * r - b * s + c * p + d * q) (a * s + b * r - c * q + d * p) negate (Q a b c d) = Q (-a) (-b) (-c) (-d) abs q = quaternionFromScalar (normQ q) signum (Q 0 0 0 0) = 0 signum q@(Q a b c d) = Q (a/n) (b/n) (c/n) (d/n) where n = normQ q fromInteger n = quaternionFromScalar (fromInteger n)   main :: IO () main = do let q, q1, q2 :: Quaternion Double q = Q 1 2 3 4 q1 = Q 2 3 4 5 q2 = Q 3 4 5 6 print $ (Q 0 1 0 0) * (Q 0 0 1 0) * (Q 0 0 0 1) -- i*j*k; prints "Q (-1.0) 0.0 0.0 0.0" print $ q1 * q2 -- prints "Q (-56.0) 16.0 24.0 26.0" print $ q2 * q1 -- prints "Q (-56.0) 18.0 20.0 28.0" print $ q1 * q2 == q2 * q1 -- prints "False" print $ imagQ q -- prints "[2.0,3.0,4.0]"
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#COBOL
COBOL
cobc -x -free -frelax quine.cob
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PureBasic
PureBasic
NewList MyStack()   Procedure Push(n) Shared MyStack() LastElement(MyStack()) AddElement(MyStack()) MyStack()=n EndProcedure   Procedure Pop() Shared MyStack() Protected n If FirstElement(MyStack()) ; e.g. Stack not empty n=MyStack() DeleteElement(MyStack(),1) EndIf ProcedureReturn n EndProcedure   Procedure Empty() Shared MyStack() If ListSize(MyStack())=0 ProcedureReturn #True EndIf ProcedureReturn #False EndProcedure   ;---- Example of implementation ---- Push(3) Push(1) Push(4) Push(1) Push(5) While Not Empty() Debug Pop() Wend  
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Python
Python
import Queue my_queue = Queue.Queue() my_queue.put("foo") my_queue.put("bar") my_queue.put("baz") print my_queue.get() # foo print my_queue.get() # bar print my_queue.get() # baz
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#PL.2FI
PL/I
  quick: procedure options (main); /* 4 April 2014 */   partition: procedure (list, left, right, pivot_Index) returns (fixed binary); declare list (*) fixed binary; declare (left, right, pivot_index) fixed binary; declare (store_index, pivot_value) fixed binary; declare I fixed binary;   pivot_Value = list(pivot_Index); call swap (pivot_Index, right); /* Move pivot to end */ store_Index = left; do i = left to right-1; if list(i) < pivot_Value then do; call swap (store_Index, i); store_Index = store_index + 1; end; end; call swap (right, store_Index); /* Move pivot to its final place */ return (store_Index);   swap: procedure (i, j); declare (i, j) fixed binary; declare t fixed binary;   t = list(i); list(i) = list(j); list(j) = t; end swap; end partition;   /* Returns the n-th smallest element of list within left..right inclusive */ /* (i.e. left <= n <= right). */ quick_select: procedure (list, left, right, n) recursive returns (fixed binary); declare list(*) fixed binary; declare (left, right, n) fixed binary; declare pivot_index fixed binary;   if left = right then /* If the list contains only one element */ return ( list(left) ); /* Return that element */ pivot_Index = (left+right)/2; /* select a pivot_Index between left and right, */ /* e.g. left + Math.floor(Math.random() * (right - left + 1)) */ pivot_Index = partition(list, left, right, pivot_Index); /* The pivot is in its final sorted position. */ if n = pivot_Index then return ( list(n) ); else if n < pivot_Index then return ( quick_select(list, left, pivot_Index - 1, n) ); else return ( quick_select(list, pivot_Index + 1, right, n) );   end quick_select;   declare a(10) fixed binary static initial (9, 8, 7, 6, 5, 0, 1, 2, 3, 4); declare I fixed binary;   do i = 1 to 10; put skip edit ('The ', trim(i), '-th element is ', quick_select((a), 1, 10, (i) )) (a); end;   end quick;
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#PowerShell
PowerShell
  function partition($list, $left, $right, $pivotIndex) { $pivotValue = $list[$pivotIndex] $list[$pivotIndex], $list[$right] = $list[$right], $list[$pivotIndex] $storeIndex = $left foreach ($i in $left..($right-1)) { if ($list[$i] -lt $pivotValue) { $list[$storeIndex],$list[$i] = $list[$i], $list[$storeIndex] $storeIndex += 1 } } $list[$right],$list[$storeIndex] = $list[$storeIndex], $list[$right] $storeIndex }   function rank($list, $left, $right, $n) { if ($left -eq $right) {$list[$left]} else { $pivotIndex = Get-Random -Minimum $left -Maximum $right $pivotIndex = partition $list $left $right $pivotIndex if ($n -eq $pivotIndex) {$list[$n]} elseif ($n -lt $pivotIndex) {(rank $list $left ($pivotIndex - 1) $n)} else {(rank $list ($pivotIndex+1) $right $n)} } }   function quickselect($list) { $right = $list.count-1 foreach($left in 0..$right) {rank $list $left $right $left} } $arr = @(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) "$(quickselect $arr)"  
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Julia
Julia
  function sprintfrange{T<:Integer}(a::Array{T,1}) len = length(a) 0 < len || return "" dropme = falses(len) dropme[2:end-1] = Bool[a[i-1]==a[i]-1 && a[i+1]==a[i]+1 for i in 2:(len-1)] s = [string(i) for i in a] s[dropme] = "X" s = join(s, ",") replace(s, r",[,X]+,", "-") end   testa = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]   println("Testing range-style formatting.") println(" ", testa, "\n =>\n ", sprintfrange(testa))  
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
#PARI.2FGP
PARI/GP
rnormal()={ my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296)),u1=random(2^pr)*1.>>pr,u2=random(2^pr)*1.>>pr); sqrt(-2*log(u1))*cos(2*Pi*u2) \\ in previous version "u1" instead of "u2" was used --> has given crap distribution \\ Could easily be extended with a second normal at very little cost. }; vector(1000,unused,rnormal()/2+1)
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
#Pascal
Pascal
  function rnorm (mean, sd: real): real; {Calculates Gaussian random numbers according to the Box-Müller approach} var u1, u2: real; begin u1 := random; u2 := random; rnorm := mean * abs(1 + sqrt(-2 * (ln(u1))) * cos(2 * pi * u2) * sd); /* error !?! Shouldn't it be "mean +" instead of "mean *" ? */ end;
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#PicoLisp
PicoLisp
(de rdConf (File) (in File (while (read) (set @ (or (pack (clip (line))) T)) ) ) )   (rdConf "conf.txt") (println FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY) (bye)
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Oforth
Oforth
: addRange( s res -- ) | i n | s asInteger dup ifNotNull: [ res add return ] drop s indexOfFrom('-', 2) ->i s left( i 1- ) asInteger s right( s size i - ) asInteger for: n [ n res add ] ;   : rangeExpand ( s -- [ n ] ) ArrayBuffer new s wordsWith( ',' ) apply( #[ over addRange ] ) ;
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#ooRexx
ooRexx
  list = '-6,-3--1,3-5,7-11,14,15,17-20' expanded = expandRanges(list)   say "Original list: ["list"]" say "Expanded list: ["expanded~tostring("l", ",")"]"   -- expand a string expression a range of numbers into a list -- of values for the range. This returns an array ::routine expandRanges use strict arg list values = list~makearray(',') -- build this up using an array first. Make this at least the -- size of the original value set. expanded = .array~new(values~items)   -- now process each element in the range loop element over values -- if this is a valid number, it's not a range, so add it directly if element~datatype('whole') then expanded~append(element) else do -- search for the divider, starting from the second position -- to allow for the starting value to be a minus sign. split = element~pos('-', 2) parse var element start =(split) +1 finish loop i = start to finish expanded~append(i) end end end return expanded  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#OCaml
OCaml
let () = let ic = open_in "input.txt" in try while true do let line = input_line ic in print_endline line done with End_of_file -> close_in ic
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Oforth
Oforth
: readFile(fileName) | line | File new(fileName) forEach: line [ line println ] ;
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Red
Red
>> reverse "asdf" == "fdsa"
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ERRE
ERRE
PROGRAM CLASS_DEMO   CLASS QUEUE   LOCAL SP LOCAL DIM STACK[100]   FUNCTION ISEMPTY() ISEMPTY=(SP=0) END FUNCTION   PROCEDURE INIT SP=0 END PROCEDURE   PROCEDURE POP(->XX) XX=STACK[SP] SP=SP-1 END PROCEDURE   PROCEDURE PUSH(XX) SP=SP+1 STACK[SP]=XX END PROCEDURE   END CLASS   NEW PILA:QUEUE   BEGIN PILA_INIT  ! constructor FOR N=1 TO 4 DO  ! push 4 numbers PRINT("Push";N) PILA_PUSH(N) END FOR FOR I=1 TO 5 DO  ! pop 5 numbers IF NOT PILA_ISEMPTY() THEN PILA_POP(->N) PRINT("Pop";N) ELSE PRINT("Queue is empty!") END IF END FOR PRINT("* End *") END PROGRAM
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Factor
Factor
USING: accessors kernel ; IN: rosetta-code.queue-definition   TUPLE: queue head tail ; TUPLE: node value next ;   : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ;   : empty? ( queue -- ? ) head>> >boolean not ;   : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ;   : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Icon_and_Unicon
Icon and Unicon
  class Quaternion(a, b, c, d)   method norm () return sqrt (a*a + b*b + c*c + d*d) end   method negative () return Quaternion(-a, -b, -c, -d) end   method conjugate () return Quaternion(a, -b, -c, -d) end   method add (n) if type(n) == "Quaternion__state" then return Quaternion(a+n.a, b+n.b, c+n.c, d+n.d) else return Quaternion(a+n, b, c, d) end   method multiply (n) if type(n) == "Quaternion__state" then return Quaternion(a*n.a - b*n.b - c*n.c - d*n.d, a*n.b + b*n.a + c*n.d - d*n.c, a*n.c - b*n.d + c*n.a + d*n.b, a*n.d + b*n.c - c*n.b + d*n.a) else return Quaternion(a*n, b*n, c*n, d*n) end   method sign (n) return if n >= 0 then "+" else "-" end   method string () return ("" || a || sign(b) || abs(b) || "i" || sign(c) || abs(c) || "j" || sign(d) || abs(d) || "k"); end   initially(a, b, c, d) self.a := if /a then 0 else a self.b := if /b then 0 else b self.c := if /c then 0 else c self.d := if /d then 0 else d end  
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#CoffeeScript
CoffeeScript
s="s=#&# ;alert s.replace(/&/,s).replace /#(?=[^&;'(]|';;$)/g, '#';;" ;alert s.replace(/&/,s).replace /#(?=[^&;'(]|';;$)/g, '"';;
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Quackery
Quackery
[ [] ] is queue ( --> q )   [ nested join ] is push ( q x --> q )   [ behead ] is pop ( q --> q x )   [ [] = ] is empty? ( q --> b )
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Racket
Racket
#lang racket   (require data/queue)   (define queue (make-queue))   (enqueue! queue 'black) (queue-empty? queue) ; #f   (enqueue! queue 'red) (enqueue! queue 'green)   (dequeue! queue) ; 'black (dequeue! queue) ; 'red (dequeue! queue) ; 'green   (queue-empty? queue) ; #t
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#PureBasic
PureBasic
  Procedure QuickPartition (Array L(1), left, right, pivotIndex) pivotValue = L(pivotIndex) Swap L(pivotIndex) , L(right); Move pivot To End storeIndex = left For i=left To right-1 If L(i) < pivotValue Swap L(storeIndex),L(i) storeIndex+1 EndIf Next i Swap L(right), L(storeIndex) ; Move pivot To its final place ProcedureReturn storeIndex EndProcedure Procedure QuickSelect(Array L(1), left, right, k) Repeat If left = right:ProcedureReturn L(left):EndIf pivotIndex.i= left; Select pivotIndex between left And right pivotIndex= QuickPartition(L(), left, right, pivotIndex) If k = pivotIndex ProcedureReturn L(k) ElseIf k < pivotIndex right= pivotIndex - 1 Else left= pivotIndex + 1 EndIf ForEver EndProcedure Dim L.i(9) For i=0 To 9 Read L(i) Next i DataSection Data.i 9, 8, 7, 6, 5, 0, 1, 2, 3, 4 EndDataSection For i=0 To 9 Debug QuickSelect(L(),0,9,i) Next i
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#K
K
grp : {(&~1=0,-':x)_ x} fmt : {:[1=#s:$x;s;(*s),:[3>#s;",";"-"],*|s]} erng: {{x,",",y}/,//'fmt'grp x}
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
#Perl
Perl
my $PI = 2 * atan2 1, 0;   my @nums = map { 1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand) } 1..1000;
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
#Phix
Phix
function RandomNormal() return sqrt(-2*log(rnd())) * cos(2*PI*rnd()) end function sequence s = repeat(0,1000) for i=1 to length(s) do s[i] = 1 + 0.5 * RandomNormal() end for
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#PL.2FI
PL/I
  set: procedure options (main); declare text character (100) varying; declare (fullname, favouritefruit) character (100) varying initial (''); declare needspeeling bit (1) static initial ('0'b); declare seedsremoved bit (1) static initial ('0'b); declare otherfamily(10) character (100) varying; declare (i, j) fixed binary; declare in file;   open file (in) title ( '/RD-CON.DAT,TYPE(TEXT),RECSIZE(200)' );   on endfile (in) go to variables;   otherfamily = ''; j = 0;   do forever; get file (in) edit (text) (L); text = trim(text);   if length(text) = 0 then iterate; if substr(text, 1, 1) = ';' then iterate; if substr(text, 1, 1) = '#' then iterate; if length(text) >= 9 then if substr(text, 1, 9) = 'FULLNAME ' then fullname = trim( substr(text, 9) ); if length(text) >= 15 then if substr(text, 1, 15) = 'FAVOURITEFRUIT ' then favouritefruit = trim( substr(text, 15) ); if length(text) >= 12 then if text = 'NEEDSPEELING' then needspeeling = '1'b; if length(text) >= 12 then if text = 'SEEDSREMOVED' then seedsremoved = '1'b; if length(text) >= 12 then if substr(text, 1, 12) = 'OTHERFAMILY ' then do; text = trim(substr(text, 12) ); i = index(text, ','); do while (i > 0); j = j + 1; otherfamily(j) = substr(text, 1, i-1); text = trim(substr(text, i+1)); i = index(text, ','); end; j = j + 1; otherfamily(j) = trim(text); end; end;   variables: put skip data (fullname); put skip data (favouritefruit); put skip data (needspeeling); put skip data (seedsremoved); do i = 1 to j; put skip data (otherfamily(i)); end;   end set;  
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Oz
Oz
declare fun {Expand RangeDesc} {Flatten {Map {ParseDesc RangeDesc} ExpandRange}} end   fun {ParseDesc Txt} {Map {String.tokens Txt &,} ParseRange} end   fun {ParseRange R} if {Member &- R.2} then First Second in {String.token R.2 &- ?First ?Second} {String.toInt R.1|First}#{String.toInt Second} else Singleton = {String.toInt R} in Singleton#Singleton end end   fun {ExpandRange From#To} {List.number From To 1} end in {System.showInfo {Value.toVirtualString {Expand "-6,-3--1,3-5,7-11,14,15,17-20"} 100 100}}
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#PARI.2FGP
PARI/GP
FILE *f = fopen(name, "r"); if (!f) { pari_err(openfiler, "input", name); } while(fgets(line, MAX_LINELEN, f) != NULL) { // ... }
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Pascal
Pascal
(* Read a text-file line by line *) program ReadFileByLine; var InputFile,OutputFile: text; TextLine: String; begin Assign(InputFile, 'testin.txt'); Reset(InputFile); Assign(OutputFile, 'testout.txt'); Rewrite(OutputFile); while not Eof(InputFile) do begin ReadLn(InputFile, TextLine); (* do someting with TextLine *) WriteLn(OutputFile, TextLine) end; Close(InputFile); Close(OutputFile) end.
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ReScript
ReScript
let rev_string = (s) => { let len = Js.String2.length(s) let arr = [] for i in 0 to (len-1) { let c = Js.String2.get(s, len - 1 - i) let _ = Js.Array2.push(arr, c) } Js.String2.concatMany("", arr) }   Js.log(rev_string("abcdefg"))
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Fantom
Fantom
  class Queue { List queue := [,]   public Void push (Obj obj) { queue.add (obj) // add to right of list }   public Obj pop () { if (queue.isEmpty) throw (Err("queue is empty")) else { return queue.removeAt(0) // removes left-most item } }   public Bool isEmpty () { queue.isEmpty } }  
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Forth
Forth
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used !   : empty? used @ 0= ; : full? used @ size = ;   : next ( ptr -- ptr ) cell+ dup end = if drop buffer then ;   : put ( n -- ) full? abort" buffer full" \ begin full? while pause repeat tail @ ! tail @ next tail ! 1 used +! ;   : get ( -- n ) empty? abort" buffer empty" \ begin empty? while pause repeat head @ @ head @ next head ! -1 used +! ;
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Idris
Idris
  module CayleyDickson   data CD : Nat -> Type -> Type where CDBase : a -> CD 0 a CDProd : CD n a -> CD n a -> CD (S n) a   pairTy : Nat -> Type -> Type pairTy Z a = a pairTy (S n) a = let b = pairTy n a in (b, b)   fromPair : (n : Nat) -> pairTy n a -> CD n a fromPair Z x = CDBase x fromPair (S m) (x, y) = CDProd (fromPair m x) $ fromPair m y   toPair : CD n a -> pairTy n a toPair (CDBase x) = x toPair (CDProd x v) = (toPair x, toPair v)   first : CD n a -> a first (CDBase x) = x first (CDProd x v) = first x   fromBase : Num a => (n : Nat) -> a -> CD n a fromBase Z x = CDBase x fromBase (S m) x = CDProd (fromBase m x) $ fromBase m 0   multSclr : Num a => CD n a -> a -> CD n a multSclr (CDBase x) y = CDBase $ x * y multSclr (CDProd x v) y = CDProd (multSclr x y) $ multSclr v y   divSclr : Fractional a => CD n a -> a -> CD n a divSclr (CDBase x) y = CDBase $ x / y divSclr (CDProd x v) y = CDProd (divSclr x y) $ divSclr v y   plusCD : Num a => CD n a -> CD n a -> CD n a plusCD (CDBase x) (CDBase y) = CDBase $ x + y plusCD (CDProd x v) (CDProd y w) = CDProd (plusCD x y) $ plusCD v w   negCD : Neg a => CD n a -> CD n a negCD (CDBase x) = CDBase $ negate x negCD (CDProd x v) = CDProd (negCD x) $ negCD v   minusCD : Neg a => CD n a -> CD n a -> CD n a minusCD (CDBase x) (CDBase y) = CDBase $ x - y minusCD (CDProd x v) (CDProd y w) = CDProd (minusCD x y) $ minusCD v w   conjCD : Neg a => CD n a -> CD n a conjCD (CDBase x) = CDBase x conjCD (CDProd x v) = CDProd (conjCD x) $ negCD v   multCD : Neg a => CD n a -> CD n a -> CD n a multCD (CDBase x) (CDBase y) = CDBase $ x * y multCD (CDProd x v) (CDProd y w) = CDProd (minusCD (multCD x y) (multCD (conjCD w) v)) $ plusCD (multCD w x) $ multCD v $ conjCD y   absSqrCD : Neg a => CD n a -> CD n a absSqrCD x = multCD x $ conjCD x   sqrLnCD : Neg a => CD n a -> a sqrLnCD = first . absSqrCD   recipCD : Neg a => Fractional a => CD n a -> CD n a recipCD x = conjCD $ divSclr x $ sqrLnCD x   divCD : Neg a => Fractional a => CD n a -> CD n a -> CD n a divCD x y = multCD x $ recipCD y   absCD : CD n Double -> Double absCD x = sqrt $ sqrLnCD x   showComps : Show a => CD n a -> String showComps (CDBase x) = show x showComps (CDProd x v) = showComps x ++ ", " ++ showComps v   Eq a => Eq (CD n a) where (CDBase x) == (CDBase y) = x == y (CDProd x v) == (CDProd y w) = x == y && v == w   Show a => Show (CD n a) where show x = "(" ++ showComps x ++ ")"   Neg a => Num (CD n a) where (+) = plusCD (*) = multCD fromInteger m {n} = fromBase n $ fromInteger m   Neg a => Neg (CD n a) where negate = negCD (-) = minusCD   (Neg a, Fractional a) => Fractional (CD n a) where (/) = divCD recip = recipCD   Abs (CD n Double) where abs {n} = fromBase n . absCD  
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Commodore_BASIC
Commodore BASIC
10 DATA 49,54,48,32,78,61,51,51,48,13,49,55,48,32,68,73,77,32,65,40,78,41,13 20 DATA 49,56,48,32,70,79,82,32,73,61,48,32,84,79,32,78,13,49,57,48,32,58,32 30 DATA 82,69,65,68,32,65,40,73,41,13,50,48,48,32,78,69,88,84,32,73,13,50,49 40 DATA 48,32,70,79,82,32,73,61,48,32,84,79,32,49,52,32,13,50,50,48,32,58,32 50 DATA 80,82,73,78,84,32,77,73,68,36,40,83,84,82,36,40,40,73,43,49,41,42,49 60 DATA 48,41,44,50,41,59,34,32,68,65,84,65,32,34,59,77,73,68,36,40,83,84,82 70 DATA 36,40,65,40,73,42,50,51,41,41,44,50,41,59,13,50,51,48,32,58,32,70,79 80 DATA 82,32,74,61,49,32,84,79,32,50,50,13,50,52,48,32,58,32,32,32,75,61,73 90 DATA 42,50,51,43,74,13,50,53,48,32,58,32,32,32,73,70,32,75,32,60,61,32,78 100 DATA 32,84,72,69,78,32,80,82,73,78,84,32,34,44,34,59,77,73,68,36,40,83,84 110 DATA 82,36,40,65,40,75,41,41,44,50,41,59,13,50,54,48,32,58,32,78,69,88,84 120 DATA 32,74,13,50,55,48,32,58,32,80,82,73,78,84,13,50,56,48,32,78,69,88,84 130 DATA 32,73,13,50,57,48,32,70,79,82,32,73,61,48,32,84,79,32,78,13,51,48,48 140 DATA 32,58,32,80,82,73,78,84,32,67,72,82,36,40,65,40,73,41,41,59,13,51,49 150 DATA 48,32,78,69,88,84,32,73,13 160 N=330 170 DIM A(N) 180 FOR I=0 TO N 190 : READ A(I) 200 NEXT I 210 FOR I=0 TO 14 220 : PRINT MID$(STR$((I+1)*10),2);" DATA ";MID$(STR$(A(I*23)),2); 230 : FOR J=1 TO 22 240 : K=I*23+J 250 : IF K <= N THEN PRINT ",";MID$(STR$(A(K)),2); 260 : NEXT J 270 : PRINT 280 NEXT I 290 FOR I=0 TO N 300 : PRINT CHR$(A(I)); 310 NEXT I
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Common_Lisp
Common Lisp
((lambda (s) (print (list s (list 'quote s)))) '(lambda (s) (print (list s (list 'quote s)))))
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Raku
Raku
push (aka enqueue) -- @list.push pop (aka dequeue) -- @list.shift empty -- [email protected]
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#REBOL
REBOL
; Create and populate a FIFO:   q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 ; Did I mention that REBOL has 'money!' datatype? q/push [Athos Porthos Aramis] ; List elements pushed on one by one. q/push [[Huey Dewey Lewey]] ; This list is preserved as a list.   ; Dump it out, with narrative:   print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#Python
Python
import random   def partition(vector, left, right, pivotIndex): pivotValue = vector[pivotIndex] vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] # Move pivot to end storeIndex = left for i in range(left, right): if vector[i] < pivotValue: vector[storeIndex], vector[i] = vector[i], vector[storeIndex] storeIndex += 1 vector[right], vector[storeIndex] = vector[storeIndex], vector[right] # Move pivot to its final place return storeIndex   def _select(vector, left, right, k): "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive." while True: pivotIndex = random.randint(left, right) # select pivotIndex between left and right pivotNewIndex = partition(vector, left, right, pivotIndex) pivotDist = pivotNewIndex - left if pivotDist == k: return vector[pivotNewIndex] elif k < pivotDist: right = pivotNewIndex - 1 else: k -= pivotDist + 1 left = pivotNewIndex + 1   def select(vector, k, left=None, right=None): """\ Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1]. left, right default to (0, len(vector) - 1) if omitted """ if left is None: left = 0 lv1 = len(vector) - 1 if right is None: right = lv1 assert vector and k >= 0, "Either null vector or k < 0 " assert 0 <= left <= lv1, "left is out of range" assert left <= right <= lv1, "right is out of range" return _select(vector, left, right, k)   if __name__ == '__main__': v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] print([select(v, i) for i in range(10)])
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Kotlin
Kotlin
// version 1.0.6   fun extractRange(list: List<Int>): String { if (list.isEmpty()) return "" val sb = StringBuilder() var first = list[0] var prev = first   fun append(index: Int) { if (first == prev) sb.append(prev) else if (first == prev - 1) sb.append(first, ",", prev) else sb.append(first, "-", prev) if (index < list.size - 1) sb.append(",") }   for (i in 1 until list.size) { if (list[i] == prev + 1) prev++ else { append(i) first = list[i] prev = first } } append(list.size - 1) return sb.toString() }   fun main(args: Array<String>) { val list1 = listOf(-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20) println(extractRange(list1)) println() val list2 = listOf(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39) println(extractRange(list2)) }
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def RandomNormal drop rand log -2 * sqrt 2 pi * rand * cos * 0.5 * 1 + enddef   1000 var n 0 n repeat   getid RandomNormal map   dup sum n / var mean "Mean: " print mean print nl   0 swap n for get mean - 2 power rot + swap endfor swap n / sqrt "Standard deviation: " print print
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
#PHP
PHP
function random() { return mt_rand() / mt_getrandmax(); }   $pi = pi(); // Set PI   $a = array(); for ($i = 0; $i < 1000; $i++) { $a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);   }
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#PowerShell
PowerShell
  function Read-ConfigurationFile { [CmdletBinding()] Param ( # Path to the configuration file. Default is "C:\ConfigurationFile.cfg" [Parameter(Mandatory=$false, Position=0)] [string] $Path = "C:\ConfigurationFile.cfg" )   [string]$script:fullName = "" [string]$script:favouriteFruit = "" [bool]$script:needsPeeling = $false [bool]$script:seedsRemoved = $false [string[]]$script:otherFamily = @()   function Get-Value ([string]$Line) { if ($Line -match "=") { [string]$value = $Line.Split("=",2).Trim()[1] } elseif ($Line -match " ") { [string]$value = $Line.Split(" ",2).Trim()[1] }   $value }   # Process each line in file that is not a comment. Get-Content $Path | Select-String -Pattern "^[^#;]" | ForEach-Object {   [string]$line = $_.Line.Trim()   if ($line -eq [String]::Empty) { # do nothing for empty lines } elseif ($line.ToUpper().StartsWith("FULLNAME")) { $script:fullName = Get-Value $line } elseif ($line.ToUpper().StartsWith("FAVOURITEFRUIT")) { $script:favouriteFruit = Get-Value $line } elseif ($line.ToUpper().StartsWith("NEEDSPEELING")) { $script:needsPeeling = $true } elseif ($line.ToUpper().StartsWith("SEEDSREMOVED")) { $script:seedsRemoved = $true } elseif ($line.ToUpper().StartsWith("OTHERFAMILY")) { $script:otherFamily = (Get-Value $line).Split(',').Trim() } }   Write-Verbose -Message ("{0,-15}= {1}" -f "FULLNAME", $script:fullName) Write-Verbose -Message ("{0,-15}= {1}" -f "FAVOURITEFRUIT", $script:favouriteFruit) Write-Verbose -Message ("{0,-15}= {1}" -f "NEEDSPEELING", $script:needsPeeling) Write-Verbose -Message ("{0,-15}= {1}" -f "SEEDSREMOVED", $script:seedsRemoved) Write-Verbose -Message ("{0,-15}= {1}" -f "OTHERFAMILY", ($script:otherFamily -join ", ")) }  
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Perl
Perl
sub rangex { map { /^(.*\d)-(.+)$/ ? $1..$2 : $_ } split /,/, shift }   # Test and display print join(',', rangex('-6,-3--1,3-5,7-11,14,15,17-20')), "\n";