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/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
|
#REXX
|
REXX
|
/*REXX pgm generates 1,000 normally distributed numbers: mean=1, standard deviation=½.*/
numeric digits 20 /*the default decimal digit precision=9*/
parse arg n seed . /*allow specification of N and the seed*/
if n=='' | n=="," then n=1000 /*N: is the size of the array. */
if datatype(seed,'W') then call random ,,seed /*SEED: for repeatable random numbers. */
newMean=1 /*the desired new mean (arithmetic avg)*/
sd=1/2 /*the desired new standard deviation. */
do g=1 for n /*generate N uniform random #'s (0,1].*/
#.g = random(1, 1e5) / 1e5 /*REXX's RANDOM BIF generates integers.*/
end /*g*/ /* [↑] random integers ──► fractions. */
say ' old mean=' mean()
say 'old standard deviation=' stdDev()
call pi; pi2=pi * 2 /*define pi and also 2 * pi. */
say
do j=1 to n-1 by 2; m=j+1 /*step through the iterations by two. */
_=sd * sqrt(ln(#.j) * -2) /*calculate the used-twice expression.*/
#.j=_ * cos(pi2 * #.m) + newMean /*utilize the Box─Muller method. */
#.m=_ * sin(pi2 * #.m) + newMean /*random number must be: (0,1] */
end /*j*/
say ' new mean=' mean()
say 'new standard deviation=' stdDev()
exit /*stick a fork in it, we're all done. */
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
mean: _=0; do k=1 for n; _=_ + #.k; end; return _/n
stdDev: _avg=mean(); _=0; do k=1 for n; _=_ + (#.k - _avg)**2; end; return sqrt(_/n)
e: e =2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e /*digs overkill*/
pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi /* " " */
r2r: return arg(1) // (pi() * 2) /*normalize ang*/
sin: procedure; parse arg x;x=r2r(x);numeric fuzz min(5,digits()-3);if abs(x)=pi then return 0;return .sincos(x,x,1)
.sincos:parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
ln: procedure; parse arg x,f; call e; ig= x>1.5; is=1 - 2 * (ig\==1); ii=0; xx=x
do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end
xx=izz;ii=ii+is*2**k;end;x=x*e**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi * .5
numeric fuzz min(6, digits() - 3); if a=pi then return -1
if a=hpi | a=hpi*3 then return 0; if a=pi/3 then return .5
if a=pi * 2/3 then return -.5; return .sinCos(1,1,-1)
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6
numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ %2
m.=9; do j=0 while h>9; m.j=h; h=h%2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1
|
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
|
#Ruby
|
Ruby
|
fullname = favouritefruit = ""
needspeeling = seedsremoved = false
otherfamily = []
IO.foreach("config.file") do |line|
line.chomp!
key, value = line.split(nil, 2)
case key
when /^([#;]|$)/; # ignore line
when "FULLNAME"; fullname = value
when "FAVOURITEFRUIT"; favouritefruit = value
when "NEEDSPEELING"; needspeeling = true
when "SEEDSREMOVED"; seedsremoved = true
when "OTHERFAMILY"; otherfamily = value.split(",").map(&:strip)
when /^./; puts "#{key}: unknown key"
end
end
puts "fullname = #{fullname}"
puts "favouritefruit = #{favouritefruit}"
puts "needspeeling = #{needspeeling}"
puts "seedsremoved = #{seedsremoved}"
otherfamily.each_with_index do |name, i|
puts "otherfamily(#{i+1}) = #{name}"
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
|
#Python
|
Python
|
def rangeexpand(txt):
lst = []
for r in txt.split(','):
if '-' in r[1:]:
r0, r1 = r[1:].split('-', 1)
lst += range(int(r[0] + r0), int(r1) + 1)
else:
lst.append(int(r))
return lst
print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))
|
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.
|
#REXX
|
REXX
|
/*REXX program reads and displays (with a count) a file, one line at a time. */
parse arg fID . /*obtain optional argument from the CL.*/
if fID=='' then exit 8 /*Was no fileID specified? Then quit. */
say center(' displaying file: ' fID" ", 79, '═') /*show the name of the file being read.*/
call linein fID, 1, 0 /*see the comment in the section header*/
say /* [↓] show a file's contents (lines).*/
do #=1 while lines(fID)\==0 /*loop whilst there are lines in file. */
y= linein(fID) /*read a line and assign contents to Y.*/
say y /*show the content of the line (record)*/
end /*#*/
say /*stick a fork in it, we're all done. */
say center(' file ' fID " has " #-1 ' records.', 79, '═') /*show rec count. */
call lineout fID /*close the input file (most REXXes). */
|
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
|
#Rust
|
Rust
|
let mut buffer = b"abcdef".to_vec();
buffer.reverse();
assert_eq!(buffer, b"fedcba");
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
# Use a record to hold a Queue, using a list as the concrete implementation
record Queue(items)
procedure make_queue ()
return Queue ([])
end
procedure queue_push (queue, item)
put (queue.items, item)
end
# if the queue is empty, this will 'fail' and return nothing
procedure queue_pop (queue)
return pop (queue.items)
end
procedure queue_empty (queue)
return *queue.items = 0
end
# procedure to test class
procedure main ()
queue := make_queue()
# add the numbers 1 to 5
every (item := 1 to 5) do
queue_push (queue, item)
# pop them in the added order, and show a message when queue is empty
every (1 to 6) do {
write ("Popped value: " || queue_pop (queue))
if (queue_empty (queue)) then write ("empty queue")
}
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.
|
#Lua
|
Lua
|
Quaternion = {}
function Quaternion.new( a, b, c, d )
local q = { a = a or 1, b = b or 0, c = c or 0, d = d or 0 }
local metatab = {}
setmetatable( q, metatab )
metatab.__add = Quaternion.add
metatab.__sub = Quaternion.sub
metatab.__unm = Quaternion.unm
metatab.__mul = Quaternion.mul
return q
end
function Quaternion.add( p, q )
if type( p ) == "number" then
return Quaternion.new( p+q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a+q, p.b, p.c, p.d )
else
return Quaternion.new( p.a+q.a, p.b+q.b, p.c+q.c, p.d+q.d )
end
end
function Quaternion.sub( p, q )
if type( p ) == "number" then
return Quaternion.new( p-q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a-q, p.b, p.c, p.d )
else
return Quaternion.new( p.a-q.a, p.b-q.b, p.c-q.c, p.d-q.d )
end
end
function Quaternion.unm( p )
return Quaternion.new( -p.a, -p.b, -p.c, -p.d )
end
function Quaternion.mul( p, q )
if type( p ) == "number" then
return Quaternion.new( p*q.a, p*q.b, p*q.c, p*q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a*q, p.b*q, p.c*q, p.d*q )
else
return Quaternion.new( p.a*q.a - p.b*q.b - p.c*q.c - p.d*q.d,
p.a*q.b + p.b*q.a + p.c*q.d - p.d*q.c,
p.a*q.c - p.b*q.d + p.c*q.a + p.d*q.b,
p.a*q.d + p.b*q.c - p.c*q.b + p.d*q.a )
end
end
function Quaternion.conj( p )
return Quaternion.new( p.a, -p.b, -p.c, -p.d )
end
function Quaternion.norm( p )
return math.sqrt( p.a^2 + p.b^2 + p.c^2 + p.d^2 )
end
function Quaternion.print( p )
print( string.format( "%f + %fi + %fj + %fk\n", p.a, p.b, p.c, p.d ) )
end
|
http://rosettacode.org/wiki/Quine
|
Quine
|
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program or self-reproducing computer program
self-copying program or self-copying computer program
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
Task
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
Next to the Quines presented here, many other versions can be found on the Quine page.
Related task
print itself.
|
#E
|
E
|
" =~ x; println(E.toQuote(x),x)" =~ x; println(E.toQuote(x),x)
|
http://rosettacode.org/wiki/Quickselect_algorithm
|
Quickselect algorithm
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Use the quickselect algorithm on the vector
[9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page.
Note: Quicksort has a separate task.
|
#Standard_ML
|
Standard ML
|
fun quickselect (_, _, []) = raise Fail "empty"
| quickselect (k, cmp, x :: xs) = let
val (ys, zs) = List.partition (fn y => cmp (y, x) = LESS) xs
val l = length ys
in
if k < l then
quickselect (k, cmp, ys)
else if k > l then
quickselect (k-l-1, cmp, zs)
else
x
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.
|
#Swift
|
Swift
|
func select<T where T : Comparable>(var elements: [T], n: Int) -> T {
var r = indices(elements)
while true {
let pivotIndex = partition(&elements, r)
if n == pivotIndex {
return elements[pivotIndex]
} else if n < pivotIndex {
r.endIndex = pivotIndex
} else {
r.startIndex = pivotIndex+1
}
}
}
for i in 0 ..< 10 {
let a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
print(select(a, i))
if i < 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
|
#MiniScript
|
MiniScript
|
extractRange = function(ints)
result = []
idx = 0
while idx < ints.len
runLen = 1
while idx+runLen < ints.len and ints[idx+runLen] == ints[idx] + runLen
runLen = runLen + 1
end while
if runLen > 2 then
result.push ints[idx] + "-" + ints[idx+runLen-1]
idx = idx + runLen
else
result.push ints[idx]
idx = idx + 1
end if
end while
return join(result, ",")
end function
test = [ 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 extractRange(test)
|
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
|
#Ring
|
Ring
|
for i = 1 to 10
see random(i) + nl
next i
|
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
|
#Ruby
|
Ruby
|
Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }
|
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
|
#Run_BASIC
|
Run BASIC
|
dim param$(6)
dim paramVal$(6)
param$(1) = "fullname"
param$(2) = "favouritefruit"
param$(3) = "needspeeling"
param$(4) = "seedsremoved"
param$(5) = "otherfamily"
for i = 1 to 6
paramVal$(i) = "false"
next i
open DefaultDir$ + "\public\a.txt" for binary as #f
while not(eof(#f))
line input #f, a$
a$ = trim$(a$)
if instr("#;",left$(a$,1)) = 0 and a$ <> "" then
thisParam$ = lower$(word$(a$,1," "))
for i = 1 to 5
if param$(i) = thisParam$ then
paramVal$(i) = "true"
aa$ = trim$(mid$(a$,len(thisParam$)+2))
if aa$ <> "" then paramVal$(i) = aa$
end if
next i
end if
wend
close #f
for i = 1 to 5
if instr(paramVal$(i),",") > 0 then
for j = 1 to 2
print param$(i);"(";j;")";chr$(9);trim$(word$(paramVal$(i),j,","))
next j
else
print param$(i);chr$(9);paramVal$(i)
end if
next i
|
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
|
#R
|
R
|
rangeExpand <- function(text) {
lst <- gsub("(\\d)-", "\\1:", unlist(strsplit(text, ",")))
unlist(sapply(lst, function (x) eval(parse(text=x))), use.names=FALSE)
}
rangeExpand("-6,-3--1,3-5,7-11,14,15,17-20")
[1] -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20
|
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.
|
#Ring
|
Ring
|
fp = fopen("C:\Ring\ReadMe.txt","r")
r = ""
while isstring(r)
r = fgetc(fp)
if r = char(10) see nl
else see r ok
end
fclose(fp)
|
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.
|
#Ruby
|
Ruby
|
IO.foreach "foobar.txt" do |line|
# Do something with line.
puts line
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
|
#S-lang
|
S-lang
|
variable sa = "Hello, World", aa = Char_Type[strlen(sa)+1];
init_char_array(aa, sa);
array_reverse(aa);
% print(aa);
% Unfortunately, strjoin() only joins strings, so we map char()
% [sadly named: actually converts char into single-length string]
% onto the array:
print( strjoin(array_map(String_Type, &char, aa), "") );
|
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
|
#J
|
J
|
queue_fifo_=: ''
pop_fifo_=: verb define
r=. {. ::] queue
queue=: }.queue
r
)
push_fifo_=: verb define
queue=: queue,y
y
)
isEmpty_fifo_=: verb define
0=#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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module CheckIt {
class Quaternion {
\\ by default are double
a,b,c,d
Property ToString$ {
Value {
link parent a,b,c, d to a,b,c,d
value$=format$("{0} + {1}i + {2}j + {3}k",a,b,c,d)
}
}
Property Norm { Value}
Operator "==" {
read n
push .a==n.a and .b==n.b and .c==n.c and .d==n.d
}
Module CalcNorm {
.[Norm]<=sqrt(.a**2+.b**2+.c**2+.d**2)
}
Operator Unary {
.a-! : .b-! : .c-! :.d-!
}
Function Conj {
q=this
for q {
.b-! : .c-! :.d-!
}
=q
}
Function Add {
q=this
for q {
.a+=Number : .CalcNorm
}
=q
}
Operator "+" {
Read q2
For this, q2 {
.a+=..a :.b+=..b:.c+=..c:.d+=..d
.CalcNorm
}
}
Function Mul(r) {
q=this
for q {
.a*=r:.b*=r:.c*=r:.d*=r:.CalcNorm
}
=q
}
Operator "*" {
Read q2
For This, q2 {
Push .a*..a-.b*..b-.c*..c-.d*..d
Push .a*..b+.b*..a+.c*..d-.d*..c
Push .a*..c-.b*..d+.c*..a+.d*..b
.d<=.a*..d+.b*..c-.c*..b+.d*..a
Read .c, .b, .a
.CalcNorm
}
}
class:
module Quaternion {
if match("NNNN") then {
Read .a,.b,.c,.d
.CalcNorm
}
}
}
\\ variables
r=7
q=Quaternion(1,2,3,4)
q1=Quaternion(2,3,4,5)
q2=Quaternion(3,4,5,6)
\\ perform negate, conjugate, multiply by real, add a real, multiply quanterions, multiply in reverse order
qneg=-q
qconj=q.conj()
qmul=q.Mul(r)
qadd=q.Add(r)
q1q2=q1*q2
q2q1=q2*q1
Print "q = ";q.ToString$
Print "Normal q = ";q.Norm
Print "Neg q = ";qneg.ToString$
Print "Conj q = ";qconj.ToString$
Print "Mul q 7 = ";qmul.ToString$
Print "Add q 7 = ";qadd.ToString$
Print "q1 = ";q1.ToString$
Print "q2 = ";q2.ToString$
Print "q1 * q2 = ";q1q2.ToString$
Print "q2 * q1 = ";q2q1.ToString$
Print q1==q1 ' true
Print q1q2==q2q1 ' false
\\ multiplication and equality in one expression
Print (q1 * q2 == q2 * q1)=false
Print (q1 * q2 == q1 * q2)=True
}
CheckIt
|
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.
|
#Elixir
|
Elixir
|
a = <<"a = ~p~n:io.fwrite(a,[a])~n">>
:io.fwrite(a,[a])
|
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.
|
#Tcl
|
Tcl
|
# Swap the values at two indices of a list
proc swap {list i j} {
upvar 1 $list l
set tmp [lindex $l $i]
lset l $i [lindex $l $j]
lset l $j $tmp
}
proc quickselect {vector k {left 0} {right ""}} {
set last [expr {[llength $vector] - 1}]
if {$right eq ""} {
set right $last
}
# Sanity assertions
if {![llength $vector] || $k <= 0} {
error "Either empty vector, or k <= 0"
} elseif {![tcl::mathop::<= 0 $left $last]} {
error "left is out of range"
} elseif {![tcl::mathop::<= $left $right $last]} {
error "right is out of range"
}
# the _select core, inlined
while 1 {
set pivotIndex [expr {int(rand()*($right-$left))+$left}]
# the partition core, inlined
set pivotValue [lindex $vector $pivotIndex]
swap vector $pivotIndex $right
set storeIndex $left
for {set i $left} {$i <= $right} {incr i} {
if {[lindex $vector $i] < $pivotValue} {
swap vector $storeIndex $i
incr storeIndex
}
}
swap vector $right $storeIndex
set pivotNewIndex $storeIndex
set pivotDist [expr {$pivotNewIndex - $left + 1}]
if {$pivotDist == $k} {
return [lindex $vector $pivotNewIndex]
} elseif {$k < $pivotDist} {
set right [expr {$pivotNewIndex - 1}]
} else {
set k [expr {$k - $pivotDist}]
set left [expr {$pivotNewIndex + 1}]
}
}
}
|
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
|
#MUMPS
|
MUMPS
|
RANGCONT(X) ;Integer range contraction
NEW Y,I,CONT,NOTFIRST,CURR,PREV,NEXT,SEQ SET Y="",SEQ=0,PREV="",CONT=0
FOR I=1:1:$LENGTH(X,",") DO
.SET NOTFIRST=$LENGTH(Y),CURR=$PIECE(X,",",I),NEXT=$PIECE(X,",",I+1)
.FOR Q:$EXTRACT(CURR)'=" " S CURR=$EXTRACT(CURR,2,$LENGTH(CURR)) ;clean up leading spaces
.S SEQ=((CURR-1)=PREV)&((CURR+1)=NEXT)
.IF 'NOTFIRST SET Y=CURR
.IF NOTFIRST DO
..;Order matters due to flags
..IF CONT&SEQ ;Do nothing
..IF 'CONT&'SEQ SET Y=Y_","_CURR
..IF CONT&'SEQ SET Y=Y_CURR,CONT=0
..IF 'CONT&SEQ SET Y=Y_"-",CONT=1
.SET PREV=CURR
IF CONT SET Y=Y_PREV
K I,CONT,NOTFIRST,CURR,PREV,NEXT,SEQ
QUIT Y
|
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
|
#Run_BASIC
|
Run BASIC
|
dim a(1000)
pi = 22/7
for i = 1 to 1000
a( i) = 1 + .5 * (sqr(-2 * log(rnd(0))) * cos(2 * pi * rnd(0)))
next i
|
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
|
#Rust
|
Rust
|
extern crate rand;
use rand::distributions::{Normal, IndependentSample};
fn main() {
let mut rands = [0.0; 1000];
let normal = Normal::new(1.0, 0.5);
let mut rng = rand::thread_rng();
for num in rands.iter_mut() {
*num = normal.ind_sample(&mut rng);
}
}
|
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
|
#Rust
|
Rust
|
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
let path = String::from("file.conf");
let cfg = config_from_file(path);
println!("{:?}", cfg);
}
fn config_from_file(path: String) -> Config {
let path = Path::new(&path);
let file = File::open(path).expect("File not found or cannot be opened");
let content = BufReader::new(&file);
let mut cfg = Config::new();
for line in content.lines() {
let line = line.expect("Could not read the line");
// Remove whitespaces at the beginning and end
let line = line.trim();
// Ignore comments and empty lines
if line.starts_with("#") || line.starts_with(";") || line.is_empty() {
continue;
}
// Split line into parameter name and rest tokens
let tokens = Vec::from_iter(line.split_whitespace());
let name = tokens.first().unwrap();
let tokens = tokens.get(1..).unwrap();
// Remove the equal signs
let tokens = tokens.iter().filter(|t| !t.starts_with("="));
// Remove comment after the parameters
let tokens = tokens.take_while(|t| !t.starts_with("#") && !t.starts_with(";"));
// Concat back the parameters into one string to split for separated parameters
let mut parameters = String::new();
tokens.for_each(|t| { parameters.push_str(t); parameters.push(' '); });
// Splits the parameters and trims
let parameters = parameters.split(',').map(|s| s.trim());
// Converts them from Vec<&str> into Vec<String>
let parameters: Vec<String> = parameters.map(|s| s.to_string()).collect();
// Setting the config parameters
match name.to_lowercase().as_str() {
"fullname" => cfg.full_name = parameters.get(0).cloned(),
"favouritefruit" => cfg.favourite_fruit = parameters.get(0).cloned(),
"needspeeling" => cfg.needs_peeling = true,
"seedsremoved" => cfg.seeds_removed = true,
"otherfamily" => cfg.other_family = Some(parameters),
_ => (),
}
}
cfg
}
#[derive(Clone, Debug)]
struct Config {
full_name: Option<String>,
favourite_fruit: Option<String>,
needs_peeling: bool,
seeds_removed: bool,
other_family: Option<Vec<String>>,
}
impl Config {
fn new() -> Config {
Config {
full_name: None,
favourite_fruit: None,
needs_peeling: false,
seeds_removed: false,
other_family: None,
}
}
}
|
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
|
#Racket
|
Racket
|
#lang racket
(define (range-expand s)
(append*
(for/list ([r (regexp-split "," s)])
(match (regexp-match* "(-?[0-9]+)-(-?[0-9]+)" r
#:match-select cdr)
[(list (list f t))
(range (string->number f) (+ (string->number t) 1))]
[(list)
(list (string->number r))]))))
(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
|
#Raku
|
Raku
|
sub range-expand (Str $range-description) {
my token number { '-'? \d+ }
my token range { (<&number>) '-' (<&number>) }
$range-description
.split(',')
.map({ .match(&range) ?? $0..$1 !! +$_ })
.flat
}
say range-expand('-6,-3--1,3-5,7-11,14,15,17-20').join(', ');
|
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.
|
#Run_BASIC
|
Run BASIC
|
open DefaultDir$ + "\public\filetest.txt" for input as #f
while not(eof(#f))
line input #f, a$
print a$
wend
close #f
|
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.
|
#Rust
|
Rust
|
use std::io::{BufReader,BufRead};
use std::fs::File;
fn main() {
let file = File::open("file.txt").unwrap();
for line in BufReader::new(file).lines() {
println!("{}", line.unwrap());
}
}
|
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
|
#SAS
|
SAS
|
data _null_;
length a b $11;
a="I am Legend";
b=reverse(a);
put a;
put b;
run;
|
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
|
#Java
|
Java
|
public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){ //standard queue name for "push"
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{//standard queue name for "pop"
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}
|
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.
|
#Maple
|
Maple
|
with(ArrayTools);
module Quaternion()
option object;
local real := 0;
local i := 0;
local j := 0;
local k := 0;
export getReal::static := proc(self::Quaternion, $)
return self:-real;
end proc;
export getI::static := proc(self::Quaternion, $)
return self:-i;
end proc;
export getJ::static := proc(self::Quaternion, $)
return self:-j;
end proc;
export getK::static := proc(self::Quaternion, $)
return self:-k;
end proc;
export Norm::static := proc(self::Quaternion, $)
return sqrt(self:-real^2 + self:-i^2 + self:-j^2 + self:-k^2);
end proc;
# NegativeQuaternion returns the additive inverse of the quaternion
export NegativeQuaternion::static := proc(self::Quaternion, $)
return Quaternion(- self:-real, - self:-i, - self:-j, - self:-k);
end proc;
export Conjugate::static := proc(self::Quaternion, $)
return Quaternion(self:-real, - self:-i, - self:-j, - self:-k);
end proc;
# quaternion addition
export `+`::static := overload ([
proc(self::Quaternion, x::Quaternion) option overload;
return Quaternion(self:-real + getReal(x), self:-i + getI(x), self:-j + getJ(x), self:-k + getK(x));
end proc,
proc(self::Quaternion, x::algebraic) option overload;
return Quaternion(self:-real + x, self:-i, self:-j, self:-k);
end proc,
proc(x::algebraic, self::Quaternion) option overload;
return Quaternion(x + self:-real, self:-i, self:-j, self:-k);
end
]);
# convert quaternion to additive inverse
export `-`::static := overload([
proc(self::Quaternion) option overload;
return Quaternion(-self:-real, -self:-i, -self:-j, -self:-k);
end
]);
# quaternion multiplication is non-abelian so the `.` operator needs to be used
export `.`::static := overload([
proc(self::Quaternion, x::Quaternion) option overload;
return Quaternion(self:-real * getReal(x) - self:-i * getI(x) - self:-j * getJ(x) - self:-k * getK(x),
self:-real * getI(x) + self:-i * getReal(x) + self:-j * getK(x) - self:-k * getJ(x),
self:-real * getJ(x) + self:-j * getReal(x) - self:-i * getK(x) + self:-k * getI(x),
self:-real * getK(x) + self:-k * getReal(x) + self:-i * getJ(x) - self:-j * getI(x));
end proc,
proc(self::Quaternion, x::algebraic) option overload;
return Quaternion(self:-real * x, self:-i * x, self:-j * x, self:-k * x);
end proc,
proc(x::algebraic, self::Quaternion) option overload;
return Quaternion(self:-real * x, self:-i * x, self:-j * x, self:-k * x);
end
]);
# redirect division to `.` operator
export `*`::static := overload([
proc(self::Quaternion, x::Quaternion) option overload;
use `*` = `.` in return self * x; end use
end proc,
proc(self::Quaternion, x::algebraic) option overload;
use `*` = `.` in return x * self; end use
end proc,
proc(x::algebraic, self::Quaternion) option overload;
use `*` = `.` in return x * self; end use
end
]);
# convert quaternion to multiplicative inverse
export `/`::static := overload([
proc(self::Quaternion) option overload;
return Conjugate(self) . (1/(Norm(self)^2));
end proc
]);
# QuaternionCommutator computes the commutator of self and x
export QuaternionCommutator::static := proc(x::Quaternion, y::Quaternion, $)
return (x . y) - (y . x);
end proc;
# display quaternion
export ModulePrint::static := proc(self::Quaternion, $);
return cat(self:-real, " + ", self:-i, "i + ", self:-j, "j + ", self:-k, "k"):
end proc;
export ModuleApply::static := proc()
Object(Quaternion, _passed);
end proc;
export ModuleCopy::static := proc(new::Quaternion, proto::Quaternion, R::algebraic, imag::algebraic, J::algebraic, K::algebraic, $)
new:-real := R;
new:-i := imag;
new:-j := J;
new:-k := K;
end proc;
end module:
q := Quaternion(1, 2, 3, 4):
q1 := Quaternion(2, 3, 4, 5):
q2 := Quaternion(3, 4, 5, 6):
r := 7:
quats := Array([q, q1, q2]):
print("q, q1, q2"):
seq(quats[i], i = 1..3);
print("norms"):
seq(Norm(quats[i]), i = 1..3);
print("negative"):
seq(NegativeQuaternion(quats[i]), i = 1..3);
print("conjugate"):
seq(Conjugate(quats[i]), i = 1..3);
print("addition of real number 7"):
seq(quats[i] + r, i = 1..3);
print("multiplication by real number 7"):
seq(quats[i] . r, i = 1..3);
print("division by real number 7"):
seq(quats[i] / 7, i = 1..3);
print("add quaternions q1 and q2"):
q1 + q2;
print("multiply quaternions q1 and q2");
q1 . q2;
print("multiply quaternions q2 and q1"):
q2 . q1;
print("quaternion commutator of q1 and q2"):
QuaternionCommutator(q1,q2);
print("divide q1 by q2"):
q1 / q2;
|
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.
|
#Erlang
|
Erlang
|
PROGRAM QUINE
BEGIN
READ(D$,Y$)
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(X$)
END LOOP
RESTORE
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(D$;CHR$(34);X$;CHR$(34);CHR$(41))
END LOOP
PRINT(D$;CHR$(34);CHR$(34);CHR$(41))
PRINT(Y$)
DATA("DATA(")
DATA("END PROGRAM")
DATA("PROGRAM QUINE")
DATA("BEGIN")
DATA("READ(D$,Y$)")
DATA("LOOP")
DATA(" READ(X$)")
DATA(" EXIT IF LEN(X$)<1")
DATA(" PRINT(X$)")
DATA("END LOOP")
DATA("RESTORE")
DATA("LOOP")
DATA(" READ(X$)")
DATA(" EXIT IF LEN(X$)<1")
DATA(" PRINT(D$;CHR$(34);X$;CHR$(34);CHR$(41))")
DATA("END LOOP")
DATA("PRINT(D$;CHR$(34);CHR$(34);CHR$(41))")
DATA("PRINT(Y$)")
DATA("")
END PROGRAM
|
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.
|
#VBA
|
VBA
|
Dim s As Variant
Private Function quick_select(ByRef s As Variant, k As Integer) As Integer
Dim left As Integer, right As Integer, pos As Integer
Dim pivotValue As Integer, tmp As Integer
left = 1: right = UBound(s)
Do While left < right
pivotValue = s(k)
tmp = s(k)
s(k) = s(right)
s(right) = tmp
pos = left
For i = left To right
If s(i) < pivotValue Then
tmp = s(i)
s(i) = s(pos)
s(pos) = tmp
pos = pos + 1
End If
Next i
tmp = s(right)
s(right) = s(pos)
s(pos) = tmp
If pos = k Then
Exit Do
End If
If pos < k Then
left = pos + 1
Else
right = pos - 1
End If
Loop
quick_select = s(k)
End Function
Public Sub main()
Dim r As Integer, i As Integer
s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]
For i = 1 To 10
r = quick_select(s, i) 's is ByRef parameter
Debug.Print IIf(i < 10, r & ", ", "" & r);
Next i
End Sub
|
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
|
#NetRexx
|
NetRexx
|
/*NetRexx program to test range extraction. ***************************
* 07.08.2012 Walter Pachl derived from my Rexx Version
* Changes: line continuation in aaa assignment changed
* 1e99 -> 999999999
* Do -> Loop
* words(aaa) -> aaa.words()
* word(aaa,i) -> aaa.word(i)
**********************************************************************/
Say 'NetRexx program derived from Rexx'
aaa='0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29'
aaa=aaa' 30 31 32 33 35 36 37 38 39'
say 'old='aaa;
aaa=aaa 999999999 /* artificial number at the end */
i=0 /* initialize index */
ol='' /* initialize output string */
comma='' /* will become a ',' lateron */
inrange=0
Loop While i<=aaa.words /* loop for all numbers */
i=i+1 /* index of next number */
n=aaa.word(i) /* the now current number */
If n=999999999 Then Leave /* we are at the end */
If inrange Then Do /* range was opened */
If aaa.word(i+1)<>n+1 Then Do /* following word not in range */
ol=ol||n /* so this number is the end */
inrange=0 /* and the range is over */
End /* else ignore current number */
End
Else Do /* not in a range */
ol=ol||comma||n /* add number (with comma) */
comma=',' /* to the output string */
If aaa.word(i+2)=n+2 Then Do /* if the nr after the next fits */
inrange=1 /* open a range */
ol=ol'-' /* append the range connector */
End
End
End
Say 'new='ol
|
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
|
#SAS
|
SAS
|
/* Generate 1000 random numbers with mean 1 and standard deviation 0.5.
SAS version 9.2 was used to create this code.*/
data norm1000;
call streaminit(123456);
/* Set the starting point, so we can replicate results.
If you want different results each time, comment the above line. */
do i=1 to 1000;
r=rand('normal',1,0.5);
output;
end;
run;
|
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
|
#Sather
|
Sather
|
class MAIN is
main is
a:ARRAY{FLTD} := #(1000);
i:INT;
RND::seed(2010);
loop i := 1.upto!(1000) - 1;
a[i] := 1.0d + 0.5d * RND::standard_normal;
end;
-- testing the distribution
mean ::= a.reduce(bind(_.plus(_))) / a.size.fltd;
#OUT + "mean " + mean + "\n";
a.map(bind(_.minus(mean)));
a.map(bind(_.pow(2.0d)));
dev ::= (a.reduce(bind(_.plus(_))) / a.size.fltd).sqrt;
#OUT + "dev " + dev + "\n";
end;
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
|
#Scala
|
Scala
|
val conf = scala.io.Source.fromFile("config.file").
getLines.
toList.
filter(_.trim.size > 0).
filterNot("#;" contains _(0)).
map(_ split(" ", 2) toList).
map(_ :+ "true" take 2).
map {
s:List[String] => (s(0).toLowerCase, s(1).split(",").map(_.trim).toList)
}.toMap
|
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
|
#Raven
|
Raven
|
define get_num use $lst
# "-22" split by "-" is [ "", "22" ] so check if
# first list item is "" -> a negative number
$lst 0 get "" = if
# negative number
#
# convert str to integer and multiply by -1
-1 $lst 1 get 0 prefer *
$lst shift $lst shift drop drop
else
# positive number
$lst 0 get 0 prefer
$lst shift drop
define range_expand use $rng
[ ] as $res
$rng "," split each as $r
$r m/^(-?\d+)-(-?\d+)$/ TRUE = if
$r s/-/g as $parts
$parts get_num as $from
$parts get_num as $to
# int list to str list, then joined by ","
group
$from $to 1 range each "" prefer
list "," join $res push
# range doesn't include the $to, so add to end of generated range
$to "%d" $res push
else
$r $res push
$res "," join print
"\n" print
'-6,-3--1,3-5,7-11,14,15,17-20' range_expand
|
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
|
#REXX
|
REXX
|
/*REXX program expands an ordered list of integers into an expanded list. */
old= '-6,-3--1, 3-5, 7-11, 14,15,17-20'; a=translate(old,,',')
new= /*translate [↑] commas (,) ───► blanks*/
do until a==''; parse var a X a /*obtain the next integer ──or── range.*/
p=pos('-', X, 2) /*find the location of a dash (maybe). */
if p==0 then new=new X /*append integer X to the new list.*/
else do j=left(X,p-1) to substr(X,p+1); new=new j
end /*j*/ /*append a single [↑] integer at a time*/
end /*until*/
/*stick a fork in it, we're all done. */
new=translate( strip(new), ',', " ") /*remove the first blank, add commas. */
say 'old list: ' old /*show the old list of numbers/ranges.*/
say 'new list: ' new /* " " new " " numbers. */
|
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.
|
#Scala
|
Scala
|
import scala.io._
Source.fromFile("foobar.txt").getLines.foreach(println)
|
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.
|
#Scheme
|
Scheme
|
; Commented line below should be uncommented to use read-line with Guile
;(use-modules (ice-9 rdelim))
(define file (open-input-file "input.txt"))
(do ((line (read-line file) (read-line file))) ((eof-object? line))
(display line)
(newline))
|
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
|
#Sather
|
Sather
|
class MAIN is
main is
s ::= "asdf";
reversed ::= s.reverse;
-- current implementation does not handle multibyte encodings correctly
end;
end;
|
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
|
#JavaScript
|
JavaScript
|
var fifo = [];
fifo.push(42); // Enqueue.
fifo.push(43);
var x = fifo.shift(); // Dequeue.
alert(x); // 42
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
<<Quaternions`
q=Quaternion[1,2,3,4]
q1=Quaternion[2,3,4,5]
q2=Quaternion[3,4,5,6]
r=7
->Quaternion[1,2,3,4]
->Quaternion[2,3,4,5]
->Quaternion[3,4,5,6]
->7
Abs[q]
->√30
-q
->Quaternion[-1,-2,-3,-4]
Conjugate[q]
->Quaternion[1,-2,-3,-4]
r+q
->Quaternion[8,2,3,4]
q+r
->Quaternion[8,2,3,4]
q1+q2
->Quaternion[5,7,9,11]
q*r
->Quaternion[7,14,21,28]
r*q
->Quaternion[7,14,21,28]
q1**q2
->Quaternion[-56,16,24,26]
q2**q1
->Quaternion[-56,18,20,28]
|
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.
|
#ERRE
|
ERRE
|
PROGRAM QUINE
BEGIN
READ(D$,Y$)
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(X$)
END LOOP
RESTORE
LOOP
READ(X$)
EXIT IF LEN(X$)<1
PRINT(D$;CHR$(34);X$;CHR$(34);CHR$(41))
END LOOP
PRINT(D$;CHR$(34);CHR$(34);CHR$(41))
PRINT(Y$)
DATA("DATA(")
DATA("END PROGRAM")
DATA("PROGRAM QUINE")
DATA("BEGIN")
DATA("READ(D$,Y$)")
DATA("LOOP")
DATA(" READ(X$)")
DATA(" EXIT IF LEN(X$)<1")
DATA(" PRINT(X$)")
DATA("END LOOP")
DATA("RESTORE")
DATA("LOOP")
DATA(" READ(X$)")
DATA(" EXIT IF LEN(X$)<1")
DATA(" PRINT(D$;CHR$(34);X$;CHR$(34);CHR$(41))")
DATA("END LOOP")
DATA("PRINT(D$;CHR$(34);CHR$(34);CHR$(41))")
DATA("PRINT(Y$)")
DATA("")
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.
|
#Euphoria
|
Euphoria
|
constant p="constant p=%s%s%s printf(1,p,{34,p,34})" printf(1,p,{34,p,34})
|
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.
|
#Wren
|
Wren
|
import "/sort" for Find
var a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
for (k in 0..9) {
System.write(Find.quick(a, k))
if (k < 9) System.write(", ")
}
System.print()
|
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
|
#Nim
|
Nim
|
import parseutils, re, strutils, sequtils
proc extractRange(input: string): string =
var list = input.replace(re"\s+").split(',').map(parseInt)
var ranges: seq[string]
var i = 0
while i < list.len:
var first = list[i] # first element in the current range
var offset = i
while True: # skip ahead to the end of the current range
if i + 1 >= list.len:
# reached end of the list
break
if list[i + 1] - (i + 1) != first - offset:
# next element isn't in the current range
break
i.inc
var last = list[i] # last element in the current range
case last - first
of 0: ranges.add($first)
of 1: ranges.add("$1,$2".format(first, last))
else: ranges.add("$1-$2".format(first, last))
i.inc
return ranges.join(",")
echo("""
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""".extractRange)
|
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
|
#Scala
|
Scala
|
List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)
|
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
|
#Scheme
|
Scheme
|
; linear congruential generator given in C99 section 7.20.2.1
(define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))
; uniform real numbers in open interval (0, 1)
(define (unif-rand seed) (let ((r (c-rand seed))) (lambda () (/ (+ (r) 1) 32769.0))))
; Box-Muller method to generate normal distribution
(define (normal-rand unif m s)
(let ((? #t) (! 0.0) (twopi (* 2.0 (acos -1.0))))
(lambda ()
(set! ? (not ?))
(if ? !
(let ((a (sqrt (* -2.0 (log (unif))))) (b (* twopi (unif))))
(set! ! (+ m (* s a (sin b))))
(+ m (* s a (cos b))))))))
(define rnorm (normal-rand (unif-rand 0) 1.0 0.5))
; auxiliary function to get a list of 'n random numbers from generator 'r
(define (rand-list r n) = (if (zero? n) '() (cons (r) (rand-list r (- n 1)))))
(define v (rand-list rnorm 1000))
v
#|
(-0.27965824722565835
-0.8870860825789542
0.6499618744638194
0.31336141955110863
...
0.5648743998193049
0.8282656735558756
0.6399951934564637
0.7699535302478072)
|#
; check mean and standard deviation
(define (mean-sdev v)
(let loop ((v v) (a 0) (b 0) (n 0))
(if (null? v)
(let ((mean (/ a n)))
(list mean (sqrt (/ (- b (* n mean mean)) (- n 1)))))
(let ((x (car v)))
(loop (cdr v) (+ a x) (+ b (* x x)) (+ n 1))))))
(mean-sdev v)
; (0.9562156817697293 0.5097087109575911)
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "scanfile.s7i";
var string: fullname is "";
var string: favouritefruit is "";
var boolean: needspeeling is FALSE;
var boolean: seedsremoved is FALSE;
var array string: otherfamily is 0 times "";
const proc: main is func
local
var file: configFile is STD_NULL;
var string: symbol is "";
var integer: index is 0;
begin
configFile := open("readcfg.txt", "r");
configFile.bufferChar := getc(configFile);
symbol := lower(getWord(configFile));
while symbol <> "" do
skipSpace(configFile);
if symbol = "#" or symbol = ";" then
skipLine(configFile);
elsif symbol = "fullname" then
fullname := getLine(configFile);
elsif symbol = "favouritefruit" then
favouritefruit := getLine(configFile);
elsif symbol = "needspeeling" then
needspeeling := TRUE;
elsif symbol = "seedsremoved" then
seedsremoved := TRUE;
elsif symbol = "otherfamily" then
otherfamily := split(getLine(configFile), ",");
for key index range otherfamily do
otherfamily[index] := trim(otherfamily[index]);
end for;
else
writeln(" *** Illegal line " <& literal(getLine(configFile)));
end if;
symbol := lower(getWord(configFile));
end while;
close(configFile);
writeln("fullname: " <& fullname);
writeln("favouritefruit: " <& favouritefruit);
writeln("needspeeling: " <& needspeeling);
writeln("seedsremoved: " <& seedsremoved);
for key index range otherfamily do
writeln(("otherfamily[" <& index <& "]:") rpad 16 <& otherfamily[index]);
end for;
end func;
|
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
|
#Ring
|
Ring
|
# Project : Range expansion
int = "-6,-3--1,3-5,7-11,14,15,17-20"
int = str2list(substr(int, ",", nl))
newint = []
for n=1 to len(int)
nrint = substr(int[n], "-")
nrint2 = substr(int[n], "--")
if nrint2 > 0
temp1 = left(int[n], nrint2 -1)
temp2 = right(int[n], len(int[n]) - nrint2)
add(newint, [temp1,temp2])
else
if len(int[n]) <= 2
add(newint, [int[n], ""])
else
if nrint > 0 and nrint2 = 0
temp1 = left(int[n], nrint - 1)
temp2 = right(int[n], len(int[n]) - nrint)
add(newint, [temp1,temp2])
ok
ok
ok
next
showarray(newint)
func showarray(vect)
see "["
svect = ""
for n = 1 to len(vect)
if newint[n][2] != ""
for nr = newint[n][1] to newint[n][2]
svect = svect +"" + nr + ", "
next
else
svect = svect +"" + newint[n][1] + ", "
ok
next
svect = left(svect, len(svect) - 2)
see svect
see "]" + nl
|
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
|
#Ruby
|
Ruby
|
def range_expand(rng)
rng.split(',').flat_map do |part|
if part =~ /^(-?\d+)-(-?\d+)$/
($1.to_i .. $2.to_i).to_a
else
Integer(part)
end
end
end
p range_expand('-6,-3--1,3-5,7-11,14,15,17-20')
|
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.
|
#Sed
|
Sed
|
#!/bin/sed -f
p
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const proc: main is func
local
var file: aFile is STD_NULL;
var string: line is "";
begin
aFile := open("input.txt", "r");
while hasNext(aFile) do
readln(aFile, line);
writeln("LINE: " <& line);
end while;
end func;
|
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
|
#Scala
|
Scala
|
"asdf".reverse
|
http://rosettacode.org/wiki/Queue/Definition
|
Queue/Definition
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#jq
|
jq
|
# An empty queue:
def fifo: [];
def push(e): [e] + .;
def pop: [.[0], .[1:]];
def pop_or_error: if length == 0 then error("pop_or_error") else pop end;
def empty: length == 0;
|
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
|
#Julia
|
Julia
|
struct Queue{T}
a::Array{T,1}
end
Queue() = Queue(Any[])
Queue(a::DataType) = Queue(a[])
Queue(a) = Queue(typeof(a)[])
Base.isempty(q::Queue) = isempty(q.a)
function Base.pop!(q::Queue{T}) where {T}
!isempty(q) || error("queue must be non-empty")
pop!(q.a)
end
function Base.push!(q::Queue{T}, x::T) where {T}
pushfirst!(q.a, x)
return q
end
function Base.push!(q::Queue{Any}, x::T) where {T}
pushfirst!(q.a, x)
return 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.
|
#Mercury
|
Mercury
|
:- module quaternion.
:- interface.
:- import_module float.
:- type quaternion
---> q( w :: float,
i :: float,
j :: float,
k :: float ).
% conversion
:- func r(float) = quaternion is det.
% operations
:- func norm(quaternion) = float is det.
:- func -quaternion = quaternion is det.
:- func conjugate(quaternion) = quaternion is det.
:- func quaternion + quaternion = quaternion is det.
:- func quaternion * quaternion = quaternion is det.
:- implementation.
:- import_module math.
% conversion
r(W) = q(W, 0.0, 0.0, 0.0).
% operations
norm(q(W, I, J, K)) = math.sqrt(W*W + I*I + J*J + K*K).
-q(W, I, J, K) = q(-W, -I, -J, -K).
conjugate(q(W, I, J, K)) = q(W, -I, -J, -K).
q(W0, I0, J0, K0) + q(W1, I1, J1, K1) = q(W0+W1, I0+I1, J0+J1, K0+K1).
q(W0, I0, J0, K0) * q(W1, I1, J1, K1) = q(W0*W1 - I0*I1 - J0*J1 - K0*K1,
W0*I1 + I0*W1 + J0*K1 - K0*J1,
W0*J1 - I0*K1 + J0*W1 + K0*I1,
W0*K1 + I0*J1 - J0*I1 + K0*W1 ).
|
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.
|
#F.23
|
F#
|
let s = "let s = {0}{1}{0} in System.Console.WriteLine(s, char 34, s);;" in System.Console.WriteLine(s, char 34, s);;
|
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.
|
#zkl
|
zkl
|
fcn qselect(list,nth){ // in place quick select
fcn(list,left,right,nth){
if (left==right) return(list[left]);
pivotIndex:=(left+right)/2; // or median of first,middle,last
// partition
pivot:=list[pivotIndex];
list.swap(pivotIndex,right); // move pivot to end
pivotIndex := left;
i:=left; do(right-left){ // foreach i in ([left..right-1])
if (list[i] < pivot){
list.swap(i,pivotIndex);
pivotIndex += 1;
}
i += 1;
}
list.swap(pivotIndex,right); // move pivot to final place
if (nth==pivotIndex) return(list[nth]);
if (nth<pivotIndex) return(self.fcn(list,left,pivotIndex-1,nth));
return(self.fcn(list,pivotIndex+1,right,nth));
}(list.copy(),0,list.len()-1,nth);
}
|
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
|
#Oberon-2
|
Oberon-2
|
MODULE RangeExtraction;
IMPORT Out;
PROCEDURE Range(s: ARRAY OF INTEGER);
VAR
i,j: INTEGER;
PROCEDURE Emit(sep: CHAR);
BEGIN
IF i > 2 THEN
Out.Int(s[j],3);Out.Char('-');Out.Int(s[j + i - 1],3);Out.Char(sep);
INC(j,i)
ELSE
Out.Int(s[j],3);Out.Char(sep);
INC(j)
END;
END Emit;
BEGIN
j := 0;i := -1;
LOOP
INC(i);
IF j + i >= LEN(s) THEN
Emit(0AX);
EXIT
ELSIF s[j + i] # (s[j] + i) THEN
Emit(',');
i := 0;
END
END
END Range;
VAR
seq0: ARRAY 33 OF INTEGER;
seq1: ARRAY 20 OF INTEGER;
BEGIN
seq0[0] := 0;
seq0[1] := 1;
seq0[2] := 2;
seq0[3] := 4;
seq0[4] := 6;
seq0[5] := 7;
seq0[6] := 8;
seq0[7] := 11;
seq0[8] := 12;
seq0[9] := 14;
seq0[10] := 15;
seq0[11] := 16;
seq0[12] := 17;
seq0[13] := 18;
seq0[14] := 19;
seq0[15] := 20;
seq0[16] := 21;
seq0[17] := 22;
seq0[18] := 23;
seq0[19] := 24;
seq0[20] := 25;
seq0[21] := 27;
seq0[22] := 28;
seq0[23] := 29;
seq0[24] := 30;
seq0[25] := 31;
seq0[26] := 32;
seq0[27] := 33;
seq0[28] := 35;
seq0[29] := 36;
seq0[30] := 37;
seq0[31] := 38;
seq0[32] := 39;
Range(seq0);
seq1[0] := -6;
seq1[1] := -3;
seq1[2] := -2;
seq1[3] := -1;
seq1[4] := 0;
seq1[5] := 1;
seq1[6] := 3;
seq1[7] := 4;
seq1[8] := 5;
seq1[9] := 7;
seq1[10] := 8;
seq1[11] := 9;
seq1[12] := 10;
seq1[13] := 11;
seq1[14] := 14;
seq1[15] := 15;
seq1[16] := 17;
seq1[17] := 18;
seq1[18] := 19;
seq1[19] := 20;
Range(seq1)
END RangeExtraction.
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const func float: frand is func # Uniform distribution, (0..1]
result
var float: frand is 0.0;
begin
repeat
frand := rand(0.0, 1.0);
until frand <> 0.0;
end func;
const func float: randomNormal is # Normal distribution, centered on 0, std dev 1
return sqrt(-2.0 * log(frand)) * cos(2.0 * PI * frand);
const proc: main is func
local
var integer: i is 0;
var array float: rands is 1000 times 0.0;
begin
for i range 1 to length(rands) do
rands[i] := 1.0 + 0.5 * randomNormal;
end for;
end func;
|
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
|
#Sidef
|
Sidef
|
var arr = 1000.of { 1 + (0.5 * sqrt(-2 * 1.rand.log) * cos(Num.tau * 1.rand)) }
arr.each { .say }
|
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
|
#SenseTalk
|
SenseTalk
|
// read the configuration file and get a list of just the interesting lines
set lines to each line of file "config.txt" where char 1 of each isn't in ("#", ";", "")
set the listFormat's quotes to quote -- be sure to quote values for evaluating
repeat with each configLine in lines
put word 1 of configLine into varName
insert varName into variableNames -- make a list of all config variables
put (words 2 to last of configLine) split by comma into values
put trim of each item of values into values -- trim any leading/trailing spaces
if values is empty then set values to true -- no value means boolean true
do "set" && varName && "to" && values -- assign value to variable
end repeat
repeat with each name in variableNames
put "Variable" && name && "is" && value(name)
end repeat
|
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
|
#Run_BASIC
|
Run BASIC
|
PRINT rangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")
end
function rangeExpand$(range$)
[loop]
i = INSTR(range$, "-", i+1)
IF i THEN
j = i
WHILE MID$(range$,j-1,1) <> "," AND j <> 1
j = j - 1
wend
IF i > j then
IF MID$(range$,j,i-j) <> str$(i-j)+" " THEN
t$ = ""
FOR k = VAL(MID$(range$,j)) TO VAL(MID$(range$,i+1))-1
t$ = t$ + str$(k) + ","
NEXT k
range$ = LEFT$(range$,j-1) + t$ + MID$(range$,i+1)
i = j + LEN(t$) + 2
end if
end if
end if
if i <> 0 then goto [loop]
rangeExpand$ = range$
end function
|
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
|
#Rust
|
Rust
|
use std::str::FromStr;
// Precondition: range doesn't contain multibyte UTF-8 characters
fn range_expand(range : &str) -> Vec<i32> {
range.split(',').flat_map(|item| {
match i32::from_str(item) {
Ok(n) => n..n+1,
_ => {
let dashpos=
match item.rfind("--") {
Some(p) => p,
None => item.rfind('-').unwrap(),
};
let rstart=i32::from_str(
unsafe{ item.slice_unchecked(0,dashpos)} ).unwrap();
let rend=i32::from_str(
unsafe{ item.slice_unchecked(dashpos+1,item.len()) } ).unwrap();
rstart..rend+1
},
}
}).collect()
}
fn main() {
println!("{:?}", range_expand("-6,-3--1,3-5,7-11,14,15,17-20"));
}
|
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.
|
#SenseTalk
|
SenseTalk
|
repeat with each line of file "input.txt"
put it
end repeat
|
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.
|
#Sidef
|
Sidef
|
File(__FILE__).open_r.each { |line|
print line
}
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Scheme
|
Scheme
|
(define (string-reverse s)
(list->string (reverse (string->list s))))
|
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
|
#Klingphix
|
Klingphix
|
{ include ..\Utilitys.tlhy }
"..\Utilitys.tlhy" load
:push! { l i -- l&i }
0 put
;
:empty? { l -- flag }
len not { len 0 equal }
;
:pop! { l -- l-1 }
empty? (
["Empty"]
[pop swap]
) if
;
( ) { empty queue }
1 push! 2 push! 3 push!
pop! ? pop! ? pop! ? pop! ?
"End " input
|
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.
|
#Nim
|
Nim
|
import math, tables
type Quaternion* = object
a, b, c, d: float
func initQuaternion*(a, b, c, d = 0.0): Quaternion =
Quaternion(a: a, b: b, c: c, d: d)
func `-`*(q: Quaternion): Quaternion =
initQuaternion(-q.a, -q.b, -q.c, -q.d)
func `+`*(q: Quaternion; r: float): Quaternion =
initQuaternion(q.a + r, q.b, q.c, q.d)
func `+`*(r: float; q: Quaternion): Quaternion =
initQuaternion(q.a + r, q.b, q.c, q.d)
func `+`*(q1, q2: Quaternion): Quaternion =
initQuaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + q2.d)
func `*`*(q: Quaternion; r: float): Quaternion =
initQuaternion(q.a * r, q.b * r, q.c * r, q.d * r)
func `*`*(r: float; q: Quaternion): Quaternion =
initQuaternion(q.a * r, q.b * r, q.c * r, q.d * r)
func `*`*(q1, q2: Quaternion): Quaternion =
initQuaternion(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)
func conjugate*(q: Quaternion): Quaternion =
initQuaternion(q.a, -q.b, -q.c, -q.d)
func norm*(q: Quaternion): float =
sqrt(q.a * q.a + q.b * q.b + q.c * q.c + q.d * q.d)
func `==`*(q: Quaternion; r: float): bool =
if q.b != 0 or q.c != 0 or q.d != 0: false
else: q.a == r
func `$`(q: Quaternion): string =
## Return the representation of a quaternion.
const Letter = {"a": "", "b": "i", "c": "j", "d": "k"}.toTable
if q == 0: return "0"
for name, value in q.fieldPairs:
if value != 0:
var val = value
if result.len != 0:
result.add if value >= 0: '+' else: '-'
val = abs(val)
result.add $val & Letter[name]
when isMainModule:
let
q = initQuaternion(1, 2, 3, 4)
q1 = initQuaternion(2, 3, 4, 5)
q2 = initQuaternion(3, 4, 5, 6)
r = 7.0
echo "∥q∥ = ", norm(q)
echo "-q = ", -q
echo "q* = ", conjugate(q)
echo "q + r = ", q + r
echo "r + q = ", r + q
echo "q1 + q2 = ", q1 + q2
echo "qr = ", q * r
echo "rq = ", r * q
echo "q1 * q2 = ", q1 * q2
echo "q2 * q1 = ", 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.
|
#Factor
|
Factor
|
"%s [ 34 1string dup surround ] keep printf" [ 34 1string dup surround ] keep printf
|
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
|
#Objeck
|
Objeck
|
class IdentityMatrix {
function : Main(args : String[]) ~ Nil {
Compress2Range("-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20")->PrintLine();
Compress2Range("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")->PrintLine();
}
function : Compress2Range(expanded : String) ~ String {
result := "";
nums := expanded->ReplaceAll(" ", "")->Split(",");
firstNum := nums[0]->ToInt();
rangeSize := 0;
for(i:= 1; i < nums->Size(); i += 1;) {
thisNum := nums[i]->ToInt();
if(thisNum - firstNum - rangeSize = 1) {
rangeSize += 1;
}
else{
if(rangeSize <> 0){
result->Append(firstNum);
result->Append((rangeSize = 1) ? ",": "-");
result->Append(firstNum+rangeSize);
result->Append(",");
rangeSize := 0;
}
else {
result->Append(firstNum);
result->Append(",");
};
firstNum := thisNum;
};
};
if(rangeSize <> 0){
result->Append(firstNum);
result->Append((rangeSize = 1) ? "," : "-");
result->Append(firstNum + rangeSize);
rangeSize := 0;
}
else {
result->Append(firstNum);
};
return result;
}
}
|
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
|
#Standard_ML
|
Standard ML
|
val seed = 0w42;
val gen = Rand.mkRandom seed;
fun random_gaussian () =
1.0 + Math.sqrt (~2.0 * Math.ln (Rand.norm (gen ()))) * Math.cos (2.0 * Math.pi * Rand.norm (gen ()));
val a = List.tabulate (1000, fn _ => random_gaussian ());
|
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
|
#Stata
|
Stata
|
clear all
set obs 1000
gen x=rnormal(1,0.5)
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#Sidef
|
Sidef
|
var fullname = (var favouritefruit = "");
var needspeeling = (var seedsremoved = false);
var otherfamily = [];
ARGF.each { |line|
var(key, value) = line.strip.split(/\h+/, 2)...;
given(key) {
when (nil) { }
when (/^([#;]|\h*$)/) { }
when ("FULLNAME") { fullname = value }
when ("FAVOURITEFRUIT") { favouritefruit = value }
when ("NEEDSPEELING") { needspeeling = true }
when ("SEEDSREMOVED") { seedsremoved = true }
when ("OTHERFAMILY") { otherfamily = value.split(',')»strip»() }
default { say "#{key}: unknown key" }
}
}
say "fullname = #{fullname}";
say "favouritefruit = #{favouritefruit}";
say "needspeeling = #{needspeeling}";
say "seedsremoved = #{seedsremoved}";
otherfamily.each_kv {|i, name|
say "otherfamily(#{i+1}) = #{name}";
}
|
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
|
#S-lang
|
S-lang
|
variable r_expres = "-6,-3--1,3-5,7-11,14,15,17-20", s, r_expan = {}, dpos, i;
foreach s (strchop(r_expres, ',', 0))
{
% S-Lang built-in RE's are fairly limited, and have a quirk:
% grouping is done with \\( and \\), not ( and )
% [PCRE and Oniguruma RE's are available via standard libraries]
if (string_match(s, "-?[0-9]+\\(-\\)-?[0-9]+", 1)) {
(dpos, ) = string_match_nth(1);
% Create/loop-over a "range array": from num before - to num after it:
foreach i ( [integer(substr(s, 1, dpos)) : integer(substr(s, dpos+2, -1))] )
list_append(r_expan, string(i));
}
else
list_append(r_expan, s);
}
print(strjoin(list_to_array(r_expan), ", "));
|
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
|
#Scala
|
Scala
|
def rangex(str: String): Seq[Int] =
str split "," flatMap { (s) =>
val r = """(-?\d+)(?:-(-?\d+))?""".r
val r(a,b) = s
if (b == null) Seq(a.toInt) else a.toInt to b.toInt
}
|
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.
|
#Smalltalk
|
Smalltalk
|
(StandardFileStream oldFileNamed: 'test.txt') contents lines do: [ :each | Transcript show: each. ]
|
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.
|
#SNOBOL4
|
SNOBOL4
|
input(.infile,20,"readfrom.txt") :f(end)
rdloop output = infile :s(rdloop)
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
|
#Scratch
|
Scratch
|
#!/bin/sed -f
/../! b
# Reverse a line. Begin embedding the line between two newlines
s/^.*$/\
&\
/
# Move first character at the end. The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx
# Remove the newline markers
s/\n//g
|
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
|
#Kotlin
|
Kotlin
|
// version 1.1.2
import java.util.LinkedList
class Queue<E> {
private val data = LinkedList<E>()
val size get() = data.size
val empty get() = size == 0
fun push(element: E) = data.add(element)
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty queue")
return data.removeFirst()
}
val top: E
get() {
if (empty) throw RuntimeException("Empty queue can't have a top element")
return data.first()
}
fun clear() = data.clear()
override fun toString() = data.toString()
}
fun main(args: Array<String>) {
val q = Queue<Int>()
(1..5).forEach { q.push(it) }
println(q)
println("Size of queue = ${q.size}")
print("Popping: ")
(1..3).forEach { print("${q.pop()} ") }
println("\nRemaining in queue: $q")
println("Top element is now ${q.top}")
q.clear()
println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
try {
q.pop()
}
catch (e: Exception) {
println(e.message)
}
}
|
http://rosettacode.org/wiki/Quaternion_type
|
Quaternion type
|
Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
where the real part, a is -3.0 and the complex part, b is +2.0.
A quaternion has one real part and three imaginary parts, i, j, and k.
A quaternion might be written as a + bi + cj + dk.
In the quaternion numbering system:
i∙i = j∙j = k∙k = i∙j∙k = -1, or more simply,
ii = jj = kk = ijk = -1.
The order of multiplication is important, as, in general, for two quaternions:
q1 and q2: q1q2 ≠ q2q1.
An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position.
So the example above would be written as (1, 2, 3, 4)
Task
Given the three quaternions and their components:
q = (1, 2, 3, 4) = (a, b, c, d)
q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number r = 7.
Create functions (or classes) to perform simple maths with quaternions including computing:
The norm of a quaternion:
=
a
2
+
b
2
+
c
2
+
d
2
{\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}}
The negative of a quaternion:
= (-a, -b, -c, -d)
The conjugate of a quaternion:
= ( a, -b, -c, -d)
Addition of a real number r and a quaternion q:
r + q = q + r = (a+r, b, c, d)
Addition of two quaternions:
q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
Multiplication of a real number and a quaternion:
qr = rq = (ar, br, cr, dr)
Multiplication of two quaternions q1 and q2 is given by:
( a1a2 − b1b2 − c1c2 − d1d2,
a1b2 + b1a2 + c1d2 − d1c2,
a1c2 − b1d2 + c1a2 + d1b2,
a1d2 + b1c2 − c1b2 + d1a2 )
Show that, for the two quaternions q1 and q2:
q1q2 ≠ q2q1
If a language has built-in support for quaternions, then use it.
C.f.
Vector products
On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
|
#OCaml
|
OCaml
|
type quaternion = {a: float; b: float; c: float; d: float}
let norm q = sqrt (q.a**2.0 +.
q.b**2.0 +.
q.c**2.0 +.
q.d**2.0 )
let floatneg r = ~-. r (* readability *)
let negative q =
{a = floatneg q.a;
b = floatneg q.b;
c = floatneg q.c;
d = floatneg q.d }
let conjugate q =
{a = q.a;
b = floatneg q.b;
c = floatneg q.c;
d = floatneg q.d }
let addrq r q = {q with a = q.a +. r}
let addq q1 q2 =
{a = q1.a +. q2.a;
b = q1.b +. q2.b;
c = q1.c +. q2.c;
d = q1.d +. q2.d }
let multrq r q =
{a = q.a *. r;
b = q.b *. r;
c = q.c *. r;
d = q.d *. r }
let multq q1 q2 =
{a = q1.a*.q2.a -. q1.b*.q2.b -. q1.c*.q2.c -. q1.d*.q2.d;
b = q1.a*.q2.b +. q1.b*.q2.a +. q1.c*.q2.d -. q1.d*.q2.c;
c = q1.a*.q2.c -. q1.b*.q2.d +. q1.c*.q2.a +. q1.d*.q2.b;
d = q1.a*.q2.d +. q1.b*.q2.c -. q1.c*.q2.b +. q1.d*.q2.a }
let qmake a b c d = {a;b;c;d} (* readability omitting a= b=... *)
let qstring q =
Printf.sprintf "(%g, %g, %g, %g)" q.a q.b q.c q.d ;;
(* test data *)
let q = qmake 1.0 2.0 3.0 4.0
let q1 = qmake 2.0 3.0 4.0 5.0
let q2 = qmake 3.0 4.0 5.0 6.0
let r = 7.0
let () = (* written strictly to spec *)
let pf = Printf.printf in
pf "starting with data q=%s, q1=%s, q2=%s, r=%g\n" (qstring q) (qstring q1) (qstring q2) r;
pf "1. norm of q = %g \n" (norm q) ;
pf "2. negative of q = %s \n" (qstring (negative q));
pf "3. conjugate of q = %s \n" (qstring (conjugate q));
pf "4. adding r to q = %s \n" (qstring (addrq r q));
pf "5. adding q1 and q2 = %s \n" (qstring (addq q1 q2));
pf "6. multiply r and q = %s \n" (qstring (multrq r q));
pf "7. multiply q1 and q2 = %s \n" (qstring (multq q1 q2));
pf "8. instead q2 * q1 = %s \n" (qstring (multq q2 q1));
pf "\n";
|
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.
|
#FALSE
|
FALSE
|
["'[,34,$!34,'],!"]'[,34,$!34,'],!
|
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
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
NSString *extractRanges(NSArray *nums) {
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
for (NSNumber *n in nums) {
if ([n integerValue] < 0)
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"negative number not supported" userInfo:nil];
[indexSet addIndex:[n unsignedIntegerValue]];
}
NSMutableString *s = [[NSMutableString alloc] init];
[indexSet enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
if (s.length)
[s appendString:@","];
if (range.length == 1)
[s appendFormat:@"%lu", range.location];
else if (range.length == 2)
[s appendFormat:@"%lu,%lu", range.location, range.location+1];
else
[s appendFormat:@"%lu-%lu", range.location, range.location+range.length-1];
}];
return s;
}
int main() {
@autoreleasepool {
NSLog(@"%@", extractRanges(@[@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]));
}
return 0;
}
|
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
|
#Tcl
|
Tcl
|
package require Tcl 8.5
variable ::pi [expr acos(0)]
proc ::tcl::mathfunc::nrand {} {
expr {sqrt(-2*log(rand())) * cos(2*$::pi*rand())}
}
set mean 1.0
set stddev 0.5
for {set i 0} {$i < 1000} {incr i} {
lappend result [expr {$mean + $stddev*nrand()}]
}
|
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
|
#Smalltalk
|
Smalltalk
|
dict := Dictionary new.
configFile asFilename readingLinesDo:[:line |
(line isEmpty or:[ line startsWithAnyOf:#('#' ';') ]) ifFalse:[
s := line readStream.
(s skipSeparators; atEnd) ifFalse:[
|optionName values|
optionName := s upToSeparator.
values := (s upToEnd asCollectionOfSubstringsSeparatedBy:$,)
collect:[:each | each withoutSeparators]
thenSelect:[:vals | vals notEmpty].
dict at:optionName asLowercase put:(values isEmpty
ifTrue:[true]
ifFalse:[
values size == 1
ifTrue:[values first]
ifFalse:[values]]).
]
].
]
|
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
|
#Scheme
|
Scheme
|
(define split
(lambda (str char skip count)
(let ((len (string-length str)))
(let loop ((index skip)
(last-index 0)
(result '()))
(if (= index len)
(reverse (cons (substring str last-index) result))
(if (eq? char (string-ref str index))
(loop (if (= count (+ 2 (length result)))
len
(+ index 1))
(+ index 1)
(cons char (cons (substring str last-index index)
result)))
(loop (+ index 1)
last-index
result)))))))
(define range-expand
(lambda (str)
(for-each
(lambda (token)
(if (char? token)
(display token)
(let ((range (split token #\- 1 2)))
(if (null? (cdr range))
(display (car range))
(do ((count (string->number (list-ref range 0)) (+ 1 count))
(high (string->number (list-ref range 2))))
((= count high) (display high))
(display count)
(display ","))))))
(split str #\, 0 0))
(newline)))
|
http://rosettacode.org/wiki/Read_a_file_line_by_line
|
Read a file line by line
|
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
|
#Sparkling
|
Sparkling
|
let f = fopen("foo.txt", "r");
if f != nil {
var line;
while (line = fgetline(f)) != nil {
print(line);
}
fclose(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
|
#Sed
|
Sed
|
#!/bin/sed -f
/../! b
# Reverse a line. Begin embedding the line between two newlines
s/^.*$/\
&\
/
# Move first character at the end. The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx
# Remove the newline markers
s/\n//g
|
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
|
#LabVIEW
|
LabVIEW
|
define myqueue => type {
data store = list
public onCreate(...) => {
if(void != #rest) => {
with item in #rest do .`store`->insert(#item)
}
}
public push(value) => .`store`->insertLast(#value)
public pop => {
handle => {
.`store`->removefirst
}
return .`store`->first
}
public isEmpty => (.`store`->size == 0)
}
|
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.
|
#Octave
|
Octave
|
pkg install -forge quaternion
|
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.
|
#Fish
|
Fish
|
00000000000000000000++++++++++++++++++ v
2[$:{:@]$g:0=?v >o:4a*=?!v~1+:3=?;0ao>
>~" "^ >1+ ^
|
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
|
#OCaml
|
OCaml
|
let range_extract = function
| [] -> []
| x::xs ->
let f (i,j,ret) k =
if k = succ j then (i,k,ret) else (k,k,(i,j)::ret) in
let (m,n,ret) = List.fold_left f (x,x,[]) xs in
List.rev ((m,n)::ret)
let string_of_range rng =
let str (a,b) =
if a = b then string_of_int a
else Printf.sprintf "%d%c%d" a (if b = succ a then ',' else '-') b in
String.concat "," (List.map str rng)
let () =
let li =
[ 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 ]
in
let rng = range_extract li in
print_endline(string_of_range rng)
|
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
|
#TI-83_BASIC
|
TI-83 BASIC
|
randNorm(1,.5)
|
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
|
#TorqueScript
|
TorqueScript
|
for (%i = 0; %i < 1000; %i++)
%list[%i] = 1 + mSqrt(-2 * mLog(getRandom())) * mCos(2 * $pi * getRandom());
|
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
|
#Tcl
|
Tcl
|
proc readConfig {filename {defaults {}}} {
global cfg
# Read the file in
set f [open $filename]
set contents [read $f]
close $f
# Set up the defaults, if supplied
foreach {var defaultValue} $defaults {
set cfg($var) $defaultValue
}
# Parse the file's contents
foreach line [split $contents "\n"] {
set line [string trim $line]
# Skip comments
if {[string match "#*" $line] || [string match ";*" $line]} continue
# Skip blanks
if {$line eq ""} continue
if {[regexp {^\w+$} $line]} {
# Boolean case
set cfg([string tolower $line]) true
} elseif {[regexp {^(\w+)\s+([^,]+)$} $line -> var value]} {
# Simple value case
set cfg([string tolower $var]) $value
} elseif {[regexp {^(\w+)\s+(.+)$} $line -> var listValue]} {
# List value case
set cfg([string tolower $var]) {}
foreach value [split $listValue ","] {
lappend cfg([string tolower $var]) [string trim $value]
}
} else {
error "malformatted config file: $filename"
}
}
}
# Need to supply some default values due to config file grammar ambiguities
readConfig "fruit.cfg" {
needspeeling false
seedsremoved false
}
puts "Full name: $cfg(fullname)"
puts "Favourite: $cfg(favouritefruit)"
puts "Peeling? $cfg(needspeeling)"
puts "Unseeded? $cfg(seedsremoved)"
puts "Family: $cfg(otherfamily)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.