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/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.
#BQN
BQN
•Out 1⌽∾˜18⥊•Repr"•Out 1⌽∾˜18⥊•Repr"
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
#Lasso
Lasso
push: queue->insert pop: queue->get empty: queue->size == 0
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
#Logo
Logo
make "fifo [] print empty? :fifo  ; true queue "fifo 1 queue "fifo 2 queue "fifo 3 show :fifo  ; [1 2 3] print dequeue "fifo  ; 1 show :fifo  ; [2 3] print empty? :fifo  ; 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.
#JavaScript
JavaScript
// this just helps make partition read better function swap(items, firstIndex, secondIndex) { var temp = items[firstIndex]; items[firstIndex] = items[secondIndex]; items[secondIndex] = temp; };   // many algorithms on this page violate // the constraint that partition operates in place function partition(array, from, to) { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random var pivotIndex = getRandomInt(from, to), pivot = array[pivotIndex]; swap(array, pivotIndex, to); pivotIndex = from;   for(var i = from; i <= to; i++) { if(array[i] < pivot) { swap(array, pivotIndex, i); pivotIndex++; } }; swap(array, pivotIndex, to);   return pivotIndex; };   // later versions of JS have TCO so this is safe function quickselectRecursive(array, from, to, statistic) { if(array.length === 0 || statistic > array.length - 1) { return undefined; };   var pivotIndex = partition(array, from, to); if(pivotIndex === statistic) { return array[pivotIndex]; } else if(pivotIndex < statistic) { return quickselectRecursive(array, pivotIndex, to, statistic); } else if(pivotIndex > statistic) { return quickselectRecursive(array, from, pivotIndex, statistic); } };   function quickselectIterative(array, k) { if(array.length === 0 || k > array.length - 1) { return undefined; };   var from = 0, to = array.length, pivotIndex = partition(array, from, to);   while(pivotIndex !== k) { pivotIndex = partition(array, from, to); if(pivotIndex < k) { from = pivotIndex; } else if(pivotIndex > k) { to = pivotIndex; } };   return array[pivotIndex]; };   KthElement = { find: function(array, element) { var k = element - 1; return quickselectRecursive(array, 0, array.length, k); // you can also try out the Iterative version // return quickselectIterative(array, k); } }
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function formatRange (a() As Integer) As String Dim lb As Integer = LBound(a) Dim ub As Integer = UBound(a) If ub = - 1 Then Return "" If lb = ub Then Return Str(a(lb)) Dim rangeCount As Integer = 1 Dim range As String = Str(a(lb)) For i As Integer = lb + 1 To ub If a(i) = a(i - 1) + 1 Then rangeCount += 1 ElseIf rangeCount = 1 Then range += "," + Str(a(i)) ElseIf rangeCount = 2 Then rangeCount = 1 range += "," + Str(a(i-1)) + "," + Str(a(i)) Else rangeCount = 1 range += "-" + Str(a(i-1)) + "," + Str(a(i)) End If Next If rangeCount = 2 Then range += "," + Str(a(ub)) ElseIf rangeCount > 2 Then range += "-" + Str(a(ub)) End If Return range End Function   Dim a(1 To 20) As Integer = {-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20} Print formatRange(a()) Print   Dim b(1 To 33) As Integer => _ { _ 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 _ }   Print formatRange(b()) Print Print "Press any key to continue" Sleep
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Function StdDev (A()) { \\ A() has a copy of values N=Len(A()) if N<1 then Error "Empty Array" M=Each(A()) k=0 \\ make sum, dev same type as A(k) sum=A(k)-A(k) dev=sum \\ find mean While M { sum+=Array(M) } Mean=sum/N \\ make a pointet to A() P=A() \\ subtruct from each item P-=Mean   M=Each(P) While M { dev+=Array(M)*Array(M) } \\ as pointer to arrray =(if(dev>0->Sqrt(dev/N), 0), Mean) } Function randomNormal { \\ by default all numbers are double \\ cos() get degrees =1+Cos(360 * rnd) * Sqrt(-2 * Ln(rnd)) /2 } \\ fill array calling randomNormal() for each item Dim A(1000)<<randomNormal() \\ we can pass a pointer to array and place it to stack of values DisplayMeanAndStdDeviation(A()) ' mean ~ 1 std deviation ~0.5 \\ check M2000 rnd only Dim B(1000)<<rnd DisplayMeanAndStdDeviation(B()) ' mean ~ 0.5 std deviation ~0.28     DisplayMeanAndStdDeviation((0,0,14,14)) ' mean = 7 std deviation = 7 DisplayMeanAndStdDeviation((0,6,8,14)) ' mean = 7 std deviation = 5 DisplayMeanAndStdDeviation((6,6,8,8)) ' mean = 7 std deviation = 1   Sub DisplayMeanAndStdDeviation(A) \\ push to stack all items of an array (need an array pointer) Push  ! StdDev(A) \\ read from strack two numbers Print "Mean is "; Number Print "Standard Deviation is "; Number End Sub } Checkit  
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
#Maple
Maple
with(Statistics): Sample(Normal(1, 0.5), 1000);
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
#Nanoquery
Nanoquery
import Nanoquery.IO import dict   def get_config(fname) f = new(File).open(fname) lines = split(f.readAll(), "\n")   values = new(Dict) for line in lines line = trim(line) if len(line) > 0 if not (line .startswith. "#") or (line .startswith. ";") tokens = split(line, " ")   if len(tokens) = 1 values.add(upper(tokens[0]), true) else parameters = list() parameter = "" for i in range(1, len(tokens) - 1) parameter += tokens[i] + " " if parameter .endswith. ", " parameter = parameter.substring(0, len(parameter) - 2) parameters.append(trim(parameter)) parameter = "" end end parameters.append(trim(parameter)) if len(parameters) > 1 values.add(upper(tokens[0]), parameters) else values.add(upper(tokens[0]), parameters[0]) end end end end end   return values end   println get_config(args[2])
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
#Julia
Julia
slurp(s) = readcsv(IOBuffer(s))   conv(s)= colon(map(x->parse(Int,x),match(r"^(-?\d+)-(-?\d+)$", s).captures)...)   expand(s) = mapreduce(x -> isa(x,Number)? Int(x) : conv(x), vcat, slurp(s))
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.
#Liberty_BASIC
Liberty BASIC
filedialog "Open","*.txt",file$ if file$="" then end open file$ for input as #f while not(eof(#f)) line input #f, t$ print t$ wend close #f
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
#PureBasic
PureBasic
Debug ReverseString("!dekrow tI")
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
#Common_Lisp
Common Lisp
(defstruct (queue (:constructor %make-queue)) (items '() :type list) (tail '() :type list))   (defun make-queue () "Returns an empty queue." (%make-queue))   (defun queue-empty-p (queue) "Returns true if the queue is empty." (endp (queue-items queue)))   (defun enqueue (item queue) "Enqueue item in queue. Returns the queue." (prog1 queue (if (queue-empty-p queue) (setf (queue-items queue) (list item) (queue-tail queue) (queue-items queue)) (setf (cdr (queue-tail queue)) (list item) (queue-tail queue) (cdr (queue-tail queue))))))   (defun dequeue (queue) "Dequeues an item from queue. Signals an error if queue is empty." (if (queue-empty-p queue) (error "Cannot dequeue from empty queue.") (pop (queue-items queue))))
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.
#Elena
Elena
import system'math; import extensions; import extensions'text;   struct Quaternion { rprop real A; rprop real B; rprop real C; rprop real D;   constructor new(a, b, c, d) <= new(cast real(a), cast real(b), cast real(c), cast real(d));   constructor new(real a, real b, real c, real d) { A := a; B := b; C := c; D := d }   constructor(real r) { A := r; B := 0.0r; C := 0.0r; D := 0.0r }   real Norm = (A*A + B*B + C*C + D*D).sqrt();   Quaternion Negative = Quaternion.new(A.Negative,B.Negative,C.Negative,D.Negative);   Quaternion Conjugate = Quaternion.new(A,B.Negative,C.Negative,D.Negative);   Quaternion add(Quaternion q) = Quaternion.new(A + q.A, B + q.B, C + q.C, D + q.D);   Quaternion multiply(Quaternion q) = Quaternion.new( A * q.A - B * q.B - C * q.C - D * q.D, A * q.B + B * q.A + C * q.D - D * q.C, A * q.C - B * q.D + C * q.A + D * q.B, A * q.D + B * q.C - C * q.B + D * q.A);   Quaternion add(real r) <= add(Quaternion.new(r,0,0,0));   Quaternion multiply(real r) <= multiply(Quaternion.new(r,0,0,0));   bool equal(Quaternion q) = (A == q.A) && (B == q.B) && (C == q.C) && (D == q.D);   string toPrintable() = new StringWriter().printFormatted("Q({0}, {1}, {2}, {3})",A,B,C,D); }   public program() { auto q := Quaternion.new(1,2,3,4); auto q1 := Quaternion.new(2,3,4,5); auto q2 := Quaternion.new(3,4,5,6); real r := 7;   console.printLine("q = ", q); console.printLine("q1 = ", q1); console.printLine("q2 = ", q2); console.printLine("r = ", r);   console.printLine("q.Norm() = ", q.Norm); console.printLine("q1.Norm() = ", q1.Norm); console.printLine("q2.Norm() = ", q2.Norm);   console.printLine("-q = ", q.Negative); console.printLine("q.Conjugate() = ", q.Conjugate);   console.printLine("q + r = ", q + r); console.printLine("q1 + q2 = ", q1 + q2); console.printLine("q2 + q1 = ", q2 + q1);   console.printLine("q * r = ", q * r); console.printLine("q1 * q2 = ", q1 * q2); console.printLine("q2 * q1 = ", q2 * q1);   console.printLineFormatted("q1*q2 {0} q2*q1", ((q1 * q2) == (q2 * q1)).iif("==","!=")) }
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.
#Bracmat
Bracmat
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
#Lua
Lua
q = Queue.new() Queue.push( q, 5 ) Queue.push( q, "abc" )   while not Queue.empty( q ) do print( Queue.pop( q ) ) end
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckStackAsQueue { a=stack Stack a { Push 1, 2, 3 Print number=3 Print number=2 Print number=1 Print Empty=True Push "A", "B", "C" Print letter$="C" Print letter$="B" Print letter$="A" Print Empty=True Push 1,"OK" } Print Len(a)=2, StackItem(a, 2)=1, StackItem$(a, 1)="OK" Print StackType$(a, 1)="String", StackType$(a,2)="Number" } CheckStackAsQueue  
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.
#jq
jq
# Emit the k-th smallest item in the input array, # or nothing if k is too small or too large. # The smallest corresponds to k==1. # The input array may hold arbitrary JSON entities, including null. def quickselect(k):   def partition(pivot): reduce .[] as $x # state: [less, other] ( [ [], [] ]; # two empty arrays: if $x < pivot then .[0] += [$x] # add x to less else .[1] += [$x] # add x to other end );   # recursive inner function has arity 0 for efficiency def qs: # state: [kn, array] where kn counts from 0 .[0] as $kn | .[1] as $a | $a[0] as $pivot | ($a[1:] | partition($pivot)) as $p | $p[0] as $left | ($left|length) as $ll | if $kn == $ll then $pivot elif $kn < $ll then [$kn, $left] | qs else [$kn - $ll - 1, $p[1] ] | qs end;   if length < k or k <= 0 then empty else [k-1, .] | qs end;
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.
#Julia
Julia
v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] @show v partialsort(v, 1: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
#Gambas
Gambas
siInput As New Short[] siInput1 As Short[] = [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] siInput2 As Short[] = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] sOutput As New String[] siCount As Short siNum As Short '__________________ Public Sub Main() Dim siLoop As Short   For siLoop = 0 To 1 If siLoop = 0 Then siInput = siInput1.Copy() Else siInput = siInput2.Copy() siCount = 0 siNum = 0 Repeat If siInput[siCount + 1] = siInput[siCount] + 1 Then Inc siCount Else GetOutput Endif Until siCount = siInput.Max   GetOutput Print sOutput.join(", ") sOutput.clear Next   End '__________________ Public Sub GetOutput()   If siNum = siCount Then sOutput.add(siInput[siNum]) Inc siCount siNum = siCount End If   If siNum <> siCount Then If siNum = siCount - 1 Then sOutput.add(siInput[siNum]) sOutput.add(siInput[siNum + 1]) siCount += 2 siNum += 2 Return End If sOutput.Add(siInput[siNum] & "-" & siInput[siCount]) Inc siCount siNum = siCount End If   End
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RandomReal[NormalDistribution[1, 1/2], 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
#MATLAB
MATLAB
mu = 1; sd = 0.5; x = randn(1000,1) * sd + mu;  
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
#Nim
Nim
import re, strformat, strutils, tables   var configs: OrderedTable[string, seq[string]] var parsed: seq[string]   for line in "demo.config".lines(): let line = line.strip() if line != "" and not line.startswith(re"#|;"): parsed = line.split(re"\s*=\s*|\s+", 1) configs[parsed[0].toLower()] = if len(parsed) > 1: parsed[1].split(re"\s*,\s*") else: @[]   for key in ["fullname", "favouritefruit", "needspeeling", "seedsremoved", "otherfamily"]: if not configs.hasKey(key): echo(&"{key} = false") else: case len(configs[key]) of 0: echo(&"{key} = true") of 1: echo(&"{key} = {configs[key][0]}") else: for i, v in configs[key].pairs(): echo(&"{key}({i+1}) = {v}")
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
#K
K
grp : {1_'(&x=*x)_ x:",",x} pos : {:[3=l:#p:&"-"=x;0,p@1;2=l;p;0=*p;,0;0,p]} conv: 0${(x;1_ y)}/'{(pos x)_ x}' expd: {,/@[x;&2=#:'x;{(*x)+!1+,/-':x}]} rnge: {expd@conv grp x}
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
#Kotlin
Kotlin
// version 1.0.6   fun expandRange(s: String): MutableList<Int> { val list = mutableListOf<Int>() val items = s.split(',') var first: Int var last: Int for (item in items) { val count = item.count { it == '-' } if (count == 0 || (count == 1 && item[0] == '-')) list.add(item.toInt()) else { val items2 = item.split('-') if (count == 1) { first = items2[0].toInt() last = items2[1].toInt() } else if (count == 2) { first = items2[1].toInt() * -1 last = items2[2].toInt() } else { first = items2[1].toInt() * -1 last = items2[3].toInt() * -1 } for (i in first..last) list.add(i) } } return list }   fun main(args: Array<String>) { val s = "-6,-3--1,3-5,7-11,14,15,17-20" println(expandRange(s)) }
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.
#Lingo
Lingo
fp = xtra("fileIO").new() fp.openFile(_movie.path & "input.txt", 1) fileSize = fp.getLength() repeat while TRUE str = fp.readLine() if str.char[1] = numtochar(10) then delete char 1 of str if the last char of str = numtochar(13) then delete the last char of str put str if fp.getPosition()>=fileSize then exit repeat end repeat fp.closeFile()
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.
#LiveCode
LiveCode
command readFileLineByLine local tFile, tLines, startRead put "/usr/share/dict/words" into tFile open file tFile for text read put true into startRead repeat until it is empty and startRead is false put false into startRead read from file tFile for 1 line add 1 to tLines end repeat close file tFile put tLines end readFileLineByLine
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
#Python
Python
input()[::-1]
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
#Component_Pascal
Component Pascal
  MODULE Queue; IMPORT Boxes; TYPE Instance* = POINTER TO LIMITED RECORD size: LONGINT; first,last: LONGINT; _queue: POINTER TO ARRAY OF Boxes.Box; END;   PROCEDURE (self: Instance) Initialize(capacity: LONGINT),NEW; BEGIN self.size := 0; self.first := 0; self.last := 0; NEW(self._queue,capacity) END Initialize;   PROCEDURE New*(capacity: LONGINT): Instance; VAR aQueue: Instance; BEGIN NEW(aQueue);aQueue.Initialize(capacity);RETURN aQueue END New;   PROCEDURE (self: Instance) IsEmpty*(): BOOLEAN, NEW; BEGIN RETURN self.size = 0; END IsEmpty;   PROCEDURE (self: Instance) Capacity*(): LONGINT, NEW; BEGIN RETURN LEN(self._queue) END Capacity;   PROCEDURE (self: Instance) Size*(): LONGINT, NEW; BEGIN RETURN self.size END Size;   PROCEDURE (self: Instance) IsFull*(): BOOLEAN, NEW; BEGIN RETURN self.size = self.Capacity() END IsFull;   PROCEDURE (self: Instance) Push*(b: Boxes.Box), NEW; VAR i, j, newCapacity, oldSize: LONGINT; queue: POINTER TO ARRAY OF Boxes.Box; BEGIN INC(self.size); self._queue[self.last] := b; self.last := (self.last + 1) MOD self.Capacity(); IF self.IsFull() THEN (* grow queue *) newCapacity := self.Capacity() + (self.Capacity() DIV 2); (* new queue *) NEW(queue,newCapacity); (* move data from old to new queue *) i := self.first; j := 0; oldSize := self.Capacity() - self.first + self.last; WHILE (j < oldSize) & (j < newCapacity - 1) DO queue[j] := self._queue[i]; i := (i + 1) MOD newCapacity;INC(j) END; self._queue := queue;self.first := 0;self.last := j END END Push;   PROCEDURE (self: Instance) Pop*(): Boxes.Box, NEW; VAR b: Boxes.Box; BEGIN ASSERT(~self.IsEmpty()); DEC(self.size); b := self._queue[self.first]; self._queue[self.first] := NIL; self.first := (self.first + 1) MOD self.Capacity(); RETURN b END Pop;   END Queue.  
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.
#ERRE
ERRE
  PROGRAM QUATERNION   !$DOUBLE   TYPE QUATERNION=(A,B,C,D)   DIM Q:QUATERNION,Q1:QUATERNION,Q2:QUATERNION     DIM R:QUATERNION,S:QUATERNION,T:QUATERNION   PROCEDURE NORM(T.->NORM) NORM=SQR(T.A*T.A+T.B*T.B+T.C*T.C+T.D*T.D) END PROCEDURE   PROCEDURE NEGATIVE(T.->T.) T.A=-T.A T.B=-T.B T.C=-T.C T.D=-T.D END PROCEDURE   PROCEDURE CONJUGATE(T.->T.) T.A=T.A T.B=-T.B T.C=-T.C T.D=-T.D END PROCEDURE   PROCEDURE ADD_REAL(T.,REAL->T.) T.A=T.A+REAL T.B=T.B T.C=T.C T.D=T.D END PROCEDURE   PROCEDURE ADD(T.,S.->T.) T.A=T.A+S.A T.B=T.B+S.B T.C=T.C+S.C T.D=T.D+S.D END PROCEDURE   PROCEDURE MULT_REAL(T.,REAL->T.) T.A=T.A*REAL T.B=T.B*REAL T.C=T.C*REAL T.D=T.D*REAL END PROCEDURE   PROCEDURE MULT(T.,S.->R.) R.A=T.A*S.A-T.B*S.B-T.C*S.C-T.D*S.D R.B=T.A*S.B+T.B*S.A+T.C*S.D-T.D*S.C R.C=T.A*S.C-T.B*S.D+T.C*S.A+T.D*S.B R.D=T.A*S.D+T.B*S.C-T.C*S.B+T.D*S.A END PROCEDURE   PROCEDURE PRINTQ(T.) PRINT("(";T.A;",";T.B;",";T.C;",";T.D;")") END PROCEDURE   BEGIN Q.A=1 Q.B=2 Q.C=3 Q.D=4 Q1.A=2 Q1.B=3 Q1.C=4 Q1.D=5 Q2.A=3 Q2.B=4 Q2.C=5 Q2.D=6 REAL=7   NORM(Q.->NORM) PRINT("Norm(q)=";NORM)   NEGATIVE(Q.->T.) PRINT("Negative(q) =";) PRINTQ(T.)   CONJUGATE(Q.->T.) PRINT("Conjugate(q) =";) PRINTQ(T.)   ADD_REAL(Q.,REAL->T.) PRINT("q + real =";) PRINTQ(T.)   ! addition is commutative ADD(Q1.,Q2.->T.) PRINT("q1 + q2 =";) PRINTQ(T.)   ADD(Q2.,Q1.->T.) PRINT("q2 + q1 = ";) PRINTQ(T.)   MULT_REAL(Q.,REAL->T.) PRINT("q * real =";) PRINTQ(T.)   ! multiplication is not commutative MULT(Q1.,Q2.->R.) PRINT("q1 * q2=";) PRINTQ(R.)   MULT(Q2.,Q1.->R.) PRINT("q2 * q1=";) PRINTQ(R.) 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.
#Brainf.2A.2A.2A
Brainf***
->+>+++>>+>++>+>+++>>+>++>>>+>+>+>++>+>>>>+++>+>>++>+>+++>>++>++>>+>>+>++>++>+>>>>+++>+>>>>++>++>>>>+>>++>+>+++>>>++>>++++++>>+>>++> +>>>>+++>>+++++>>+>+++>>>++>>++>>+>>++>+>+++>>>++>>+++++++++++++>>+>>++>+>+++>+>+++>>>++>>++++>>+>>++>+>>>>+++>>+++++>>>>++>>>>+>+>+ +>>+++>+>>>>+++>+>>>>+++>+>>>>+++>>++>++>+>+++>+>++>++>>>>>>++>+>+++>>>>>+++>>>++>+>+++>+>+>++>>>>>>++>>>+>>>++>+>>>>+++>+>>>+>>++>+ >++++++++++++++++++>>>>+>+>>>+>>++>+>+++>>>++>>++++++++>>+>>++>+>>>>+++>>++++++>>>+>++>>+++>+>+>++>+>+++>>>>>+++>>>+>+>>++>+>+++>>>+ +>>++++++++>>+>>++>+>>>>+++>>++++>>+>+++>>>>>>++>+>+++>>+>++>>>>+>+>++>+>>>>+++>>+++>>>+[[->>+<<]<+]+++++[->+++++++++<]>.[+]>> [<<+++++++[->+++++++++<]>-.------------------->-[-<.<+>>]<[+]<+>>>]<<<[-[-[-[>>+<++++++[->+++++<]]>++++++++++++++<]>+++<]++++++ [->+++++++<]>+<<<-[->>>++<<<]>[->>.<<]<<]
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
#Maple
Maple
q := queue[new](); queue[enqueue](q,1); queue[enqueue](q,2); queue[enqueue](q,3); queue[empty](q); >>>false queue[dequeue](q); >>>1 queue[dequeue](q); >>>2 queue[dequeue](q); >>>3 queue[empty](q); >>>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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Empty[a_] := If[Length[a] == 0, True, False] SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem] SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]   Queue = {} -> {} Empty[Queue] -> True Push[Queue, "1"] -> {"1"} EmptyQ[Queue] ->False Pop[Queue] ->1 Pop[Queue] ->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.
#Kotlin
Kotlin
// version 1.1.2   const val MAX = Int.MAX_VALUE val rand = java.util.Random()   fun partition(list:IntArray, left: Int, right:Int, pivotIndex: Int): Int { val pivotValue = list[pivotIndex] list[pivotIndex] = list[right] list[right] = pivotValue var storeIndex = left for (i in left until right) { if (list[i] < pivotValue) { val tmp = list[storeIndex] list[storeIndex] = list[i] list[i] = tmp storeIndex++ } } val temp = list[right] list[right] = list[storeIndex] list[storeIndex] = temp return storeIndex }   tailrec fun quickSelect(list: IntArray, left: Int, right: Int, k: Int): Int { if (left == right) return list[left] var pivotIndex = left + Math.floor((rand.nextInt(MAX) % (right - left + 1)).toDouble()).toInt() pivotIndex = partition(list, left, right, pivotIndex) if (k == pivotIndex) return list[k] else if (k < pivotIndex) return quickSelect(list, left, pivotIndex - 1, k) else return quickSelect(list, pivotIndex + 1, right, k) }   fun main(args: Array<String>) { val list = intArrayOf(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) val right = list.size - 1 for (k in 0..9) { print(quickSelect(list, 0, right, k)) if (k < 9) print(", ") } println() }
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
#Go
Go
package main   import ( "errors" "fmt" "strconv" "strings" )   func main() { rf, err := rangeFormat([]int{ 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, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) }   func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
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
#Maxima
Maxima
load(distrib)$   random_normal(1.0, 0.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
#MAXScript
MAXScript
arr = #() for i in 1 to 1000 do ( a = random 0.0 1.0 b = random 0.0 1.0 c = 1.0 + 0.5 * sqrt (-2*log a) * cos (360*b) -- Maxscript cos takes degrees append arr c )
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
#OCaml
OCaml
#use "topfind" #require "inifiles" open Inifiles   let print_field ini (label, field) = try let v = ini#getval "params" field in Printf.printf "%s: %s\n" label v with Invalid_element _ -> Printf.printf "%s: not defined\n" label   let () = let ini = new inifile "./conf.ini" in let lst = [ "Full name", "FULLNAME"; "likes", "FAVOURITEFRUIT"; "needs peeling", "NEEDSPEELING"; "seeds removed", "SEEDSREMOVED"; ] in List.iter (print_field ini) lst;   let v = ini#getaval "params" "OTHERFAMILY" in print_endline "other family:"; List.iter (Printf.printf "- %s\n") v; ;;
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
#Lasso
Lasso
define range_expand(expression::string) => { local(parts) = regexp(`^(-?\d+)-(-?\d+)$`)   return ( with elm in #expression->split(`,`) let isRange = #parts->setInput(#elm)&matches select #isRange  ? (integer(#parts->matchString(1)) to integer(#parts->matchString(2)))->asString | integer(#elm)->asString )->join(', ') }   range_expand(`-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
#Liberty_BASIC
Liberty BASIC
print ExpandRange$( "-6,-3--1,3-5,7-11,14,15,17-20") end   function ExpandRange$( compressed$) for i = 1 to ItemCount( compressed$, ",") item$ = word$( compressed$, i, ",") dash = instr( item$, "-", 2) 'dash that is not the first character, is a separator if dash then for k = val( left$( item$, dash - 1)) to val( mid$( item$, dash + 1)) ExpandRange$ = ExpandRange$ + str$( k) + "," next k else ExpandRange$ = ExpandRange$ + item$ + "," end if next i ExpandRange$ = left$( ExpandRange$, len( ExpandRange$) - 1) end function   function ItemCount( list$, separator$) while word$(list$, ItemCount + 1, separator$) <> "" ItemCount = ItemCount + 1 wend end function
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.
#Logo
Logo
while [not eof?] [print readline]
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.
#Lua
Lua
filename = "input.txt" fp = io.open( filename, "r" )   for line in fp:lines() do print( line ) end   fp: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
#Quackery
Quackery
[ dup nest? if [ [] swap witheach [ nested swap join ] ] ] is reverse ( x --> x )
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
#Cowgol
Cowgol
include "strings.coh"; include "malloc.coh";   # Define types. The calling code is expected to provide a QueueData type. record QueueItem is data: QueueData; next: [QueueItem]; end record;   record QueueMeta is head: [QueueItem]; tail: [QueueItem]; end record;   typedef Queue is [QueueMeta]; const Q_NONE := 0 as [QueueItem];   # Allocate and free the queue datastructure. sub MakeQueue(): (q: Queue) is q := Alloc(@bytesof QueueMeta) as Queue; q.head := Q_NONE; q.tail := Q_NONE; end sub;   sub FreeQueue(q: Queue) is var cur := q.head; while cur != Q_NONE loop var next := cur.next; Free(cur as [uint8]); cur := next; end loop; Free(q as [uint8]); end sub;   # Check if queue is empty. sub QueueEmpty(q: Queue): (r: uint8) is r := 0; if q.head == Q_NONE then r := 1; end if; end sub;   # Enqueue and dequeue data. Cowgol has no exceptions, so the calling code # should check QueueEmpty first. sub Enqueue(q: Queue, d: QueueData) is var item := Alloc(@bytesof QueueItem) as [QueueItem]; item.data := d; item.next := Q_NONE; if q.head == Q_NONE then q.head := item; else q.tail.next := item; end if; q.tail := item; end sub;   sub Dequeue(q: Queue): (d: QueueData) is d := q.head.data; var cur := q.head; q.head := q.head.next; Free(cur as [uint8]); if q.head == Q_NONE then q.tail := Q_NONE; end if; end sub;
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.
#Euphoria
Euphoria
function norm(sequence q) return sqrt(power(q[1],2)+power(q[2],2)+power(q[3],2)+power(q[4],2)) end function   function conj(sequence q) q[2..4] = -q[2..4] return q end function   function add(object q1, object q2) if atom(q1) != atom(q2) then if atom(q1) then q1 = {q1,0,0,0} else q2 = {q2,0,0,0} end if end if return q1+q2 end function   function mul(object q1, object q2) if sequence(q1) and sequence(q2) then return { q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] - q1[4]*q2[4], q1[1]*q2[2] + q1[2]*q2[1] + q1[3]*q2[4] - q1[4]*q2[3], q1[1]*q2[3] - q1[2]*q2[4] + q1[3]*q2[1] + q1[4]*q2[2], q1[1]*q2[4] + q1[2]*q2[3] - q1[3]*q2[2] + q1[4]*q2[1] } else return q1*q2 end if end function   function quats(sequence q) return sprintf("%g + %gi + %gj + %gk",q) end function   constant q = {1, 2, 3, 4}, q1 = {2, 3, 4, 5}, q2 = {5, 6, 7, 8}, r = 7   printf(1, "norm(q) = %g\n", norm(q)) printf(1, "-q = %s\n", {quats(-q)}) printf(1, "conj(q) = %s\n", {quats(conj(q))}) printf(1, "q + r = %s\n", {quats(add(q,r))}) printf(1, "q1 + q2 = %s\n", {quats(add(q1,q2))}) printf(1, "q1 * q2 = %s\n", {quats(mul(q1,q2))}) printf(1, "q2 * q1 = %s\n", {quats(mul(q2,q1))})
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.
#Burlesque
Burlesque
blsq ) "I'm a quine." "I'm a 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
#Nemerle
Nemerle
mutable q = Queue(); // or use immutable version as per Haskell example def empty = q.IsEmpty(); // true at this point q.Push(empty); // or Enqueue(), or Add() def a = q.Pop(); // or Dequeue() or Take()
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   -- Queue Usage Demonstration Program ------------------------------------------- method main(args = String[]) public constant kew = RCQueueImpl() do say kew.pop() catch ex = IndexOutOfBoundsException say ex.getMessage say end   melancholyDane = '' melancholyDane[0] = 4 melancholyDane[1] = 'To be' melancholyDane[2] = 'or' melancholyDane[3] = 'not to be?' melancholyDane[4] = 'That is the question.'   loop p_ = melancholyDane[0] to 1 by -1 kew.push(melancholyDane[p_]) end p_   loop while \kew.empty popped = kew.pop say popped '\-' end say; say   -- demonstrate stowing something other than a text string in the queue kew.push(melancholyDane) md = kew.pop loop l_ = 1 to md[0] say md[l_] '\-' end l_ say   return   -- Queue implementation -------------------------------------------------------- class RCQueueImpl properties private qqq = Deque   method RCQueueImpl() public qqq = ArrayDeque() return   method push(stuff) public qqq.push(stuff) return   method pop() public returns Rexx signals IndexOutOfBoundsException if qqq.isEmpty then signal IndexOutOfBoundsException('The queue is empty') return Rexx qqq.pop()   method empty() public binary returns boolean return qqq.isEmpty   method isTrue public constant binary returns boolean return 1 == 1   method isFalse public constant binary returns boolean return \isTrue  
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.
#Lua
Lua
function partition (list, left, right, pivotIndex) local pivotValue = list[pivotIndex] list[pivotIndex], list[right] = list[right], list[pivotIndex] local storeIndex = left for i = left, right do if list[i] < pivotValue then list[storeIndex], list[i] = list[i], list[storeIndex] storeIndex = storeIndex + 1 end end list[right], list[storeIndex] = list[storeIndex], list[right] return storeIndex end   function quickSelect (list, left, right, n) local pivotIndex while 1 do if left == right then return list[left] end pivotIndex = math.random(left, right) pivotIndex = partition(list, left, right, pivotIndex) if n == pivotIndex then return list[n] elseif n < pivotIndex then right = pivotIndex - 1 else left = pivotIndex + 1 end end end   math.randomseed(os.time()) local vec = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4} for i = 1, 10 do print(i, quickSelect(vec, 1, #vec, i) .. " ") end
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
#Groovy
Groovy
def range = { s, e -> s == e ? "${s}," : s == e - 1 ? "${s},${e}," : "${s}-${e}," }   def compressList = { list -> def sb, start, end (sb, start, end) = [''<<'', list[0], list[0]] for (i in list[1..-1]) { (sb, start, end) = i == end + 1 ? [sb, start, i] : [sb << range(start, end), i, i] } (sb << range(start, end))[0..-2].toString() }   def compressRanges = { expanded -> compressList(Eval.me('[' + expanded + ']')) }
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
#Metafont
Metafont
numeric col[];   m := 0;  % m holds the mean, for testing purposes for i = 1 upto 1000: col[i] := 1 + .5normaldeviate; m := m + col[i]; endfor   % testing m := m / 1000;  % finalize the computation of the mean   s := 0;  % in s we compute the standard deviation for i = 1 upto 1000: s := s + (col[i] - m)**2; endfor s := sqrt(s / 1000);   show m, s;  % and let's show that really they get what we wanted end
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
#MiniScript
MiniScript
randNormal = function(mean=0, stddev=1) return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev end function   x = [] for i in range(1,1000) x.push randNormal(1, 0.5) 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
#ooRexx
ooRexx
  #!/usr/bin/rexx /*.----------------------------------------------------------------------.*/ /*|readconfig: Read keyword value pairs from a configuration file into |*/ /*| Rexx variables. |*/ /*| |*/ /*|Usage: |*/ /*| .-~/rosetta.conf-. |*/ /*|>>-readconfig-+----------------+------------------------------------><|*/ /*| |-configfilename-| |*/ /*| |-- -? ----------| |*/ /*| |-- -h ----------| |*/ /*| '- --help -------' |*/ /*| |*/ /*|where |*/ /*| configfilename |*/ /*| is the name of the configuration file to be processed. if not|*/ /*| specified, ~/rosetta.conf is used. |*/ /*| |*/ /*|All values retrieved from the configuration file are stored in |*/ /*|compound variables with the stem config. Variables with multiple |*/ /*|values have a numeric index appended, and the highest index number |*/ /*|is stored in the variable with index 0; e.g. if CONFIG.OTHERFAMILY.1 |*/ /*|and CONFIG.OTHERFAMILY.2 have values assigned, CONFIG.OTHERFAMILY.0 = |*/ /*|2. |*/ /*|-?, -h or --help all cause this documentation to be displayed. |*/ /*| |*/ /*|This program was tested using Open Object Rexx 4.1.1. It should work |*/ /*|with most other dialects as well. |*/ /*'----------------------------------------------------------------------'*/ call usage arg(1) trace normal signal on any name error   /* Prepare for processing the configuration file. */ keywords = 'FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY'   /* Set default values for configuration variables here */ config_single?. = 1 config. = '' config.NEEDSPEELING = 0 config.SEEDSREMOVED = 1   /* Validate command line inputs. */ parse arg configfilename   if length(configfilename) = 0 then configfilename = '~/rosetta.conf'   configfile = stream(configfilename,'COMMAND','QUERY EXISTS')   if length(configfile) = 0 then do say configfilename 'was not found.' exit 28 end   signal on notready /* if an I/O error occurs. */   /* Open the configuration file. */ response = stream(configfile,'COMMAND','OPEN READ SHARED')   /* Parse the contents of the configuration file into variables. */ do while lines(configfile) > 0 statement = linein(configfile)   select when left(statement,1) = '#', | left(statement,1) = ';', | length(strip(statement)) = 0, then /* a comment or a blank line. */ nop /* skip it. */   otherwise do if pos('=',word(statement,1)) > 0, | left(word(statement,2),1) = '=', then /* a keyword/value pair with = between. */ parse var statement keyword '=' value   else /* a keyword/value pair with no =. */ parse var statement keyword value   keyword = translate(strip(keyword)) /* make it uppercase. */ single? = pos(',',value) = 0 /* a single value, or multiple values? */ call value 'CONFIG_single?.'keyword,single? /* remember. */   if single? then do if length(value) > 0 then call value 'CONFIG.'keyword,strip(value) end /* strip keeps internal whitespace only. */   else /* store each value with its index. */ do v = 1 by 1 while length(value) > 0 parse var value value1 ',' value   if length(value1) > 0 then do call value 'CONFIG.'keyword'.'v,strip(value1) call value 'CONFIG.'keyword'.0',v /* remember this. */ end end end end end   /* Display the values of the configuration variables. */ say 'Values associated with configuration file' configfilename':' say   do while words(keywords) > 0 parse var keywords keyword keywords   if value('CONFIG_single?.'keyword) then say right(keyword,20) '= "'value('CONFIG.'keyword)'"'   else do lastv = value('CONFIG.'keyword'.0')   do v = 1 to lastv say right(keyword,20-(length(v)+2))'['v'] = "'value('CONFIG.'keyword'.'v)'"' end end end   say   notready: /* I/O errors come here. */ filestatus = stream(configfile,'STATE')   if filestatus \= 'READY' then say 'An I/O error occurred; the file status is' filestatus'.'   response = stream(configfile,'COMMAND','CLOSE')   error: /*? = sysdumpvariables() */ /* see everything Rexx used. */ exit   usage: procedure trace normal   if arg(1) = '-h', | arg(1) = '-?', | arg(1) = '--help' then do line = '/*|' say   do l = 3 by 1 while line~left(3) = '/*|' line = sourceline(l) parse var line . '/*|' text '|*/' . say text end   say exit 0 end return  
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
#Lingo
Lingo
-- Note: currently does not support extra white space in input string on expandRange (str) res = "" _player.itemDelimiter = "," cnt = str.item.count repeat with i = 1 to cnt part = str.item[i] pos = offset("-", part.char[2..part.length]) if pos>0 then a = integer(part.char[1..pos]) b = integer(part.char[pos+2..part.length]) repeat with j = a to b put j&"," after res end repeat else put part&"," after res end if end repeat delete the last char of res return res 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
#LiveCode
LiveCode
function range beginning ending stepping local tRange, tBegin, tEnd, tstep if stepping is empty or stepping is 0 then put 1 into tstep else put abs(stepping) into tstep end if   if ending is empty or isNumber(ending) is not true then put 0 into tEnd else put ending into tEnd end if   if beginning is empty or isNumber(beginning) is not true then put 0 into tBegin else put beginning into tBegin end if   repeat with r = tBegin to tEnd step tstep put space & r after tRange end repeat return word 1 to -1 of tRange end range   function expandRange rangeExpr put rangeExpr into tRange split tRange by comma repeat with n = 1 to the number of elements of tRange if matchText(tRange[n],"^(\-*\d+)\-(\-*\d+)",beginning, ending) then put range(beginning, ending, 1) & space after z else put tRange[n] & space after z end if end repeat return z 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.
#M2000_Interpreter
M2000 Interpreter
  Module checkit { \\ prepare a file document a$ a$={First Line Second line Third Line } Save.Doc a$, "checkthis.txt", 0 ' 0 for UTF-16LE Flush Open "checkthis.txt" For Wide Input as #F While not Eof(#f) { Data Seek(#f) Line Input #F, b$ Print b$ } Close #f Dim Index() \\ copy stack to index(), flush stack Index()=Array([]) \\ change base to base 1 Dim Base 1, Index(len(index())) Open "checkthis.txt" For Wide Input as #F Seek#F, Index(2) Line Input #F, b$ Print b$ ' print second line Close #f \\ prepare Ansi file Print "Ansi File" Save.Doc a$, "checkthis.txt", 1033 ' we use specific locale Flush \\ flush the stack to get indexes oldlocale=locale locale 1033 \\ no Wide clause Open "checkthis.txt" For Input as #F While not Eof(#f) { Data Seek(#f) Line Input #F, b$ Print b$ } Close #f Dim Index() \\ copy stack to index(), flush stack Index()=Array([]) \\ change base to base 1 Dim Base 1, Index(len(index())) Open "checkthis.txt" For Input as #F Seek#F, Index(2) Line Input #F, b$ Print b$ ' print second line Close #f locale oldlocale } checkit  
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.
#Maple
Maple
path := "file.txt": while (true) do input := readline(path): if input = 0 then break; end if: #The line is stored in input end do:
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
#Qi
Qi
(REVERSE "ABCD")
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
#D
D
queue: { :start 0 :end 0 }   enqueue q item: set-to q q!end item set-to q :end ++ q!end   dequeue q: if empty q: Raise :value-error "popping from empty queue" q! q!start delete-from q q!start set-to q :start ++ q!start   empty q: = q!start q!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.
#F.23
F#
open System   [<Struct; StructuralEquality; NoComparison>] type Quaternion(r : float, i : float, j : float, k : float) = member this.A = r member this.B = i member this.C = j member this.D = k   new (f : float) = Quaternion(f, 0., 0., 0.)   static member (~-) (q : Quaternion) = Quaternion(-q.A, -q.B, -q.C, -q.D)   static member (+) (q1 : Quaternion, q2 : Quaternion) = Quaternion(q1.A + q2.A, q1.B + q2.B, q1.C + q2.C, q1.D + q2.D) static member (+) (q : Quaternion, r : float) = q + Quaternion(r) static member (+) (r : float, q: Quaternion) = Quaternion(r) + q   static member (*) (q1 : Quaternion, q2 : Quaternion) = Quaternion( q1.A * q2.A - q1.B * q2.B - q1.C * q2.C - q1.D * q2.D, q1.A * q2.B + q1.B * q2.A + q1.C * q2.D - q1.D * q2.C, q1.A * q2.C - q1.B * q2.D + q1.C * q2.A + q1.D * q2.B, q1.A * q2.D + q1.B * q2.C - q1.C * q2.B + q1.D * q2.A) static member (*) (q : Quaternion, r : float) = q * Quaternion(r) static member (*) (r : float, q: Quaternion) = Quaternion(r) * q   member this.Norm = Math.Sqrt(r * r + i * i + j * j + k * k)   member this.Conjugate = Quaternion(r, -i, -j, -k)   override this.ToString() = sprintf "Q(%f, %f, %f, %f)" r i j k   [<EntryPoint>] let main argv = let q = Quaternion(1., 2., 3., 4.) let q1 = Quaternion(2., 3., 4., 5.) let q2 = Quaternion(3., 4., 5., 6.) let r = 7.   printfn "q = %A" q printfn "q1 = %A" q1 printfn "q2 = %A" q2 printfn "r = %A" r   printfn "q.Norm = %A" q.Norm printfn "q1.Norm = %A" q1.Norm printfn "q2.Norm = %A" q2.Norm   printfn "-q = %A" -q printfn "q.Conjugate = %A" q.Conjugate   printfn "q + r = %A" (q + (Quaternion r)) printfn "q1 + q2 = %A" (q1 + q2) printfn "q2 + q1 = %A" (q2 + q1)   printfn "q * r = %A" (q * r) printfn "q1 * q2 = %A" (q1 * q2) printfn "q2 * q1 = %A" (q2 * q1)   printfn "q1*q2 %s q2*q1" (if (q1 * q2) = (q2 * q1) then "=" else "<>") printfn "q %s Q(1.,2.,3.,4.)" (if q = Quaternion(1., 2., 3., 4.) then "=" else "<>") 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.
#C
C
#include <stdio.h>   static char sym[] = "\n\t\\\"";   int main(void) { const char *code = "#include <stdio.h>%c%cstatic char sym[] = %c%cn%ct%c%c%c%c%c;%c%cint main(void) {%c%cconst char *code = %c%s%c;%c%cprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);%c%c%creturn 0;%c}%c"; printf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);   return 0; }  
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
#Nim
Nim
import deques   var queue = initDeque[int]()   queue.addLast(26) queue.addLast(99) queue.addLast(2) echo "Queue size: ", queue.len() echo "Popping: ", queue.popFirst() echo "Popping: ", queue.popFirst() echo "Popping: ", queue.popFirst() echo "Popping: ", queue.popFirst()
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
#Objeck
Objeck
  class Test { function : Main(args : String[]) ~ Nil { q := Struct.IntQueue->New(); q->Add(1); q->Add(2); q->Add(3);   q->Remove()->PrintLine(); q->Remove()->PrintLine(); q->Remove()->PrintLine();   q->IsEmpty()->PrintLine(); } }  
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.
#Maple
Maple
part := proc(arr, left, right, pivot) local val,safe,i: val := arr[pivot]: arr[pivot], arr[right] := arr[right], arr[pivot]: safe := left: for i from left to right do if arr[i] < val then arr[safe], arr[i] := arr[i], arr[safe]: safe := safe + 1: end if: end do: arr[right], arr[safe] := arr[safe], arr[right]: return safe: end proc:   quickselect := proc(arr,k) local pivot,left,right: left,right := 1,numelems(arr): while(true)do if left = right then return arr[left]: end if: pivot := trunc((left+right)/2); pivot := part(arr, left, right, pivot): if k = pivot then return arr[k]: elif k < pivot then right := pivot-1: else left := pivot+1: end if: end do: end proc: roll := rand(1..20): demo := Array([seq(roll(), i=1..20)]); map(x->printf("%d ", x), demo): print(quickselect(demo,7)): print(quickselect(demo,14)):
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Quickselect[ds : DataStructure["DynamicArray", _], k_] := QuickselectWorker[ds, 1, ds["Length"], k]; QuickselectWorker[ds_, low0_, high0_, k_] := Module[{pivotIdx, low = low0, high = high0}, While[True, If[low === high, Return[ds["Part", low]] ]; pivotIdx = SelectPartition[ds, low, high]; Which[k === pivotIdx, Return[ds["Part", k]], k < pivotIdx, high = pivotIdx - 1, True, low = pivotIdx + 1 ] ] ]; SelectPartition[ds_, low_, high_] := Module[{pivot = ds["Part", high], i = low, j}, Do[ If[ds["Part", j] <= pivot, ds["SwapPart", i, j]; i = i + 1 ] , {j, low, high - 1} ]; ds["SwapPart", i, high]; i ]; ds = CreateDataStructure["DynamicArray", {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]; Quickselect[ds, #] & /@ 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
#Haskell
Haskell
import Data.List (intercalate)   extractRange :: [Int] -> String extractRange = intercalate "," . f where f :: [Int] -> [String] f (x1 : x2 : x3 : xs) | x1 + 1 == x2 && x2 + 1 == x3 = (show x1 ++ '-' : show xn) : f xs' where (xn, xs') = g (x3 + 1) xs g a (n : ns) | a == n = g (a + 1) ns | otherwise = (a - 1, n : ns) g a [] = (a - 1, []) f (x : xs) = show x : f xs f [] = []
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
#Mirah
Mirah
import java.util.Random   list = double[999] mean = 1.0 std = 0.5 rng = Random.new 0.upto(998) do | i | list[i] = mean + std * rng.nextGaussian end  
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
П7 <-> П8 1/x П6 ИП6 П9 СЧ П6 1/x ln ИП8 * 2 * КвКор ИП9 2 * пи * sin * ИП7 + С/П БП 05
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
#Pascal
Pascal
#!/usr/bin/instantfpc   {$if not defined(fpc) or (fpc_fullversion < 20600)} {$error FPC 2.6.0 or greater required} {$endif}   {$mode objfpc}{$H+}   uses Classes,SysUtils,gvector,ghashmap;   type TStrHashCaseInsensitive = class class function hash(s: String; n: Integer): Integer; end;   class function TStrHashCaseInsensitive.hash(s: String; n: Integer): Integer; var x: Integer; c: Char; begin x := 0; for c in UpCase(s) do Inc(x,Ord(c)); Result := x mod n; end;   type TConfigValues = specialize TVector<String>; TConfigStorage = class(specialize THashMap<String,TConfigValues,TStrHashCaseInsensitive>) destructor Destroy; override; end;   destructor TConfigStorage.Destroy; var It: TIterator; begin if Size > 0 then begin It := Iterator; repeat It.Value.Free; until not It.Next; It.Free; end; inherited Destroy; end;   var ConfigStrings,ConfigValues: TStrings; ConfigStorage: TConfigStorage; ConfigLine,ConfigName,ConfigValue: String; SeparatorPos: Integer; begin ConfigStrings := TStringList.Create; ConfigValues := TStringList.Create; ConfigValues.Delimiter := ','; ConfigValues.StrictDelimiter := true; ConfigStorage := TConfigStorage.Create;   ConfigStrings.LoadFromFile('config.test'); for ConfigLine in ConfigStrings do begin if Length(ConfigLine) > 0 then begin case ConfigLine[1] of '#',';': ; // ignore else begin // look for = first SeparatorPos := Pos('=',ConfigLine); // if not found, then look for space if SeparatorPos = 0 then begin SeparatorPos := Pos(' ',ConfigLine); end; // found space if SeparatorPos <> 0 then begin ConfigName := UpCase(Copy(ConfigLine,1,SeparatorPos - 1)); ConfigValues.DelimitedText := Copy(ConfigLine,SeparatorPos + 1,Length(ConfigLine) - SeparatorPos); // no = or space found, take the whole line as a key name end else begin ConfigName := UpCase(Trim(ConfigLine)); end; if not ConfigStorage.Contains(ConfigName) then begin ConfigStorage[ConfigName] := TConfigValues.Create; end; for ConfigValue in ConfigValues do begin ConfigStorage[ConfigName].PushBack(Trim(ConfigValue)); end; end; end; end; end;   WriteLn('FULLNAME = ' + ConfigStorage['FULLNAME'][0]); WriteLn('FAVOURITEFRUIT = ' + ConfigStorage['FAVOURITEFRUIT'][0]); WriteLn('NEEDSPEELING = ' + BoolToStr(ConfigStorage.Contains('NEEDSPEELING'),true)); WriteLn('SEEDSREMOVED = ' + BoolToStr(ConfigStorage.Contains('SEEDSREMOVED'),true)); WriteLn('OTHERFAMILY(1) = ' + ConfigStorage['OTHERFAMILY'][0]); WriteLn('OTHERFAMILY(2) = ' + ConfigStorage['OTHERFAMILY'][1]);   ConfigStorage.Free; ConfigValues.Free; ConfigStrings.Free; 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
#Lua
Lua
function range(i, j) local t = {} for n = i, j, i<j and 1 or -1 do t[#t+1] = n end return t end   function expand_ranges(rspec) local ptn = "([-+]?%d+)%s?-%s?([-+]?%d+)" local t = {}   for v in string.gmatch(rspec, '[^,]+') do local s, e = v:match(ptn)   if s == nil then t[#t+1] = tonumber(v) else for i, n in ipairs(range(tonumber(s), tonumber(e))) do t[#t+1] = n end end end return t end   local ranges = "-6,-3--1,3-5,7-11,14,15,17-20" print(table.concat(expand_ranges(ranges), ', '))
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
strm=OpenRead["input.txt"]; If[strm=!=$Failed, While[line=!=EndOfFile, line=Read[strm]; (*Do something*) ]]; Close[strm];
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.
#MATLAB_.2F_Octave
MATLAB / Octave
  fid = fopen('foobar.txt','r'); if (fid < 0) printf('Error:could not open file\n') else while ~feof(fid), line = fgetl(fid); %% process line %% end; fclose(fid) 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
#R
R
revstring <- function(stringtorev) { return( paste( strsplit(stringtorev,"")[[1]][nchar(stringtorev):1] ,collapse="") ) }
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
queue: { :start 0 :end 0 }   enqueue q item: set-to q q!end item set-to q :end ++ q!end   dequeue q: if empty q: Raise :value-error "popping from empty queue" q! q!start delete-from q q!start set-to q :start ++ q!start   empty q: = q!start q!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.
#Factor
Factor
USING: generalizations io kernel locals math.quaternions math.vectors prettyprint sequences ; IN: rosetta-code.quaternion-type   : show ( quot -- ) [ unparse 2 tail but-last "= " append write ] [ call . ] bi  ; inline   : 2show ( quots -- ) [ 2curry show ] map-compose [ call ] each ; inline   : q+n ( q n -- q+n ) n>q q+ ;   [let { 1 2 3 4 } 7 { 2 3 4 5 } { 3 4 5 6 } :> ( q r q1 q2 ) q [ norm ] q [ vneg ] q [ qconjugate ] [ curry show ] 2tri@ { [ q r [ q+n ] ] [ q r [ q*n ] ] [ q1 q2 [ q+ ] ] [ q1 q2 [ q* ] ] [ q2 q1 [ q* ] ] } 2show ]
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.
#C.23
C#
class Program { static void Main() { var s = "class Program {{ static void Main() {{ var s = {0}{1}{0}; System.Console.WriteLine(s, (char)34, s); }} }}"; System.Console.WriteLine(s, (char)34, 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
#OCaml
OCaml
# let q = Queue.create ();; val q : '_a Queue.t = <abstr> # Queue.is_empty q;; - : bool = true # Queue.add 1 q;; - : unit = () # Queue.is_empty q;; - : bool = false # Queue.add 2 q;; - : unit = () # Queue.add 3 q;; - : unit = () # Queue.peek q;; - : int = 1 # Queue.length q;; - : int = 3 # Queue.iter (Printf.printf "%d, ") q; print_newline ();; 1, 2, 3, - : unit = () # Queue.take q;; - : int = 1 # Queue.take q;; - : int = 2 # Queue.peek q;; - : int = 3 # Queue.length q;; - : int = 1 # Queue.add 4 q;; - : unit = () # Queue.take q;; - : int = 3 # Queue.peek q;; - : int = 4 # Queue.take q;; - : int = 4 # Queue.is_empty q;; - : bool = 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.
#Mercury
Mercury
%%%-------------------------------------------------------------------   :- module quickselect_task.   :- interface. :- import_module io. :- pred main(io, io). :- mode main(di, uo) is det.   :- implementation. :- import_module array. :- import_module exception. :- import_module int. :- import_module list. :- import_module random. :- import_module random.sfc64. :- import_module string.   %%%------------------------------------------------------------------- %%% %%% Partitioning a subarray into two halves: one with elements less %%% than or equal to a pivot, the other with elements greater than or %%% equal to a pivot. %%% %%% The implementation is tail-recursive. %%%   :- pred partition(pred(T, T), T, int, int, array(T), array(T), int). :- mode partition(pred(in, in) is semidet, in, in, in, array_di, array_uo, out). partition(Less_than, Pivot, I_first, I_last, Arr0, Arr, I_pivot) :- I = I_first - 1, J = I_last + 1, partition_loop(Less_than, Pivot, I, J, Arr0, Arr, I_pivot).   :- pred partition_loop(pred(T, T), T, int, int, array(T), array(T), int). :- mode partition_loop(pred(in, in) is semidet, in, in, in, array_di, array_uo, out). partition_loop(Less_than, Pivot, I, J, Arr0, Arr, Pivot_index) :- if (I = J) then (Arr = Arr0, Pivot_index = I) else (I1 = I + 1, I2 = search_right(Less_than, Pivot, I1, J, Arr0), (if (I2 = J) then (Arr = Arr0, Pivot_index = J) else (J1 = J - 1, J2 = search_left(Less_than, Pivot, I2, J1, Arr0), swap(I2, J2, Arr0, Arr1), partition_loop(Less_than, Pivot, I2, J2, Arr1, Arr, Pivot_index)))).   :- func search_right(pred(T, T), T, int, int, array(T)) = int. :- mode search_right(pred(in, in) is semidet, in, in, in, in) = out is det. search_right(Less_than, Pivot, I, J, Arr0) = K :- if (I = J) then (I = K) else if Less_than(Pivot, Arr0^elem(I)) then (I = K) else (search_right(Less_than, Pivot, I + 1, J, Arr0) = K).   :- func search_left(pred(T, T), T, int, int, array(T)) = int. :- mode search_left(pred(in, in) is semidet, in, in, in, in) = out is det. search_left(Less_than, Pivot, I, J, Arr0) = K :- if (I = J) then (J = K) else if Less_than(Arr0^elem(J), Pivot) then (J = K) else (search_left(Less_than, Pivot, I, J - 1, Arr0) = K).   %%%------------------------------------------------------------------- %%% %%% Quickselect with a random pivot. %%% %%% The implementation is tail-recursive. One has to pass the routine %%% a random number generator of type M, attached to the IO state. %%% %%% I use a random pivot to get O(n) worst case *expected* running %%% time. Code using a random pivot is easy to write and read, and for %%% most purposes comes close enough to a criterion set by Scheme's %%% SRFI-132: "Runs in O(n) time." (See %%% https://srfi.schemers.org/srfi-132/srfi-132.html) %%% %%% Of course we are not bound here by SRFI-132, but still I respect %%% it as a guide. %%% %%% A "median of medians" pivot gives O(n) running time, but is more %%% complicated. (That is, of course, assuming you are not writing %%% your own random number generator and making it a complicated one.) %%%   %% quickselect/8 selects the (K+1)th largest element of Arr. :- pred quickselect(pred(T, T)::pred(in, in) is semidet, int::in, array(T)::array_di, array(T)::array_uo, T::out, M::in, io::di, io::uo) is det <= urandom(M, io). quickselect(Less_than, K, Arr0, Arr, Elem, M, !IO) :- bounds(Arr0, I_first, I_last), quickselect(Less_than, I_first, I_last, K, Arr0, Arr, Elem, M, !IO).   %% quickselect/10 selects the (K+1)th largest element of %% Arr[I_first..I_last]. :- pred quickselect(pred(T, T)::pred(in, in) is semidet, int::in, int::in, int::in, array(T)::array_di, array(T)::array_uo, T::out, M::in, io::di, io::uo) is det <= urandom(M, io). quickselect(Less_than, I_first, I_last, K, Arr0, Arr, Elem, M, !IO) :- if (0 =< K, K =< I_last - I_first) then (K_adjusted_for_range = K + I_first, quickselect_loop(Less_than, I_first, I_last, K_adjusted_for_range, Arr0, Arr, Elem, M, !IO)) else throw("out of range").   :- pred quickselect_loop(pred(T, T)::pred(in, in) is semidet, int::in, int::in, int::in, array(T)::array_di, array(T)::array_uo, T::out, M::in, io::di, io::uo) is det <= urandom(M, io). quickselect_loop(Less_than, I_first, I_last, K, Arr0, Arr, Elem, M, !IO) :- if (I_first = I_last) then (Arr = Arr0, Elem = Arr0^elem(I_first)) else (uniform_int_in_range(M, I_first, I_last - I_first + 1, I_pivot, !IO), Pivot = Arr0^elem(I_pivot),    %% Move the last element to where the pivot had been. Perhaps  %% the pivot was already the last element, of course. In any  %% case, we shall partition only from I_first to I_last - 1. Elem_last = Arr0^elem(I_last), Arr1 = (Arr0^elem(I_pivot) := Elem_last),    %% Partition the array in the range I_first..I_last - 1,  %% leaving out the last element (which now can be considered  %% garbage). partition(Less_than, Pivot, I_first, I_last - 1, Arr1, Arr2, I_final),    %% Now everything that is less than the pivot is to the left  %% of I_final.    %% Put the pivot at I_final, moving the element that had been  %% there to the end. If I_final = I_last, then this element is  %% actually garbage and will be overwritten with the pivot,  %% which turns out to be the greatest element. Otherwise, the  %% moved element is not less than the pivot and so the  %% partitioning is preserved. Elem_to_move = Arr2^elem(I_final), Arr3 = (Arr2^elem(I_last) := Elem_to_move), Arr4 = (Arr3^elem(I_final) := Pivot),    %% Compare I_final and K, to see what to do next. (if (I_final < K) then quickselect_loop(Less_than, I_final + 1, I_last, K, Arr4, Arr, Elem, M, !IO) else if (K < I_final) then quickselect_loop(Less_than, I_first, I_final - 1, K, Arr4, Arr, Elem, M, !IO) else (Arr = Arr4, Elem = Arr4^elem(I_final)))).   %%%-------------------------------------------------------------------   :- func example_numbers = list(int). example_numbers = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4].   main(!IO) :- (sfc64.init(P, S)), make_io_urandom(P, S, M, !IO), Print_kth_greatest = (pred(K::in, di, uo) is det --> print_kth_greatest(K, example_numbers, M)), Print_kth_least = (pred(K::in, di, uo) is det --> print_kth_least(K, example_numbers, M)), print("With < as order predicate: ", !IO), foldl(Print_kth_least, 1 `..` 10, !IO), print_line("", !IO), print("With > as order predicate: ", !IO), foldl(Print_kth_greatest, 1 `..` 10, !IO), print_line("", !IO).   :- pred print_kth_least(int::in, list(int)::in, M::in, io::di, io::uo) is det <= urandom(M, io). print_kth_least(K, Numbers_list, M, !IO) :- (array.from_list(Numbers_list, Arr0)), quickselect(<, K - 1, Arr0, _, Elem, M, !IO), print(" ", !IO), print(Elem, !IO).   :- pred print_kth_greatest(int::in, list(int)::in, M::in, io::di, io::uo) is det <= urandom(M, io). print_kth_greatest(K, Numbers_list, M, !IO) :- (array.from_list(Numbers_list, Arr0)),    %% Notice that the "Less_than" predicate is actually "greater  %% than". :) One can think of this as meaning that a greater number  %% has an *ordinal* that is "less than"; that is, it "comes before"  %% in the order. quickselect(>, K - 1, Arr0, _, Elem, M, !IO),   print(" ", !IO), print(Elem, !IO).     %%%------------------------------------------------------------------- %%% local variables: %%% mode: mercury %%% prolog-indent-width: 2 %%% end:
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary /** @see <a href="http://en.wikipedia.org/wiki/Quickselect">http://en.wikipedia.org/wiki/Quickselect</a> */   runSample(arg) return   -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method qpartition(list, ileft, iright, pivotIndex) private static pivotValue = list[pivotIndex] list = swap(list, pivotIndex, iright) -- Move pivot to end storeIndex = ileft loop i_ = ileft to iright - 1 if list[i_] <= pivotValue then do list = swap(list, storeIndex, i_) storeIndex = storeIndex + 1 end end i_ list = swap(list, iright, storeIndex) -- Move pivot to its final place return storeIndex   -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method qselectInPlace(list, k_, ileft = -1, iright = -1) public static if ileft = -1 then ileft = 1 if iright = -1 then iright = list[0]   loop label inplace forever pivotIndex = Random().nextInt(iright - ileft + 1) + ileft -- select pivotIndex between left and right pivotNewIndex = qpartition(list, ileft, iright, pivotIndex) pivotDist = pivotNewIndex - ileft + 1 select when pivotDist = k_ then do returnVal = list[pivotNewIndex] leave inplace end when k_ < pivotDist then iright = pivotNewIndex - 1 otherwise do k_ = k_ - pivotDist ileft = pivotNewIndex + 1 end end end inplace return returnVal   -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ method swap(list, i1, i2) private static if i1 \= i2 then do t1 = list[i1] list[i1] = list[i2] list[i2] = t1 end return list   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg samplelist if samplelist = '' | samplelist = '.' then samplelist = 9 8 7 6 5 0 1 2 3 4 items = samplelist.words say 'Input:' say ' 'samplelist.space(1, ',').changestr(',', ', ') say   say 'Using in-place version of the algorithm:' iv = '' loop k_ = 1 to items iv = iv qselectInPlace(buildIndexedString(samplelist), k_) end k_ say ' 'iv.space(1, ',').changestr(',', ', ') say   say 'Find the 4 smallest:' iv = '' loop k_ = 1 to 4 iv = iv qselectInPlace(buildIndexedString(samplelist), k_) end k_ say ' 'iv.space(1, ',').changestr(',', ', ') say   say 'Find the 3 largest:' iv = '' loop k_ = items - 2 to items iv = iv qselectInPlace(buildIndexedString(samplelist), k_) end k_ say ' 'iv.space(1, ',').changestr(',', ', ') say   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method buildIndexedString(samplelist) private static list = 0 list[0] = samplelist.words() loop k_ = 1 to list[0] list[k_] = samplelist.word(k_) end k_ return list  
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
#Icon_and_Unicon
Icon and Unicon
procedure main()   R := [ 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 ]   write("Input list  := ",list2string(R)) write("Extracted sting := ",s := range_extract(R) | "FAILED") end   procedure range_extract(R) #: return string/range representation of a list of unique integers local s,sep,low,high,x   every if integer(x:= !R) ~= x then fail # ensure all are integers, R := sort(set(R)) # unique, and sorted   s := sep := "" while s ||:= sep || ( low := high := get(R) ) do { # lower bound of range sep := "," while high := ( R[1] = high + 1 ) do get(R) # find the end of range if high > low+1 then s ||:= "-" || high # - record range of 3+ else if high = low+1 then push(R,high) # - range of 2, high becomes new low } return s end   procedure list2string(L) #: helper to convert list to string local s   every (s := "[ ") ||:= !L || " " return s || "]" end
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
#Modula-3
Modula-3
MODULE Rand EXPORTS Main;   IMPORT Random; FROM Math IMPORT log, cos, sqrt, Pi;   VAR rands: ARRAY [1..1000] OF LONGREAL;   (* Normal distribution. *) PROCEDURE RandNorm(): LONGREAL = BEGIN WITH rand = NEW(Random.Default).init() DO RETURN sqrt(-2.0D0 * log(rand.longreal())) * cos(2.0D0 * Pi * rand.longreal()); END; END RandNorm;   BEGIN FOR i := FIRST(rands) TO LAST(rands) DO rands[i] := 1.0D0 + 0.5D0 * RandNorm(); END; END Rand.
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
#Nanoquery
Nanoquery
list = {0} * 1000 mean = 1.0; std = 0.5 rng = new(Nanoquery.Util.Random)   for i in range(0, len(list) - 1) list[i] = mean + std * rng.getGaussian() 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
#Peloton
Peloton
* blank lines and lines beginning with # and ; should be ignored. * an all uppercase word defines a configuration symbol * no tail means a boolean true * a tail including a comma means a list * any other kind of tail is a string
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
#Maple
Maple
  ExpandRanges := proc( s :: string ) uses StringTools; local DoOne := proc( input ) uses StringTools; local lo, hi, pos; if IsDigit( input ) or input[ 1 ] = "-" and IsDigit( input[ 2 .. -1 ] ) then parse( input ) else pos := Search( "--", input ); if pos > 0 then lo := input[ 1 .. pos - 1 ]; hi := input[ 1 + pos .. -1 ]; elif input[ 1 ] = "-" then pos := FirstFromLeft( "-", input[ 2 .. -1 ] ); if pos = 0 then lo := input; hi := lo else lo := input[ 1 .. pos ]; hi := input[ 2 + pos .. -1 ]; end if; else pos := FirstFromLeft( "-", input ); if pos = 0 then error "incorrect syntax" end if; lo := input[ 1 .. pos - 1 ]; hi := input[ 1 + pos .. -1 ]; end if; lo := parse( lo ); hi := parse( hi ); seq( lo .. hi ) end if end proc: map( DoOne, map( Trim, Split( s, "," ) ) ) end proc:  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
rangeexpand[ rng_ ] := Module[ { step1 }, step1 = StringSplit[StringReplacePart[rng,"S",StringPosition[ rng,DigitCharacter~~"-"] /. {x_,y_} -> {y,y}],","]; Flatten@ToExpression/@Quiet@StringReplace[step1,x__~~"S"~~y__->"Range["<>x<>","<>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.
#Maxima
Maxima
/* Read a file and return a list of all lines */   readfile(name) := block( [v: [ ], f: openr(name), line], while stringp(line: readline(f)) do v: endcons(line, v), close(f), v )$
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
#Racket
Racket
#lang racket   (define (string-reverse s) (list->string (reverse (string->list s))))   (string-reverse "aoeu")
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
#Delphi
Delphi
program QueueDefinition;   {$APPTYPE CONSOLE}   uses System.Generics.Collections;   type TQueue = System.Generics.Collections.TQueue<Integer>;   TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end;   { TQueueHelper }   function TQueueHelper.Empty: Boolean; begin Result := count = 0; end;   function TQueueHelper.Pop: Integer; begin Result := Dequeue; end;   procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end;   var Queue: TQueue; i: Integer;   begin Queue := TQueue.Create;   for i := 1 to 1000 do Queue.push(i);   while not Queue.Empty do Write(Queue.pop, ' '); Writeln;   Queue.Free; Readln; 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.
#Forth
Forth
: quaternions 4 * floats ;   : qvariable create 1 quaternions allot ;   : q! ( a b c d q -- ) dup 3 floats + f! dup 2 floats + f! dup float+ f! f! ;   : qcopy ( src dest -- ) 1 quaternions move ;   : qnorm ( q -- f ) 0e 4 0 do dup f@ fdup f* f+ float+ loop drop fsqrt ;   : qf* ( q f -- ) 4 0 do dup f@ fover f* dup f! float+ loop fdrop drop ;   : qnegate ( q -- ) -1e qf* ;   : qconj ( q -- ) float+ 3 0 do dup f@ fnegate dup f! float+ loop drop ;   : qf+ ( q f -- ) dup f@ f+ f! ;   : q+ ( q1 q2 -- ) 4 0 do over f@ dup f@ f+ dup f! float+ swap float+ swap loop 2drop ;   \ access : q.a f@ ; : q.b float+ f@ ; : q.c 2 floats + f@ ; : q.d 3 floats + f@ ;   : q* ( dest q1 q2 -- ) over q.a dup q.d f* over q.b dup q.c f* f+ over q.c dup q.b f* f- over q.d dup q.a f* f+ over q.a dup q.c f* over q.b dup q.d f* f- over q.c dup q.a f* f+ over q.d dup q.b f* f+ over q.a dup q.b f* over q.b dup q.a f* f+ over q.c dup q.d f* f+ over q.d dup q.c f* f- over q.a dup q.a f* over q.b dup q.b f* f- over q.c dup q.c f* f- over q.d dup q.d f* f- 2drop 4 0 do dup f! float+ loop drop ;   : q= ( q1 q2 -- ? ) 4 0 do over f@ dup f@ f<> if 2drop false unloop exit then float+ swap float+ loop 2drop true ;   \ testing   : q. ( q -- ) [char] ( emit space 4 0 do dup f@ f. float+ loop drop [char] ) emit space ;   qvariable q 1e 2e 3e 4e q q! qvariable q1 2e 3e 4e 5e q1 q! create q2 3e f, 4e f, 5e f, 6e f, \ by hand   qvariable tmp qvariable m1 qvariable m2   q qnorm f. \ 5.47722557505166 q tmp qcopy tmp qnegate tmp q. \ ( -1. -2. -3. -4. ) q tmp qcopy tmp qconj tmp q. \ ( 1. -2. -3. -4. )   q m1 qcopy m1 7e qf+ m1 q. \ ( 8. 2. 3. 4. ) q m2 qcopy 7e m2 qf+ m2 q. \ ( 8. 2. 3. 4. ) m1 m2 q= . \ -1 (true)   q2 tmp qcopy q1 tmp q+ tmp q. \ ( 5. 7. 9. 11. )   q m1 qcopy m1 7e qf* m1 q. \ ( 7. 14. 21. 28. ) q m2 qcopy 7e m2 qf* m2 q. \ ( 7. 14. 21. 28. ) m1 m2 q= . \ -1 (true)   m1 q1 q2 q* m1 q. \ ( -56. 16. 24. 26. ) m2 q2 q1 q* m2 q. \ ( -56. 18. 20. 28. ) m1 m2 q= . \ 0 (false)
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.
#C.2B.2B
C++
#include<cstdio> int main(){char n[]=R"(#include<cstdio> int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}
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
#Oforth
Oforth
: testQueue | q i | Queue new ->q 20 loop: i [ i q push ] while ( q empty not ) [ q pop . ] ;
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
#ooRexx
ooRexx
  q = .queue~new -- create an instance q~queue(3) -- adds to the end, but this is at the front q~push(1) -- push on the front q~queue(2) -- add to the end say q~pull q~pull q~pull q~isempty -- should display all and be 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.
#Nim
Nim
proc qselect[T](a: var openarray[T]; k: int, inl = 0, inr = -1): T = var r = if inr >= 0: inr else: a.high var st = 0 for i in 0 ..< r: if a[i] > a[r]: continue swap a[i], a[st] inc st   swap a[r], a[st]   if k == st: a[st] elif st > k: qselect(a, k, 0, st - 1) else: qselect(a, k, st, inr)   let x = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]   for i in 0..9: var y = x echo i, ": ", qselect(y, 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
#J
J
fmt=: [: ;@(8!:0) [`]`({. ; (',-' {~ 2 < #) ; {:)@.(2 <. #) group=: <@fmt;.1~ 1 ~: 0 , 2 -~/\ ] extractRange=: ',' joinstring group
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.math.BigDecimal import java.math.MathContext   -- prologue numeric digits 20   -- get input, set defaults parse arg dp mu sigma ec . if mu = '' | mu = '.' then mean = 1.0; else mean = mu if sigma = '' | sigma = '.' then stdDeviation = 0.5; else stdDeviation = sigma if dp = '' | dp = '.' then displayPrecision = 1; else displayPrecision = dp if ec = '' | ec = '.' then elements = 1000; else elements = ec   -- set up RNG = Random() numberList = java.util.List numberList = ArrayList()   -- generate list of random numbers loop for elements rn = mean + stdDeviation * RNG.nextGaussian() numberList.add(BigDecimal(rn, MathContext.DECIMAL128)) end   -- report say "Mean: " mean say "Standard Deviation:" stdDeviation say "Precision: " displayPrecision say drawBellCurve(numberList, displayPrecision)   return   -- ----------------------------------------------------------------------------- method drawBellCurve(numberList = java.util.List, precision) static Collections.sort(numberList) val = BigDecimal lastN = '' nextN = '' loop val over numberList nextN = Rexx(val.toPlainString()).format(5, precision) select when lastN = '' then nop when lastN \= nextN then say lastN otherwise nop end say '*\-' lastN = nextN end val say lastN   return  
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
#Perl
Perl
my $fullname; my $favouritefruit; my $needspeeling; my $seedsremoved; my @otherfamily;   # configuration file definition. See read_conf_file below for explanation. my $conf_definition = { 'fullname' => [ 'string', \$fullname ], 'favouritefruit' => [ 'string', \$favouritefruit ], 'needspeeling' => [ 'boolean', \$needspeeling ], 'seedsremoved' => [ 'boolean', \$seedsremoved ], 'otherfamily' => [ 'array', \@otherfamily ], };   my $arg = shift; # take the configuration file name from the command line # (or first subroutine argument if this were in a sub) my $file; # this is going to be a file handle reference open $file, $arg or die "Can't open configuration file '$arg': $!";   read_conf_file($file, $conf_definition);   print "fullname = $fullname\n"; print "favouritefruit = $favouritefruit\n"; print "needspeeling = ", ($needspeeling ? 'true' : 'false'), "\n"; print "seedsremoved = ", ($seedsremoved ? 'true' : 'false'), "\n"; for (my $i = 0; $i < @otherfamily; ++$i) { print "otherfamily(", $i + 1, ") = ", $otherfamily[$i], "\n"; }   # read_conf_file: Given a file handle opened for reading and a configuration definition, # read the file. # If the configuration file doesn't match the definition, raise an exception with "die". # The configuration definition is (a reference to) an associative array # where the keys are the configuration variable names in all lower case # and the values are references to arrays. # The first element of each of these arrays is the expected type: 'boolean', 'string', or 'array'; # the second element is a reference to the variable that should be assigned the data. sub read_conf_file { my ($fh, $def) = @_; # copy parameters   local $_; # avoid interfering with use of $_ in main program while (<$fh>) { # read a line from $fh into $_ until end of file next if /^#/; # skip "#" comments next if /^;/; # skip ";" comments next if /^$/; # skip blank lines chomp; # strip final newline   $_ =~ /^\s*(\w+)\s*(.*)$/i or die "Syntax error"; my $key = $1; my $rest = $2; $key =~ tr/[A-Z]/[a-z]/; # convert keyword to lower case   if (!exists $def->{$key}) { die "Unknown keyword: '$key'"; }   if ($def->{$key}[0] eq 'boolean') { if ($rest) { die "Syntax error: extra data following boolean '$key'"; } ${$def->{$key}[1]} = 1; next; # done with this line, go back to "while" }   $rest =~ s/\s*$//; # drop trailing whitespace $rest =~ s/^=\s*//; # drop equals sign if present   if ($def->{$key}[0] eq 'string') { ${$def->{$key}[1]} = $rest; } elsif ($def->{$key}[0] eq 'array') { @{$def->{$key}[1]} = split /\s*,\s*/, $rest; } else { die "Internal error (unknown type in configuration definition)"; } } }  
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
#MATLAB_.2F_Octave
MATLAB / Octave
function L=range_expansion(S) % Range expansion if nargin < 1; S='[]'; end   if ~all(isdigit(S) | (S=='-') | (S==',') | isspace(S)) error 'invalid input'; end ixr = find(isdigit(S(1:end-1)) & S(2:end) == '-')+1; S(ixr)=':'; S=['[',S,']']; L=eval(S);
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.
#Mercury
Mercury
:- module read_a_file_line_by_line. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module int, list, require, string.   main(!IO) :- io.open_input("test.txt", OpenResult, !IO), ( OpenResult = ok(File), read_file_line_by_line(File, 0, !IO)  ; OpenResult = error(Error), error(io.error_message(Error)) ).   :- pred read_file_line_by_line(io.text_input_stream::in, int::in, io::di, io::uo) is det.   read_file_line_by_line(File, !.LineCount, !IO) :-  % We could also use io.read_line/3 which returns a list of characters  % instead of a string. io.read_line_as_string(File, ReadLineResult, !IO), ( ReadLineResult = ok(Line),  !:LineCount = !.LineCount + 1, io.format("%d: %s", [i(!.LineCount), s(Line)], !IO), read_file_line_by_line(File, !.LineCount, !IO)  ; ReadLineResult = eof  ; ReadLineResult = error(Error), error(io.error_message(Error)) ).
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.
#Neko
Neko
/** Read a file line by line, in Neko <doc><pre>Tectonics: nekoc readfile.neko neko readfile [filename]</pre></doc> */     var stdin = $loader.loadprim("std@file_stdin", 0)() var file_open = $loader.loadprim("std@file_open", 2) var file_read_char = $loader.loadprim("std@file_read_char", 1)   /* Read a line from file f into string s returning length without any newline */ var NEKO_MAX = 1 << 29 var strsize = 256 var NEWLINE = 10 var readline = function(f) { var s = $smake(strsize) var len = 0 var ch var file_exception = false while true { try ch = file_read_char(f) catch problem { file_exception = problem; break; } if ch == NEWLINE break; if $sset(s, len, ch) == null break; else len += 1   if len == strsize - 1 { strsize *= 2 if strsize > NEKO_MAX $throw("Out of string space for readline") var t = s s = $smake(strsize) $sblit(s, 0, t, 0, $ssize(t)) } } if $istrue(file_exception) $rethrow(file_exception) return $ssub(s, 0, len) }   var infile var cli = $loader.args[0] if cli == null infile = stdin else { cli = $string(cli) try infile = file_open(cli, "r") catch problem $print(problem, " Can't open ", cli, "\n") } if infile == null $throw("Can't open " + cli)   var str while true { try { str = readline(infile) $print(":", str, ":\n") } catch a break; }  
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
#Raku
Raku
say "hello world".flip; say "as⃝df̅".flip; say 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺'.flip;
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
#E
E
def makeQueue() { def [var head, var tail] := Ref.promise()   def writer { to enqueue(value) { def [nh, nt] := Ref.promise() tail.resolve([value, nh]) tail := nt } }   def reader { to empty() { return !Ref.isResolved(head) }   to dequeue(whenEmpty) { if (Ref.isResolved(head)) { def [value, next] := head head := next return value } else { throw.eject(whenEmpty, "pop() of empty queue") } } }   return [reader, writer] }