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.
|
#Stata
|
Stata
|
* Read rows 20 to 30 from somedata.dta
. use somedata in 20/30, clear
* Read rows for which the variable x is positive
. use somedata if x>0, clear
|
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.
|
#Tcl
|
Tcl
|
proc getNthLineFromFile {filename n} {
set f [open $filename]
while {[incr n -1] > 0} {
if {[gets $f line] < 0} {
close $f
error "no such line"
}
}
close $f
return $line
}
puts [getNthLineFromFile example.txt 7]
|
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.
|
#Delphi
|
Delphi
|
program Quickselect_algorithm;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function quickselect(list: TArray<Integer>; k: Integer): Integer;
procedure Swap(i, j: Integer);
var
tmp: Integer;
begin
tmp := list[i];
list[i] := list[j];
list[j] := tmp;
end;
begin
repeat
var px := length(list) div 2;
var pv := list[px];
var last := length(list) - 1;
Swap(px, last);
var i := 0;
for var j := 0 to last - 1 do
if list[j] < pv then
begin
swap(i, j);
inc(i);
end;
if i = k then
exit(pv);
if k < i then
delete(list, i, length(list))
else
begin
Swap(i, last);
delete(list, 0, i + 1);
dec(k, i + 1);
end;
until false;
end;
begin
var i := 0;
while True do
begin
var v: TArray<Integer> := [9, 8, 7, 6, 5, 0, 1, 2, 3, 4];
if i = length(v) then
Break;
Writeln(quickselect(v, i));
inc(i);
end;
Readln;
end.
|
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
|
Ramer-Douglas-Peucker line simplification
|
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–Peucker algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: 1.0.
Display the remaining points here.
Reference
the Wikipedia article: Ramer-Douglas-Peucker algorithm.
|
#Rust
|
Rust
|
#[derive(Copy, Clone)]
struct Point {
x: f64,
y: f64,
}
use std::fmt;
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
// Returns the distance from point p to the line between p1 and p2
fn perpendicular_distance(p: &Point, p1: &Point, p2: &Point) -> f64 {
let dx = p2.x - p1.x;
let dy = p2.y - p1.y;
(p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.x).abs() / dx.hypot(dy)
}
fn rdp(points: &[Point], epsilon: f64, result: &mut Vec<Point>) {
let n = points.len();
if n < 2 {
return;
}
let mut max_dist = 0.0;
let mut index = 0;
for i in 1..n - 1 {
let dist = perpendicular_distance(&points[i], &points[0], &points[n - 1]);
if dist > max_dist {
max_dist = dist;
index = i;
}
}
if max_dist > epsilon {
rdp(&points[0..=index], epsilon, result);
rdp(&points[index..n], epsilon, result);
} else {
result.push(points[n - 1]);
}
}
fn ramer_douglas_peucker(points: &[Point], epsilon: f64) -> Vec<Point> {
let mut result = Vec::new();
if points.len() > 0 && epsilon >= 0.0 {
result.push(points[0]);
rdp(points, epsilon, &mut result);
}
result
}
fn main() {
let points = vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 0.1 },
Point { x: 2.0, y: -0.1 },
Point { x: 3.0, y: 5.0 },
Point { x: 4.0, y: 6.0 },
Point { x: 5.0, y: 7.0 },
Point { x: 6.0, y: 8.1 },
Point { x: 7.0, y: 9.0 },
Point { x: 8.0, y: 9.0 },
Point { x: 9.0, y: 9.0 },
];
for p in ramer_douglas_peucker(&points, 1.0) {
println!("{}", p);
}
}
|
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
|
Ramer-Douglas-Peucker line simplification
|
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–Peucker algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: 1.0.
Display the remaining points here.
Reference
the Wikipedia article: Ramer-Douglas-Peucker algorithm.
|
#Sidef
|
Sidef
|
func perpendicular_distance(Arr start, Arr end, Arr point) {
((point == start) || (point == end)) && return 0
var (Δx, Δy ) = ( end »-« start)...
var (Δpx, Δpy) = (point »-« start)...
var h = hypot(Δx, Δy)
[\Δx, \Δy].map { *_ /= h }
(([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).sum.sqrt
}
func Ramer_Douglas_Peucker(Arr points { .all { .len > 1 } }, ε = 1) {
points.len == 2 && return points
var d = (^points -> map {
perpendicular_distance(points[0], points[-1], points[_])
})
if (d.max > ε) {
var i = d.index(d.max)
return [Ramer_Douglas_Peucker(points.ft(0, i), ε).ft(0, -2)...,
Ramer_Douglas_Peucker(points.ft(i), ε)...]
}
return [points[0,-1]]
}
say Ramer_Douglas_Peucker(
[[0,0],[1,0.1],[2,-0.1],[3,5],[4,6],[5,7],[6,8.1],[7,9],[8,9],[9,9]]
)
|
http://rosettacode.org/wiki/Range_extraction
|
Range extraction
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
|
#EchoLisp
|
EchoLisp
|
(define task '(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))
;; 1- GROUPING
(define (group-range item acc)
(if
(or (empty? acc) (!= (caar acc) (1- item)))
(cons (cons item item) acc)
(begin (set-car! (car acc) item) acc)))
;; intermediate result
;; (foldl group-range () task)
;; → ((39 . 35) (33 . 27) (25 . 14) (12 . 11) (8 . 6) (4 . 4) (2 . 0))
;; 2- FORMATTING
(define (range->string range)
(let ((from (rest range)) (to (first range)))
(cond
((= from to) (format "%d " from))
((= to (1+ from)) (format "%d, %d " from to))
(else (format "%d-%d " from to)))))
;; 3 - FINAL
(string-join (map range->string (reverse (foldl group-range () task))) ",")
→ "0-2 ,4 ,6-8 ,11, 12 ,14-25 ,27-33 ,35-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
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
const mean = 1.0
const stdv = .5
const n = 1000
func main() {
var list [n]float64
rand.Seed(time.Now().UnixNano())
for i := range list {
list[i] = mean + stdv*rand.NormFloat64()
}
// show computed mean and stdv of list
var s, sq float64
for _, v := range list {
s += v
}
cm := s / n
for _, v := range list {
d := v - cm
sq += d * d
}
fmt.Printf("mean %.3f, stdv %.3f\n", cm, math.Sqrt(sq/(n-1)))
// show histogram by hdiv divisions per stdv over +/-hrange stdv
const hdiv = 3
const hrange = 2
var h [1 + 2*hrange*hdiv]int
for _, v := range list {
bin := hrange*hdiv + int(math.Floor((v-mean)/stdv*hdiv+.5))
if bin >= 0 && bin < len(h) {
h[bin]++
}
}
const hscale = 10
for _, c := range h {
fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale))
}
}
|
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.
|
#Quackery
|
Quackery
|
typedef unsigned long long u8;
typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;
#define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
u8 ranval( ranctx *x ) {
u8 e = x->a - rot(x->b, 7);
x->a = x->b ^ rot(x->c, 13);
x->b = x->c + rot(x->d, 37);
x->c = x->d + e;
x->d = e + x->a;
return x->d;
}
void raninit( ranctx *x, u8 seed ) {
u8 i;
x->a = 0xf1ea5eed, x->b = x->c = x->d = seed;
for (i=0; i<20; ++i) {
(void)ranval(x);
}
}
|
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.
|
#R
|
R
|
?RNG
help.search("Distribution", package="stats")
|
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.
|
#Racket
|
Racket
|
import util::Math;
arbInt(int limit); // generates an arbitrary integer below limit
arbRat(int limit, int limit); // generates an arbitrary rational number between the limits
arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0]
arbSeed(int seed);
|
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
|
#JavaScript
|
JavaScript
|
function parseConfig(config) {
// this expression matches a line starting with an all capital word,
// and anything after it
var regex = /^([A-Z]+)(.*)$/mg;
var configObject = {};
// loop until regex.exec returns null
var match;
while (match = regex.exec(config)) {
// values will typically be an array with one element
// unless we want an array
// match[0] is the whole match, match[1] is the first group (all caps word),
// and match[2] is the second (everything through the end of line)
var key = match[1], values = match[2].split(",");
if (values.length === 1) {
configObject[key] = values[0];
}
else {
configObject[key] = values.map(function(value){
return value.trim();
});
}
}
return configObject;
}
|
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
|
#Fortran
|
Fortran
|
MODULE HOMEONTHERANGE
CONTAINS !The key function.
CHARACTER*200 FUNCTION ERANGE(TEXT) !Expands integer ranges in a list.
Can't return a character value of variable size.
CHARACTER*(*) TEXT !The list on input.
CHARACTER*200 ALINE !Scratchpad for output.
INTEGER N,N1,N2 !Numbers in a range.
INTEGER I,I1 !Steppers.
ALINE = "" !Scrub the scratchpad.
L = 0 !No text has been placed.
I = 1 !Start at the start.
CALL FORASIGN !Find something to look at.
Chug through another number or number - number range.
R:DO WHILE(EATINT(N1)) !If I can grab a first number, a term has begun.
N2 = N1 !Make the far end the same.
IF (PASSBY("-")) CALL EATINT(N2) !A hyphen here is not a minus sign.
IF (L.GT.0) CALL EMIT(",") !Another, after what went before?
DO N = N1,N2,SIGN(+1,N2 - N1) !Step through the range, possibly backwards.
CALL SPLOT(N) !Roll a number.
IF (N.NE.N2) CALL EMIT(",") !Perhaps another follows.
END DO !On to the next number.
IF (.NOT.PASSBY(",")) EXIT R !More to come?
END DO R !So much for a range.
Completed the scan. Just return the result.
ERANGE = ALINE(1:L) !Present the result. Fiddling ERANGE is bungled by some compilers.
CONTAINS !Some assistants for the scan to save on repetition and show intent.
SUBROUTINE FORASIGN !Look for one.
1 IF (I.LE.LEN(TEXT)) THEN !After a thingy,
IF (TEXT(I:I).LE." ") THEN !There may follow spaces.
I = I + 1 !So,
GO TO 1 !Speed past any.
END IF !So that the caller can see
END IF !Whatever substantive character follows.
END SUBROUTINE FORASIGN !Simple enough.
LOGICAL FUNCTION PASSBY(C) !Advances the scan if a certain character is seen.
Could consider or ignore case for letters, but this is really for single symbols.
CHARACTER*1 C !The character.
PASSBY = .FALSE. !Pessimism.
IF (I.LE.LEN(TEXT)) THEN !Can't rely on I.LE.LEN(TEXT) .AND. TEXT(I:I)...
IF (TEXT(I:I).EQ.C) THEN !Curse possible full evaluation.
PASSBY = .TRUE. !Righto, C is seen.
I = I + 1 !So advance the scan.
CALL FORASIGN !And see what follows.
END IF !So much for a match.
END IF !If there is something to be uinspected.
END FUNCTION PASSBY !Can't rely on testing PASSBY within PASSBY either.
LOGICAL FUNCTION EATINT(N) !Convert text into an integer.
INTEGER N !The value to be ascertained.
INTEGER D !A digit.
LOGICAL NEG !In case of a minus sign.
EATINT = .FALSE. !Pessimism.
IF (I.GT.LEN(TEXT)) RETURN !Anything to look at?
N = 0 !Scrub to start with.
IF (PASSBY("+")) THEN !A plus sign here can be ignored.
NEG = .FALSE. !So, there's no minus sign.
ELSE !And if there wasn't a plus,
NEG = PASSBY("-") !A hyphen here is a minus sign.
END IF !One way or another, NEG is initialised.
IF (I.GT.LEN(TEXT)) RETURN !Nothing further! We wuz misled!
Chug through digits. Can develop -2147483648, thanks to the workings of two's complement.
10 D = ICHAR(TEXT(I:I)) - ICHAR("0") !Hope for a digit.
IF (0.LE.D .AND. D.LE.9) THEN !Is it one?
N = N*10 + D !Yes! Assimilate it, negatively.
I = I + 1 !Advance one.
IF (I.LE.LEN(TEXT)) GO TO 10 !And see what comes next.
END IF !So much for a sequence of digits.
IF (NEG) N = -N !Apply the minus sign.
EATINT = .TRUE. !Should really check for at least one digit.
CALL FORASIGN !Ram into whatever follows.
END FUNCTION EATINT !Integers are easy. Could check for no digits seen.
SUBROUTINE EMIT(C) !Rolls forth one character.
CHARACTER*1 C !The character.
L = L + 1 !Advance the finger.
IF (L.GT.LEN(ALINE)) STOP "Ran out of ALINE!" !Maybe not.
ALINE(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 ALINE 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 FUNCTION ERANGE !A bit tricky.
END MODULE HOMEONTHERANGE
PROGRAM POKE
USE HOMEONTHERANGE
CHARACTER*(200) SOME
SOME = "-6,-3--1,3-5,7-11,14,15,17-20"
SOME = ERANGE(SOME)
WRITE (6,*) SOME !If ERANGE(SOME) then the function usually can't write output also.
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.
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Open "input.txt" For Input As #1
Dim line_ As String
While Not Eof(1)
Line Input #1, line_ '' read each line
Print line_ '' echo it to the console
Wend
Close #1
Print
Print "Press any key to quit"
Sleep
|
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.
|
#Scala
|
Scala
|
object RankingMethods extends App {
case class Score(score: Int, name: String) // incoming data
case class Rank[Precision](rank: Precision, names: List[String]) // outgoing results (can be int or double)
case class State[Precision](n: Int, done: List[Rank[Precision]]) { // internal state, no mutable variables
def next(n: Int, next: Rank[Precision]) = State(n, next :: done)
}
def grouped[Precision](list: List[Score]) = // group names together by score, with highest first
(scala.collection.immutable.TreeMap[Int, List[Score]]() ++ list.groupBy(-_.score))
.values.map(_.map(_.name)).foldLeft(State[Precision](1, Nil)) _
// Ranking methods:
def rankStandard(list: List[Score]) =
grouped[Int](list){case (state, names) => state.next(state.n+names.length, Rank(state.n, names))}.done.reverse
def rankModified(list: List[Score]) =
rankStandard(list).map(r => Rank(r.rank+r.names.length-1, r.names))
def rankDense(list: List[Score]) =
grouped[Int](list){case (state, names) => state.next(state.n+1, Rank(state.n, names))}.done.reverse
def rankOrdinal(list: List[Score]) =
list.zipWithIndex.map{case (score, n) => Rank(n+1, List(score.name))}
def rankFractional(list: List[Score]) =
rankStandard(list).map(r => Rank((2*r.rank+r.names.length-1.0)/2, r.names))
// Tests:
def parseScores(s: String) = s split "\\s+" match {case Array(s,n) => Score(s.toInt, n)}
val test = List("44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen").map(parseScores)
println("Standard:")
println(rankStandard(test) mkString "\n")
println("\nModified:")
println(rankModified(test) mkString "\n")
println("\nDense:")
println(rankDense(test) mkString "\n")
println("\nOrdinal:")
println(rankOrdinal(test) mkString "\n")
println("\nFractional:")
println(rankFractional(test) mkString "\n")
}
|
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
|
#PicoLisp
|
PicoLisp
|
(pack (flip (chop "äöüÄÖÜß")))
|
http://rosettacode.org/wiki/Random_number_generator_(device)
|
Random number generator (device)
|
Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
|
#XPL0
|
XPL0
|
code Ran=1;
int R;
R:= Ran($7FFF_FFFF)
|
http://rosettacode.org/wiki/Random_number_generator_(device)
|
Random number generator (device)
|
Task
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
Related task
Random_number_generator_(included)
|
#zkl
|
zkl
|
const RANDOM_PATH="/dev/urandom";
fin,buf:=File(RANDOM_PATH,"r"), fin.read(4);
fin.close(); // GC would also close the file
println(buf.toBigEndian(0,4)); // 4 bytes @ offset 0
|
http://rosettacode.org/wiki/Random_Latin_squares
|
Random Latin squares
|
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
A randomised Latin square generates random configurations of the symbols for any given n.
Example n=4 randomised Latin square
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
Task
Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
Use the function to generate and show here, two randomly generated squares of size 5.
Note
Strict Uniformity in the random generation is a hard problem and not a requirement of the task.
Reference
Wikipedia: Latin square
OEIS: A002860
|
#Ring
|
Ring
|
load "stdlib.ring"
load "guilib.ring"
###====================================================================================
size = 10
time1 = 0
bwidth = 0
bheight = 0
a2DSquare = newlist(size,size)
a2DFinal = newlist(size,size)
aList = 1:size
aList2 = RandomList(aList)
GenerateRows(aList2)
ShuffleCols(a2DSquare, a2DFinal)
C_SPACING = 1
Button = newlist(size,size)
LayoutButtonRow = list(size)
C_ButtonOrangeStyle = 'border-radius:1x;color:black; background-color: orange'
###====================================================================================
MyApp = New qApp {
StyleFusion()
win = new qWidget() {
workHeight = win.height()
fontSize = 8 + (300/size)
wwidth = win.width()
wheight = win.height()
bwidth = wwidth/size
bheight = wheight/size
setwindowtitle("Random Latin Squares")
move(555,0)
setfixedsize(1000,1000)
myfilter = new qallevents(win)
myfilter.setResizeEvent("resizeBoard()")
installeventfilter(myfilter)
LayoutButtonMain = new QVBoxLayout() {
setSpacing(C_SPACING)
setContentsmargins(50,50,50,50)
}
LayoutButtonStart = new QHBoxLayout() {
setSpacing(C_SPACING)
setContentsmargins(0,0,0,0)
}
btnStart = new qPushButton(win) {
setFont(new qFont("Calibri",fontsize,2100,0))
resize(bwidth,bheight)
settext(" Start ")
setstylesheet(C_ButtonOrangeStyle)
setclickevent("gameSolution()")
}
sizeBtn = new qlabel(win)
{
setFont(new qFont("Calibri",fontsize,2100,0))
resize(bwidth,bheight)
setStyleSheet("background-color:rgb(255,255,204)")
setText(" Size: ")
}
lineSize = new qLineEdit(win)
{
setFont(new qFont("Calibri",fontsize,2100,0))
resize(bwidth,bheight)
setStyleSheet("background-color:rgb(255,255,204)")
setAlignment( Qt_AlignHCenter)
setAlignment( Qt_AlignVCenter)
setreturnPressedEvent("newBoardSize()")
setText(string(size))
}
btnExit = new qPushButton(win) {
setFont(new qFont("Calibri",fontsize,2100,0))
resize(bwidth,bheight)
settext(" Exit ")
setstylesheet(C_ButtonOrangeStyle)
setclickevent("pExit()")
}
LayoutButtonStart.AddWidget(btnStart)
LayoutButtonStart.AddWidget(sizeBtn)
LayoutButtonStart.AddWidget(lineSize)
LayoutButtonStart.AddWidget(btnExit)
LayoutButtonMain.AddLayout(LayoutButtonStart)
for Row = 1 to size
LayoutButtonRow[Row] = new QHBoxLayout() {
setSpacing(C_SPACING)
setContentsmargins(0,0,0,0)
}
for Col = 1 to size
Button[Row][Col] = new qlabel(win) {
setFont(new qFont("Calibri",fontsize,2100,0))
resize(bwidth,bheight)
}
LayoutButtonRow[Row].AddWidget(Button[Row][Col])
next
LayoutButtonMain.AddLayout(LayoutButtonRow[Row])
next
setLayout(LayoutButtonMain)
show()
}
exec()
}
###====================================================================================
func newBoardSize()
nrSize = number(lineSize.text())
if nrSize = 1
? "Enter: Size > 1"
return
ok
for Row = 1 to size
for Col = 1 to size
Button[Row][Col].settext("")
next
next
newWindow(nrSize)
###====================================================================================
func newWindow(newSize)
time1 = clock()
for Row = 1 to size
for Col = 1 to size
Button[Row][Col].delete()
next
next
size = newSize
bwidth = ceil((win.width() - 8) / size)
bheight = ceil((win.height() - 32) / size)
fontSize = 8 + (300/size)
if size > 16
fontSize = 8 + (150/size)
ok
if size < 8
fontSize = 30 + (150/size)
ok
if size = 2
fontSize = 10 + (100/size)
ok
btnStart.setFont(new qFont("Calibri",fontsize,2100,0))
sizeBtn.setFont(new qFont("Calibri",fontsize,2100,0))
lineSize.setFont(new qFont("Calibri",fontsize,2100,0))
btnExit.setFont(new qFont("Calibri",fontsize,2100,0))
LayoutButtonStart = new QHBoxLayout() {
setSpacing(C_SPACING)
setContentsmargins(0,0,0,0)
}
Button = newlist(size,size)
LayoutButtonRow = list(size)
for Row = 1 to size
LayoutButtonRow[Row] = new QHBoxLayout() {
setSpacing(C_SPACING)
setContentsmargins(0,0,0,0)
}
for Col = 1 to size
Button[Row][Col] = new qlabel(win) {
setFont(new qFont("Calibri",fontsize,2100,0))
resize(bwidth,bheight)
}
LayoutButtonRow[Row].AddWidget(Button[Row][Col])
next
LayoutButtonMain.AddLayout(LayoutButtonRow[Row])
next
win.setLayout(LayoutButtonMain)
return
###====================================================================================
func resizeBoard
bwidth = ceil((win.width() - 8) / size)
bheight = ceil((win.height() - 32) / size)
for Row = 1 to size
for Col = 1 to size
Button[Row][Col].resize(bwidth,bheight)
next
next
###====================================================================================
Func pExit
MyApp.quit()
###====================================================================================
func gameSolution()
a2DSquare = newlist(size,size)
a2DFinal = newlist(size,size)
aList = 1:size
aList2 = RandomList(aList)
GenerateRows(aList2)
ShuffleCols(a2DSquare, a2DFinal)
for nRow = 1 to size
for nCol = 1 to size
Button[nRow][nCol].settext("-")
next
next
for nRow = 1 to size
for nCol = 1 to size
Button[nRow][nCol].resize(bwidth,bheight)
Button[nRow][nCol].settext(string(a2DSquare[nRow][nCol]))
next
next
time2 = clock()
time3 = (time2 - time1)/1000
? "Elapsed time: " + time3 + " ms at size = " + size + nl
###====================================================================================
// Scramble the numbers in the List
// Uniq random picks, then shorten list by each pick
Func RandomList(aInput)
aOutput = []
while len(aInput) > 1
nIndex = random(len(aInput)-1)
nIndex++
aOutput + aInput[nIndex]
del(aInput,nIndex)
end
aOutput + aInput[1]
return aOutput
###====================================================================================
// Generate Rows of data. Put them in the 2DArray
Func GenerateRows(aInput)
aOutput = []
size = len(aInput)
shift = 1
for k = 1 to size // Make 8 Rows of lists
aOutput = []
for i = 1 to size // make a list
pick = i + shift // shift every Row by +1 more
if pick > size pick = pick - size ok
aOutput + aInput[pick]
next
a2DSquare[k] = aOutput // Row of Output to a2DSquare
shift++ // shift next line by +1 more
if shift > size shift = 1 ok
next
return
###====================================================================================
// Shift random Rows into a2DFinal, then random Cols
Func ShuffleCols(a2DSquare, a2DFinal)
aSuffle = 1:size
aSuffle2 = RandomList(aSuffle) // Pick random Col to insert in a2DFinal
for i = 1 to size // Row
pick = aSuffle2[i]
for j = 1 to size // Col
a2DFinal[i][j] = a2DSquare[pick][j] // i-Row-Col j-Horz-Vert
next
next
a2DSquare = a2DFinal // Now do the verticals
aSuffle = 1:size
aSuffle2 = RandomList(aSuffle)
for i = 1 to size // Row
pick = aSuffle2[i]
for j = 1 to size // Col
a2DFinal[j][i] = a2DSquare[j][pick] //Reverse i-j , i-Row-Col j-Horz-Vert
next
next
return
###====================================================================================
|
http://rosettacode.org/wiki/Random_Latin_squares
|
Random Latin squares
|
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
A randomised Latin square generates random configurations of the symbols for any given n.
Example n=4 randomised Latin square
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
Task
Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
Use the function to generate and show here, two randomly generated squares of size 5.
Note
Strict Uniformity in the random generation is a hard problem and not a requirement of the task.
Reference
Wikipedia: Latin square
OEIS: A002860
|
#Ruby
|
Ruby
|
N = 5
def generate_square
perms = (1..N).to_a.permutation(N).to_a.shuffle
square = []
N.times do
square << perms.pop
perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} }
end
square
end
def print_square(square)
cell_size = N.digits.size + 1
strings = square.map!{|row| row.map!{|el| el.to_s.rjust(cell_size)}.join }
puts strings, "\n"
end
2.times{print_square( generate_square)}
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#Ursala
|
Ursala
|
#import flo
in =
@lrzyCipPX ~|afatPRZaq ~&EZ+fleq~~lrPrbr2G&& ~&B+fleq~~lrPrbl2G!| -&
~&Y+ ~~lrPrbl2G fleq,
^E(fleq@lrrPX,@rl fleq\0.)^/~&lr ^(~&r,times)^/minus@llPrll2X vid+ minus~~rbbI&-
|
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
|
#AWK
|
AWK
|
#!/usr/bin/awk -f
BEGIN {
delete q
print "empty? " emptyP()
print "push " push("a")
print "push " push("b")
print "empty? " emptyP()
print "pop " pop()
print "pop " pop()
print "empty? " emptyP()
print "pop " pop()
}
function push(n) {
q[length(q)+1] = n
return n
}
function pop() {
if (emptyP()) {
print "Popping from empty queue."
exit
}
r = q[length(q)]
delete q[length(q)]
return r
}
function emptyP() {
return length(q) == 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.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
typedef struct quaternion
{
double q[4];
} quaternion_t;
quaternion_t *quaternion_new(void)
{
return malloc(sizeof(quaternion_t));
}
quaternion_t *quaternion_new_set(double q1,
double q2,
double q3,
double q4)
{
quaternion_t *q = malloc(sizeof(quaternion_t));
if (q != NULL) {
q->q[0] = q1; q->q[1] = q2; q->q[2] = q3; q->q[3] = q4;
}
return q;
}
void quaternion_copy(quaternion_t *r, quaternion_t *q)
{
size_t i;
if (r == NULL || q == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = q->q[i];
}
double quaternion_norm(quaternion_t *q)
{
size_t i;
double r = 0.0;
if (q == NULL) {
fprintf(stderr, "NULL quaternion in norm\n");
return 0.0;
}
for(i = 0; i < 4; i++) r += q->q[i] * q->q[i];
return sqrt(r);
}
void quaternion_neg(quaternion_t *r, quaternion_t *q)
{
size_t i;
if (q == NULL || r == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = -q->q[i];
}
void quaternion_conj(quaternion_t *r, quaternion_t *q)
{
size_t i;
if (q == NULL || r == NULL) return;
r->q[0] = q->q[0];
for(i = 1; i < 4; i++) r->q[i] = -q->q[i];
}
void quaternion_add_d(quaternion_t *r, quaternion_t *q, double d)
{
if (q == NULL || r == NULL) return;
quaternion_copy(r, q);
r->q[0] += d;
}
void quaternion_add(quaternion_t *r, quaternion_t *a, quaternion_t *b)
{
size_t i;
if (r == NULL || a == NULL || b == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = a->q[i] + b->q[i];
}
void quaternion_mul_d(quaternion_t *r, quaternion_t *q, double d)
{
size_t i;
if (r == NULL || q == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = q->q[i] * d;
}
bool quaternion_equal(quaternion_t *a, quaternion_t *b)
{
size_t i;
for(i = 0; i < 4; i++) if (a->q[i] != b->q[i]) return false;
return true;
}
#define A(N) (a->q[(N)])
#define B(N) (b->q[(N)])
#define R(N) (r->q[(N)])
void quaternion_mul(quaternion_t *r, quaternion_t *a, quaternion_t *b)
{
size_t i;
double ri = 0.0;
if (r == NULL || a == NULL || b == NULL) return;
R(0) = A(0)*B(0) - A(1)*B(1) - A(2)*B(2) - A(3)*B(3);
R(1) = A(0)*B(1) + A(1)*B(0) + A(2)*B(3) - A(3)*B(2);
R(2) = A(0)*B(2) - A(1)*B(3) + A(2)*B(0) + A(3)*B(1);
R(3) = A(0)*B(3) + A(1)*B(2) - A(2)*B(1) + A(3)*B(0);
}
#undef A
#undef B
#undef R
void quaternion_print(quaternion_t *q)
{
if (q == NULL) return;
printf("(%lf, %lf, %lf, %lf)\n",
q->q[0], q->q[1], q->q[2], q->q[3]);
}
|
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.
|
#BASIC
|
BASIC
|
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
|
#E
|
E
|
def [reader, writer] := makeQueue()
require(escape empty { reader.dequeue(empty); false } catch _ { true })
writer.enqueue(1)
writer.enqueue(2)
require(reader.dequeue(throw) == 1)
writer.enqueue(3)
require(reader.dequeue(throw) == 2)
require(reader.dequeue(throw) == 3)
require(escape empty { reader.dequeue(empty); false } catch _ { true })
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Elena
|
Elena
|
import system'collections;
import extensions;
public program()
{
// Create a queue and "push" items into it
var queue := new Queue();
queue.push:1;
queue.push:3;
queue.push:5;
// "Pop" items from the queue in FIFO order
console.printLine(queue.pop()); // 1
console.printLine(queue.pop()); // 3
console.printLine(queue.pop()); // 5
// To tell if the queue is empty, we check the count
console.printLine("queue is ",(queue.Length == 0).iif("empty","nonempty"));
// If we try to pop from an empty queue, an exception
// is thrown.
queue.pop() | on:(e){ console.writeLine:"Queue empty." }
}
|
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.
|
#TorqueScript
|
TorqueScript
|
%file = new fileObject();
%file.openForRead("File/Path.txt");
$seventhLine = "";
while(!%file.isEOF())
{
%line++;
if(%line == 7)
{
$seventhLine = %file.readLine();
if($seventhLine $= "")
{
error("Line 7 of the file is blank!");
}
}
}
%file.close();
%file.delete();
if(%line < 7)
{
error("The file does not have seven lines!");
}
|
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.
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
file="lines.txt"
ERROR/STOP OPEN (file,READ,-std-)
line2fetch=7
|
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.
|
#EasyLang
|
EasyLang
|
func qselect k d[] . res .
#
subr partition
mid = left
for i = left + 1 to right
if d[i] < d[left]
mid += 1
swap d[i] d[mid]
.
.
swap d[left] d[mid]
.
right = len d[] - 1
repeat
call partition
until mid = k
if mid < k
left = mid + 1
else
right = mid - 1
.
.
res = d[k]
.
d[] = [ 9 8 7 6 5 0 1 2 3 4 ]
for i range len d[]
call qselect i d[] r
print r
.
|
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.
|
#Elixir
|
Elixir
|
defmodule Quick do
def select(k, [x|xs]) do
{ys, zs} = Enum.partition(xs, fn e -> e < x end)
l = length(ys)
cond do
k < l -> select(k, ys)
k > l -> select(k - l - 1, zs)
true -> x
end
end
def test do
v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
Enum.map(0..length(v)-1, fn i -> select(i,v) end)
|> IO.inspect
end
end
Quick.test
|
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
|
Ramer-Douglas-Peucker line simplification
|
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–Peucker algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: 1.0.
Display the remaining points here.
Reference
the Wikipedia article: Ramer-Douglas-Peucker algorithm.
|
#Swift
|
Swift
|
struct Point: CustomStringConvertible {
let x: Double, y: Double
var description: String {
return "(\(x), \(y))"
}
}
// Returns the distance from point p to the line between p1 and p2
func perpendicularDistance(p: Point, p1: Point, p2: Point) -> Double {
let dx = p2.x - p1.x
let dy = p2.y - p1.y
let d = (p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.x)
return abs(d)/(dx * dx + dy * dy).squareRoot()
}
func ramerDouglasPeucker(points: [Point], epsilon: Double) -> [Point] {
var result : [Point] = []
func rdp(begin: Int, end: Int) {
guard end > begin else {
return
}
var maxDist = 0.0
var index = 0
for i in begin+1..<end {
let dist = perpendicularDistance(p: points[i], p1: points[begin],
p2: points[end])
if dist > maxDist {
maxDist = dist
index = i
}
}
if maxDist > epsilon {
rdp(begin: begin, end: index)
rdp(begin: index, end: end)
} else {
result.append(points[end])
}
}
if points.count > 0 && epsilon >= 0.0 {
result.append(points[0])
rdp(begin: 0, end: points.count - 1)
}
return result
}
let points = [
Point(x: 0.0, y: 0.0),
Point(x: 1.0, y: 0.1),
Point(x: 2.0, y: -0.1),
Point(x: 3.0, y: 5.0),
Point(x: 4.0, y: 6.0),
Point(x: 5.0, y: 7.0),
Point(x: 6.0, y: 8.1),
Point(x: 7.0, y: 9.0),
Point(x: 8.0, y: 9.0),
Point(x: 9.0, y: 9.0)
]
print("\(ramerDouglasPeucker(points: points, epsilon: 1.0))")
|
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
|
Ramer-Douglas-Peucker line simplification
|
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–Peucker algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: 1.0.
Display the remaining points here.
Reference
the Wikipedia article: Ramer-Douglas-Peucker algorithm.
|
#Wren
|
Wren
|
import "/dynamic" for Tuple
var Point = Tuple.create("Point", ["x", "y"])
var rdp // recursive
rdp = Fn.new { |l, eps|
var x = 0
var dMax = -1
var p1 = l[0]
var p2 = l[-1]
var x21 = p2.x - p1.x
var y21 = p2.y - p1.y
var i = 0
for (p in l[1..-1]) {
var d = (y21*p.x - x21*p.y + p2.x*p1.y - p2.y*p1.x).abs
if (d > dMax) {
x = i + 1
dMax = d
}
i = i + 1
}
if (dMax > eps) {
return rdp.call(l[0..x], eps) + rdp.call(l[x..-1], eps)[1..-1]
}
return [l[0], l[-1]]
}
var points = [
Point.new(0, 0), Point.new(1, 0.1), Point.new(2, -0.1), Point.new(3, 5), Point.new(4, 6),
Point.new(5, 7), Point.new(6, 8.1), Point.new(7, 9), Point.new(8, 9), Point.new(9, 9)
]
System.print(rdp.call(points, 1))
|
http://rosettacode.org/wiki/Range_extraction
|
Range extraction
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
|
#Eiffel
|
Eiffel
|
class
RANGE
create
make
feature
make
local
extended_range: STRING
do
extended_range := "0, 1, 2, 4, 6, 7, 8, 11, 12, 14, " +
"15, 16, 17, 18, 19, 20, 21, 22, 23, 24, " +
"25, 27, 28, 29, 30, 31, 32, 33, 35, 36, " +
"37, 38, 39"
print("Extended range: " + extended_range + "%N")
print("Extracted range: " + extracted_range(extended_range) + "%N%N")
end
feature
extracted_range(sequence: STRING): STRING
local
elements: LIST[STRING]
first, curr: STRING
subrange_size, index: INTEGER
do
sequence.replace_substring_all (", ", ",")
elements := sequence.split (',')
from
index := 2
first := elements.at (1)
subrange_size := 0
Result := ""
until
index > elements.count
loop
curr := elements.at (index)
if curr.to_integer - first.to_integer - subrange_size = 1
then
subrange_size := subrange_size + 1
else
Result.append(first)
if (subrange_size <= 1)
then
Result.append (", ")
else
Result.append (" - ")
end
if (subrange_size >= 1)
then
Result.append ((first.to_integer + subrange_size).out)
Result.append (", ")
end
first := curr
subrange_size := 0
end
index := index + 1
end
Result.append(first)
if (subrange_size <= 1)
then
Result.append (", ")
else
Result.append (" - ")
end
if (subrange_size >= 1)
then
Result.append ((first.to_integer + subrange_size).out)
end
end
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
|
#Groovy
|
Groovy
|
rnd = new Random()
result = (1..1000).inject([]) { r, i -> r << rnd.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
|
#Haskell
|
Haskell
|
import System.Random
pairs :: [a] -> [(a,a)]
pairs (x:y:zs) = (x,y):pairs zs
pairs _ = []
gauss mu sigma (r1,r2) =
mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)
gaussians :: (RandomGen g, Random a, Floating a) => Int -> g -> [a]
gaussians n g = take n $ map (gauss 1.0 0.5) $ pairs $ randoms g
result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g
|
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.
|
#Raku
|
Raku
|
import util::Math;
arbInt(int limit); // generates an arbitrary integer below limit
arbRat(int limit, int limit); // generates an arbitrary rational number between the limits
arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0]
arbSeed(int seed);
|
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.
|
#Rascal
|
Rascal
|
import util::Math;
arbInt(int limit); // generates an arbitrary integer below limit
arbRat(int limit, int limit); // generates an arbitrary rational number between the limits
arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0]
arbSeed(int seed);
|
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.
|
#REXX
|
REXX
|
/*(below) returns a random integer between 100 & 200, inclusive.*/
y = random(100, 200)
|
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.
|
#Ring
|
Ring
|
nr = 10
for i = 1 to nr
see random(i) + nl
next
|
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.
|
#Ruby
|
Ruby
|
rmd(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
|
#jq
|
jq
|
def parse:
def uc: .name | ascii_upcase;
def parse_boolean:
capture( "(?<name>^[^ ] *$)" )
| { (uc) : true };
def parse_var_value:
capture( "(?<name>^[^ ]+)[ =] *(?<value>[^,]+ *$)" )
| { (uc) : .value };
def parse_var_array:
capture( "(?<name>^[^ ]+)[ =] *(?<value>.*)" )
| { (uc) : (.value | sub(" +$";"") | [splits(", *")]) };
reduce inputs as $i ({};
if $i|length == 0 or test("^[#;]") then .
else . + ($i | ( parse_boolean // parse_var_value // parse_var_array // {} ))
end);
parse
|
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
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1) = Mid(s, position(i - 1) + 1, length)
Next
End Sub
Function expandRange(s As Const String) As String
If s = "" Then Return ""
Dim b() As String
Dim c() As String
Dim result As String = ""
Dim As Integer start = 0, finish = 0, length
split s, ",", b()
For i As Integer = LBound(b) To UBound(b)
split b(i), "-", c()
length = UBound(c) - LBound(c) + 1
If length = 1 Then
start = ValLng(c(LBound(c)))
finish = start
ElseIf length = 2 Then
If Left(b(i), 1) = "-" Then
start = -ValLng(c(UBound(c)))
finish = start
Else
start = ValLng(c(LBound(c)))
finish = ValLng(c(UBound(c)))
End If
ElseIf length = 3 Then
start = -ValLng(c(LBound(c) + 1))
finish = ValLng(c(UBound(c)))
Else
start = -ValLng(c(LBound(c) + 1))
finish = -ValLng(c(UBound(c)))
End If
For j As Integer = start To finish
result += Str(j) + ", "
Next j
Next i
Return Left(result, Len(result) - 2) '' get rid of final ", "
End Function
Dim s As String = "-6,-3--1,3-5,7-11,14,15,17-20"
Print expandRange(s)
Print
Print "Press any key to quit"
Sleep
|
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.
|
#Frink
|
Frink
|
for line = lines["file:yourfile.txt"]
println[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.
|
#Gambas
|
Gambas
|
Public Sub Main()
Dim hFile As File
Dim sLine As String
hFile = Open "../InputText.txt" For Input
While Not Eof(hFile)
Line Input #hFile, sLine
Print sLine
Wend
End
|
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.
|
#Sidef
|
Sidef
|
var scores = [
Pair(Solomon => 44),
Pair(Jason => 42),
Pair(Errol => 42),
Pair(Garry => 41),
Pair(Bernard => 41),
Pair(Barry => 41),
Pair(Stephen => 39),
]
func tiers(s) {
s.group_by { .value }.kv.sort.flip.map { .value.map{.key} }
}
func standard(s) {
var rank = 1
gather {
for players in tiers(s) {
take(Pair(rank, players))
rank += players.len
}
}
}
func modified(s) {
var rank = 0
gather {
for players in tiers(s) {
rank += players.len
take(Pair(rank, players))
}
}
}
func dense(s) {
tiers(s).map_kv { |k,v| Pair(k+1, v) }
}
func ordinal(s) {
s.map_kv { |k,v| Pair(k+1, v.key) }
}
func fractional(s) {
var rank = 1
gather {
for players in tiers(s) {
var beg = rank
var end = (rank += players.len)
take(Pair(sum(beg ..^ end) / players.len, players))
}
}
}
func display(r) {
say r.map {|a| '%3s : %s' % a... }.join("\n")
}
say "Standard:"; display( standard(scores))
say "\nModified:"; display( modified(scores))
say "\nDense:"; display( dense(scores))
say "\nOrdinal:"; display( ordinal(scores))
say "\nFractional:"; display(fractional(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
|
#Pike
|
Pike
|
reverse("foo");
|
http://rosettacode.org/wiki/Random_Latin_squares
|
Random Latin squares
|
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
A randomised Latin square generates random configurations of the symbols for any given n.
Example n=4 randomised Latin square
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
Task
Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
Use the function to generate and show here, two randomly generated squares of size 5.
Note
Strict Uniformity in the random generation is a hard problem and not a requirement of the task.
Reference
Wikipedia: Latin square
OEIS: A002860
|
#Wren
|
Wren
|
import "random" for Random
var rand = Random.new()
var printSquare = Fn.new { |latin|
for (row in latin) System.print(row)
System.print()
}
var latinSquare = Fn.new { |n|
if (n <= 0) {
System.print("[]\n")
return
}
var latin = List.filled(n, null)
for (i in 0...n) {
latin[i] = List.filled(n, 0)
if (i == n - 1) break
for (j in 0...n) latin[i][j] = j
}
// first row
rand.shuffle(latin[0])
// middle row(s)
for (i in 1...n-1) {
var shuffled = false
while (!shuffled) {
rand.shuffle(latin[i])
var shuffling = false
for (k in 0...i) {
for (j in 0...n) {
if (latin[k][j] == latin[i][j]) {
shuffling = true
break
}
}
if (shuffling) break
}
if (!shuffling) shuffled = true
}
}
// last row
for (j in 0...n) {
var used = List.filled(n, false)
for (i in 0...n-1) used[latin[i][j]] = true
for (k in 0...n) {
if (!used[k]) {
latin[n-1][j] = k
break
}
}
}
printSquare.call(latin)
}
latinSquare.call(5)
latinSquare.call(5)
latinSquare.call(10) // for good measure
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Math
Module RayCasting
Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}
Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}
Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}
Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}
Private shapes As Integer()()() = {square, squareHole, strange, hexagon}
Public Sub Main()
Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}
For Each shape As Integer()() In shapes
For Each point As Double() In testPoints
Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7)))
Next
Console.WriteLine()
Next
End Sub
Private Function Contains(shape As Integer()(), point As Double()) As Boolean
Dim inside As Boolean = False
Dim length As Integer = shape.Length
For i As Integer = 0 To length - 1
If Intersects(shape(i), shape((i + 1) Mod length), point) Then
inside = Not inside
End If
Next
Return inside
End Function
Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean
If a(1) > b(1) Then Return Intersects(b, a, p)
If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001
If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False
If p(0) < Min(a(0), b(0)) Then Return True
Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))
Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))
Return red >= blue
End Function
End Module
|
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
|
#Batch_File
|
Batch File
|
@echo off
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: FIFO queue usage
:: Define the queue
call :newQueue myQ
:: Populate the queue
for %%A in (value1 value2 value3) do call :enqueue myQ %%A
:: Test if queue is empty by examining the tail "attribute"
if myQ.tail==0 (echo myQ is empty) else (echo myQ is NOT empty)
:: Peek at the head of the queue
call:peekQueue myQ val && echo a peek at the head of myQueue shows !val!
:: Process the first queue value
call :dequeue myQ val && echo dequeued myQ value=!val!
:: Add some more values to the queue
for %%A in (value4 value5 value6) do call :enqueue myQ %%A
:: Process the remainder of the queue
:processQueue
call :dequeue myQ val || goto :queueEmpty
echo dequeued myQ value=!val!
goto :processQueue
:queueEmpty
:: Test if queue is empty using the empty "method"/"macro". Use of the
:: second IF statement serves to demonstrate the negation of the empty
:: "method". A single IF could have been used with an ELSE clause instead.
if %myQ.empty% echo myQ is empty
if not %myQ.empty% echo myQ is NOT empty
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: FIFO queue definition
:newQueue qName
set /a %~1.head=1, %~1.tail=0
:: Define an empty "method" for this queue as a sort of macro
set "%~1.empty=^!%~1.tail^! == 0"
exit /b
:enqueue qName value
set /a %~1.tail+=1
set %~1.!%~1.tail!=%2
exit /b
:dequeue qName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because queue was empty
if !%~1.tail! equ 0 exit /b 1
for %%N in (!%~1.head!) do (
set %~2=!%~1.%%N!
set %~1.%%N=
)
if !%~1.head! == !%~1.tail! (set /a "%~1.head=1, %~1.tail=0") else set /a %~1.head+=1
exit /b 0
:peekQueue qName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because queue was empty
if !%~1.tail! equ 0 exit /b 1
for %%N in (!%~1.head!) do set %~2=!%~1.%%N!
exit /b 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.
|
#C.23
|
C#
|
using System;
struct Quaternion : IEquatable<Quaternion>
{
public readonly double A, B, C, D;
public Quaternion(double a, double b, double c, double d)
{
this.A = a;
this.B = b;
this.C = c;
this.D = d;
}
public double Norm()
{
return Math.Sqrt(A * A + B * B + C * C + D * D);
}
public static Quaternion operator -(Quaternion q)
{
return new Quaternion(-q.A, -q.B, -q.C, -q.D);
}
public Quaternion Conjugate()
{
return new Quaternion(A, -B, -C, -D);
}
// implicit conversion takes care of real*quaternion and real+quaternion
public static implicit operator Quaternion(double d)
{
return new Quaternion(d, 0, 0, 0);
}
public static Quaternion operator +(Quaternion q1, Quaternion q2)
{
return new Quaternion(q1.A + q2.A, q1.B + q2.B, q1.C + q2.C, q1.D + q2.D);
}
public static Quaternion operator *(Quaternion q1, Quaternion q2)
{
return new Quaternion(
q1.A * q2.A - q1.B * q2.B - q1.C * q2.C - q1.D * q2.D,
q1.A * q2.B + q1.B * q2.A + q1.C * q2.D - q1.D * q2.C,
q1.A * q2.C - q1.B * q2.D + q1.C * q2.A + q1.D * q2.B,
q1.A * q2.D + q1.B * q2.C - q1.C * q2.B + q1.D * q2.A);
}
public static bool operator ==(Quaternion q1, Quaternion q2)
{
return q1.A == q2.A && q1.B == q2.B && q1.C == q2.C && q1.D == q2.D;
}
public static bool operator !=(Quaternion q1, Quaternion q2)
{
return !(q1 == q2);
}
#region Object Members
public override bool Equals(object obj)
{
if (obj is Quaternion)
return Equals((Quaternion)obj);
return false;
}
public override int GetHashCode()
{
return A.GetHashCode() ^ B.GetHashCode() ^ C.GetHashCode() ^ D.GetHashCode();
}
public override string ToString()
{
return string.Format("Q({0}, {1}, {2}, {3})", A, B, C, D);
}
#endregion
#region IEquatable<Quaternion> Members
public bool Equals(Quaternion other)
{
return other == this;
}
#endregion
}
|
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.
|
#Batch_File
|
Batch File
|
@type %0
|
http://rosettacode.org/wiki/Queue/Usage
|
Queue/Usage
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Illustration of FIFO behavior
Task
Create a queue data structure and demonstrate its operations.
(For implementations of queues, see the FIFO task.)
Operations:
push (aka enqueue) - add element
pop (aka dequeue) - pop first element
empty - return truth value when empty
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Elisa
|
Elisa
|
defmodule Queue do
def empty?([]), do: true
def empty?(_), do: false
def pop([h|t]), do: {h,t}
def push(q,t), do: q ++ [t]
def front([h|_]), do: h
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
|
#Elixir
|
Elixir
|
defmodule Queue do
def empty?([]), do: true
def empty?(_), do: false
def pop([h|t]), do: {h,t}
def push(q,t), do: q ++ [t]
def front([h|_]), do: h
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
|
#Erlang
|
Erlang
|
1> Q = fifo:new().
{fifo,[],[]}
2> fifo:empty(Q).
true
3> Q2 = fifo:push(Q,1).
{fifo,[1],[]}
4> Q3 = fifo:push(Q2,2).
{fifo,[2,1],[]}
5> fifo:empty(Q3).
false
6> fifo:pop(Q3).
{1,{fifo,[],[2]}}
7> {Popped, Q} = fifo:pop(Q2).
{1,{fifo,[],[]}}
8> fifo:pop(fifo:new()).
** exception error: 'empty fifo'
in function fifo:pop/1
|
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.
|
#TXR
|
TXR
|
@(skip nil 7)
@line
|
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.
|
#UNIX_Shell
|
UNIX Shell
|
get_nth_line() {
local file=$1 n=$2 line
while ((n-- > 0)); do
if ! IFS= read -r line; then
echo "No such line $2 in $file"
return 1
fi
done < "$file"
echo "$line"
}
get_nth_line filename 7
|
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.
|
#Erlang
|
Erlang
|
-module(quickselect).
-export([test/0]).
test() ->
V = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4],
lists:map(
fun(I) -> quickselect(I,V) end,
lists:seq(0, length(V) - 1)
).
quickselect(K, [X | Xs]) ->
{Ys, Zs} =
lists:partition(fun(E) -> E < X end, Xs),
L = length(Ys),
if
K < L ->
quickselect(K, Ys);
K > L ->
quickselect(K - L - 1, Zs);
true ->
X
end.
|
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
|
Ramer-Douglas-Peucker line simplification
|
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–Peucker algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: 1.0.
Display the remaining points here.
Reference
the Wikipedia article: Ramer-Douglas-Peucker algorithm.
|
#Yabasic
|
Yabasic
|
sub perpendicularDistance(tabla(), i, ini, fin)
local dx, cy, mag, pvx, pvy, pvdot, dsx, dsy, ax, ay
dx = tabla(fin, 1) - tabla(ini, 1)
dy = tabla(fin, 2) - tabla(ini, 2)
//Normalise
mag = (dx^2 + dy^2)^0.5
if mag > 0 dx = dx / mag : dy = dy / mag
pvx = tabla(i, 1) - tabla(ini, 1)
pvy = tabla(i, 2) - tabla(ini, 2)
//Get dot product (project pv onto normalized direction)
pvdot = dx * pvx + dy * pvy
//Scale line direction vector
dsx = pvdot * dx
dsy = pvdot * dy
//Subtract this from pv
ax = pvx - dsx
ay = pvy - dsy
return (ax^2 + ay^2)^0.5
end sub
sub DouglasPeucker(PointList(), ini, fin, epsilon)
local dmax, index, i, d
// Find the point with the maximum distance
for i = ini + 1 to fin
d = perpendicularDistance(PointList(), i, ini, fin)
if d > dmax index = i : dmax = d
next
// If max distance is greater than epsilon, recursively simplify
if dmax > epsilon then
PointList(index, 3) = true
// Recursive call
DouglasPeucker(PointList(), ini, index, epsilon)
DouglasPeucker(PointList(), index, fin, epsilon)
end if
end sub
data 0,0, 1,0.1, 2,-0.1, 3,5, 4,6, 5,7, 6,8.1, 7,9, 8,9, 9,9
dim matriz(10, 3)
for i = 1 to 10
read matriz(i, 1), matriz(i, 2)
next
DouglasPeucker(matriz(), 1, 10, 1)
matriz(1, 3) = true : matriz(10, 3) = true
for i = 1 to 10
if matriz(i, 3) print matriz(i, 1), matriz(i, 2)
next
|
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
|
Ramer-Douglas-Peucker line simplification
|
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–Peucker algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: 1.0.
Display the remaining points here.
Reference
the Wikipedia article: Ramer-Douglas-Peucker algorithm.
|
#zkl
|
zkl
|
fcn perpendicularDistance(start,end, point){ // all are tuples: (x,y) -->|d|
dx,dy := end .zipWith('-,start); // deltas
dpx,dpy := point.zipWith('-,start);
mag := (dx*dx + dy*dy).sqrt();
if(mag>0.0){ dx/=mag; dy/=mag; }
p,dsx,dsy := dx*dpx + dy*dpy, p*dx, p*dy;
((dpx - dsx).pow(2) + (dpy - dsy).pow(2)).sqrt()
}
fcn RamerDouglasPeucker(points,epsilon=1.0){ // list of tuples --> same
if(points.len()==2) return(points); // but we'll do one point
d:=points.pump(List, // first result/element is always zero
fcn(p, s,e){ perpendicularDistance(s,e,p) }.fp1(points[0],points[-1]));
index,dmax := (0.0).minMaxNs(d)[1], d[index]; // minMaxNs-->index of min & max
if(dmax>epsilon){
return(RamerDouglasPeucker(points[0,index],epsilon)[0,-1].extend(
RamerDouglasPeucker(points[index,*],epsilon)))
} else return(points[0],points[-1]);
}
|
http://rosettacode.org/wiki/Range_extraction
|
Range extraction
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
|
#Elixir
|
Elixir
|
defmodule RC do
def range_extract(list) do
max = Enum.max(list) + 2
sorted = Enum.sort([max|list])
candidate_number = hd(sorted)
current_number = hd(sorted)
extract(tl(sorted), candidate_number, current_number, [])
end
defp extract([], _, _, range), do: Enum.reverse(range) |> Enum.join(",")
defp extract([next|rest], candidate, current, range) when current+1 >= next do
extract(rest, candidate, next, range)
end
defp extract([next|rest], candidate, current, range) when candidate == current do
extract(rest, next, next, [to_string(current)|range])
end
defp extract([next|rest], candidate, current, range) do
separator = if candidate+1 == current, do: ",", else: "-"
str = "#{candidate}#{separator}#{current}"
extract(rest, next, next, [str|range])
end
end
list = [
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
]
IO.inspect RC.range_extract(list)
|
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
|
#HicEst
|
HicEst
|
REAL :: n=1000, m=1, s=0.5, array(n)
pi = 4 * ATAN(1)
array = s * (-2*LOG(RAN(1)))^0.5 * COS(2*pi*RAN(1)) + m
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
local L
L := list(1000)
every L[1 to 1000] := 1.0 + 0.5 * sqrt(-2.0 * log(?0)) * cos(2.0 * &pi * ?0)
every write(!L)
end
|
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.
|
#Run_BASIC
|
Run BASIC
|
rmd(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.
|
#Rust
|
Rust
|
import scala.util.Random
/**
* Histogram of 200 throws with two dices.
*/
object Throws extends App {
Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2)
.take(200).groupBy(identity).toList.sortBy(_._1)
.foreach {
case (a, b) => println(f"$a%2d:" + "X" * b.size)
}
}
|
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.
|
#Scala
|
Scala
|
import scala.util.Random
/**
* Histogram of 200 throws with two dices.
*/
object Throws extends App {
Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2)
.take(200).groupBy(identity).toList.sortBy(_._1)
.foreach {
case (a, b) => println(f"$a%2d:" + "X" * b.size)
}
}
|
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
|
#Julia
|
Julia
|
function readconf(file)
vars = Dict()
for line in eachline(file)
line = strip(line)
if !isempty(line) && !startswith(line, '#') && !startswith(line, ';')
fspace = searchindex(line, " ")
if fspace == 0
vars[Symbol(lowercase(line))] = true
else
vname, line = Symbol(lowercase(line[1:fspace-1])), line[fspace+1:end]
value = ',' ∈ line ? strip.(split(line, ',')) : line
vars[vname] = value
end
end
end
for (vname, value) in vars
eval(:($vname = $value))
end
return vars
end
readconf("test.conf")
@show fullname favouritefruit needspeeling otherfamily
|
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
|
#Go
|
Go
|
package main
import (
"fmt"
"strconv"
"strings"
)
const input = "-6,-3--1,3-5,7-11,14,15,17-20"
func main() {
fmt.Println("range:", input)
var r []int
var last int
for _, part := range strings.Split(input, ",") {
if i := strings.Index(part[1:], "-"); i == -1 {
n, err := strconv.Atoi(part)
if err != nil {
fmt.Println(err)
return
}
if len(r) > 0 {
if last == n {
fmt.Println("duplicate value:", n)
return
} else if last > n {
fmt.Println("values not ordered:", last, ">", n)
return
}
}
r = append(r, n)
last = n
} else {
n1, err := strconv.Atoi(part[:i+1])
if err != nil {
fmt.Println(err)
return
}
n2, err := strconv.Atoi(part[i+2:])
if err != nil {
fmt.Println(err)
return
}
if n2 < n1+2 {
fmt.Println("invalid range:", part)
return
}
if len(r) > 0 {
if last == n1 {
fmt.Println("duplicate value:", n1)
return
} else if last > n1 {
fmt.Println("values not ordered:", last, ">", n1)
return
}
}
for i = n1; i <= n2; i++ {
r = append(r, i)
}
last = n2
}
}
fmt.Println("expanded:", r)
}
|
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.
|
#GAP
|
GAP
|
ReadByLines := function(name)
local file, line, count;
file := InputTextFile(name);
count := 0;
while true do
line := ReadLine(file);
if line = fail then
break;
fi;
count := count + 1;
od;
CloseStream(file);
return count;
end;
# With [http://www.ibiblio.org/pub/docs/misc/amnesty.txt amnesty.txt]
ReadByLines("amnesty.txt");
# 384
|
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.
|
#Genie
|
Genie
|
[indent=4]
/*
Read file line by line, in Genie
valac readFileLines.gs
./readFileLines [filename]
*/
init
fileName:string
fileName = (args[1] is null) ? "readFileLines.gs" : args[1]
var file = FileStream.open(fileName, "r")
if file is null
stdout.printf("Error: %s did not open\n", fileName)
return
lines:int = 0
line:string? = file.read_line()
while line is not null
lines++
stdout.printf("%04d %s\n", lines, line)
line = file.read_line()
|
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.
|
#Tcl
|
Tcl
|
proc rank {rankingMethod sortedList} {
# Extract the groups in the data (this is pointless for ordinal...)
set s [set group [set groups {}]]
foreach {score who} $sortedList {
if {$score != $s} {
lappend groups [llength $group]
set s $score
set group {}
}
lappend group $who
}
lappend groups [llength $group]
# Construct the rankings; note that we have a zero-sized leading group
set n 1; set m 0
foreach g $groups {
switch $rankingMethod {
standard {
lappend result {*}[lrepeat $g $n]
incr n $g
}
modified {
lappend result {*}[lrepeat $g [incr m $g]]
}
dense {
lappend result {*}[lrepeat $g $m]
incr m
}
ordinal {
for {set i 0} {$i < $g} {incr i} {
lappend result [incr m]
}
}
fractional {
set val [expr {($n + [incr n $g] - 1) / 2.0}]
lappend result {*}[lrepeat $g [format %g $val]]
}
}
}
return $result
}
set data {
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
}
foreach method {standard modified dense ordinal fractional} {
puts "Using method '$method'...\n Rank\tScore\tWho"
foreach rank [rank $method $data] {score who} $data {
puts " $rank\t$score\t$who"
}
}
|
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
|
#PL.2FI
|
PL/I
|
s = reverse(s);
|
http://rosettacode.org/wiki/Random_Latin_squares
|
Random Latin squares
|
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
A randomised Latin square generates random configurations of the symbols for any given n.
Example n=4 randomised Latin square
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
Task
Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
Use the function to generate and show here, two randomly generated squares of size 5.
Note
Strict Uniformity in the random generation is a hard problem and not a requirement of the task.
Reference
Wikipedia: Latin square
OEIS: A002860
|
#zkl
|
zkl
|
fcn randomLatinSquare(n,symbols=[1..]){ //--> list of lists
if(n<=0) return(T);
square,syms := List(), symbols.walker().walk(n);
do(n){ syms=syms.copy(); square.append(syms.append(syms.pop(0))) }
// shuffle rows, transpose & shuffle columns
T.zip(square.shuffle().xplode()).shuffle();
}
fcn rls2String(square){ square.apply("concat"," ").concat("\n") }
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#Wren
|
Wren
|
import "/fmt" for Fmt
class RayCasting {
static intersects(a, b, p) {
if (a[1] > b[1]) return intersects(b, a, p)
if (p[1] == a[1] || p[1] == b[1]) p[1] = p[1] + 0.0001
if (p[1] > b[1] || p[1] < a[1] || p[0] >= a[0].max(b[0])) return false
if (p[0] < a[0].min(b[0])) return true
var red = (p[1] - a[1]) / (p[0] - a[0])
var blue = (b[1] - a[1]) / (b[0] - a[0])
return red >= blue
}
static contains(shape, pnt) {
var inside = false
var len = shape.count
for (i in 0...len) {
if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside
}
return inside
}
static square { [[0, 0], [20, 0], [20, 20], [0, 20]] }
static squareHole { [[0, 0], [20, 0], [20, 20], [0, 20], [5, 5], [15, 5], [15, 15], [5, 15]] }
static strange { [[0, 0], [5, 5], [0, 20], [5, 15], [15, 15], [20, 20], [20, 0]] }
static hexagon { [[6, 0], [14, 0], [20, 10], [14, 20], [6, 20], [0, 10]] }
static shapes { [square, squareHole, strange, hexagon] }
}
var testPoints = [[10, 10], [10, 16], [-20, 10], [0, 10], [20, 10], [16, 10], [20, 20]]
for (shape in RayCasting.shapes) {
for (pnt in testPoints) Fmt.write("$7s ", RayCasting.contains(shape, pnt))
System.print()
}
|
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
|
#BBC_BASIC
|
BBC BASIC
|
FIFOSIZE = 1000
FOR n = 3 TO 5
PRINT "Push ";n : PROCenqueue(n)
NEXT
PRINT "Pop " ; FNdequeue
PRINT "Push 6" : PROCenqueue(6)
REPEAT
PRINT "Pop " ; FNdequeue
UNTIL FNisempty
PRINT "Pop " ; FNdequeue
END
DEF PROCenqueue(n) : LOCAL f%
DEF FNdequeue : LOCAL f% : f% = 1
DEF FNisempty : LOCAL f% : f% = 2
PRIVATE fifo(), rptr%, wptr%
DIM fifo(FIFOSIZE-1)
CASE f% OF
WHEN 0:
wptr% = (wptr% + 1) MOD FIFOSIZE
IF rptr% = wptr% ERROR 100, "Error: queue overflowed"
fifo(wptr%) = n
WHEN 1:
IF rptr% = wptr% ERROR 101, "Error: queue empty"
rptr% = (rptr% + 1) MOD FIFOSIZE
= fifo(rptr%)
WHEN 2:
= (rptr% = wptr%)
ENDCASE
ENDPROC
|
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.
|
#C.2B.2B
|
C++
|
#include <iostream>
using namespace std;
template<class T = double>
class Quaternion
{
public:
T w, x, y, z;
// Numerical constructor
Quaternion(const T &w, const T &x, const T &y, const T &z): w(w), x(x), y(y), z(z) {};
Quaternion(const T &x, const T &y, const T &z): w(T()), x(x), y(y), z(z) {}; // For 3-rotations
Quaternion(const T &r): w(r), x(T()), y(T()), z(T()) {};
Quaternion(): w(T()), x(T()), y(T()), z(T()) {};
// Copy constructor and assignment
Quaternion(const Quaternion &q): w(q.w), x(q.x), y(q.y), z(q.z) {};
Quaternion& operator=(const Quaternion &q) { w=q.w; x=q.x; y=q.y; z=q.z; return *this; }
// Unary operators
Quaternion operator-() const { return Quaternion(-w, -x, -y, -z); }
Quaternion operator~() const { return Quaternion(w, -x, -y, -z); } // Conjugate
// Norm-squared. SQRT would have to be made generic to be used here
T normSquared() const { return w*w + x*x + y*y + z*z; }
// In-place operators
Quaternion& operator+=(const T &r)
{ w += r; return *this; }
Quaternion& operator+=(const Quaternion &q)
{ w += q.w; x += q.x; y += q.y; z += q.z; return *this; }
Quaternion& operator-=(const T &r)
{ w -= r; return *this; }
Quaternion& operator-=(const Quaternion &q)
{ w -= q.w; x -= q.x; y -= q.y; z -= q.z; return *this; }
Quaternion& operator*=(const T &r)
{ w *= r; x *= r; y *= r; z *= r; return *this; }
Quaternion& operator*=(const Quaternion &q)
{
T oldW(w), oldX(x), oldY(y), oldZ(z);
w = oldW*q.w - oldX*q.x - oldY*q.y - oldZ*q.z;
x = oldW*q.x + oldX*q.w + oldY*q.z - oldZ*q.y;
y = oldW*q.y + oldY*q.w + oldZ*q.x - oldX*q.z;
z = oldW*q.z + oldZ*q.w + oldX*q.y - oldY*q.x;
return *this;
}
Quaternion& operator/=(const T &r)
{ w /= r; x /= r; y /= r; z /= r; return *this; }
Quaternion& operator/=(const Quaternion &q)
{
T oldW(w), oldX(x), oldY(y), oldZ(z), n(q.normSquared());
w = (oldW*q.w + oldX*q.x + oldY*q.y + oldZ*q.z) / n;
x = (oldX*q.w - oldW*q.x + oldY*q.z - oldZ*q.y) / n;
y = (oldY*q.w - oldW*q.y + oldZ*q.x - oldX*q.z) / n;
z = (oldZ*q.w - oldW*q.z + oldX*q.y - oldY*q.x) / n;
return *this;
}
// Binary operators based on in-place operators
Quaternion operator+(const T &r) const { return Quaternion(*this) += r; }
Quaternion operator+(const Quaternion &q) const { return Quaternion(*this) += q; }
Quaternion operator-(const T &r) const { return Quaternion(*this) -= r; }
Quaternion operator-(const Quaternion &q) const { return Quaternion(*this) -= q; }
Quaternion operator*(const T &r) const { return Quaternion(*this) *= r; }
Quaternion operator*(const Quaternion &q) const { return Quaternion(*this) *= q; }
Quaternion operator/(const T &r) const { return Quaternion(*this) /= r; }
Quaternion operator/(const Quaternion &q) const { return Quaternion(*this) /= q; }
// Comparison operators, as much as they make sense
bool operator==(const Quaternion &q) const
{ return (w == q.w) && (x == q.x) && (y == q.y) && (z == q.z); }
bool operator!=(const Quaternion &q) const { return !operator==(q); }
// The operators above allow quaternion op real. These allow real op quaternion.
// Uses the above where appropriate.
template<class T> friend Quaternion<T> operator+(const T &r, const Quaternion<T> &q);
template<class T> friend Quaternion<T> operator-(const T &r, const Quaternion<T> &q);
template<class T> friend Quaternion<T> operator*(const T &r, const Quaternion<T> &q);
template<class T> friend Quaternion<T> operator/(const T &r, const Quaternion<T> &q);
// Allows cout << q
template<class T> friend ostream& operator<<(ostream &io, const Quaternion<T> &q);
};
// Friend functions need to be outside the actual class definition
template<class T>
Quaternion<T> operator+(const T &r, const Quaternion<T> &q)
{ return q+r; }
template<class T>
Quaternion<T> operator-(const T &r, const Quaternion<T> &q)
{ return Quaternion<T>(r-q.w, q.x, q.y, q.z); }
template<class T>
Quaternion<T> operator*(const T &r, const Quaternion<T> &q)
{ return q*r; }
template<class T>
Quaternion<T> operator/(const T &r, const Quaternion<T> &q)
{
T n(q.normSquared());
return Quaternion(r*q.w/n, -r*q.x/n, -r*q.y/n, -r*q.z/n);
}
template<class T>
ostream& operator<<(ostream &io, const Quaternion<T> &q)
{
io << q.w;
(q.x < T()) ? (io << " - " << (-q.x) << "i") : (io << " + " << q.x << "i");
(q.y < T()) ? (io << " - " << (-q.y) << "j") : (io << " + " << q.y << "j");
(q.z < T()) ? (io << " - " << (-q.z) << "k") : (io << " + " << q.z << "k");
return io;
}
|
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.
|
#BBC_BASIC
|
BBC BASIC
|
PRINT $(PAGE+22)$(PAGE+21):REM PRINT $(PAGE+22)$(PAGE+21):REM
|
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
|
#Factor
|
Factor
|
USING: combinators deques dlists kernel prettyprint ;
IN: rosetta-code.queue-usage
DL{ } clone { ! make new queue
[ [ 1 ] dip push-front ] ! push 1
[ [ 2 ] dip push-front ] ! push 2
[ [ 3 ] dip push-front ] ! push 3
[ . ] ! DL{ 3 2 1 }
[ pop-back drop ] ! pop 1 (and discard)
[ pop-back drop ] ! pop 2 (and discard)
[ pop-back drop ] ! pop 3 (and discard)
[ deque-empty? . ] ! t
} cleave
|
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
|
#Fantom
|
Fantom
|
class Main
{
public static Void main ()
{
q := Queue()
q.push (1)
q.push ("a")
echo ("Is empty? " + q.isEmpty)
echo ("Element: " + q.pop)
echo ("Element: " + q.pop)
echo ("Is empty? " + q.isEmpty)
try { q.pop } catch (Err e) { echo (e.msg) }
}
}
|
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.
|
#Ursa
|
Ursa
|
decl string<> lines
decl file f
f.open "filename.txt"
set lines (f.readlines)
f.close
if (< (size lines) 7)
out "the file has less than seven lines" endl console
stop
end if
out "the seventh line in the file is:" endl endl console
out lines<6> endl console
|
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.
|
#VBScript
|
VBScript
|
Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
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.
|
#F.23
|
F#
|
let rec quickselect k list =
match list with
| [] -> failwith "Cannot take largest element of empty list."
| [a] -> a
| x::xs ->
let (ys, zs) = List.partition (fun arg -> arg < x) xs
let l = List.length ys
if k < l then quickselect k ys
elif k > l then quickselect (k-l-1) zs
else x
//end quickselect
[<EntryPoint>]
let main args =
let v = [9; 8; 7; 6; 5; 0; 1; 2; 3; 4]
printfn "%A" [for i in 0..(List.length v - 1) -> quickselect i v]
0
|
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
|
#Emacs_Lisp
|
Emacs Lisp
|
(require 'gnus-range)
(defun rangext (lst)
(mapconcat (lambda (item)
(if (consp item)
(if (= (+ 1 (car item)) (cdr item))
(format "%d,%d" (car item) (cdr item))
(format "%d-%d" (car item) (cdr item)))
(format "%d" item)))
(gnus-compress-sequence lst)
","))
(rangext '(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))
;; => "0-2,4,6-8,11,12,14-25,27-33,35-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
|
#IDL
|
IDL
|
result = 1.0 + 0.5*randomn(seed,1000)
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#J
|
J
|
urand=: ?@$ 0:
zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand
1 + 0.5 * zrand 100
|
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.
|
#Seed7
|
Seed7
|
say 1.rand # random float in the interval [0,1)
say 100.irand # random integer in the interval [0,100)
|
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.
|
#Sidef
|
Sidef
|
say 1.rand # random float in the interval [0,1)
say 100.irand # random integer in the interval [0,100)
|
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.
|
#Sparkling
|
Sparkling
|
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.
|
#Standard_ML
|
Standard ML
|
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.
|
#Stata
|
Stata
|
rand
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#Kotlin
|
Kotlin
|
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
data class Configuration(val map: Map<String, Any?>) {
val fullName: String by map
val favoriteFruit: String by map
val needsPeeling: Boolean by map
val otherFamily: List<String> by map
}
fun main(args: Array<String>) {
val lines = Files.readAllLines(Paths.get("src/configuration.txt"), StandardCharsets.UTF_8)
val keyValuePairs = lines.map{ it.trim() }
.filterNot { it.isEmpty() }
.filterNot(::commentedOut)
.map(::toKeyValuePair)
val configurationMap = hashMapOf<String, Any>("needsPeeling" to false)
for (pair in keyValuePairs) {
val (key, value) = pair
when (key) {
"FULLNAME" -> configurationMap.put("fullName", value)
"FAVOURITEFRUIT" -> configurationMap.put("favoriteFruit", value)
"NEEDSPEELING" -> configurationMap.put("needsPeeling", true)
"OTHERFAMILY" -> configurationMap.put("otherFamily", value.split(" , ").map { it.trim() })
else -> println("Encountered unexpected key $key=$value")
}
}
println(Configuration(configurationMap))
}
private fun commentedOut(line: String) = line.startsWith("#") || line.startsWith(";")
private fun toKeyValuePair(line: String) = line.split(Regex(" "), 2).let {
Pair(it[0], if (it.size == 1) "" else it[1])
}
|
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
|
#Groovy
|
Groovy
|
def expandRanges = { compressed ->
Eval.me('['+compressed.replaceAll(~/(\d)-/, '$1..')+']').flatten().toString()[1..-2]
}
|
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.
|
#Go
|
Go
|
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func init() {
log.SetFlags(log.Lshortfile)
}
func main() {
// Open an input file, exit on error.
inputFile, err := os.Open("byline.go")
if err != nil {
log.Fatal("Error opening input file:", err)
}
// Closes the file when we leave the scope of the current function,
// this makes sure we never forget to close the file if the
// function can exit in multiple places.
defer inputFile.Close()
scanner := bufio.NewScanner(inputFile)
// scanner.Scan() advances to the next token returning false if an error was encountered
for scanner.Scan() {
fmt.Println(scanner.Text())
}
// When finished scanning if any error other than io.EOF occured
// it will be returned by scanner.Err().
if err := scanner.Err(); err != nil {
log.Fatal(scanner.Err())
}
}
|
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.
|
#True_BASIC
|
True BASIC
|
LET 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 ---"
LET ptosnom(1) = 1
FOR i = 2 to n
NEXT i
CALL MostarTabla
PRINT "--- Modified ranking ---"
LET ptosnom(n) = n
FOR i = n-1 to 1 step -1
IF puntos(i) = puntos(i+1) then LET ptosnom(i) = ptosnom(i+1) else LET ptosnom(i) = i
NEXT i
CALL MostarTabla
PRINT "--- Ordinal ranking ---"
FOR i = 1 to n
LET ptosnom(i) = i
NEXT i
CALL MostarTabla
PRINT "--- Fractional ranking ---"
LET i = 1
LET j = 2
DO
IF j <= n then
IF (puntos(j-1) = puntos(j)) then
LET j = j + 1
END IF
END IF
FOR k = i to j-1
LET ptosnom(k) = (i+j-1) / 2
NEXT k
LET i = j
LET j = j + 1
LOOP UNTIL i > n
CALL MOSTARTABLA
DATA 44, "Solomon", 42, "Jason", 42, "Errol", 41, "Garry", 41, "Bernard", 41, "Barry", 39, "Stephen"
END
|
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.
|
#Visual_FoxPro
|
Visual FoxPro
|
#DEFINE CTAB CHR(9)
#DEFINE CRLF CHR(13) + CHR(10)
LOCAL lcTxt As String, i As Integer
CLOSE DATABASES ALL
SET SAFETY OFF
CLEAR
CREATE CURSOR scores (score I, name V(8), rownum I AUTOINC)
INDEX ON score TAG score COLLATE "Machine"
SET ORDER TO 0
INSERT INTO scores (score, name) VALUES (44, "Solomon")
INSERT INTO scores (score, name) VALUES (42, "Jason")
INSERT INTO scores (score, name) VALUES (42, "Errol")
INSERT INTO scores (score, name) VALUES (41, "Garry")
INSERT INTO scores (score, name) VALUES (41, "Bernard")
INSERT INTO scores (score, name) VALUES (41, "Barry")
INSERT INTO scores (score, name) VALUES (39, "Stephen")
CREATE CURSOR ranks (sc_rank I, mod_rank I, dense I, ordinal I, fractional B(1), score I, name V(8))
INDEX ON score TAG score COLLATE "Machine"
SET ORDER TO 0
APPEND FROM DBF("scores") FIELDS score, name
Std_Comp()
Modified()
Dense()
Ordinal()
Fractional()
COPY TO ranks.txt TYPE DELIMITED WITH TAB
lcTxt = ""
FOR i = 1 TO FCOUNT()
lcTxt = lcTxt + FIELD(i) + CTAB
ENDFOR
lcTxt = LEFT(lcTxt, LEN(lcTxt) - 1) + CRLF + FILETOSTR("ranks.txt")
STRTOFILE(lcTxt, "ranks.txt")
MODIFY FILE ranks.txt
SET SAFETY ON
FUNCTION ScoreGroup(aa)
LOCAL n As Integer
SELECT score, COUNT(*) As num FROM scores ;
GROUP BY score ORDER BY score DESC INTO ARRAY aa
n = _TALLY
RETURN n
ENDFUNC
PROCEDURE Std_Comp
LOCAL n, i, nn
LOCAL ARRAY a[1]
SELECT ranks
BLANK FIELDS sc_rank ALL
nn = ScoreGroup(@a)
n = 1
FOR i = 1 TO nn
REPLACE sc_rank WITH n FOR score = a[i,1]
n = n + a[i,2]
ENDFOR
ENDPROC
PROCEDURE Modified
LOCAL n, i, nn
LOCAL ARRAY a[1]
SELECT ranks
BLANK FIELDS mod_rank ALL
nn = ScoreGroup(@a)
n = 0
FOR i = 1 TO nn
n = n + a[i,2]
REPLACE mod_rank WITH n FOR score = a[i,1]
ENDFOR
ENDPROC
PROCEDURE Dense
LOCAL n, i, nn
LOCAL ARRAY a[1]
SELECT ranks
BLANK FIELDS dense ALL
nn = ScoreGroup(@a)
SELECT ranks
n = 0
FOR i = 1 TO nn
n = n + a[i,2]
REPLACE dense WITH i FOR score = a[i,1]
ENDFOR
ENDPROC
PROCEDURE Ordinal
SELECT ranks
BLANK FIELDS ordinal ALL
REPLACE ordinal WITH RECNO() ALL
ENDPROC
PROCEDURE Fractional
LOCAL i As Integer, nn As Integer
LOCAL ARRAY a[1]
SELECT ranks
BLANK FIELDS fractional ALL
SELECT CAST(AVG(rownum) As B(1)), score FROM scores ;
GROUP BY score ORDER BY score DESC INTO ARRAY a
nn = _TALLY
FOR i = 1 TO nn
REPLACE fractional WITH a[i,1] FOR score = a[i,2]
ENDFOR
ENDPROC
|
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_English
|
Plain English
|
To run:
Start up.
Put "asdf" into a string.
Reverse the string.
Shut down.
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#zkl
|
zkl
|
const E = 0.0001;
fcn rayHitsSeg([(Px,Py)],[(Ax,Ay)],[(Bx,By)]){ // --> Bool
if(Py==Ay or Py==By) Py+=E;
if(Py<Ay or Py>By or Px>Ax.max(Bx)) False
else if(Px<Ax.min(Bx)) True
else try{ ( (Py - Ay)/(Px - Ax) )>=( (By - Ay)/(Bx - Ax) ) } //blue>=red
catch(MathError){ Px==Ax } // divide by zero == ∞, only blue?
}
fcn pointInPoly(point, polygon){ // --> Bool, polygon is ( (a,b),(c,d).. )
polygon.filter('wrap([(ab,cd)]){ a,b:=ab; c,d:=cd;
if(b<=d) rayHitsSeg(point,ab,cd); // left point has smallest y coordinate
else rayHitsSeg(point,cd,ab);
})
.len().isOdd; // True if crossed an odd number of borders ie inside polygon
}
|
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
|
#BQN
|
BQN
|
queue ← {
data ← ⟨⟩
Push ⇐ {data∾˜↩𝕩}
Pop ⇐ {
𝕊𝕩:
0=≠data ? •Show "Cannot pop from empty queue";
(data↓˜↩¯1)⊢⊑⌽data
}
Empty ⇐ {𝕊𝕩: 0=≠data}
Display ⇐ {𝕊𝕩: •Show data}
}
q1 ← queue
•Show q1.Empty@
q1.Push 3
q1.Push 4
q1.Display@
•Show q1.Pop@
q1.Display@
|
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.
|
#CLU
|
CLU
|
quat = cluster is make, minus, norm, conj, add, addr, mul, mulr,
equal, get_a, get_b, get_c, get_d, q_form
rep = struct[a,b,c,d: real]
make = proc (a,b,c,d: real) returns (cvt)
return (rep${a:a, b:b, c:c, d:d})
end make
minus = proc (q: cvt) returns (cvt)
return (down(make(-q.a, -q.b, -q.c, -q.d)))
end minus
norm = proc (q: cvt) returns (real)
return ((q.a**2.0 + q.b**2.0 + q.c**2.0 + q.d**2.0) ** 0.5)
end norm
conj = proc (q: cvt) returns (cvt)
return (down(make(q.a, -q.b, -q.c, q.d)))
end conj
add = proc (q1, q2: cvt) returns (cvt)
return (down(make(q1.a+q2.a, q1.b+q2.b, q1.c+q2.c, q1.d+q2.d)))
end add
addr = proc (q: cvt, r: real) returns (cvt)
return (down(make(q.a+r, q.b+r, q.c+r, q.d+r)))
end addr
mul = proc (q1, q2: cvt) returns (cvt)
a: real := q1.a*q2.a - q1.b*q2.b - q1.c*q2.c - q1.d*q2.d
b: real := q1.a*q2.b + q1.b*q2.a + q1.c*q2.d - q1.d*q2.c
c: real := q1.a*q2.c - q1.b*q2.d + q1.c*q2.a + q1.d*q2.b
d: real := q1.a*q2.d + q1.b*q2.c - q1.c*q2.b + q1.d*q2.a
return (down(make(a,b,c,d)))
end mul
mulr = proc (q: cvt, r: real) returns (cvt)
return (down(make(q.a*r, q.b*r, q.c*r, q.d*r)))
end mulr
equal = proc (q1, q2: cvt) returns (bool)
return (q1.a = q2.a & q1.b = q2.b & q1.c = q2.c & q1.d = q2.d)
end equal
get_a = proc (q: cvt) returns (real) return (q.a) end get_a
get_b = proc (q: cvt) returns (real) return (q.b) end get_b
get_c = proc (q: cvt) returns (real) return (q.c) end get_c
get_d = proc (q: cvt) returns (real) return (q.d) end get_d
q_form = proc (q: cvt, a, b: int) returns (string)
return ( f_form(q.a, a, b) || " + "
|| f_form(q.b, a, b) || "i + "
|| f_form(q.c, a, b) || "j + "
|| f_form(q.d, a, b) || "k" )
end q_form
end quat
start_up = proc ()
po: stream := stream$primary_output()
q0: quat := quat$make(1.0, 2.0, 3.0, 4.0)
q1: quat := quat$make(2.0, 3.0, 4.0, 5.0)
q2: quat := quat$make(3.0, 4.0, 5.0, 6.0)
r: real := 7.0
stream$putl(po, " q0 = " || quat$q_form(q0, 3, 3))
stream$putl(po, " q1 = " || quat$q_form(q1, 3, 3))
stream$putl(po, " q2 = " || quat$q_form(q2, 3, 3))
stream$putl(po, " r = " || f_form(r, 3, 3))
stream$putl(po, "")
stream$putl(po, "norm(q0) = " || f_form(quat$norm(q0), 3, 3))
stream$putl(po, " -q0 = " || quat$q_form(-q0, 3, 3))
stream$putl(po, "conj(q0) = " || quat$q_form(quat$conj(q0), 3, 3))
stream$putl(po, " q0 + r = " || quat$q_form(quat$addr(q0, r), 3, 3))
stream$putl(po, " q1 + q2 = " || quat$q_form(q1 + q2, 3, 3))
stream$putl(po, " q0 * r = " || quat$q_form(quat$mulr(q0, r), 3, 3))
stream$putl(po, " q1 * q2 = " || quat$q_form(q1 * q2, 3, 3))
stream$putl(po, " q2 * q1 = " || quat$q_form(q2 * q1, 3, 3))
if q1*q2 ~= q2*q1 then stream$putl(po, "q1 * q2 ~= q2 * q1") end
end start_up
|
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.
|
#BCPL
|
BCPL
|
get "libhdr"
let start() be
$( let x = table
13,10,32,32,32,32,108,101,116,32,110,32,61,32,48,
13,10,32,32,32,32,119,114,105,116,101,115,40,34,103,
101,116,32,42,34,108,105,98,104,100,114,42,34,42,78,
42,78,108,101,116,32,115,116,97,114,116,40,41,32,98,
101,42,78,36,40,32,32,108,101,116,32,120,32,61,32,
116,97,98,108,101,42,78,32,32,32,32,34,41,13,10,
13,10,32,32,32,32,119,104,105,108,101,32,120,33,110,
32,126,61,32,48,32,100,111,13,10,32,32,32,32,36,
40,32,32,119,114,105,116,101,102,40,34,37,78,44,34,
44,120,33,110,41,13,10,32,32,32,32,32,32,32,32,
110,32,58,61,32,110,32,43,32,49,13,10,32,32,32,
32,32,32,32,32,105,102,32,110,32,114,101,109,32,49,
53,32,61,32,48,32,116,104,101,110,32,119,114,105,116,
101,115,40,34,42,78,32,32,32,32,34,41,13,10,32,
32,32,32,36,41,13,10,32,32,32,32,13,10,32,32,
32,32,119,114,105,116,101,115,40,34,48,42,78,34,41,
13,10,32,32,32,32,13,10,32,32,32,32,110,32,58,
61,32,48,13,10,32,32,32,32,119,104,105,108,101,32,
120,33,110,32,126,61,32,48,32,100,111,13,10,32,32,
32,32,36,40,32,32,119,114,99,104,40,120,33,110,41,
13,10,32,32,32,32,32,32,32,32,110,32,58,61,32,
110,32,43,32,49,13,10,32,32,32,32,36,41,13,10,
36,41,13,10,0
let n = 0
writes("get *"libhdr*"*N*Nlet start() be*N$( let x = table*N ")
while x!n ~= 0 do
$( writef("%N,",x!n)
n := n + 1
if n rem 15 = 0 then writes("*N ")
$)
writes("0*N")
n := 0
while x!n ~= 0 do
$( wrch(x!n)
n := n + 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
|
#Forth
|
Forth
|
: cqueue: ( n -- <text>)
create \ compile time: build the data structure in memory
dup
dup 1- and abort" queue size must be power of 2"
0 , \ write pointer "HEAD"
0 , \ read pointer "TAIL"
0 , \ byte counter
dup 1- , \ mask value used for wrap around
allot ; \ run time: returns the address of this data structure
\ calculate offsets into the queue data structure
: ->head ( q -- adr ) ; \ syntactic sugar
: ->tail ( q -- adr ) cell+ ;
: ->cnt ( q -- adr ) 2 cells + ;
: ->msk ( q -- adr ) 3 cells + ;
: ->data ( q -- adr ) 4 cells + ;
: head++ ( q -- ) \ circular increment head pointer of a queue
dup >r ->head @ 1+ r@ ->msk @ and r> ->head ! ;
: tail++ ( q -- ) \ circular increment tail pointer of a queue
dup >r ->tail @ 1+ r@ ->msk @ and r> ->tail ! ;
: qempty ( q -- flag)
dup ->head off dup ->tail off dup ->cnt off \ reset all fields to "off" (zero)
->cnt @ 0= ; \ per the spec qempty returns a flag
: cnt=msk? ( q -- flag) dup >r ->cnt @ r> ->msk @ = ;
: ?empty ( q -- ) ->cnt @ 0= abort" queue is empty" ;
: ?full ( q -- ) cnt=msk? abort" queue is full" ;
: 1+! ( adr -- ) 1 swap +! ; \ increment contents of adr
: 1-! ( adr -- ) -1 swap +! ; \ decrement contents of adr
: qc@ ( queue -- char ) \ fetch next char in queue
dup >r ?empty \ abort if empty
r@ ->cnt 1-! \ decr. the counter
r@ tail++
r@ ->data r> ->tail @ + c@ ; \ calc. address and fetch the byte
: qc! ( char queue -- )
dup >r ?full \ abort if q full
r@ ->cnt 1+! \ incr. the counter
r@ head++
r@ ->data r> ->head @ + c! ; \ data+head = adr, and store the char
|
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
|
#Fortran
|
Fortran
|
module fifo_nodes
type fifo_node
integer :: datum
! the next part is not variable and must be present
type(fifo_node), pointer :: next
logical :: valid
end type fifo_node
end module fifo_nodes
program FIFOTest
use fifo
implicit none
type(fifo_head) :: thehead
type(fifo_node), dimension(5) :: ex, xe
integer :: i
call new_fifo(thehead)
do i = 1, 5
ex(i)%datum = i
call fifo_enqueue(thehead, ex(i))
end do
i = 1
do
call fifo_dequeue(thehead, xe(i))
print *, xe(i)%datum
i = i + 1
if ( fifo_isempty(thehead) ) exit
end do
end program FIFOTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.