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/Read_a_specific_line_from_a_file
|
Read a specific line from a file
|
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
|
#Vedit_macro_language
|
Vedit macro language
|
File_Open("example.txt", BROWSE)
Goto_Line(7)
if (Cur_Line < 7) {
Statline_Message("File contains too few lines")
} else {
if (At_EOL) {
Statline_Message("Empty line")
}
Reg_Copy(10, 1)
}
Buf_Close(NOMSG)
|
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.
|
#Factor
|
Factor
|
USING: combinators kernel make math locals prettyprint sequences ;
IN: rosetta-code.quickselect
:: quickselect ( k seq -- n )
seq unclip :> ( xs x )
xs [ x < ] partition :> ( ys zs )
ys length :> l
{
{ [ k l < ] [ k ys quickselect ] }
{ [ k l > ] [ k l - 1 - zs quickselect ] }
[ x ]
} cond ;
: quickselect-demo ( -- )
{ 9 8 7 6 5 0 1 2 3 4 } dup length <iota> swap
[ [ quickselect , ] curry each ] { } make . ;
MAIN: quickselect-demo
|
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.
|
#Fortran
|
Fortran
|
INTEGER FUNCTION FINDELEMENT(K,A,N) !I know I can.
Chase an order statistic: FindElement(N/2,A,N) leads to the median, with some odd/even caution.
Careful! The array is shuffled: for i < K, A(i) <= A(K); for i > K, A(i) >= A(K).
Charles Anthony Richard Hoare devised this method, as related to his famous QuickSort.
INTEGER K,N !Find the K'th element in order of an array of N elements, not necessarily in order.
INTEGER A(N),HOPE,PESTY !The array, and like associates.
INTEGER L,R,L2,R2 !Fingers.
L = 1 !Here we go.
R = N !The bounds of the work area within which the K'th element lurks.
DO WHILE (L .LT. R) !So, keep going until it is clamped.
HOPE = A(K) !If array A is sorted, this will be rewarded.
L2 = L !But it probably isn't sorted.
R2 = R !So prepare a scan.
DO WHILE (L2 .LE. R2) !Keep squeezing until the inner teeth meet.
DO WHILE (A(L2) .LT. HOPE) !Pass elements less than HOPE.
L2 = L2 + 1 !Note that at least element A(K) equals HOPE.
END DO !Raising the lower jaw.
DO WHILE (HOPE .LT. A(R2)) !Elements higher than HOPE
R2 = R2 - 1 !Are in the desired place.
END DO !And so we speed past them.
IF (L2 - R2) 1,2,3 !How have the teeth paused?
1 PESTY = A(L2) !On grit. A(L2) > HOPE and A(R2) < HOPE.
A(L2) = A(R2) !So swap the two troublemakers.
A(R2) = PESTY !To be as if they had been in the desired order all along.
2 L2 = L2 + 1 !Advance my teeth.
R2 = R2 - 1 !As if they hadn't paused on this pest.
3 END DO !And resume the squeeze, hopefully closing in K.
IF (R2 .LT. K) L = L2 !The end point gives the order position of value HOPE.
IF (K .LT. L2) R = R2 !But we want the value of order position K.
END DO !Have my teeth met yet?
FINDELEMENT = A(K) !Yes. A(K) now has the K'th element in order.
END FUNCTION FINDELEMENT !Remember! Array A has likely had some elements moved!
PROGRAM POKE
INTEGER FINDELEMENT !Not the default type for F.
INTEGER N !The number of elements.
PARAMETER (N = 10) !Fixed for the test problem.
INTEGER A(66) !An array of integers.
DATA A(1:N)/9, 8, 7, 6, 5, 0, 1, 2, 3, 4/ !The specified values.
WRITE (6,1) A(1:N) !Announce, and add a heading.
1 FORMAT ("Selection of the i'th element in order from an array.",/
1 "The array need not be in order, and may be reordered.",/
2 " i Val:Array elements...",/,8X,666I2)
DO I = 1,N !One by one,
WRITE (6,2) I,FINDELEMENT(I,A,N),A(1:N) !Request the i'th element.
2 FORMAT (I3,I4,":",666I2) !Match FORMAT 1.
END DO !On to the next trial.
END !That was easy.
|
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
|
#Erlang
|
Erlang
|
-module( range ).
-export( [extraction/1, task/0] ).
extraction( [H | T] ) when is_integer(H) ->
Reversed_extracts = extraction_acc( lists:foldl(fun extraction/2, {H, []}, T) ),
string:join( lists:reverse(Reversed_extracts), "," ).
task() ->
io:fwrite( "~p~n", [extraction([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])] ).
extraction( N, {Start, Acc} ) when N =:= Start + 1 -> {Start, N, Acc};
extraction( N, {Start, Acc} ) -> {N, extraction_acc( {Start, Acc} )};
extraction( N, {Start, Stop, Acc} ) when N =:= Stop + 1 -> {Start, N, Acc};
extraction( N, {Start, Stop, Acc} ) -> {N, extraction_acc( {Start, Stop, Acc} )}.
extraction_acc( {N, Acc} ) -> [erlang:integer_to_list(N) | Acc];
extraction_acc( {Start, Stop, Acc} ) when Stop > Start + 1 -> [erlang:integer_to_list(Start) ++ "-" ++ erlang:integer_to_list(Stop) | Acc];
extraction_acc( {Start, Stop, Acc} ) -> [erlang:integer_to_list(Stop), erlang:integer_to_list(Start) | Acc]. % Reversed
|
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
|
#Java
|
Java
|
double[] list = new double[1000];
double mean = 1.0, std = 0.5;
Random rng = new Random();
for(int i = 0;i<list.length;i++) {
list[i] = mean + std * rng.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
|
#JavaScript
|
JavaScript
|
function randomNormal() {
return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}
var a = []
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
}
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Tcl
|
Tcl
|
rand
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#TI-83_BASIC
|
TI-83 BASIC
|
rand
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#TXR
|
TXR
|
echo $RANDOM
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#UNIX_Shell
|
UNIX Shell
|
echo $RANDOM
|
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
|
#Ksh
|
Ksh
|
#!/bin/ksh
# Read a configuration file
# # Variables:
#
# # The configuration file (below) could be read in from a file
# But this method keeps everything together.
# e.g. config=$(< /path/to/config_file)
integer config_num=0
config='# 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'
isComment='#|;'
paraDelim=' |='
boolean="SEEDSREMOVED|NEEDSPEELING"
typeset -T Config_t=(
typeset -h 'Full name' fullname
typeset -h 'Favorite fruit' favouritefruit
typeset -h 'Boolean NEEDSPEELING' needspeeling=false
typeset -h 'Boolean SEEDSREMOVED' seedsremoved=false
typeset -a -h 'Other family' otherfamily
function set_name {
typeset fn ; fn=$(echo $1) # Strip any leading/trailing white space
_.fullname="${fn}"
}
function set_fruit {
typeset fruit ; fruit=$(echo $1)
_.favouritefruit="${fruit}"
}
function set_bool {
typeset bool ; typeset -u bool=$1
case ${bool} in
NEEDSPEELING) _.needspeeling=true ;;
SEEDSREMOVED) _.seedsremoved=true ;;
esac
}
function set_family {
typeset ofam ; ofam=$(echo $1)
typeset farr i ; typeset -a farr ; integer i
oldIFS="$IFS" ; IFS=',' ; farr=( ${ofam} ) ; IFS="${oldIFS}"
for ((i=0; i<${#farr[*]}; i++)); do
_.otherfamily[i]=$(echo ${farr[i]})
done
}
)
# # Functions:
#
# # Function _parseconf(config) - Parse uncommented lines
#
function _parseconf {
typeset _cfg ; _cfg="$1"
typeset _conf ; nameref _conf="$2"
echo "${_cfg}" | \
while read; do
[[ $REPLY == @(${isComment})* ]] || [[ $REPLY == '' ]] && continue
_parseline "$REPLY" _conf
done
}
function _parseline {
typeset _line ; _line=$(echo $1)
typeset _conf ; nameref _conf="$2"
typeset _param _value ; typeset -u _param
_param=${_line%%+(${paraDelim})*}
_value=${_line#*+(${paraDelim})}
if [[ ${_param} == @(${boolean}) ]]; then
_conf.set_bool ${_param}
else
case ${_param} in
FULLNAME) _conf.set_name "${_value}" ;;
FAVOURITEFRUIT) _conf.set_fruit ${_value} ;;
OTHERFAMILY) _conf.set_family "${_value}" ;;
esac
fi
}
######
# main #
######
typeset -a configuration # Indexed array of configurations
Config_t configuration[config_num]
_parseconf "${config}" configuration[config_num]
for cnum in ${!configuration[*]}; do
printf "fullname = %s\n" "${configuration[cnum].fullname}"
printf "favouritefruit = %s\n" ${configuration[cnum].favouritefruit}
printf "needspeeling = %s\n" ${configuration[cnum].needspeeling}
printf "seedsremoved = %s\n" ${configuration[cnum].seedsremoved}
for ((i=0; i<${#configuration[cnum].otherfamily[*]}; i++)); do
print "otherfamily($((i+1))) = ${configuration[cnum].otherfamily[i]}"
done
done
|
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
|
#Haskell
|
Haskell
|
> expandRange "-6,-3--1,3-5,7-11,14,15,17-20"
[-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.
|
#Groovy
|
Groovy
|
new File("Test.txt").eachLine { line, lineNumber ->
println "processing line $lineNumber: $line"
}
|
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.
|
#Haskell
|
Haskell
|
main = do
file <- readFile "linebyline.hs"
mapM_ putStrLn (lines file)
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
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
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#Wren
|
Wren
|
import "/math" for Nums
import "/fmt" for Fmt
/* all ranking functions assume the array of Pairs is non-empty and already sorted
by decreasing order of scores and then, if the scores are equal, by reverse
alphabetic order of names
*/
var standardRanking = Fn.new { |scores|
var rankings = List.filled(scores.count, 0)
rankings[0] = 1
for (i in 1...scores.count) {
rankings[i] = (scores[i][0] == scores[i-1][0]) ? rankings[i-1] : i + 1
}
return rankings
}
var modifiedRanking = Fn.new { |scores|
var rankings = List.filled(scores.count, 0)
rankings[0] = 1
for (i in 1...scores.count) {
rankings[i] = i + 1
var currScore = scores[i][0]
for (j in i-1..0) {
if (currScore != scores[j][0]) break
rankings[j] = i + 1
}
}
return rankings
}
var denseRanking = Fn.new { |scores|
var rankings = List.filled(scores.count, 0)
rankings[0] = 1
var prevRanking = 1
for (i in 1...scores.count) {
rankings[i] = (scores[i][0] == scores[i-1][0]) ? prevRanking : (prevRanking = prevRanking+1)
}
return rankings
}
var ordinalRanking = Fn.new { |scores| (1..scores.count).toList }
var fractionalRanking = Fn.new { |scores|
var rankings = List.filled(scores.count, 0)
rankings[0] = 1
for (i in 1...scores.count) {
var k = i
var currScore = scores[i][0]
for (j in i-1..0) {
if (currScore != scores[j][0]) break
k = j
}
var avg = Nums.mean(k..i) + 1
for (m in k..i) rankings[m] = avg
}
return rankings
}
var printRankings = Fn.new { |title, rankings, scores|
System.print(title + ":")
for (i in 0...rankings.count) {
System.print("%(rankings[i]) %(scores[i][0]) %(scores[i][1])")
}
System.print()
}
var printFractionalRankings = Fn.new { |title, rankings, scores|
System.print(title + ":")
for (i in 0...rankings.count) {
Fmt.print("$3.2f $d $s", rankings[i], scores[i][0], scores[i][1])
}
System.print()
}
var scores = [[44, "Solomon"], [42, "Jason"], [42, "Errol"], [41, "Garry"],
[41, "Bernard"], [41, "Barry"], [39, "Stephen"]]
printRankings.call("Standard ranking", standardRanking.call(scores), scores)
printRankings.call("Modified ranking", modifiedRanking.call(scores), scores)
printRankings.call("Dense ranking", denseRanking.call(scores), scores)
printRankings.call("Ordinal ranking", ordinalRanking.call(scores), scores)
printFractionalRankings.call("Fractional ranking", fractionalRanking.call(scores), scores)
|
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
|
#Plain_TeX
|
Plain TeX
|
\def\gobtoA#1\revA{}\def\gobtoB#1\revB{}
\def\reverse#1{\reversei{}#1\revA\revB\revB\revB\revB\revB\revB\revB\revB\revA}
\def\reversei#1#2#3#4#5#6#7#8#9{\gobtoB#9\revend\revB\reversei{#9#8#7#6#5#4#3#2#1}}
\def\revend\revB\reversei#1#2\revA{\gobtoA#1}
\reverse{Rosetta}
\bye
|
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
|
#Bracmat
|
Bracmat
|
( queue
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
( dequeue
= x
. !(its.list):?(its.list) (.?x)
& !x
)
(empty=.!(its.list):)
)
|
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.
|
#Common_Lisp
|
Common Lisp
|
(defclass quaternion () ((a :accessor q-a :initarg :a :type real)
(b :accessor q-b :initarg :b :type real)
(c :accessor q-c :initarg :c :type real)
(d :accessor q-d :initarg :d :type real))
(:default-initargs :a 0 :b 0 :c 0 :d 0))
(defun make-q (&optional (a 0) (b 0) (c 0) (d 0))
(make-instance 'quaternion :a a :b b :c c :d d))
(defgeneric sum (x y))
(defmethod sum ((x quaternion) (y quaternion))
(make-q (+ (q-a x) (q-a y))
(+ (q-b x) (q-b y))
(+ (q-c x) (q-c y))
(+ (q-d x) (q-d y))))
(defmethod sum ((x quaternion) (y real))
(make-q (+ (q-a x) y) (q-b x) (q-c x) (q-d x)))
(defmethod sum ((x real) (y quaternion))
(make-q (+ (q-a y) x) (q-b y) (q-c y) (q-d y)))
(defgeneric sub (x y))
(defmethod sub ((x quaternion) (y quaternion))
(make-q (- (q-a x) (q-a y))
(- (q-b x) (q-b y))
(- (q-c x) (q-c y))
(- (q-d x) (q-d y))))
(defmethod sub ((x quaternion) (y real))
(make-q (- (q-a x) y)
(q-b x)
(q-c x)
(q-d x)))
(defmethod sub ((x real) (y quaternion))
(make-q (- (q-a y) x)
(q-b y)
(q-c y)
(q-d y)))
(defgeneric mul (x y))
(defmethod mul ((x quaternion) (y real))
(make-q (* (q-a x) y)
(* (q-b x) y)
(* (q-c x) y)
(* (q-d x) y)))
(defmethod mul ((x real) (y quaternion))
(make-q (* (q-a y) x)
(* (q-b y) x)
(* (q-c y) x)
(* (q-d y) x)))
(defmethod mul ((x quaternion) (y quaternion))
(make-q (- (* (q-a x) (q-a y)) (* (q-b x) (q-b y)) (* (q-c x) (q-c y)) (* (q-d x) (q-d y)))
(- (+ (* (q-a x) (q-b y)) (* (q-b x) (q-a y)) (* (q-c x) (q-d y))) (* (q-d x) (q-c y)))
(- (+ (* (q-a x) (q-c y)) (* (q-c x) (q-a y)) (* (q-d x) (q-b y))) (* (q-b x) (q-d y)))
(- (+ (* (q-a x) (q-d y)) (* (q-b x) (q-c y)) (* (q-d x) (q-a y))) (* (q-c x) (q-b y)))))
(defmethod norm ((x quaternion))
(+ (sqrt (q-a x)) (sqrt (q-b x)) (sqrt (q-c x)) (sqrt (q-d x))))
(defmethod print-object ((x quaternion) stream)
(format stream "~@f~@fi~@fj~@fk" (q-a x) (q-b x) (q-c x) (q-d x)))
(defvar q (make-q 0 1 0 0))
(defvar q1 (make-q 0 0 1 0))
(defvar q2 (make-q 0 0 0 1))
(defvar r 7)
(format t "q+q1+q2 = ~a~&" (reduce #'sum (list q q1 q2)))
(format t "r*(q+q1+q2) = ~a~&" (mul r (reduce #'sum (list q q1 q2))))
(format t "q*q1*q2 = ~a~&" (reduce #'mul (list q q1 q2)))
(format t "q-q1-q2 = ~a~&" (reduce #'sub (list q 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.
|
#beeswax
|
beeswax
|
_4~++~+.@1~0@D@1J
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task
Declare_Queue(String) '' expand Queue type for Strings
Dim stringQueue As Queue(String)
With stringQueue '' push some strings into the Queue
.push("first")
.push("second")
.push("third")
.push("fourth")
.push("fifth")
End With
Print "Number of Strings in the Queue :" ; stringQueue.count
Print "Capacity of string Queue :" ; stringQueue.capacity
Print
' now pop them
While Not stringQueue.empty
Print stringQueue.pop(); " popped"
Wend
Print
Print "Number of Strings in the Queue :" ; stringQueue.count
Print "Capacity of string Queue :" ; stringQueue.capacity '' capacity should be unchanged
Print "Is Queue empty now : "; stringQueue.empty
Print
Print "Press any key to quit"
Sleep
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Go
|
Go
|
package main
import (
"fmt"
"queue"
)
func main() {
q := new(queue.Queue)
fmt.Println("empty?", q.Empty())
x := "black"
fmt.Println("push", x)
q.Push(x)
fmt.Println("empty?", q.Empty())
r, ok := q.Pop()
if ok {
fmt.Println(r, "popped")
} else {
fmt.Println("pop failed")
}
var n int
for _, x := range []string{"blue", "red", "green"} {
fmt.Println("pushing", x)
q.Push(x)
n++
}
for i := 0; i < n; i++ {
r, ok := q.Pop()
if ok {
fmt.Println(r, "popped")
} else {
fmt.Println("pop failed")
}
}
}
|
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
|
Read a specific line from a file
|
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
|
#Wren
|
Wren
|
import "io" for File
var lines = File.read("input.txt").replace("\r", "").split("\n")
if (lines.count < 7) {
System.print("There are only %(lines.count) lines in the file")
} else {
var line7 = lines[6].trim()
if (line7 == "") {
System.print("The seventh line is empty")
} else {
System.print("The seventh line is : %(line7)")
}
}
/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/
|
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.
|
#FreeBASIC
|
FreeBASIC
|
Dim Shared As Long array(9), pivote
Function QuickPartition (array() As Long, izda As Long, dcha As Long, pivote As Long) As Long
Dim As Long pivotValue = array(pivote)
Swap array(pivote), array(dcha)
Dim As Long indice = izda
For i As Long = izda To dcha-1
If array(i) < pivotValue Then
Swap array(indice), array(i)
indice += 1
End If
Next i
Swap array(dcha), array(indice)
Return indice
End Function
Function QuickSelect(array() As Long, izda As Long, dcha As Long, k As Long) As Long
Do
If izda = dcha Then Return array(izda) : End If
pivote = izda
pivote = QuickPartition(array(), izda, dcha, pivote)
Select Case k
Case pivote
Return array(k)
Case Is < pivote
dcha = pivote - 1
Case Is > pivote
izda = pivote + 1
End Select
Loop
End Function
Dim As Long a = Lbound(array), b = Ubound(array)
Print "Array desordenado: ";
For i As Long = a To b
Read array(i)
Print array(i);
Next i
Data 9, 8, 7, 6, 5, 0, 1, 2, 3, 4
Print !"\n\n Array ordenado: ";
For i As Long = a To b
Print QuickSelect(array(), a, b, i);
Next i
Sleep
|
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
|
#Euphoria
|
Euphoria
|
function extract_ranges(sequence s)
integer first
sequence out
out = ""
if length(s) = 0 then
return out
end if
first = 1
for i = 2 to length(s) do
if s[i] != s[i-1]+1 then
if first = i-1 then
out &= sprintf("%d,", s[first])
elsif first = i-2 then
out &= sprintf("%d,%d,", {s[first],s[i-1]})
else
out &= sprintf("%d-%d,", {s[first],s[i-1]})
end if
first = i
end if
end for
if first = length(s) then
out &= sprintf("%d", s[first])
elsif first = length(s)-1 then
out &= sprintf("%d,%d", {s[first],s[$]})
else
out &= sprintf("%d-%d", {s[first],s[$]})
end if
return out
end function
puts(1, extract_ranges({0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}))
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#jq
|
jq
|
# 15-bit integers generated using the same formula as rand() from the Microsoft C Runtime.
# The random numbers are in [0 -- 32767] inclusive.
# Input: an array of length at least 2 interpreted as [count, state, ...]
# Output: [count+1, newstate, r] where r is the next pseudo-random number.
def next_rand_Microsoft:
.[0] as $count | .[1] as $state
| ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ] ;
|
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
|
#Julia
|
Julia
|
randn(1000) * 0.5 + 1
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Ursa
|
Ursa
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
]
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Ursala
|
Ursala
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
]
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Wee_Basic
|
Wee Basic
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
]
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Wren
|
Wren
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
]
|
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
|
#Lasso
|
Lasso
|
local(config = '# 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
')
// if config is in a file collect it like this
//local(config = file('path/and/file.name') -> readstring)
define getconfig(term::string, config::string) => {
local(
regexp = regexp(-find = `(?m)^` + #term + `($|\s*=\s*|\s+)(.*)$`, -input = #config, -ignorecase),
result
)
while(#regexp -> find) => {
#result = (#regexp -> groupcount > 1 ? (#regexp -> matchString(2) -> trim& || true))
if(#result -> asstring >> ',') => {
#result = #result -> split(',')
#result -> foreach => {#1 -> trim}
}
return #result
}
return false
}
local(
fullname = getconfig('FULLNAME', #config),
favorite = getconfig('FAVOURITEFRUIT', #config),
sedsremoved = getconfig('SEEDSREMOVED', #config),
needspeel = getconfig('NEEDSPEELING', #config),
otherfamily = getconfig('OTHERFAMILY', #config)
)
#fullname
'<br />'
#favorite
'<br />'
#sedsremoved
'<br />'
#needspeel
'<br />'
#otherfamily
'<br />'
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
s := "-6,-3--1,3-5,7-11,14,15,17-20"
write("Input string := ",s)
write("Expanded list := ", list2string(range_expand(s)) | "FAILED")
end
procedure range_expand(s) #: return list of integers extracted from an ordered string representation
local R,low,high
R := []
s ? until pos(0) do {
put(R,low := integer(tab(upto(',-')|0))| fail) # get lower bound
if ="-" || (high := integer(tab(find(",")|0))|fail) then
until low = high do put(R,low +:= 1) # find range
=","
}
return R
end
procedure list2string(L) #: helper function to convert a list to a string
local s
every (s := "[ ") ||:= !L || " "
return s || "]"
end
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
f := open("input.txt","r") | stop("cannot open file ",fn)
while line := read(f)
close(f)
end
|
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.
|
#J
|
J
|
cocurrent 'linereader'
NB. configuration parameter
blocksize=: 400000
NB. implementation
offset=: 0
position=: 0
buffer=: ''
lines=: ''
create=: monad define
name=: boxxopen y
size=: 1!:4 name
blocks=: 2 <@(-~/\)\ ~. size <. blocksize * i. 1 + >. size % blocksize
)
readblocks=: monad define
if. 0=#blocks do. return. end.
if. 1<#lines do. return. end.
whilst. -.LF e.chars do.
buffer=: buffer,chars=. 1!:11 name,{.blocks
blocks=: }.blocks
lines=: <;._2 buffer,LF
end.
buffer=: _1{::lines
)
next=: monad define
if. (#blocks)*.2>#lines do. readblocks'' end.
r=. 0{::lines
lines=: }.lines
r
)
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
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
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#Yabasic
|
Yabasic
|
n = 7
dim puntos(7), ptosnom(7), nombre$(7)
sub MostarTabla()
for i = 1 to n
print str$(ptosnom(i)), " ", puntos(i), " ", nombre$(i)
next i
print
end sub
print "Puntuaciones a clasificar (mejores primero):"
for i = 1 to n
read puntos(i), nombre$(i)
print " ", puntos(i), " ", nombre$(i)
next i
print
print "--- Standard ranking ---"
ptosnom(1) = 1
for i = 2 to n
if puntos(i) = puntos(i-1) then ptosnom(i) = ptosnom(i-1) else ptosnom(i) = i : fi
next i
MostarTabla()
print "--- Modified ranking ---"
ptosnom(n) = n
for i = n-1 to 1 step -1
if puntos(i) = puntos(i+1) then ptosnom(i) = ptosnom(i+1) else ptosnom(i) = i : fi
next i
MostarTabla()
print "--- Ordinal ranking ---"
for i = 1 to n
ptosnom(i) = i
next i
MostarTabla()
print "--- Fractional ranking ---"
i = 1
j = 2
repeat
if j <= n then
if (puntos(j-1) = puntos(j)) then j = j + 1 : fi
end if
for k = i to j-1
ptosnom(k) = (i+j-1) / 2
next k
i = j
j = j + 1
until i > n
MostarTabla()
data 44, "Solomon", 42, "Jason", 42, "Errol", 41, "Garry", 41, "Bernard", 41, "Barry", 39, "Stephen"
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
|
#Pop11
|
Pop11
|
define reverse_string(s);
lvars i, l = length(s);
for i from l by -1 to 1 do
s(i);
endfor;
consstring(l);
enddefine;
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA; /* type of data to store in queue */
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
// Fixed bug where it failed to resizes
if (q->tail == q->alloc) { /* needs more room */
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) { /* reduce allocated storage no longer needed */
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}
|
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.
|
#Crystal
|
Crystal
|
class Quaternion
property a, b, c, d
def initialize(@a : Int64, @b : Int64, @c : Int64, @d : Int64) end
def norm; Math.sqrt(a**2 + b**2 + c**2 + d**2) end
def conj; Quaternion.new(a, -b, -c, -d) end
def +(n) Quaternion.new(a + n, b, c, d) end
def -(n) Quaternion.new(a - n, b, c, d) end
def -() Quaternion.new(-a, -b, -c, -d) end
def *(n) Quaternion.new(a * n, b * n, c * n, d * n) end
def ==(rhs : Quaternion) self.to_s == rhs.to_s end
def +(rhs : Quaternion)
Quaternion.new(a + rhs.a, b + rhs.b, c + rhs.c, d + rhs.d)
end
def -(rhs : Quaternion)
Quaternion.new(a - rhs.a, b - rhs.b, c - rhs.c, d - rhs.d)
end
def *(rhs : Quaternion)
Quaternion.new(
a * rhs.a - b * rhs.b - c * rhs.c - d * rhs.d,
a * rhs.b + b * rhs.a + c * rhs.d - d * rhs.c,
a * rhs.c - b * rhs.d + c * rhs.a + d * rhs.b,
a * rhs.d + b * rhs.c - c * rhs.b + d * rhs.a)
end
def to_s(io : IO) io << "(#{a} #{sgn(b)}i #{sgn(c)}j #{sgn(d)}k)\n" end
private def sgn(n) n.sign|1 == 1 ? "+ #{n}" : "- #{n.abs}" end
end
struct Number
def +(rhs : Quaternion)
Quaternion.new(rhs.a + self, rhs.b, rhs.c, rhs.d)
end
def -(rhs : Quaternion)
Quaternion.new(-rhs.a + self, -rhs.b, -rhs.c, -rhs.d)
end
def *(rhs : Quaternion)
Quaternion.new(rhs.a * self, rhs.b * self, rhs.c * self, rhs.d * self)
end
end
q0 = Quaternion.new(a: 1, b: 2, c: 3, d: 4)
q1 = Quaternion.new(2, 3, 4, 5)
q2 = Quaternion.new(3, 4, 5, 6)
r = 7
puts "q0 = #{q0}"
puts "q1 = #{q1}"
puts "q2 = #{q2}"
puts "r = #{r}"
puts
puts "normal of q0 = #{q0.norm}"
puts "-q0 = #{-q0}"
puts "conjugate of q0 = #{q0.conj}"
puts "q0 * (conjugate of q0) = #{q0 * q0.conj}"
puts "(conjugate of q0) * q0 = #{q0.conj * q0}"
puts
puts "r + q0 = #{r + q0}"
puts "q0 + r = #{q0 + r}"
puts
puts " q0 - r = #{q0 - r}"
puts "-q0 - r = #{-q0 - r}"
puts " r - q0 = #{r - q0}"
puts "-q0 + r = #{-q0 + r}"
puts
puts "r * q0 = #{r * q0}"
puts "q0 * r = #{q0 * r}"
puts
puts "q0 + q1 = #{q0 + q1}"
puts "q0 - q1 = #{q2 - q1}"
puts "q0 * q1 = #{q0 * q1}"
puts
puts " q0 + q1 * q2 = #{q0 + q1 * q2}"
puts "(q0 + q1) * q2 = #{(q0 + q1) * q2}"
puts
puts " q0 * q1 * q2 = #{q0 * q1 * q2}"
puts "(q0 * q1) * q2 = #{(q0 * q1) * q2}"
puts " q0 * (q1 * q2) = #{q0 * (q1 * q2)}"
puts
puts "q1 * q2 = #{q1 * q2}"
puts "q2 * q1 = #{q2 * q1}"
puts
puts "q1 * q2 != q2 * q1 => #{(q1 * q2) != (q2 * q1)}"
puts "q1 * q2 == q2 * q1 => #{(q1 * q2) == (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.
|
#Befunge
|
Befunge
|
:0g,:66+`#@_1+
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Groovy
|
Groovy
|
def q = new LinkedList()
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Haskell
|
Haskell
|
Prelude> :l fifo.hs
[1 of 1] Compiling Main ( fifo.hs, interpreted )
Ok, modules loaded: Main.
*Main> let q = emptyFifo
*Main> isEmpty q
True
*Main> let q' = push q 1
*Main> isEmpty q'
False
*Main> let q'' = foldl push q' [2..4]
*Main> let (v,q''') = pop q''
*Main> v
Just 1
*Main> let (v',q'''') = pop q'''
*Main> v'
Just 2
*Main> let (v'',q''''') = pop q''''
*Main> v''
Just 3
*Main> let (v''',q'''''') = pop q'''''
*Main> v'''
Just 4
*Main> let (v'''',q''''''') = pop q''''''
*Main> v''''
Nothing
|
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
|
Read a specific line from a file
|
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
def MaxLen = 82; \maximum length of line that can be stored (incl CR+LF)
func ReadLine(N, L); \Read line N from input file and return it in string L
int N; char L;
int I, C;
[for I:= 1 to N-1 do \skip to start of specified line
repeat C:= ChIn(1);
if C = $1A\EOF\ then
[Text(0, "File only has "); IntOut(0, I);
Text(0, " lines^M^J"); return false];
until C = $0A\LF\;
I:= 0;
repeat C:= ChIn(1);
if C = $1A\EOF\ then
[Text(0, "Line is empty (EOF)^M^L"); return false];
L(I):= C; I:= I+1;
until C=$0A\LF\ or I>=MaxLen;
if I >= MaxLen then Text(0, "Line might be truncated^M^J");
if I = 2 then Text(0, "Line is empty^M^J");
L(I-1):= L(I-1) ! $80; \terminate string
return true;
];
char LineN(MaxLen);
if ReadLine(7, LineN) then Text(0, LineN)
|
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
|
Read a specific line from a file
|
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
|
#zkl
|
zkl
|
reg line; do(7){line=File.stdin.readln()} println(">>>",line);
|
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.
|
#Go
|
Go
|
package main
import "fmt"
func quickselect(list []int, k int) int {
for {
// partition
px := len(list) / 2
pv := list[px]
last := len(list) - 1
list[px], list[last] = list[last], list[px]
i := 0
for j := 0; j < last; j++ {
if list[j] < pv {
list[i], list[j] = list[j], list[i]
i++
}
}
// select
if i == k {
return pv
}
if k < i {
list = list[:i]
} else {
list[i], list[last] = list[last], list[i]
list = list[i+1:]
k -= i + 1
}
}
}
func main() {
for i := 0; ; i++ {
v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
if i == len(v) {
return
}
fmt.Println(quickselect(v, i))
}
}
|
http://rosettacode.org/wiki/Range_extraction
|
Range extraction
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
|
#F.23
|
F#
|
let extractRanges = function
| [] -> Seq.empty
| x::xr ->
let rec loop ys first last = seq {
match ys with
| y::yr when y = last + 1 -> yield! loop yr first y // add to current range
| y::yr -> yield (first, last) // finish current range
yield! loop yr y y // and start next
| [] -> yield (first, last) } // finish final range
loop xr x x
let rangeToString (s,e) =
match e-s with
| 0 -> sprintf "%d" s
| 1 -> sprintf "%d,%d" s e
| _ -> sprintf "%d-%d" s e
let extract = extractRanges >> Seq.map rangeToString >> String.concat ","
printfn "%s" (extract [ 0; 1; 2; 4; 6; 7; 8; 11; 12; 14; 15; 16; 17; 18; 19; 20; 21;
22; 23; 24; 25; 27; 28; 29; 30; 31; 32; 33; 35; 36; 37; 38; 39 ])
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#Kotlin
|
Kotlin
|
// version 1.0.6
import java.util.Random
fun main(args: Array<String>) {
val r = Random()
val da = DoubleArray(1000)
for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian()
// now check actual mean and SD
val mean = da.average()
val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average())
println("Mean is $mean")
println("S.D. is $sd")
}
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
]
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#zkl
|
zkl
|
ld a,r
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Z80_Assembly
|
Z80 Assembly
|
ld a,r
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
dim confKeys$(100)
dim confValues$(100)
optionCount = ParseConfiguration("a.txt")
fullName$ = GetOption$( "FULLNAME", optionCount)
favouriteFruit$ = GetOption$( "FAVOURITEFRUIT", optionCount)
needsPeeling = HasOption("NEEDSPEELING", optionCount)
seedsRemoved = HasOption("SEEDSREMOVED", optionCount)
otherFamily$ = GetOption$( "OTHERFAMILY", optionCount) 'it's easier to keep the comma-separated list as a string
print "Full name: "; fullName$
print "likes: "; favouriteFruit$
print "needs peeling: "; needsPeeling
print "seeds removed: "; seedsRemoved
print "other family:"
otherFamily$ = GetOption$( "OTHERFAMILY", optionCount)
counter = 1
while word$(otherFamily$, counter, ",") <> ""
print counter; ". "; trim$(word$(otherFamily$, counter, ","))
counter = counter + 1
wend
end
'parses the configuration file, stores the uppercase keys in array confKeys$ and corresponding values in confValues$
'returns the number of key-value pairs found
function ParseConfiguration(fileName$)
count = 0
open fileName$ for input as #f
while not(eof(#f))
line input #f, s$
if not(Left$(s$,1) = "#" or Left$( s$,1) = ";" or trim$(s$) = "") then 'ignore empty and comment lines
s$ = trim$(s$)
key$ = ParseKey$(s$)
value$ = trim$(Mid$(s$,len(key$) + 1))
if Left$( value$,1) = "=" then value$ = trim$(Mid$(value$,2)) 'optional =
count = count + 1
confKeys$(count) = upper$(key$)
confValues$(count) = value$
end if
wend
close #f
ParseConfiguration = count
end function
function ParseKey$(s$)
'key is the first word in s$, delimited by whitespace or =
s$ = word$(s$, 1)
ParseKey$ = trim$(word$(s$, 1, "="))
end function
function GetOption$( key$, optionCount)
index = Find.confKeys( 1, optionCount, key$)
if index > 0 then GetOption$ =(confValues$(index))
end function
function HasOption(key$, optionCount)
HasOption = Find.confKeys( 1, optionCount, key$) > 0
end function
function Find.confKeys( Start, Finish, value$)
Find.confKeys = -1
for i = Start to Finish
if confKeys$(i) = value$ then Find.confKeys = i : exit for
next i
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
|
#J
|
J
|
require'strings'
thru=: <. + i.@(+*)@-~
num=: _&".
normaliz=: rplc&(',-';',_';'--';'-_')@,~&','
subranges=:<@(thru/)@(num;._2)@,&'-';._1
rngexp=: ;@subranges@normaliz
|
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.
|
#Java
|
Java
|
import java.io.BufferedReader;
import java.io.FileReader;
/**
* Reads a file line by line, processing each line.
*
* @author $Author$
* @version $Revision$
*/
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
// ...
}
public static void main(String[] args) {
for (String filename : args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
processLine(++lineNo, line);
}
}
catch (Exception x) {
x.printStackTrace();
}
finally {
if (fr != null) {
try {br.close();} catch (Exception ignoreMe) {}
try {fr.close();} catch (Exception ignoreMe) {}
}
}
}
}
}
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
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
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#zkl
|
zkl
|
fcn group(scores){ // group like scores into one list --> list of lists
sink:=List();
scores.reduce('wrap(ps,sn,buf){
if(sn[0]!=ps){ sink.append(buf.copy()); buf.clear(); }
buf+sn;
sn[0];
},scores[0][0],buf:=List());
sink.append(buf);
}
fcn print(list,rank){
list.apply2('wrap(sn){ "%2s: %s (%d)".fmt(rank,sn[1],sn[0]):println(_); });
}
fcn rankViaStandard(scores){
rank:=1;
foreach group in (group(scores)){ print(group,rank); rank+=group.len(); }
}
fcn rankViaModified(scores){
rank:=0;
foreach group in (group(scores)){ rank+=group.len(); print(group,rank); }
}
fcn rankViaDense(scores){
rank:=1;
foreach group in (group(scores)){ print(group,rank); rank+=1; }
}
fcn rankViaOrdinal(scores){
scores.apply2('wrap(sn,rr){ "%2s: %s (%d)".fmt(rr.inc(),sn[1],sn[0]):println(_); },Ref(1));
}
fcn rankViaFractional(scores){
rank:=1;
foreach group in (group(scores)){
n:=group.len(); r:=rank.reduce(n,'+,0.0)/n; rank+=n;
print(group,"%5.2f".fmt(r));
}
}
|
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
|
#PostScript
|
PostScript
|
/reverse{
/str exch def
/temp str 0 get def
/i 0 def
str length 2 idiv{
/temp str i get def
str i str str length i sub 1 sub get put
str str length i sub 1 sub temp put
/i i 1 add def
}repeat
str pstack
}def
|
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
|
#C.23
|
C#
|
public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
//Uses object initializers to set fields of new node
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == 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.
|
#D
|
D
|
import std.math, std.numeric, std.traits, std.conv, std.complex;
struct Quat(T) if (isFloatingPoint!T) {
alias CT = Complex!T;
union {
struct { T re, i, j, k; } // Default init to NaN.
struct { CT x, y; }
struct { T[4] vector; }
}
string toString() const pure /*nothrow*/ @safe {
return vector.text;
}
@property T norm2() const pure nothrow @safe @nogc { /// Norm squared.
return re ^^ 2 + i ^^ 2 + j ^^ 2 + k ^^ 2;
}
@property T abs() const pure nothrow @safe @nogc { /// Norm.
return sqrt(norm2);
}
@property T arg() const pure nothrow @safe @nogc { /// Theta.
return acos(re / abs); // this may be incorrect...
}
@property Quat!T conj() const pure nothrow @safe @nogc { /// Conjugate.
return Quat!T(re, -i, -j, -k);
}
@property Quat!T recip() const pure nothrow @safe @nogc { /// Reciprocal.
return Quat!T(re / norm2, -i / norm2, -j / norm2, -k / norm2);
}
@property Quat!T pureim() const pure nothrow @safe @nogc { /// Pure imagery.
return Quat!T(0, i, j, k);
}
@property Quat!T versor() const pure nothrow @safe @nogc { /// Unit versor.
return this / abs;
}
/// Unit versor of imagery part.
@property Quat!T iversor() const pure nothrow @safe @nogc {
return pureim / pureim.abs;
}
/// Assignment.
Quat!T opAssign(U : T)(Quat!U z) pure nothrow @safe @nogc {
x = z.x; y = z.y;
return this;
}
Quat!T opAssign(U : T)(Complex!U c) pure nothrow @safe @nogc {
x = c; y = 0;
return this;
}
Quat!T opAssign(U : T)(U r) pure nothrow @safe @nogc
if (isNumeric!U) {
re = r; i = 0; y = 0;
return this;
}
/// Test for equal, not ordered so no opCmp.
bool opEquals(U : T)(Quat!U z) const pure nothrow @safe @nogc {
return re == z.re && i == z.i && j == z.j && k == z.k;
}
bool opEquals(U : T)(Complex!U c) const pure nothrow @safe @nogc {
return re == c.re && i == c.im && j == 0 && k == 0;
}
bool opEquals(U : T)(U r) const pure nothrow @safe @nogc
if (isNumeric!U) {
return re == r && i == 0 && j == 0 && k == 0;
}
/// Unary op.
Quat!T opUnary(string op)() const pure nothrow @safe @nogc
if (op == "+") {
return this;
}
Quat!T opUnary(string op)() const pure nothrow @safe @nogc
if (op == "-") {
return Quat!T(-re, -i, -j, -k);
}
/// Binary op, Quaternion on left of op.
Quat!(CommonType!(T,U)) opBinary(string op, U)(Quat!U z)
const pure nothrow @safe @nogc {
alias typeof(return) C;
static if (op == "+" ) {
return C(re + z.re, i + z.i, j + z.j, k + z.k);
} else static if (op == "-") {
return C(re - z.re, i - z.i, j - z.j, k - z.k);
} else static if (op == "*") {
return C(re * z.re - i * z.i - j * z.j - k * z.k,
re * z.i + i * z.re + j * z.k - k * z.j,
re * z.j - i * z.k + j * z.re + k * z.i,
re * z.k + i * z.j - j * z.i + k * z.re);
} else static if (op == "/") {
return this * z.recip;
}
}
/// Extend complex to quaternion.
Quat!(CommonType!(T,U)) opBinary(string op, U)(Complex!U c)
const pure nothrow @safe @nogc {
return opBinary!op(typeof(return)(c.re, c.im, 0, 0));
}
/// For scalar.
Quat!(CommonType!(T,U)) opBinary(string op, U)(U r)
const pure nothrow @safe @nogc
if (isNumeric!U) {
alias typeof(return) C;
static if (op == "+" ) {
return C(re + r, i, j, k);
} else static if (op == "-") {
return C(re - r, i, j, k);
} else static if (op == "*") {
return C(re * r, i * r, j * r, k * r);
} else static if (op == "/") {
return C(re / r, i / r, j / r, k / r);
} else static if (op == "^^") {
return pow(r);
}
}
/// Power function.
Quat!(CommonType!(T,U)) pow(U)(U r)
const pure nothrow @safe @nogc
if (isNumeric!U) {
return (abs^^r) * exp(r * iversor * arg);
}
/// Handle binary op if Quaternion on right of op and left is
/// not quaternion.
Quat!(CommonType!(T,U)) opBinaryRight(string op, U)(Complex!U c)
const pure nothrow @safe @nogc {
alias typeof(return) C;
auto w = C(c.re, c.im, 0, 0);
return w.opBinary!(op)(this);
}
Quat!(CommonType!(T,U)) opBinaryRight(string op, U)(U r)
const pure nothrow @safe @nogc
if (isNumeric!U) {
alias typeof(return) C;
static if (op == "+" || op == "*") {
return opBinary!op(r);
} else static if (op == "-") {
return C(r - re , -i, -j, -k);
} else static if (op == "/") {
auto w = C(re, i, j, k);
return w.recip * r;
}
}
}
HT exp(HT)(HT z) pure nothrow @safe @nogc
if (is(HT T == Quat!T)) {
immutable inorm = z.pureim.abs;
return std.math.exp(z.re) * (cos(inorm) + z.iversor * sin(inorm));
}
HT log(HT)(HT z) pure nothrow @safe @nogc
if (is(HT T == Quat!T)) {
return std.math.log(z.abs) + z.iversor * acos(z.re / z.abs);
}
void main() @safe { // Demo code.
import std.stdio;
alias QR = Quat!real;
enum real r = 7.0;
immutable QR q = QR(2, 3, 4, 5),
q1 = QR(2, 3, 4, 5),
q2 = QR(3, 4, 5, 6);
writeln("1. q - norm: ", q.abs);
writeln("2. q - negative: ", -q);
writeln("3. q - conjugate: ", q.conj);
writeln("4. r + q: ", r + q);
writeln(" q + r: ", q + r);
writeln("5. q1 + q2: ", q1 + q2);
writeln("6. r * q: ", r * q);
writeln(" q * r: ", q * r);
writeln("7. q1 * q2: ", q1 * q2);
writeln(" q2 * q1: ", q2 * q1);
writeln("8. q1 * q2 != q2 * Q1 ? ", q1 * q2 != q2 * q1);
immutable QR i = QR(0, 1, 0, 0),
j = QR(0, 0, 1, 0),
k = QR(0, 0, 0, 1);
writeln("9.1 i * i: ", i * i);
writeln(" J * j: ", j * j);
writeln(" k * k: ", k * k);
writeln(" i * j * k: ", i * j * k);
writeln("9.2 q1 / q2: ", q1 / q2);
writeln("9.3 q1 / q2 * q2: ", q1 / q2 * q2);
writeln(" q2 * q1 / q2: ", q2 * q1 / q2);
writeln("9.4 exp(pi * i): ", exp(PI * i));
writeln(" exp(pi * j): ", exp(PI * j));
writeln(" exp(pi * k): ", exp(PI * k));
writeln(" exp(q): ", exp(q));
writeln(" log(q): ", log(q));
writeln(" exp(log(q)): ", exp(log(q)));
writeln(" log(exp(q)): ", log(exp(q)));
immutable s = q.exp.log;
writeln("9.5 let s = log(exp(q)): ", s);
writeln(" exp(s): ", exp(s));
writeln(" log(s): ", log(s));
writeln(" exp(log(s)): ", exp(log(s)));
writeln(" log(exp(s)): ", log(exp(s)));
}
|
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.
|
#Binary_Lambda_Calculus
|
Binary Lambda Calculus
|
000101100100011010000000000001011011110010111100111111011111011010000101100100011010000000000001011011110010111100111111011111011010
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(arglist)
queue := []
write("Usage:\nqueue x x x - x - - - - -\n\t- pops elements\n\teverything else pushes")
write("Queue is:")
every x := !arglist do {
case x of {
"-" : pop(queue) | write("pop(empty) failed.") # pop if the next arglist[i] is a -
default : put(queue,x) # push arglist[i]
}
if empty(queue) then writes("empty")
else every writes(!queue," ")
write()
}
end
procedure empty(X) #: fail if X is not empty
if *X = 0 then return
end
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#J
|
J
|
queue=: conew 'fifo'
isEmpty__queue ''
1
push__queue 9
9
push__queue 8
8
push__queue 7
7
isEmpty__queue ''
0
pop__queue ''
9
pop__queue ''
8
pop__queue ''
7
isEmpty__queue ''
1
|
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.
|
#Haskell
|
Haskell
|
import Data.List (partition)
quickselect
:: Ord a
=> [a] -> Int -> a
quickselect (x:xs) k
| k < l = quickselect ys k
| k > l = quickselect zs (k - l - 1)
| otherwise = x
where
(ys, zs) = partition (< x) xs
l = length ys
main :: IO ()
main =
print
((fmap . quickselect) <*> zipWith const [0 ..] $
[9, 8, 7, 6, 5, 0, 1, 2, 3, 4])
|
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
|
#Factor
|
Factor
|
USING: formatting io kernel math math.parser sequences
splitting.monotonic ;
IN: rosetta-code.range-extraction
: make-range ( seq -- str )
[ first ] [ last ] bi "%d-%d" sprintf ;
: make-atomic ( seq -- str ) [ number>string ] map "," join ;
: extract-range ( seq -- str )
[ - -1 = ] monotonic-split
[ dup length 2 > [ make-range ] [ make-atomic ] if ] map
"," join ;
{
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
} extract-range print
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#LabVIEW
|
LabVIEW
|
dim a(1000)
mean =1
sd =0.5
for i = 1 to 1000 ' throw 1000 normal variates
a( i) =mean +sd *( 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
|
#Liberty_BASIC
|
Liberty BASIC
|
dim a(1000)
mean =1
sd =0.5
for i = 1 to 1000 ' throw 1000 normal variates
a( i) =mean +sd *( sqr( -2 * log( rnd( 0))) * cos( 2 * pi * rnd( 0)))
next i
|
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
|
#Lua
|
Lua
|
conf = {}
fp = io.open( "conf.txt", "r" )
for line in fp:lines() do
line = line:match( "%s*(.+)" )
if line and line:sub( 1, 1 ) ~= "#" and line:sub( 1, 1 ) ~= ";" then
option = line:match( "%S+" ):lower()
value = line:match( "%S*%s*(.*)" )
if not value then
conf[option] = true
else
if not value:find( "," ) then
conf[option] = value
else
value = value .. ","
conf[option] = {}
for entry in value:gmatch( "%s*(.-)," ) do
conf[option][#conf[option]+1] = entry
end
end
end
end
end
fp:close()
print( "fullname = ", conf["fullname"] )
print( "favouritefruit = ", conf["favouritefruit"] )
if conf["needspeeling"] then print( "needspeeling = true" ) else print( "needspeeling = false" ) end
if conf["seedsremoved"] then print( "seedsremoved = true" ) else print( "seedsremoved = false" ) end
if conf["otherfamily"] then
print "otherfamily:"
for _, entry in pairs( conf["otherfamily"] ) do
print( "", entry )
end
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
|
#Java
|
Java
|
import java.util.*;
class RangeExpander implements Iterator<Integer>, Iterable<Integer> {
private static final Pattern TOKEN_PATTERN = Pattern.compile("([+-]?\\d+)-([+-]?\\d+)");
private final Iterator<String> tokensIterator;
private boolean inRange;
private int upperRangeEndpoint;
private int nextRangeValue;
public RangeExpander(String range) {
String[] tokens = range.split("\\s*,\\s*");
this.tokensIterator = Arrays.asList(tokens).iterator();
}
@Override
public boolean hasNext() {
return hasNextRangeValue() || this.tokensIterator.hasNext();
}
private boolean hasNextRangeValue() {
return this.inRange && this.nextRangeValue <= this.upperRangeEndpoint;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (hasNextRangeValue()) {
return this.nextRangeValue++;
}
String token = this.tokensIterator.next();
Matcher matcher = TOKEN_PATTERN.matcher(token);
if (matcher.find()) {
this.inRange = true;
this.upperRangeEndpoint = Integer.valueOf(matcher.group(2));
this.nextRangeValue = Integer.valueOf(matcher.group(1));
return this.nextRangeValue++;
}
this.inRange = false;
return Integer.valueOf(token);
}
@Override
public Iterator<Integer> iterator() {
return this;
}
}
class RangeExpanderTest {
public static void main(String[] args) {
RangeExpander re = new RangeExpander("-6,-3--1,3-5,7-11,14,15,17-20");
for (int i : re) {
System.out.print(i + " ");
}
}
}
|
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.
|
#JavaScript
|
JavaScript
|
var fs = require("fs");
var readFile = function(path) {
return fs.readFileSync(path).toString();
};
console.log(readFile('file.txt'));
|
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.
|
#jq
|
jq
|
$ seq 0 5 | jq -R 'tonumber|sin'
0
0.8414709848078965
0.9092974268256817
0.1411200080598672
-0.7568024953079282
-0.9589242746631385
|
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
|
#PowerBASIC
|
PowerBASIC
|
#DIM ALL
#COMPILER PBCC 6
FUNCTION PBMAIN () AS LONG
CON.PRINT STRREVERSE$("PowerBASIC")
END FUNCTION
|
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
|
#C.2B.2B
|
C++
|
namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 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.
|
#Delphi
|
Delphi
|
unit Quaternions;
interface
type
TQuaternion = record
A, B, C, D: double;
function Init (aA, aB, aC, aD : double): TQuaternion;
function Norm : double;
function Conjugate : TQuaternion;
function ToString : string;
class operator Negative (Left : TQuaternion): TQuaternion;
class operator Positive (Left : TQuaternion): TQuaternion;
class operator Add (Left, Right : TQuaternion): TQuaternion;
class operator Add (Left : TQuaternion; Right : double): TQuaternion; overload;
class operator Add (Left : double; Right : TQuaternion): TQuaternion; overload;
class operator Subtract (Left, Right : TQuaternion): TQuaternion;
class operator Multiply (Left, Right : TQuaternion): TQuaternion;
class operator Multiply (Left : TQuaternion; Right : double): TQuaternion; overload;
class operator Multiply (Left : double; Right : TQuaternion): TQuaternion; overload;
end;
implementation
uses
SysUtils;
{ TQuaternion }
function TQuaternion.Init(aA, aB, aC, aD: double): TQuaternion;
begin
A := aA;
B := aB;
C := aC;
D := aD;
result := Self;
end;
function TQuaternion.Norm: double;
begin
result := sqrt(sqr(A) + sqr(B) + sqr(C) + sqr(D));
end;
function TQuaternion.Conjugate: TQuaternion;
begin
result.B := -B;
result.C := -C;
result.D := -D;
end;
class operator TQuaternion.Negative(Left: TQuaternion): TQuaternion;
begin
result.A := -Left.A;
result.B := -Left.B;
result.C := -Left.C;
result.D := -Left.D;
end;
class operator TQuaternion.Positive(Left: TQuaternion): TQuaternion;
begin
result := Left;
end;
class operator TQuaternion.Add(Left, Right: TQuaternion): TQuaternion;
begin
result.A := Left.A + Right.A;
result.B := Left.B + Right.B;
result.C := Left.C + Right.C;
result.D := Left.D + Right.D;
end;
class operator TQuaternion.Add(Left: TQuaternion; Right: double): TQuaternion;
begin
result.A := Left.A + Right;
result.B := Left.B;
result.C := Left.C;
result.D := Left.D;
end;
class operator TQuaternion.Add(Left: double; Right: TQuaternion): TQuaternion;
begin
result.A := Left + Right.A;
result.B := Right.B;
result.C := Right.C;
result.D := Right.D;
end;
class operator TQuaternion.Subtract(Left, Right: TQuaternion): TQuaternion;
begin
result.A := Left.A - Right.A;
result.B := Left.B - Right.B;
result.C := Left.C - Right.C;
result.D := Left.D - Right.D;
end;
class operator TQuaternion.Multiply(Left, Right: TQuaternion): TQuaternion;
begin
result.A := Left.A * Right.A - Left.B * Right.B - Left.C * Right.C - Left.D * Right.D;
result.B := Left.A * Right.B + Left.B * Right.A + Left.C * Right.D - Left.D * Right.C;
result.C := Left.A * Right.C - Left.B * Right.D + Left.C * Right.A + Left.D * Right.B;
result.D := Left.A * Right.D + Left.B * Right.C - Left.C * Right.B + Left.D * Right.A;
end;
class operator TQuaternion.Multiply(Left: double; Right: TQuaternion): TQuaternion;
begin
result.A := Left * Right.A;
result.B := Left * Right.B;
result.C := Left * Right.C;
result.D := Left * Right.D;
end;
class operator TQuaternion.Multiply(Left: TQuaternion; Right: double): TQuaternion;
begin
result.A := Left.A * Right;
result.B := Left.B * Right;
result.C := Left.C * Right;
result.D := Left.D * Right;
end;
function TQuaternion.ToString: string;
begin
result := Format('%f + %fi + %fj + %fk', [A, B, C, D]);
end;
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.
|
#Bob
|
Bob
|
c=","; n="\n"; q="\""; s="\\";
v=\[
"c=\",\"; n=\"\\n\"; q=\"\\\"\"; s=\"\\\\\";",
"v=\\[",
"define prtQuote(str) {",
" local j,t,v;",
" stdout.Display(q);",
" for (j=0; j<str.size; j++) {",
" t = str.Substring(j,1);",
" if (t==q) { stdout.Display(s); }",
" if (t==s) { stdout.Display(s); }",
" stdout.Display(t);",
" }",
" stdout.Display(q);",
"}",
"for(i=0; i<2; i++){ stdout.Display(v[i]); stdout.Display(n); }",
"for(i=0; i<v.size-1; i++){ prtQuote(v[i]); stdout.Display(c); stdout.Display(n); }",
"prtQuote(v[v.size-1]); stdout.Display(n);",
"stdout.Display(v[v.size-1]); stdout.Display(n);",
"for(i=2; i<v.size-1; i++){ stdout.Display(v[i]); stdout.Display(n); }",
"];"
];
define prtQuote(str) {
local j,t,v;
stdout.Display(q);
for (j=0; j<str.size; j++) {
t = str.Substring(j,1);
if (t==q) { stdout.Display(s); }
if (t==s) { stdout.Display(s); }
stdout.Display(t);
}
stdout.Display(q);
}
for(i=0; i<2; i++){ stdout.Display(v[i]); stdout.Display(n); }
for(i=0; i<v.size-1; i++){ prtQuote(v[i]); stdout.Display(c); stdout.Display(n); }
prtQuote(v[v.size-1]); stdout.Display(n);
stdout.Display(v[v.size-1]); stdout.Display(n);
for(i=2; i<v.size-1; i++){ stdout.Display(v[i]); stdout.Display(n); }
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Java
|
Java
|
import java.util.LinkedList;
import java.util.Queue;
...
Queue<Integer> queue = new LinkedList<Integer>();
System.out.println(queue.isEmpty()); // empty test - true
// queue.remove(); // would throw NoSuchElementException
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println(queue); // [1, 2, 3]
System.out.println(queue.remove()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#JavaScript
|
JavaScript
|
var f = new Array();
print(f.length);
f.push(1,2); // can take multiple arguments
f.push(3);
f.shift();
f.shift();
print(f.length);
print(f.shift())
print(f.length == 0);
print(f.shift());
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(A)
every writes(" ",select(1 to *A, A, 1, *A)|"\n")
end
procedure select(k,A,min,max)
repeat {
pNI := partition(?(max-min)+min, A, min, max)
pD := pNI - min + 1
if pD = k then return A[pNI]
if k < pD then max := pNI-1
else (k -:= pD, min := pNI+1)
}
end
procedure partition(pivot,A,min,max)
pV := (A[max] :=: A[pivot])
sI := min
every A[i := min to max-1] <= pV do (A[sI] :=: A[i], sI +:= 1)
A[max] :=: A[sI]
return sI
end
|
http://rosettacode.org/wiki/Range_extraction
|
Range extraction
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
|
#Forth
|
Forth
|
create values
here
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 ,
here swap - 1 cells / constant /values
: clip 1- swap cell+ swap ; \ reduce array
: .range2 0 .r ." -" 0 .r ; \ difference two or more
: .range1 0 .r ." , " 0 .r ; \ difference one
: .range0 drop 0 .r ; \ no difference
\ select printing routine
create .range ' .range0 , ' .range1 , ' .range2 ,
does> >r over over - 2 min cells r> + @ execute ;
: .ranges ( a n --)
over @ dup >r >r \ setup first value
begin
clip dup \ check length array
while
over @ dup r@ 1+ = \ check if range breaks
if r> drop >r else r> r> .range ." , " dup >r >r then
repeat 2drop r> r> .range cr \ print last range
;
values /values .ranges
|
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
|
#Lingo
|
Lingo
|
-- Returns a random float value in range 0..1
on randf ()
n = random(the maxinteger)-1
return n / float(the maxinteger-1)
end
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#Lobster
|
Lobster
|
let mean = 1.0
let stdv = 0.5
let count = 1000
// stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
def stats(xs: [float]) -> float, float: // variance, mean
var M = xs[0]
var S = 0.0
var n = 1.0
for(xs.length - 1) i:
let x = xs[i + 1]
n = n + 1.0
let mm = (x - M)
M += mm / n
S += mm * (x - M)
return (if n > 0.0: S / n else: 0.0), M
def test_random_normal() -> [float]:
rnd_seed(floor(seconds_elapsed() * 1000000))
let r = vector_reserve(typeof return, count)
for (count):
r.push(rnd_gaussian() * stdv + mean)
let cvar, cmean = stats(r)
let cstdv = sqrt(cvar)
print concat_string(["Mean: ", string(cmean), ", Std.Deviation: ", string(cstdv)], "")
test_random_normal()
|
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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[CreateVar, ImportConfig];
CreateVar[x_, y_String: "True"] := Module[{},
If[StringFreeQ[y, ","]
,
ToExpression[x <> "=" <> y]
,
ToExpression[x <> "={" <> StringJoin@Riffle[StringSplit[y, ","], ","] <> "}"]
]
]
ImportConfig[configfile_String] := Module[{data},
(*data = ImportString[configfile, "List", "Numeric" -> False];*)
data=Import[configfile,"List","Numeric"\[Rule]False];
data = StringTrim /@ data;
data = Select[data, # =!= "" &];
data = Select[data, ! StringMatchQ[#, "#" | ";" ~~ ___] &];
data = If[! StringFreeQ[#, " "], StringSplit[#, " ", 2], {#}] & /@ data;
CreateVar @@@ data;
]
ImportConfig[file]
|
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
|
#JavaScript
|
JavaScript
|
#!/usr/bin/env js
function main() {
print(rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20'));
}
function rangeExpand(rangeExpr) {
function getFactors(term) {
var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);
if (!matches) return {first:Number(term)};
return {first:Number(matches[1]), last:Number(matches[2])};
}
function expandTerm(term) {
var factors = getFactors(term);
if (factors.length < 2) return [factors.first];
var range = [];
for (var n = factors.first; n <= factors.last; n++) {
range.push(n);
}
return range;
}
var result = [];
var terms = rangeExpr.split(/,/);
for (var t in terms) {
result = result.concat(expandTerm(terms[t]));
}
return result;
}
main();
|
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.
|
#Jsish
|
Jsish
|
/* Read by line, in Jsish */
var f = new Channel('read-by-line.jsi');
var line;
while (line = f.gets()) puts(line);
f.close();
|
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.
|
#Julia
|
Julia
|
open("input_file","r") do f
for line in eachline(f)
println("read line: ", line)
end
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
|
#PowerShell
|
PowerShell
|
$s = "asdf"
|
http://rosettacode.org/wiki/Queue/Definition
|
Queue/Definition
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Implement a FIFO queue.
Elements are added at one side and popped from the other in the order of insertion.
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
Errors:
handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See
Queue/Usage for the built-in FIFO or queue of your language or standard library.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Clojure
|
Clojure
|
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY)
#'user/empty-queue
user=> (def aqueue (atom empty-queue))
#'user/aqueue
; Check if queue is empty
user=> (empty? @aqueue)
true
; As with other Clojure data structures, you can add items using conj and into
user=> (swap! aqueue conj 1)
user=> (swap! aqueue into [2 3 4])
user=> (pprint @aqueue)
<-(1 2 3 4)-<
; You can read the head of the queue with peek
user=> (peek @aqueue)
1
; You can remove the head producing a new queue using pop
user=> (pprint (pop @aqueue))
<-(2 3 4)-<
; pop returns a new queue, the original is still intact
user=> (pprint @aqueue)
<-(1 2 3 4)-<
; you can treat a queue as a sequence
user=> (into [] @aqueue)
[1 2 3 4]
; but remember that using rest or next converts the queue to a seq. Compare:
user=> (-> @aqueue rest (conj 5) pprint)
(5 2 3 4)
; with:
user=> (-> @aqueue pop (conj 5) pprint)
<-(2 3 4 5)-<
|
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.
|
#E
|
E
|
interface Quaternion guards QS {}
def makeQuaternion(a, b, c, d) {
return def quaternion implements QS {
to __printOn(out) {
out.print("(", a, " + ", b, "i + ")
out.print(c, "j + ", d, "k)")
}
# Task requirement 1
to norm() {
return (a**2 + b**2 + c**2 + d**2).sqrt()
}
# Task requirement 2
to negate() {
return makeQuaternion(-a, -b, -c, -d)
}
# Task requirement 3
to conjugate() {
return makeQuaternion(a, -b, -c, -d)
}
# Task requirement 4, 5
# This implements q + r; r + q is deliberately prohibited by E
to add(other :any[Quaternion, int, float64]) {
switch (other) {
match q :Quaternion {
return makeQuaternion(
a+q.a(), b+q.b(), c+q.c(), d+q.d())
}
match real {
return makeQuaternion(a+real, b, c, d)
}
}
}
# Task requirement 6, 7
# This implements q * r; r * q is deliberately prohibited by E
to multiply(other :any[Quaternion, int, float64]) {
switch (other) {
match q :Quaternion {
return makeQuaternion(
a*q.a() - b*q.b() - c*q.c() - d*q.d(),
a*q.b() + b*q.a() + c*q.d() - d*q.c(),
a*q.c() - b*q.d() + c*q.a() + d*q.b(),
a*q.d() + b*q.c() - c*q.b() + d*q.a())
}
match real {
return makeQuaternion(real*a, real*b, real*c, real*d)
}
}
}
to a() { return a }
to b() { return b }
to c() { return c }
to d() { return d }
}
}
|
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.
|
#bootBASIC
|
bootBASIC
|
10 list
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Julia
|
Julia
|
using DataStructures
queue = Queue(String)
@show enqueue!(queue, "foo")
@show enqueue!(queue, "bar")
@show dequeue!(queue) # -> foo
@show dequeue!(queue) # -> bar
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Kotlin
|
Kotlin
|
// version 1.1.2
import java.util.*
fun main(args: Array<String>) {
val q: Queue<Int> = ArrayDeque<Int>()
(1..5).forEach { q.add(it) }
println(q)
println("Size of queue = ${q.size}")
print("Removing: ")
(1..3).forEach { print("${q.remove()} ") }
println("\nRemaining in queue: $q")
println("Head element is now ${q.element()}")
q.clear()
println("After clearing, queue is ${if(q.isEmpty()) "empty" else "not empty"}")
try {
q.remove()
}
catch (e: NoSuchElementException) {
println("Can't remove elements from an empty queue")
}
}
|
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.
|
#J
|
J
|
quickselect=:4 :0
if. 0=#y do. _ return. end.
n=.?#y
m=.n{y
if. x < m do.
x quickselect (m>y)#y
else.
if. x > m do.
x quickselect (m<y)#y
else.
m
end.
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.
|
#Java
|
Java
|
import java.util.Random;
public class QuickSelect {
private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
E pivotVal = arr[pivot];
swap(arr, pivot, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i].compareTo(pivotVal) < 0) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, right, storeIndex);
return storeIndex;
}
private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (right >= left) {
int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
if (pivotIndex == n) {
return arr[pivotIndex];
} else if (pivotIndex < n) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return null;
}
private static void swap(Object[] arr, int i1, int i2) {
if (i1 != i2) {
Object temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
System.out.print(select(input, i));
if (i < 9) System.out.print(", ");
}
System.out.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
|
#Fortran
|
Fortran
|
SUBROUTINE IRANGE(TEXT) !Identifies integer ranges in a list of integers.
Could make this a function, but then a maximum text length returned would have to be specified.
CHARACTER*(*) TEXT !The list on input, the list with ranges on output.
INTEGER LOTS !Once again, how long is a piece of string?
PARAMETER (LOTS = 666) !This should do, at least for demonstrations.
INTEGER VAL(LOTS) !The integers of the list.
INTEGER N !Count of numbers.
INTEGER I,I1 !Steppers.
N = 1 !Presume there to be one number.
DO I = 1,LEN(TEXT) !Then by noticing commas,
IF (TEXT(I:I).EQ.",") N = N + 1 !Determine how many more there are.
END DO !Step alonmg the text.
IF (N.LE.2) RETURN !One comma = two values. Boring.
IF (N.GT.LOTS) STOP "Too many values!"
READ (TEXT,*) VAL(1:N) !Get the numbers, with free-format flexibility.
TEXT = "" !Scrub the parameter!
L = 0 !No text has been placed.
I1 = 1 !Start the scan.
10 IF (L.GT.0) CALL EMIT(",") !A comma if there is prior text.
CALL SPLOT(VAL(I1)) !The first number always appears.
DO I = I1 + 1,N !Now probe ahead
IF (VAL(I - 1) + 1 .NE. VAL(I)) EXIT !While values are consecutive.
END DO !Up to the end of the remaining list.
IF (I - I1 .GT. 2) THEN !More than two consecutive values seen?
CALL EMIT("-") !Yes!
CALL SPLOT(VAL(I - 1)) !The ending number of a range.
I1 = I !Finger the first beyond the run.
ELSE !But if too few to be worth a span,
I1 = I1 + 1 !Just finger the next number.
END IF !So much for that starter.
IF (I.LE.N) GO TO 10 !Any more?
CONTAINS !Some assistants to save on repetition.
SUBROUTINE EMIT(C) !Rolls forth one character.
CHARACTER*1 C !The character.
L = L + 1 !Advance the finger.
IF (L.GT.LEN(TEXT)) STOP "Ran out of text!" !Maybe not.
TEXT(L:L) = C !And place the character.
END SUBROUTINE EMIT !That was simple.
SUBROUTINE SPLOT(N) !Rolls forth a signed number.
INTEGER N !The number.
CHARACTER*12 FIELD !Sufficient for 32-bit integers.
INTEGER I !A stepper.
WRITE (FIELD,"(I0)") N!Roll the number, with trailing spaces.
DO I = 1,12 !Now transfer the text of the number.
IF (FIELD(I:I).LE." ") EXIT !Up to the first space.
CALL EMIT(FIELD(I:I)) !One by one.
END DO !On to the end.
END SUBROUTINE SPLOT !Not so difficult either.
END !So much for IRANGE.
PROGRAM POKE
CHARACTER*(200) SOME
SOME = " 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, "
1 //" 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,"
2 //"25, 27, 28, 29, 30, 31, 32, 33, 35, 36, "
3 //"37, 38, 39 "
CALL IRANGE(SOME)
WRITE (6,*) SOME
END
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#Logo
|
Logo
|
to random.float ; 0..1
localmake "max.int lshift -1 -1
output quotient random :max.int :max.int
end
to random.gaussian
output product cos random 360 sqrt -2 / ln random.float
end
make "randoms cascade 1000 [fput random.gaussian / 2 + 1 ?] []
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#Lua
|
Lua
|
local list = {}
for i = 1, 1000 do
list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
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
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function R = readconf(configfile)
% READCONF reads configuration file.
%
% The value of boolean parameters can be tested with
% exist(parameter,'var')
if nargin<1,
configfile = 'q.conf';
end;
fid = fopen(configfile);
if fid<0, error('cannot open file %s\n',a); end;
while ~feof(fid)
line = strtrim(fgetl(fid));
if isempty(line) || all(isspace(line)) || strncmp(line,'#',1) || strncmp(line,';',1),
; % no operation
else
[var,tok] = strtok(line,' \t=');
var = upper(var);
if any(tok==','),
k = 1;
while (1)
[val, tok]=strtok(tok,',');
R.(var){k} = strtrim(val); % return value of function
eval(sprintf('%s{%i}=''%s'';',var,k,strtrim(val))); % stores variable in local workspace
if isempty(tok), break; end;
k=k+1;
end;
else
tok = strtrim(tok);
R.(var) = tok; % return value of function
eval(sprintf('%s=''%s''; ',var,tok)); % stores variable in local workspace
end;
end;
end;
fclose(fid);
whos, % shows the parameter in the local workspace
|
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
|
#jq
|
jq
|
def expand_range:
def number: "-?[0-9]+";
def expand: [range(.[0]; .[1] + 1)];
split(",")
| reduce .[] as $r
( []; . +
($r | if test("^\(number)$") then [tonumber]
else sub( "(?<x>\(number))-(?<y>\(number))"; "\(.x):\(.y)")
| split(":") | map(tonumber) | expand
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
|
#Jsish
|
Jsish
|
#!/usr/bin/env jsish
"use strict";
/* Range expansion, in Jsish */
function rangeExpand(rangeExpr) {
function getFactors(term) {
var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);
if (!matches) return {first:Number(term)};
return {first:Number(matches[1]), last:Number(matches[2])};
}
function expandTerm(term) {
var factors = getFactors(term);
if (factors.length < 2) return [factors.first];
var range = [];
for (var n = factors.first; n <= factors.last; n++) {
range.push(n);
}
return range;
}
var result = [];
var terms = rangeExpr.split(",");
for (var t in terms) {
result = result.concat(expandTerm(terms[t]));
}
return result;
}
if (Interp.conf('unitTest')) {
; rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20');
}
/*
=!EXPECTSTART!=
rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20') ==> [ -6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 ]
=!EXPECTEND!=
*/
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.1.2
import java.io.File
fun main(args: Array<String>) {
File("input.txt").forEachLine { println(it) }
}
|
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.
|
#Lasso
|
Lasso
|
local(f) = file('foo.txt')
handle => {#f->close}
#f->forEachLine => {^
#1
'<br>' // note this simply inserts an HTML line break between each 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
|
#Prolog
|
Prolog
|
reverse("abcd", L), string_to_list(S,L).
|
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
|
#CoffeeScript
|
CoffeeScript
|
# Implement a fifo as an array of arrays, to
# greatly amortize dequeue costs, at some expense of
# memory overhead and insertion time. The speedup
# depends on the underlying JS implementation, but
# it's significant on node.js.
Fifo = ->
max_chunk = 512
arr = [] # array of arrays
count = 0
self =
enqueue: (elem) ->
if count == 0 or arr[arr.length-1].length >= max_chunk
arr.push []
count += 1
arr[arr.length-1].push elem
dequeue: (elem) ->
throw Error("queue is empty") if count == 0
val = arr[0].shift()
count -= 1
if arr[0].length == 0
arr.shift()
val
is_empty: (elem) ->
count == 0
# test
do ->
max = 5000000
q = Fifo()
for i in [1..max]
q.enqueue
number: i
console.log q.dequeue()
while !q.is_empty()
v = q.dequeue()
console.log v
|
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.
|
#Eero
|
Eero
|
#import <Foundation/Foundation.h>
interface Quaternion : Number
// Properties -- note that this is an immutable class.
double real, i, j, k {readonly}
end
implementation Quaternion
initWithReal: double, i: double, j: double, k: double, return instancetype
self = super.init
if self
_real = real; _i = i; _j = j; _k = k
return self
+new: double real, ..., return instancetype
va_list args
va_start(args, real)
object := Quaternion.alloc.initWithReal: real,
i: va_arg(args, double),
j: va_arg(args, double),
k: va_arg(args, double)
va_end(args)
return object
descriptionWithLocale: id, return String = String.stringWithFormat:
'(%.1f, %.1f, %.1f, %.1f)', self.real, self.i, self.j, self.k
norm, return double =
sqrt(self.real * self.real +
self.i * self.i + self.j * self.j + self.k * self.k)
negative, return Quaternion =
Quaternion.new: -self.real, -self.i, -self.j, -self.k
conjugate, return Quaternion =
Quaternion.new: self.real, -self.i, -self.j, -self.k
// Overload "+" operator (left operand is Quaternion)
plus: Number operand, return Quaternion
real := self.real, i = self.i, j = self.j, k = self.k
if operand.isKindOfClass: Quaternion.class
q := (Quaternion)operand
real += q.real; i += q.i; j += q.j; k += q.k
else
real += (double)operand
return Quaternion.new: real, i, j, k
// Overload "*" operator (left operand is Quaternion)
multipliedBy: Number operand, return Quaternion
real := self.real, i = self.i, j = self.j, k = self.k
if operand.isKindOfClass: Quaternion.class
q := (Quaternion)operand
real = self.real * q.real - self.i* q.i - self.j * q.j - self.k * q.k
i = self.real * q.i + self.i * q.real + self.j * q.k - self.k * q.j
j = self.real * q.j - self.i * q.k + self.j * q.real + self.k * q.i
k = self.real * q.k + self.i * q.j - self.j * q.i + self.k * q.real
else
real *= (double)operand
i *= (double)operand; j *= (double)operand; k *= (double)operand
return Quaternion.new: real, i, j, k
end
implementation Number (QuaternionOperators)
// Overload "+" operator (left operand is Number)
plus: Quaternion operand, return Quaternion
real := (double)self + operand.real
return Quaternion.new: real, operand.i, operand.j, operand.k
// Overload "*" operator (left operand is Number)
multipliedBy: Quaternion operand, return Quaternion
r := (double)self
return Quaternion.new: r * operand.real, r * operand.i,
r * operand.j, r * operand.k
end
int main()
autoreleasepool
q := Quaternion.new: 1.0, 2.0, 3.0, 4.0
q1 := Quaternion.new: 2.0, 3.0, 4.0, 5.0
q2 := Quaternion.new: 3.0, 4.0, 5.0, 6.0
Log( 'q = %@', q )
Log( 'q1 = %@', q1 )
Log( 'q2 = %@\n\n', q2 )
Log( 'q norm = %.3f', q.norm )
Log( 'q negative = %@', q.negative )
Log( 'q conjugate = %@', q.conjugate )
Log( '7 + q = %@', 7.0 + q )
Log( 'q + 7 = %@', q + 7.0 )
Log( 'q1 + q2 = %@', q1 + q2 )
Log( '7 * q = %@', 7 * q)
Log( 'q * 7 = %@', q * 7.0 )
Log( 'q1 * q2 = %@', q1 * q2 )
Log( 'q2 * q1 = %@', q2 * q1 )
return 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.