task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Random_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
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
namespace RandomLatinSquares {
using Matrix = List<List<int>>;
// Taken from https://stackoverflow.com/a/1262619
static class Helper {
private static readonly Random rng = new Random();
public static void Shuffle<T>(this IList<T> list) {
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
class Program {
static void PrintSquare(Matrix latin) {
foreach (var row in latin) {
Console.Write('[');
var it = row.GetEnumerator();
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", ");
Console.Write(it.Current);
}
Console.WriteLine(']');
}
Console.WriteLine();
}
static void LatinSquare(int n) {
if (n <= 0) {
Console.WriteLine("[]");
return;
}
var latin = new Matrix();
for (int i = 0; i < n; i++) {
List<int> temp = new List<int>();
for (int j = 0; j < n; j++) {
temp.Add(j);
}
latin.Add(temp);
}
// first row
latin[0].Shuffle();
// middle row(s)
for (int i = 1; i < n - 1; i++) {
bool shuffled = false;
while (!shuffled) {
latin[i].Shuffle();
for (int k = 0; k < i; k++) {
for (int j = 0; j < n; j++) {
if (latin[k][j] == latin[i][j]) {
goto shuffling;
}
}
}
shuffled = true;
shuffling: { }
}
}
// last row
for (int j = 0; j < n; j++) {
List<bool> used = new List<bool>();
for (int i = 0; i < n; i++) {
used.Add(false);
}
for (int i = 0; i < n-1; i++) {
used[latin[i][j]] = true;
}
for (int k = 0; k < n; k++) {
if (!used[k]) {
latin[n - 1][j] = k;
break;
}
}
}
PrintSquare(latin);
}
static void Main() {
LatinSquare(5);
LatinSquare(5);
LatinSquare(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 ε.)
|
#OCaml
|
OCaml
|
type point = { x:float; y:float }
type polygon = {
vertices: point array;
edges: (int * int) list;
}
let p x y = { x=x; y=y }
let square_v = [|
(p 0. 0.); (p 10. 0.); (p 10. 10.); (p 0. 10.);
(p 2.5 2.5); (p 7.5 0.1); (p 7.5 7.5); (p 2.5 7.5)
|]
let esa_v = [|
(p 3. 0.); (p 7. 0.); (p 10. 5.); (p 7. 10.); (p 3. 10.); (p 0. 5.)
|]
let esa = {
vertices = esa_v;
edges = [ (0,1); (1,2); (2,3); (3,4); (4,5); (5,0) ]
}
let square = {
vertices = square_v;
edges = [ (0,1); (1,2); (2,3); (3,0) ]
}
let squarehole = {
vertices = square_v;
edges = [ (0,1); (1,2); (2,3); (3,0); (4,5); (5,6); (6,7); (7,4) ]
}
let strange = {
vertices = square_v;
edges = [ (0,4); (4,3); (3,7); (7,6); (6,2); (2,1); (1,5); (5,0) ]
}
let min_y ~a ~b = if a.y > b.y then (b) else (a)
let coeff_ang ~pa ~pb = (pb.y -. pa.y) /. (pb.x -. pa.x)
let huge_val = infinity
let hseg_intersect_seg ~s ~a ~b =
let _eps =
if s.y = (max a.y b.y) ||
s.y = (min a.y b.y) then 0.00001 else 0.0
in
if (s.y +. _eps) > (max a.y b.y) ||
(s.y +. _eps) < (min a.y b.y) ||
s.x > (max a.x b.x) then (false)
else if s.x <= (min a.x b.x) then (true)
else
let ca = if a.x <> b.x then (coeff_ang a b) else (huge_val) in
let my = min_y ~a ~b in
let cp = if (s.x -. my.x) <> 0.0 then (coeff_ang my s) else (huge_val) in
(cp >= ca)
;;
let point_is_inside ~poly ~pt =
let cross = ref 0 in
List.iter (fun (a,b) ->
if hseg_intersect_seg pt
poly.vertices.(a)
poly.vertices.(b)
then incr cross
) poly.edges;
( (!cross mod 2) <> 0)
;;
let make_test p label s =
Printf.printf "point (%.5f,%.5f) is " p.x p.y;
print_string (if point_is_inside s p
then "INSIDE "
else "OUTSIDE ");
print_endline label;
;;
let () =
let test_points = [
(p 5. 5.); (p 5. 8.); (p 2. 2.); (p 0. 0.);
(p 10. 10.); (p 2.5 2.5); (p 0.01 5.);
(p 2.2 7.4); (p 0. 5.); (p 10. 5.); (p (-4.) 10.) ] in
List.iter (fun p ->
make_test p "square" square;
make_test p "squarehole" squarehole;
make_test p "strange" strange;
make_test p "esa" esa;
print_newline()
) test_points;
;;
|
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
|
#11l
|
11l
|
Deque[String] my_queue
my_queue.append(‘foo’)
my_queue.append(‘bar’)
my_queue.append(‘baz’)
print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())
|
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.
|
#Phixmonti
|
Phixmonti
|
include ..\Utilitys.pmt
argument 1 get "r" fopen var f drop
0
7 for
f fgets number? if f fclose exitfor else nip nip endif
endfor
print /# show -1 if past eof #/
|
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.
|
#PHP
|
PHP
|
<?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#J
|
J
|
NB. no trailing linefeed
A=: '1 2 3'
NB. removing linefeed
A=: 0 : 0-.LF
1 2 3
)
NB. removing linefeed
A=: {{)n
1 2 3
}}-.LF
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#jq
|
jq
|
def data:
"A string", 1, {"a":0}, [1,2,[3]]
;
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Julia
|
Julia
|
julia> str = "Hello, world.\n"
"Hello, world.\n"
julia> """Contains "quote" characters and
a newline"""
"Contains \"quote\" characters and \na newline"
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Lua
|
Lua
|
s1 = "This is a double-quoted 'string' with embedded single-quotes."
s2 = 'This is a single-quoted "string" with embedded double-quotes.'
s3 = "this is a double-quoted \"string\" with escaped double-quotes."
s4 = 'this is a single-quoted \'string\' with escaped single-quotes.'
s5 = [[This is a long-bracket "'string'" with embedded single- and double-quotes.]]
s6 = [=[This is a level 1 long-bracket ]]string[[ with [[embedded]] long-brackets.]=]
s7 = [==[This is a level 2 long-bracket ]=]string[=[ with [=[embedded]=] level 1 long-brackets, etc.]==]
s8 = [[This is
a long-bracket string
with embedded
line feeds]]
s9 = "any \0 form \1 of \2 string \3 may \4 contain \5 raw \6 binary \7 data \xDB"
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(s6)
print(s7)
print(s8)
print(s9) -- with audible "bell" from \7 if supported by os
print("some raw binary:", #s9, s9:byte(5), s9:byte(12), s9:byte(17))
|
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.
|
#Action.21
|
Action!
|
PROC Swap(BYTE ARRAY tab INT i,j)
BYTE tmp
tmp=tab(i) tab(i)=tab(j) tab(j)=tmp
RETURN
BYTE FUNC QuickSelect(BYTE ARRAY tab INT count,index)
INT px,i,j,k
BYTE pv
DO
px=count/2
pv=tab(px)
Swap(tab,px,count-1)
i=0
FOR j=0 TO count-2
DO
IF tab(j)<pv THEN
Swap(tab,i,j)
i==+1
FI
OD
IF i=index THEN
RETURN (pv)
ELSEIF i>index THEN
;left part of tab from 0 to i-1
count=i
ELSE
Swap(tab,i,count-1)
;right part of tab from i+1 to count-1
tab==+(i+1)
count==-(i+1)
index==-(i+1)
FI
OD
RETURN (0)
PROC Main()
DEFINE COUNT="10"
BYTE ARRAY data=[9 8 7 6 5 0 1 2 3 4],tab(COUNT)
BYTE i,res
FOR i=0 TO COUNT-1
DO
MoveBlock(tab,data,COUNT)
res=QuickSelect(tab,COUNT,i)
PrintB(res) Put(32)
OD
RETURN
|
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.
|
#Ada
|
Ada
|
----------------------------------------------------------------------
with Ada.Numerics.Float_Random;
with Ada.Text_IO;
procedure quickselect_task
is
use Ada.Numerics.Float_Random;
use Ada.Text_IO;
gen : Generator;
----------------------------------------------------------------------
--
-- procedure partition
--
-- Partitioning a subarray into two halves: one with elements less
-- than or equal to a pivot, the other with elements greater than or
-- equal to a pivot.
--
generic
type T is private;
type T_Array is array (Natural range <>) of T;
procedure partition
(less_than : access function
(x, y : T)
return Boolean;
pivot : in T;
i_first, i_last : in Natural;
arr : in out T_Array;
i_pivot : out Natural);
procedure partition
(less_than : access function
(x, y : T)
return Boolean;
pivot : in T;
i_first, i_last : in Natural;
arr : in out T_Array;
i_pivot : out Natural)
is
i, j : Integer;
temp : T;
begin
i := Integer (i_first) - 1;
j := i_last + 1;
while i /= j loop
-- Move i so everything to the left of i is less than or equal
-- to the pivot.
i := i + 1;
while i /= j and then not less_than (pivot, arr (i)) loop
i := i + 1;
end loop;
-- Move j so everything to the right of j is greater than or
-- equal to the pivot.
if i /= j then
j := j - 1;
while i /= j and then not less_than (arr (j), pivot) loop
j := j - 1;
end loop;
end if;
-- Swap entries.
temp := arr (i);
arr (i) := arr (j);
arr (j) := temp;
end loop;
i_pivot := i;
end partition;
----------------------------------------------------------------------
--
-- procedure quickselect
--
-- Quickselect with a random pivot. Returns the (k+1)st element of a
-- subarray, according to the given order predicate. Also rearranges
-- the subarray so that anything "less than" the (k+1)st element is to
-- the left of it, and anything "greater than" it is to its right.
--
-- I use a random pivot to get O(n) worst case *expected* running
-- time. Code using a random pivot is easy to write and read, and for
-- most purposes comes close enough to a criterion set by Scheme's
-- SRFI-132: "Runs in O(n) time." (See
-- https://srfi.schemers.org/srfi-132/srfi-132.html)
--
-- Of course we are not bound here by SRFI-132, but still I respect
-- it as a guide.
--
-- A "median of medians" pivot gives O(n) running time, but
-- quickselect with such a pivot is a complicated algorithm requiring
-- many comparisons of array elements. A random number generator, by
-- contrast, requires no comparisons of array elements.
--
generic
type T is private;
type T_Array is array (Natural range <>) of T;
procedure quickselect
(less_than : access function
(x, y : T)
return Boolean;
i_first, i_last : in Natural;
k : in Natural;
arr : in out T_Array;
the_element : out T;
the_elements_index : out Natural);
procedure quickselect
(less_than : access function
(x, y : T)
return Boolean;
i_first, i_last : in Natural;
k : in Natural;
arr : in out T_Array;
the_element : out T;
the_elements_index : out Natural)
is
procedure T_partition is new partition (T, T_Array);
procedure qselect
(less_than : access function
(x, y : T)
return Boolean;
i_first, i_last : in Natural;
k : in Natural;
arr : in out T_Array;
the_element : out T;
the_elements_index : out Natural)
is
i, j : Natural;
i_pivot : Natural;
i_final : Natural;
pivot : T;
begin
i := i_first;
j := i_last;
while i /= j loop
i_pivot :=
i + Natural (Float'Floor (Random (gen) * Float (j - i + 1)));
i_pivot := Natural'Min (j, i_pivot);
pivot := arr (i_pivot);
-- Move the last element to where the pivot had been. Perhaps
-- the pivot was already the last element, of course. In any
-- case, we shall partition only from i to j - 1.
arr (i_pivot) := arr (j);
-- Partition the array in the range i .. j - 1, leaving out
-- the last element (which now can be considered garbage).
T_partition (less_than, pivot, i, j - 1, arr, i_final);
-- Now everything that is less than the pivot is to the left
-- of I_final.
-- Put the pivot at i_final, moving the element that had been
-- there to the end. If i_final = j, then this element is
-- actually garbage and will be overwritten with the pivot,
-- which turns out to be the greatest element. Otherwise, the
-- moved element is not less than the pivot and so the
-- partitioning is preserved.
arr (j) := arr (i_final);
arr (i_final) := pivot;
-- Compare i_final and k, to see what to do next.
if i_final < k then
i := i_final + 1;
elsif k < i_final then
j := i_final - 1;
else
-- Exit the loop.
i := i_final;
j := i_final;
end if;
end loop;
the_element := arr (i);
the_elements_index := i;
end qselect;
begin
-- Adjust k for the subarray's position.
qselect
(less_than, i_first, i_last, k + i_first, arr, the_element,
the_elements_index);
end quickselect;
----------------------------------------------------------------------
type Integer_Array is array (Natural range <>) of Integer;
procedure integer_quickselect is new quickselect
(Integer, Integer_Array);
procedure print_kth
(less_than : access function
(x, y : Integer)
return Boolean;
k : in Positive;
i_first, i_last : in Integer;
arr : in out Integer_Array)
is
copy_of_arr : Integer_Array (0 .. i_last);
the_element : Integer;
the_elements_index : Natural;
begin
for j in 0 .. i_last loop
copy_of_arr (j) := arr (j);
end loop;
integer_quickselect
(less_than, i_first, i_last, k - 1, copy_of_arr, the_element,
the_elements_index);
Put (Integer'Image (the_element));
end print_kth;
----------------------------------------------------------------------
example_numbers : Integer_Array := (9, 8, 7, 6, 5, 0, 1, 2, 3, 4);
function lt
(x, y : Integer)
return Boolean
is
begin
return (x < y);
end lt;
function gt
(x, y : Integer)
return Boolean
is
begin
return (x > y);
end gt;
begin
Put ("With < as order predicate: ");
for k in 1 .. 10 loop
print_kth (lt'Access, k, 0, 9, example_numbers);
end loop;
Put_Line ("");
Put ("With > as order predicate: ");
for k in 1 .. 10 loop
print_kth (gt'Access, k, 0, 9, example_numbers);
end loop;
Put_Line ("");
end quickselect_task;
----------------------------------------------------------------------
|
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.
|
#FreeBASIC
|
FreeBASIC
|
Function DistanciaPerpendicular(tabla() As Double, i As Integer, ini As Integer, fin As Integer) As Double
Dim As Double dx, dy, mag, pvx, pvy, pvdot, dsx, dsy, ax, ay
dx = tabla(fin, 1) - tabla(ini, 1)
dy = tabla(fin, 2) - tabla(ini, 2)
'Normaliza
mag = (dx^2 + dy^2)^0.5
If mag > 0 Then dx /= mag : dy /= mag
pvx = tabla(i, 1) - tabla(ini, 1)
pvy = tabla(i, 2) - tabla(ini, 2)
'Producto escalado (proyecto pv en dirección normalizada)
pvdot = dx * pvx + dy * pvy
'Vector de dirección de línea de escala
dsx = pvdot * dx
dsy = pvdot * dy
'Reste esto de pv
ax = pvx - dsx
ay = pvy - dsy
Return (ax^2 + ay^2)^0.5
End Function
Sub DRDP(ListaDePuntos() As Double, ini As Integer, fin As Integer, epsilon As Double)
Dim As Double dmax, d
Dim As Integer indice, i
' Encuentra el punto con la distancia máxima
If Ubound(ListaDePuntos) < 2 Then Print "No hay suficientes puntos para simplificar " : Sleep : End
For i = ini + 1 To fin
d = DistanciaPerpendicular(ListaDePuntos(), i, ini, fin)
If d > dmax Then indice = i : dmax = d
Next
' Si la distancia máxima es mayor que épsilon, simplifique de forma recursiva
If dmax > epsilon Then
ListaDePuntos(indice, 3) = True
DRDP(ListaDePuntos(), ini, indice, epsilon)
DRDP(ListaDePuntos(), indice, fin, epsilon)
End If
End Sub
Dim As Double matriz(1 To 10, 1 To 3)
Data 0, 0, 1, 0.1, 2, -0.1, 3, 5, 4, 6, 5, 7, 6, 8.1, 7, 9, 8, 9, 9, 9
For i As Integer = Lbound(matriz) To Ubound(matriz)
Read matriz(i, 1), matriz(i, 2)
Next i
DRDP(matriz(), 1, 10, 1)
Print "Puntos restantes tras de simplificar:"
matriz(1, 3) = True : matriz(10, 3) = True
For i As Integer = Lbound(matriz) To Ubound(matriz)
If matriz(i, 3) Then Print "(";matriz(i, 1);", "; matriz(i, 2);") ";
Next i
Sleep
|
http://rosettacode.org/wiki/Ramanujan%27s_constant
|
Ramanujan's constant
|
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
|
#Julia
|
Julia
|
julia> a = BigFloat(MathConstants.e^(BigFloat(pi)))^(BigFloat(163.0)^0.5)
2.625374126407687439999999999992500725971981856888793538563373369908627075373427e+17
julia> 262537412640768744 - a
7.499274028018143111206461436626630091372924626572825942241598957614307213309258e-13
|
http://rosettacode.org/wiki/Ramanujan%27s_constant
|
Ramanujan's constant
|
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
First[RealDigits[N[Exp[Pi Sqrt[163]], 200]]]
Table[
c = N[Exp[Pi Sqrt[h]], 40];
Log10[1 - FractionalPart[c]]
,
{h, {19, 43, 67, 163}}
]
|
http://rosettacode.org/wiki/Ramanujan%27s_constant
|
Ramanujan's constant
|
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
|
#Nim
|
Nim
|
import strformat, strutils
import decimal
setPrec(75)
let pi = newDecimal("3.1415926535897932384626433832795028841971693993751058209749445923078164")
proc eval(n: int): DecimalType =
result = exp(pi * sqrt(newDecimal(n)))
func format(n: DecimalType; d: Positive): string =
## Return the representation of "n" with "d" digits of precision.
let parts = ($n).split('.')
result = parts[0] & '.' & parts[1][0..<d]
echo "Ramanujan’s constant with 50 digits of precision:"
echo eval(163).format(50)
setPrec(50)
echo()
echo "Heegner numbers yielding 'almost' integers:"
for n in [19, 43, 67, 163]:
let x = eval(n)
let k = x.roundToInt
let d = x - k
let s = if d > 0: "+ " & $d else: "- " & $(-d)
echo &"{n:3}: {x}... = {k:>18} {s}..."
|
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
|
#BBC_BASIC
|
BBC BASIC
|
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 FNrangeextract(range$)
END
DEF FNrangeextract(r$)
LOCAL f%, i%, r%, t%, t$
f% = VAL(r$)
REPEAT
i% = INSTR(r$, ",", i%+1)
t% = VALMID$(r$, i%+1)
IF t% = f% + r% + 1 THEN
r% += 1
ELSE
CASE r% OF
WHEN 0: t$ += STR$(f%) + ","
WHEN 1: t$ += STR$(f%) + "," + STR$(f% + r%) + ","
OTHERWISE: t$ += STR$(f%) + "-" + STR$(f% + r%) + ","
ENDCASE
r% = 0
f% = t%
ENDIF
UNTIL i% = 0
= LEFT$(t$)
|
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
|
#D
|
D
|
import std.stdio, std.random, std.math;
struct NormalRandom {
double mean, stdDev;
// Necessary because it also defines an opCall.
this(in double mean_, in double stdDev_) pure nothrow {
this.mean = mean_;
this.stdDev = stdDev_;
}
double opCall() const /*nothrow*/ {
immutable r1 = uniform01, r2 = uniform01; // Not nothrow.
return mean + stdDev * sqrt(-2 * r1.log) * cos(2 * PI * r2);
}
}
void main() {
double[1000] array;
auto nRnd = NormalRandom(1.0, 0.5);
foreach (ref x; array)
//x = nRnd;
x = nRnd();
}
|
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.
|
#D
|
D
|
function Random : Extended;
function Random ( LimitPlusOne : Integer ) : Integer;
procedure Randomize;
|
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.
|
#Delphi
|
Delphi
|
function Random : Extended;
function Random ( LimitPlusOne : Integer ) : Integer;
procedure Randomize;
|
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.
|
#DWScript
|
DWScript
|
!print random-int # prints a 32-bit random integer
|
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.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
!print random-int # prints a 32-bit random integer
|
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
|
#EchoLisp
|
EchoLisp
|
(edit 'preferences)
;; current contents to edit is displayed in the input box
(define (preferences)
(define-syntax-rule (++ n) (begin (set! n (1+ n)) n))
(define-syntax-rule (% a b) (modulo a b))
;; (lib 'gloops)
(lib 'timer))
;; enter new preferences
(define (preferences)
(define FULLNAME "Foo Barber")
(define FAVOURITEFRUIT 'banana)
(define NEEDSPELLING #t)
; SEEDSREMOVED
(define OTHERFAMILY '("Rhu Barber" "Harry Barber")))
|
http://rosettacode.org/wiki/Rare_numbers
|
Rare numbers
|
Definitions and restrictions
Rare numbers are positive integers n where:
n is expressed in base ten
r is the reverse of n (decimal digits)
n must be non-palindromic (n ≠ r)
(n+r) is the sum
(n-r) is the difference and must be positive
the sum and the difference must be perfect squares
Task
find and show the first 5 rare numbers
find and show the first 8 rare numbers (optional)
find and show more rare numbers (stretch goal)
Show all output here, on this page.
References
an OEIS entry: A035519 rare numbers.
an OEIS entry: A059755 odd rare numbers.
planetmath entry: rare numbers. (some hints)
author's website: rare numbers by Shyam Sunder Gupta. (lots of hints and some observations).
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
c = Compile[{{k, _Integer}},
Module[{out = {0}, start = 0, stop = 0, rlist = {0}, r = 0,
sum = 0.0, diff = 0.0, imax = 8, step = 10},
Do[
If[j == k, imax = 2, imax = 8];
Do[
If[i == 2,
start = i 10^j + 2;
stop = (i + 1) 10^j - 1;
step = 10;
,
start = i 10^j;
stop = (i + 1) 10^j - 1;
step = 1;
];
Do[
rlist = IntegerDigits[n];
r = 0;
Do[
r += rlist[[ri]] 10^(ri - 1)
,
{ri, 1, Length[rlist]}
];
If[r != n,
sum = n + r;
sum = Sqrt[sum];
If[Floor[sum] == sum,
diff = n - r;
If[diff > 0,
diff = Sqrt[diff];
If[Floor[diff] == diff,
AppendTo[out, n]
]
]
]
]
,
{n, start, stop, step}
]
,
{i, 2, imax, 2}
]
,
{j, 0, k}
];
out
]
];
Rest[c[9]] (*takes about 310 sec*)
|
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
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
var rangeString = "-6,-3--1,3-5,7-11,14,15,17-20";
var matches = Regex.Matches(rangeString, @"(?<f>-?\d+)-(?<s>-?\d+)|(-?\d+)");
var values = new List<string>();
foreach (var m in matches.OfType<Match>())
{
if (m.Groups[1].Success)
{
values.Add(m.Value);
continue;
}
var start = Convert.ToInt32(m.Groups["f"].Value);
var end = Convert.ToInt32(m.Groups["s"].Value) + 1;
values.AddRange(Enumerable.Range(start, end - start).Select(v => v.ToString()));
}
Console.WriteLine(string.Join(", ", values));
}
}
|
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.
|
#C.2B.2B
|
C++
|
#include <fstream>
#include <string>
#include <iostream>
int main( int argc , char** argv ) {
int linecount = 0 ;
std::string line ;
std::ifstream infile( argv[ 1 ] ) ; // input file stream
if ( infile ) {
while ( getline( infile , line ) ) {
std::cout << linecount << ": "
<< line << '\n' ; //supposing '\n' to be line end
linecount++ ;
}
}
infile.close( ) ;
return 0 ;
}
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.0.6
/* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores
and then, if the scores are equal, by reverse alphabetic order of names
*/
fun standardRanking(scores: Array<Pair<Int, String>>): IntArray {
val rankings = IntArray(scores.size)
rankings[0] = 1
for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) rankings[i - 1] else i + 1
return rankings
}
fun modifiedRanking(scores: Array<Pair<Int, String>>): IntArray {
val rankings = IntArray(scores.size)
rankings[0] = 1
for (i in 1 until scores.size) {
rankings[i] = i + 1
val currScore = scores[i].first
for (j in i - 1 downTo 0) {
if (currScore != scores[j].first) break
rankings[j] = i + 1
}
}
return rankings
}
fun denseRanking(scores: Array<Pair<Int, String>>): IntArray {
val rankings = IntArray(scores.size)
rankings[0] = 1
var prevRanking = 1
for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) prevRanking else ++prevRanking
return rankings
}
fun ordinalRanking(scores: Array<Pair<Int, String>>) = IntArray(scores.size) { it + 1 }
fun fractionalRanking(scores: Array<Pair<Int, String>>): DoubleArray {
val rankings = DoubleArray(scores.size)
rankings[0] = 1.0
for (i in 1 until scores.size) {
var k = i
val currScore = scores[i].first
for (j in i - 1 downTo 0) {
if (currScore != scores[j].first) break
k = j
}
val avg = (k..i).average() + 1.0
for (m in k..i) rankings[m] = avg
}
return rankings
}
fun printRankings(title: String, rankings: IntArray, scores: Array<Pair<Int, String>>) {
println(title + ":")
for (i in 0 until rankings.size) {
print ("${rankings[i]} ")
println(scores[i].toString().removeSurrounding("(", ")").replace(",", ""))
}
println()
}
fun printFractionalRankings(title: String, rankings: DoubleArray, scores: Array<Pair<Int, String>>) {
println(title + ":")
for (i in 0 until rankings.size) {
print ("${"%3.2f".format(rankings[i])} ")
println(scores[i].toString().removeSurrounding("(", ")").replace(",", ""))
}
println()
}
fun main(args: Array<String>) {
val scores = arrayOf(44 to "Solomon", 42 to "Jason", 42 to "Errol", 41 to "Garry",
41 to "Bernard", 41 to "Barry", 39 to "Stephen")
printRankings("Standard ranking", standardRanking(scores), scores)
printRankings("Modified ranking", modifiedRanking(scores), scores)
printRankings("Dense ranking", denseRanking(scores), scores)
printRankings("Ordinal ranking", ordinalRanking(scores), scores)
printFractionalRankings("Fractional ranking", fractionalRanking(scores), scores)
}
|
http://rosettacode.org/wiki/Range_consolidation
|
Range consolidation
|
Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then the result is that encompassing range.
If the ranges touch or intersect then the result is one new single range covering the overlapping ranges.
Otherwise the act of consolidation is to return the two non-touching ranges.
Given N ranges where N > 2 then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.
If N < 2 then range consolidation has no strict meaning and the input can be returned.
Example 1
Given the two ranges [1, 2.5] and [3, 4.2] then
there is no common region between the ranges and the result is the same as the input.
Example 2
Given the two ranges [1, 2.5] and [1.8, 4.7] then
there is : an overlap [2.5, 1.8] between the ranges and
the result is the single range [1, 4.7].
Note that order of bounds in a range is not (yet) stated.
Example 3
Given the two ranges [6.1, 7.2] and [7.2, 8.3] then
they touch at 7.2 and
the result is the single range [6.1, 8.3].
Example 4
Given the three ranges [1, 2] and [4, 8] and [2, 5]
then there is no intersection of the ranges [1, 2] and [4, 8]
but the ranges [1, 2] and [2, 5] overlap and
consolidate to produce the range [1, 5].
This range, in turn, overlaps the other range [4, 8], and
so consolidates to the final output of the single range [1, 8].
Task
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the normalized result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
See also
Set consolidation
Set of real numbers
|
#Phix
|
Phix
|
with javascript_semantics
function consolidate(sequence sets)
integer l = length(sets)
sequence res = repeat(0,l)
for i=1 to l do
atom {rs,re} = sets[i]
res[i] = iff(rs>re?{re,rs}:{rs,re})
end for
for i=l to 1 by -1 do
atom {il,ih} = res[i]
for j=l to i+1 by -1 do
atom {jl,jh} = res[j]
bool overlap = iff(il<=jl?jl<=ih:il<=jh)
if overlap then
{il,ih} = {min(il,jl),max(ih,jh)}
res[j] = res[l]
l -= 1
end if
end for
res[i] = {il,ih}
end for
res = sort(res[1..l])
return res
end function
procedure test(sequence set)
printf(1,"%40v => %v\n",{set,consolidate(set)})
end procedure
test({{1.1,2.2}})
test({{6.1,7.2},{7.2,8.3}})
test({{4,3},{2,1}})
test({{4,3},{2,1},{-1,-2},{3.9,10}})
test({{1,3},{-6,-1},{-4,-5},{8,2},{-6,-6}})
|
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
|
#Oforth
|
Oforth
|
reverse
|
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)
|
#Groovy
|
Groovy
|
def rng = new java.security.SecureRandom()
|
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)
|
#Haskell
|
Haskell
|
#!/usr/bin/env runhaskell
import System.Entropy
import Data.Binary.Get
import qualified Data.ByteString.Lazy as B
main = do
bytes <- getEntropy 4
print (runGet getWord32be $ B.fromChunks [bytes])
|
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)
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(A)
n := integer(A[1])|5
every !n do write(rand(4))
end
procedure rand(n)
f := open("/dev/urandom") | stop("Cannot get to urandom!")
x := 0
every !n do x := x*256 + ord(reads(f,1))
close(f)
return x
end
|
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
|
#D
|
D
|
import std.array;
import std.random;
import std.stdio;
alias Matrix = int[][];
void latinSquare(int n) {
if (n <= 0) {
writeln("[]");
return;
}
Matrix latin = uninitializedArray!Matrix(n, n);
foreach (row; latin) {
for (int i = 0; i < n; i++) {
row[i] = i;
}
}
// first row
latin[0].randomShuffle;
// middle row(s)
for (int i = 1; i < n - 1; i++) {
bool shuffled = false;
shuffling:
while (!shuffled) {
latin[i].randomShuffle;
for (int k = 0; k < i; k++) {
for (int j = 0; j < n; j++) {
if (latin[k][j] == latin[i][j]) {
continue shuffling;
}
}
}
shuffled = true;
}
}
// last row
for (int j = 0; j < n; j++) {
bool[] used = uninitializedArray!(bool[])(n);
used[] = false;
for (int i = 0; i < n - 1; i++) {
used[latin[i][j]] = true;
}
for (int k = 0; k < n; k++) {
if (!used[k]) {
latin[n - 1][j] = k;
break;
}
}
}
printSquare(latin);
}
void printSquare(Matrix latin) {
foreach (row; latin) {
writeln(row);
}
}
void main() {
latinSquare(5);
writeln;
latinSquare(5);
writeln;
latinSquare(10);
}
|
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 ε.)
|
#Perl
|
Perl
|
use strict;
use List::Util qw(max min);
sub point_in_polygon
{
my ( $point, $polygon ) = @_;
my $count = 0;
foreach my $side ( @$polygon ) {
$count++ if ray_intersect_segment($point, $side);
}
return ($count % 2 == 0) ? 0 : 1;
}
my $eps = 0.0001;
my $inf = 1e600;
sub ray_intersect_segment
{
my ($point, $segment) = @_;
my ($A, $B) = @$segment;
my @P = @$point; # copy it
($A, $B) = ($B, $A) if $A->[1] > $B->[1];
$P[1] += $eps if ($P[1] == $A->[1]) || ($P[1] == $B->[1]);
return 0 if ($P[1] < $A->[1]) || ( $P[1] > $B->[1]) || ($P[0] > max($A->[0],$B->[1]) );
return 1 if $P[0] < min($A->[0], $B->[0]);
my $m_red = ($A->[0] != $B->[0]) ? ( $B->[1] - $A->[1] )/($B->[0] - $A->[0]) : $inf;
my $m_blue = ($A->[0] != $P[0]) ? ( $P[1] - $A->[1] )/($P[0] - $A->[0]) : $inf;
return ($m_blue >= $m_red) ? 1 : 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
|
#6502_Assembly
|
6502 Assembly
|
queuePointerStart equ #$FD
queuePointerMinus1 equ #$FC ;make this equal whatever "queuePointerStart" is, minus 1.
pushQueue:
STA 0,x
DEX
RTS
popQueue:
STX temp
LDX #queuePointerStart
LDA 0,x ;get the item that's first in line
PHA
LDX #queuePointerMinus1
loop_popQueue:
LDA 0,X
STA 1,X
DEX
CPX temp
BNE loop_popQueue
LDX temp
INX
PLA ;return the item that just left the queue
RTS
isQueueEmpty:
LDA #1
CPX #queuePointerStart
BEQ yes ;return 1
SEC
SBC #1 ;return 0
yes:
RTS
|
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
|
#8th
|
8th
|
10 q:new \ create a new queue 10 deep
123 q:push
341 q:push \ push 123, 341 onto the queue
q:pop . cr \ displays 123
q:len . cr \ displays 1
q:pop . cr \ displays 341
q:len . cr \ displays 0
|
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.
|
#PicoLisp
|
PicoLisp
|
(in "file.txt"
(do 6 (line))
(or (line) (quit "No 7 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.
|
#PL.2FI
|
PL/I
|
declare text character (1000) varying, line_no fixed;
get (line_no);
on endfile (f) begin;
put skip list ('the specified line does not exist');
go to next;
end;
get file (f) edit ((text do i = 1 to line_no)) (L);
put skip list (text);
next: ;
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Nim
|
Nim
|
echo "A simple string."
echo "A simple string including tabulation special character \\t: \t."
echo """
First part of a multiple string,
followed by second part
and third part.
"""
echo r"A raw string containing a \."
# Interpolation in strings.
import strformat
const C = "constant"
const S = fmt"A string with interpolation of a {C}."
echo S
var x = 3
echo fmt"A string with interpolation of expression “2 * x + 3”: {2 * x + 3}."
echo fmt"Displaying “x” with an embedded format: {x:05}."
# Regular expression string.
import re
let r = re"\d+"
# Pegs string.
import pegs
let e = peg"\d+"
# Array literal.
echo [1, 2, 3] # Element type if implicit ("int" here).
echo [byte(1), 2, 3] # Element type is specified by the first element type.
echo [byte 1, 2, 3] # An equivalent way to specify the type.
echo @[1, 2, 3] # Sequence of ints.
# Tuples.
echo ('a', 1, true) # Tuple without explicit field names.
echo (x: 1, y: 2) # Tuple with two int fields "x" and "y".
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Phix
|
Phix
|
constant t123 = `
one
two
three
`
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Raku
|
Raku
|
/*REXX program demonstrates various ways to express a string of characters or numbers.*/
a= 'This is one method of including a '' (an apostrophe) within a string.'
b= "This is one method of including a ' (an apostrophe) within a string."
/*sometimes, an apostrophe is called */
/*a quote. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
c= "This is one method of including a "" (a double quote) within a string."
d= 'This is one method of including a " (a double quote) within a string.'
/*sometimes, a double quote is also */
/*called a quote, which can make for */
/*some confusion and bewilderment. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
f= 'This is one method of expressing a long literal by concatenations, the ' || ,
'trailing character of the above clause must contain a trailing ' || ,
'comma (,) === note the embedded trailing blank in the above 2 statements.'
/*──────────────────────────────────────────────────────────────────────────────────────*/
g= 'This is another method of expressing a long literal by ' ,
"abutments, the trailing character of the above clause must " ,
'contain a trailing comma (,)'
/*──────────────────────────────────────────────────────────────────────────────────────*/
h= 'This is another method of expressing a long literal by ' , /*still continued.*/
"abutments, the trailing character of the above clause must " ,
'contain a trailing comma (,) --- in this case, the comment /* ... */ is ' ,
'essentially is not considered to be "part of" the REXX clause.'
/*──────────────────────────────────────────────────────────────────────────────────────*/
i= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109
/*This is one way to express a list of */
/*numbers that don't have a sign. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
j= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109,
71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
/*This is one way to express a long */
/*list of numbers that don't have a */
/*sign. */
/*Note that this form of continuation */
/*implies a blank is abutted to first */
/*part of the REXX statement. */
/*Also note that some REXXs have a */
/*maximum clause length. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
k= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109,
71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
/*The J and K values are identical,*/
/*superfluous and extraneous blanks are*/
/*ignored. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
l= '-2 3 +5 7 -11 13 17 19 -23 29 -31 37 -41 43 47 -53 59 -61 67 -71 73 79 -83 89 97 -101'
/*This is one way to express a list of */
/*numbers that have a sign. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
m= a b c d f g h i j k l /*this will create a list of all the */
/*listed strings used (so far) into */
/*the variable L (with an */
/*intervening blank between each */
/*variable's value. */
|
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.
|
#ALGOL_68
|
ALGOL 68
|
BEGIN
# returns the kth lowest element of list using the quick select algorithm #
PRIO QSELECT = 1;
OP QSELECT = ( INT k, REF[]INT list )INT:
IF LWB list > UPB list THEN
# empty list #
0
ELSE
# non-empty list #
# partitions the subset of list from left to right #
PROC partition = ( REF[]INT list, INT left, right, pivot index )INT:
BEGIN
# swaps elements a and b in list #
PROC swap = ( REF[]INT list, INT a, b )VOID:
BEGIN
INT t = list[ a ];
list[ a ] := list[ b ];
list[ b ] := t
END # swap # ;
INT pivot value = list[ pivot index ];
swap( list, pivot index, right );
INT store index := left;
FOR i FROM left TO right - 1 DO
IF list[ i ] < pivot value THEN
swap( list, store index, i );
store index +:= 1
FI
OD;
swap( list, right, store index );
store index
END # partition # ;
INT left := LWB list, right := UPB list, result := 0;
BOOL found := FALSE;
WHILE NOT found DO
IF left = right THEN
result := list[ left ];
found := TRUE
ELSE
INT pivot index = partition( list, left, right, left + ENTIER ( ( random * ( right - left ) + 1 ) ) );
IF k = pivot index THEN
result := list[ k ];
found := TRUE
ELIF k < pivot index THEN
right := pivot index - 1
ELSE
left := pivot index + 1
FI
FI
OD;
result
FI # QSELECT # ;
# test cases #
FOR i TO 10 DO
[ 1 : 10 ]INT test := []INT( 9, 8, 7, 6, 5, 0, 1, 2, 3, 4 );
print( ( whole( i, -2 ), ": ", whole( i QSELECT test, -3 ), newline ) )
OD
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
type point struct{ x, y float64 }
func RDP(l []point, ε float64) []point {
x := 0
dMax := -1.
last := len(l) - 1
p1 := l[0]
p2 := l[last]
x21 := p2.x - p1.x
y21 := p2.y - p1.y
for i, p := range l[1:last] {
if d := math.Abs(y21*p.x - x21*p.y + p2.x*p1.y - p2.y*p1.x); d > dMax {
x = i + 1
dMax = d
}
}
if dMax > ε {
return append(RDP(l[:x+1], ε), RDP(l[x:], ε)[1:]...)
}
return []point{l[0], l[len(l)-1]}
}
func main() {
fmt.Println(RDP([]point{{0, 0}, {1, 0.1}, {2, -0.1},
{3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}}, 1))
}
|
http://rosettacode.org/wiki/Ramanujan%27s_constant
|
Ramanujan's constant
|
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
|
#Pari.2FGP
|
Pari/GP
|
\p 50
exp(Pi*sqrt(163))
|
http://rosettacode.org/wiki/Ramanujan%27s_constant
|
Ramanujan's constant
|
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
|
#Perl
|
Perl
|
use strict;
use warnings;
use Math::AnyNum;
sub ramanujan_const {
my ($x, $decimals) = @_;
$x = Math::AnyNum->new($x);
my $prec = (Math::AnyNum->pi * $x->sqrt)/log(10) + $decimals + 1;
local $Math::AnyNum::PREC = 4*$prec->round->numify;
exp(Math::AnyNum->pi * $x->sqrt)->round(-$decimals)->stringify;
}
my $decimals = 100;
printf("Ramanujan's constant to $decimals decimals:\n%s\n\n",
ramanujan_const(163, $decimals));
print "Heegner numbers yielding 'almost' integers:\n";
my @tests = (19, 96, 43, 960, 67, 5280, 163, 640320);
while (@tests) {
my ($h, $x) = splice(@tests, 0, 2);
my $c = ramanujan_const($h, 32);
my $n = Math::AnyNum::ipow($x, 3) + 744;
printf("%3s: %51s ≈ %18s (diff: %s)\n", $h, $c, $n, ($n - $c)->round(-32));
}
|
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
|
#Bracmat
|
Bracmat
|
( rangeExtract
= accumulator firstInRange nextInRange
, accumulate fasten rangePattern
. ( accumulate
= !accumulator
(!accumulator:|?&",")
!firstInRange
( !firstInRange+1:<>!nextInRange
& ( !firstInRange+2:!nextInRange&","
| "-"
)
-1+!nextInRange
|
)
: ?accumulator
)
& ( fasten
= [%( !accumulate
& (!sjt:?firstInRange)+1:?nextInRange
)
)
& ( rangePattern
= (
| ?
( !nextInRange
& 1+!nextInRange:?nextInRange
)
)
( &!accumulate
| (#<>!nextInRange:!fasten) !rangePattern
)
)
& :?accumulator:?firstInRange
& !arg:(|#!fasten !rangePattern)
& str$!accumulator
)
& ( test
= L A
. put$(!arg " ==>\n",LIN)
& ( !arg:(?,?)
& whl'(!arg:(?A,?arg)&(!A,!L):?L)
& whl'(!L:(?A,?L)&!A !arg:?arg)
|
)
& out$(rangeExtract$!arg)
)
& test
$ (0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39)
|
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
|
#Delphi
|
Delphi
|
program Randoms;
{$APPTYPE CONSOLE}
uses
Math;
var
Values: array[0..999] of Double;
I: Integer;
begin
// Randomize; Commented to obtain reproducible results
for I:= Low(Values) to High(Values) do
Values[I]:= RandG(1.0, 0.5); // Mean = 1.0, StdDev = 0.5
Writeln('Mean = ', Mean(Values):6:4);
Writeln('Std Deviation = ', StdDev(Values):6:4);
Readln;
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
|
#DWScript
|
DWScript
|
var values : array [0..999] of Float;
var i : Integer;
for i := values.Low to values.High do
values[i] := RandG(1, 0.5);
|
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.
|
#EchoLisp
|
EchoLisp
|
(random-seed "albert")
(random) → 0.9672510261922906 ; random float in [0 ... 1[
(random 1000) → 726 ; random integer in [0 ... 1000 [
(random -1000) → -936 ; random integer in ]-1000 1000[
(lib 'bigint)
(random 1e200) → 48635656441292641677...3917639734865662239925...9490799697903133046309616766848265781368
|
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.
|
#Elena
|
Elena
|
import extensions;
public program()
{
console.printLine(randomGenerator.nextReal());
console.printLine(randomGenerator.eval(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.
|
#Elixir
|
Elixir
|
# Seed the RNG
:random.seed(:erlang.now())
# Integer in the range 1..10
:random.uniform(10)
# Float between 0.0 and 1.0
:random.uniform()
|
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.
|
#Erlang
|
Erlang
|
random:seed(A1, A2, A3)
|
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
|
#Elixir
|
Elixir
|
defmodule Configuration_file do
def read(file) do
File.read!(file)
|> String.split(~r/\n|\r\n|\r/, trim: true)
|> Enum.reject(fn line -> String.starts_with?(line, ["#", ";"]) end)
|> Enum.map(fn line ->
case String.split(line, ~r/\s/, parts: 2) do
[option] -> {to_atom(option), true}
[option, values] -> {to_atom(option), separate(values)}
end
end)
end
def task do
defaults = [fullname: "Kalle", favouritefruit: "apple", needspeeling: false, seedsremoved: false]
options = read("configuration_file") ++ defaults
[:fullname, :favouritefruit, :needspeeling, :seedsremoved, :otherfamily]
|> Enum.each(fn x ->
values = options[x]
if is_boolean(values) or length(values)==1 do
IO.puts "#{x} = #{values}"
else
Enum.with_index(values) |> Enum.each(fn {value,i} ->
IO.puts "#{x}(#{i+1}) = #{value}"
end)
end
end)
end
defp to_atom(option), do: String.downcase(option) |> String.to_atom
defp separate(values), do: String.split(values, ",") |> Enum.map(&String.strip/1)
end
Configuration_file.task
|
http://rosettacode.org/wiki/Rare_numbers
|
Rare numbers
|
Definitions and restrictions
Rare numbers are positive integers n where:
n is expressed in base ten
r is the reverse of n (decimal digits)
n must be non-palindromic (n ≠ r)
(n+r) is the sum
(n-r) is the difference and must be positive
the sum and the difference must be perfect squares
Task
find and show the first 5 rare numbers
find and show the first 8 rare numbers (optional)
find and show more rare numbers (stretch goal)
Show all output here, on this page.
References
an OEIS entry: A035519 rare numbers.
an OEIS entry: A059755 odd rare numbers.
planetmath entry: rare numbers. (some hints)
author's website: rare numbers by Shyam Sunder Gupta. (lots of hints and some observations).
|
#Nim
|
Nim
|
import algorithm, math, strformat, times
type Llst = seq[seq[int]]
const
# Powers of 10.
P = block:
var p: array[19, int64]
p[0] = 1i64
for i in 1..18: p[i] = 10 * p[i - 1]
p
# Digital root lookup array.
Drar = block:
var drar: array[19, int]
for i in 0..18: drar[i] = i shl 1 mod 9
drar
var
d: seq[int] # permutation working slice
dac: seq[int] # running digital root slice
ac: seq[int64] # accumulator slice
pp: seq[int64] # coefficient slice that combines with digits of working slice
sr: seq[int64] # temporary list of squares used for building
var
odd = false # flag for odd number of digits
sum: int64 # calculated sum of terms (square candidate)
cn = 0 # solution counter
nd = 2 # number of digits
nd1 = nd - 1 # 'nd' helper
ln: int # previous value of 'n' (in recurse())
dl: int # length of 'd' slice
func newIntSeq(f, t, s: int): seq[int] =
## Return a sequence of integers.
result = newSeq[int]((t - f) div s + 1)
var f = f
for i in 0..result.high:
result[i] = f
inc f, s
const
Tlo = @[0, 1, 4, 5, 6] # primary differences starting point
All = newIntSeq(-9, 9, 1) # all possible differences
Odl = newIntSeq(-9, 9, 2) # odd possible differences
Evl = newIntSeq(-8, 8, 2) # even possible differences
Thi = @[4, 5, 6, 9, 10, 11, 14, 15, 16] # primary sums starting point
Alh = newIntSeq(0, 18, 1) # all possible sums
Odh = newIntSeq(1, 17, 2) # odd possible sums
Evh = newIntSeq(0, 18, 2) # even possible sums
Ten = newIntSeq(0, 9, 1) # used for odd number of digits
Z = newIntSeq(0, 0, 1) # no difference, avoids generating a bunch of negative square candidates
T7 = @[-3, 7] # shortcut for low 5
Nin = @[9] # shortcut for hi 10
Tn = @[10] # shortcut for hi 0 (unused, unneeded)
T12 = @[2, 12] # shortcut for hi 5
O11 = @[1, 11] # shortcut for hi 15
Pos = @[0, 1, 4, 5, 6, 9] # shortcut for 2nd lo 0
var
lul: Llst = @[Z, Odl, @[], @[], Evl, T7, Odl] # shortcut lookup lo primary
luh: Llst = @[Tn, Evh, @[], @[], Evh, T12, Odh, @[], @[],
Evh, Nin, Odh, @[], @[], Odh, O11, Evh] # shortcut lookup hi primary
l2l: Llst = @[Pos, @[], @[], @[], All, @[], All] # shortcut lookup lo secondary
l2h: Llst = @[@[], @[], @[], @[], Alh, @[], Alh, @[], @[],
@[], Alh, @[], @[], @[], Alh, @[], Alh] # shortcut lookup hi secondary
chTen: Llst = @[@[0, 2, 5, 8, 9], @[0, 3, 4, 6, 9], @[1, 4, 7, 8],
@[2, 3, 5, 8], @[0, 3, 6, 7, 9], @[1, 2, 4, 7],
@[2, 5, 6, 8], @[0, 1, 3, 6, 9], @[1, 4, 5, 7]]
chAH: Llst = @[@[0, 2, 5, 8, 9, 11, 14, 17, 18], @[0, 3, 4, 6, 9, 12, 13, 15, 18],
@[1, 4, 7, 8, 10, 13, 16, 17], @[2, 3, 5, 8, 11, 12, 14, 17],
@[0, 3, 6, 7, 9, 12, 15, 16, 18], @[1, 2, 4, 7, 10, 11, 13, 16],
@[2, 5, 6, 8, 11, 14, 15, 17], @[0, 1, 3, 6, 9, 10, 12, 15, 18],
@[1, 4, 5, 7, 10, 13, 14, 16]]
var lu, l2: Llst
func isr(s: int64): int64 {.inline.} =
## Return integer square root.
int64(sqrt(float(s)))
proc isRev(nd: int; f, r: int64): bool =
## Recursively determines whether 'r' is the reverse of 'f'.
let nd = nd - 1
if f div P[nd] != r mod 10: return false
if nd < 1: return true
result = isRev(nd, f mod P[nd], r div 10)
proc recurseLE5(lst: Llst; lv: int) =
## Recursive function to evaluate the permutations, no shortcuts.
if lv == dl: # Check if on last stage of permutation.
sum = ac[lv - 1]
if sum > 0:
let rt = int64(sqrt(float(sum)))
if rt * rt == sum: sr.add sum
else:
for n in lst[lv]: # Set up next permutation.
d[lv] = n
if lv == 0: ac[0] = pp[0] * n
else: ac[lv] = ac[lv - 1] + pp[lv] * n # Update accumulated sum.
recurseLE5(lst, lv + 1) # Recursively call next level.
proc recursehi(lst: var Llst; lv: int) =
## Recursive function to evaluate the hi permutations.
## Shortcuts added to avoid generating many non-squares, digital root calc added.
let lv1 = lv - 1
if lv == dl: # Check if on last stage of permutation.
sum = ac[lv1]
if (0x202021202030213 and (1 shl (sum and 63))) != 0:
# Test accumulated sum, append to result if square.
let rt = int64(sqrt(float64(sum)))
if rt * rt == sum: sr.add sum
else:
for n in lst[lv]: # Set up next permutation.
d[lv] = n
if lv == 0:
ac[0] = pp[0] * n
dac[0] = Drar[n] # Update accumulated sum and running dr.
else:
ac[lv] = ac[lv1] + pp[lv] * n
dac[lv] = dac[lv1] + Drar[n]
if dac[lv] > 8: dec dac[lv], 9
case lv # Shortcuts to be performed on designated levels.
of 0: # Primary level: set shortcuts for secondary level.
ln = n
lst[1] = lu[ln]
lst[2] = l2[n]
of 1: # Secondary level: set shortcuts for tertiary level.
case ln # For sums.
of 5, 15: lst[2] = if n < 10: Evh else: Odh
of 9: lst[2] = if (n shr 1 and 1) == 0: Evh else: Odh
of 11: lst[2] = if (n shr 1 and 1) == 1: Evh else: Odh
else: discard
else: discard
if lv == dl - 2:
# Reduce last round according to dr calc.
lst[dl - 1] = if odd: chTen[dac[dl - 2]] else: chAH[dac[dl - 2]]
recursehi(lst, lv + 1) # Recursively call next level.
proc recurselo(lst: var Llst; lv: int) =
## Recursive function to evaluate the lo permutations.
## Shortcuts added to avoid generating many non-squares.
let lv1 = lv - 1
if lv == dl: # Check if on last stage of permutation.
sum = ac[lv1]
if sum > 0:
let rt = int64(sqrt(float64(sum)))
if rt * rt == sum: sr.add sum
else:
for n in lst[lv]: # Set up next permutation.
d[lv] = n
if lv == 0: ac[0] = pp[0] * n
else: ac[lv] = ac[lv1] + pp[lv] * n # Update accumulated sum.
case lv # Shortcuts to be performed on designated levels.
of 0: # Primary level: set shortcuts for secondary level.
ln = n
lst[1] = lu[ln]
lst[2] = l2[n]
of 1: # Secondary level: set shortcuts for tertiary level.
case ln # For difs.
of 1: lst[2] = if ((n + 9) shr 1 and 1) == 0: Evl else: Odl
of 5: lst[2] = if n < 0: Evl else: Odl
else: discard
else: discard
recurselo(lst, lv + 1) # Recursively call next level.
proc listEm(lst: var Llst; plu, pl2: Llst): seq[int64] =
## Produces a list of candidate square numbers.
dl = lst.len
d = newSeq[int](dl)
sr.setLen(0)
lu = plu
l2 = pl2
ac = newSeq[int64](dl)
dac = newSeq[int](dl)
pp = newSeq[int64](dl)
# Build coefficients array.
for i in 0..<dl:
pp[i] = if lst[0].len > 6: P[nd1 - i] + P[i] else: P[nd1 - i] - P[i]
# Call appropriate recursive function.
if nd <= 5: recurseLE5(lst, 0)
elif lst[0].len > 8: recursehi(lst, 0)
else: recurselo(lst, 0)
result = sr
proc reveal(lo, hi: openArray[int64]) =
## Reveal whether combining two lists of squares can produce a rare number.
var s: seq[string] # Temporary list of results.
for l in lo:
for h in hi:
let r = (h - l) shr 1
let f = h - r # Generate all possible fwd & rev candidates from lists.
if isRev(nd, f, r):
s.add &"{f:20} {isr(h):11} {isr(l):10} "
s.sort()
if s.len > 0:
for t in s:
inc cn
let tt = if t != s[^1]: "\n" else: ""
stdout.write &"{cn:2} {t}{tt}"
else:
stdout.write &"{\"\":48}"
func formatTime(d: Duration): string =
var f = d.inMilliseconds
var s = f div 1000
f = f mod 1000
var m = s div 60
s = s mod 60
let h = m div 60
m = m mod 60
result = &"{h:02}:{m:02}:{s:02}.{f:03}"
var
lls: Llst = @[Tlo]
hls: Llst = @[Thi]
var bstart, tstart = now()
echo &"""nth {"forward":>19} {"rt.sum":>11} {"rt.dif":>10} digs {"block time":>11} {"total time":>13}"""
while nd <= 18:
if nd > 2:
if odd:
hls.add Ten
else:
lls.add All
hls[^1] = Alh
reveal(listEm(lls, lul, l2l), listEm(hls, luh, l2h))
if not odd and nd > 5:
# Restore last element of hls, so that dr shortcut doesn't mess up next nd.
hls[^1] = Alh
let bTime = formatTime(now() - bstart)
let tTime = formatTime(now() - tstart)
echo &"{nd:2}: {bTime} {tTime}"
bstart = now() # Restart block timing.
nd1 = nd
inc nd
odd = not odd
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <sstream>
#include <iterator>
#include <climits>
#include <deque>
// parse a list of numbers with ranges
//
// arguments:
// is: the stream to parse
// out: the output iterator the parsed list is written to.
//
// returns true if the parse was successful. false otherwise
template<typename OutIter>
bool parse_number_list_with_ranges(std::istream& is, OutIter out)
{
int number;
// the list always has to start with a number
while (is >> number)
{
*out++ = number;
char c;
if (is >> c)
switch(c)
{
case ',':
continue;
case '-':
{
int number2;
if (is >> number2)
{
if (number2 < number)
return false;
while (number < number2)
*out++ = ++number;
char c2;
if (is >> c2)
if (c2 == ',')
continue;
else
return false;
else
return is.eof();
}
else
return false;
}
default:
return is.eof();
}
else
return is.eof();
}
// if we get here, something went wrong (otherwise we would have
// returned from inside the loop)
return false;
}
int main()
{
std::istringstream example("-6,-3--1,3-5,7-11,14,15,17-20");
std::deque<int> v;
bool success = parse_number_list_with_ranges(example, std::back_inserter(v));
if (success)
{
std::copy(v.begin(), v.end()-1,
std::ostream_iterator<int>(std::cout, ","));
std::cout << v.back() << "\n";
}
else
std::cout << "an error occured.";
}
|
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.
|
#Clojure
|
Clojure
|
(with-open [r (clojure.java.io/reader "some-file.txt")]
(doseq [l (line-seq r)]
(println l)))
|
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.
|
#CLU
|
CLU
|
start_up = proc ()
po: stream := stream$primary_output()
% There is a special type for file names. This ensures that
% the path is valid; if not, file_name$parse would throw an
% exception (which we are just ignoring here).
fname: file_name := file_name$parse("input.txt")
% File I/O is then done through a stream just like any I/O.
% If the file were not accessible, stream$open would throw an
% exception.
fstream: stream := stream$open(fname, "read")
count: int := 0 % count the lines
while true do
% Read a line. This will end the loop once the end is reached,
% as the exception handler is outside the loop.
line: string := stream$getl(fstream)
% Show the line
count := count + 1
stream$putl(po, int$unparse(count) || ": " || line)
end except when end_of_file:
% Close the file once we're done
stream$close(fstream)
end
end start_up
|
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.
|
#Ksh
|
Ksh
|
#!/bin/ksh
exec 2> /tmp/Ranking_methods.err
# Ranking methods
#
# # 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)
# # Variables:
#
typeset -a arr=( '44 Solomon' '42 Jason' '42 Errol' '41 Garry' '41 Bernard' '41 Barry' '39 Stephen' )
integer i
# # Functions:
#
# # Function _rankStandard(arr, rankarr) - retun arr with standard ranking
#
function _rankStandard {
typeset _ranked ; nameref _ranked="$1"
typeset _i _j _scr _currank _prevscr _shelf
integer _i _j _scr _currank=1 _prevscr
typeset -a _shelf
for ((_i=0; _i<${#arr[*]}; _i++)); do
_scr=${arr[_i]%\ *}
if (( _i>0 )) && (( _scr != _prevscr )); then
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
(( _currank+=${#_shelf[*]} ))
unset _shelf ; typeset -a _shelf
fi
_shelf+=( "${arr[_i]}" )
_prevscr=${_scr}
done
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
}
# # Function _rankModified(arr, rankarr) - retun arr with modified ranking
#
function _rankModified {
typeset _ranked ; nameref _ranked="$1"
typeset _i _j _scr _currank _prevscr _shelf
integer _i _j _scr _currank=0 _prevscr
typeset -a _shelf
for ((_i=0; _i<${#arr[*]}; _i++)); do
_scr=${arr[_i]%\ *}
if (( _i>0 )) && (( _scr != _prevscr )); then
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
unset _shelf ; typeset -a _shelf
fi
_shelf+=( "${arr[_i]}" )
(( _currank++ ))
_prevscr=${_scr}
done
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
}
# # Function _rankDense(arr, rankarr) - retun arr with dense ranking
#
function _rankDense {
typeset _ranked ; nameref _ranked="$1"
typeset _i _j _scr _currank _prevscr _shelf
integer _i _j _scr _currank=0 _prevscr
typeset -a _shelf
for ((_i=0; _i<${#arr[*]}; _i++)); do
_scr=${arr[_i]%\ *}
if (( _i>0 )) && (( _scr != _prevscr )); then
(( _currank++ ))
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
unset _shelf ; typeset -a _shelf
fi
_shelf+=( "${arr[_i]}" )
_prevscr=${_scr}
done
(( _currank++ ))
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
}
# # Function _rankOrdinal(arr, rankarr) - retun arr with ordinal ranking
#
function _rankOrdinal {
typeset _ranked ; nameref _ranked="$1"
typeset _i ; integer _i
for ((_i=0; _i<${#arr[*]}; _i++)); do
_ranked+=( "$(( _i + 1 )) ${arr[_i]}" )
done
}
# # Function _rankFractional(arr, rankarr) - retun arr with Fractional ranking
#
function _rankFractional {
typeset _ranked ; nameref _ranked="$1"
typeset _i _j _scr _currank _prevscr _shelf
integer _i _j _scr _prevscr
typeset -F1 _currank=1.0
typeset -a _shelf
for ((_i=0; _i<${#arr[*]}; _i++)); do
_scr=${arr[_i]%\ *}
if (( _i>0 )) && (( _scr != _prevscr )); then
(( _currank/=${#_shelf[*]} ))
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
_currank=0.0
unset _shelf ; typeset -a _shelf
fi
(( _i>0 )) && (( _currank+=_i + 1 ))
_shelf+=( "${arr[_i]}" )
_prevscr=${_scr}
done
for ((_j=0; _j<${#_shelf[*]}; _j++)); do
(( _currank/=${#_shelf[*]} ))
_ranked+=( "${_currank} ${_shelf[_j]}" )
done
}
######
# main #
######
printf "\n\nInput Data: ${#arr[*]} records\n---------------------\n"
for ((i=0; i< ${#arr[*]}; i++)); do
print ${arr[i]}
done
typeset -a rankedarr
_rankStandard rankedarr
printf "\n\nStandard Ranking\n----------------\n"
for ((i=0; i< ${#rankedarr[*]}; i++)); do
print ${rankedarr[i]}
done
unset rankedarr ; typeset -a rankedarr
_rankModified rankedarr
printf "\n\nModified Ranking\n----------------\n"
for ((i=0; i< ${#rankedarr[*]}; i++)); do
print ${rankedarr[i]}
done
unset rankedarr ; typeset -a rankedarr
_rankDense rankedarr
printf "\n\nDense Ranking\n-------------\n"
for ((i=0; i< ${#rankedarr[*]}; i++)); do
print ${rankedarr[i]}
done
unset rankedarr ; typeset -a rankedarr
_rankOrdinal rankedarr
printf "\n\nOrdinal Ranking\n---------------\n"
for ((i=0; i< ${#rankedarr[*]}; i++)); do
print ${rankedarr[i]}
done
unset rankedarr ; typeset -a rankedarr
_rankFractional rankedarr
printf "\n\nFractional Ranking\n------------------\n"
for ((i=0; i< ${#rankedarr[*]}; i++)); do
print ${rankedarr[i]}
done
|
http://rosettacode.org/wiki/Range_consolidation
|
Range consolidation
|
Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then the result is that encompassing range.
If the ranges touch or intersect then the result is one new single range covering the overlapping ranges.
Otherwise the act of consolidation is to return the two non-touching ranges.
Given N ranges where N > 2 then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.
If N < 2 then range consolidation has no strict meaning and the input can be returned.
Example 1
Given the two ranges [1, 2.5] and [3, 4.2] then
there is no common region between the ranges and the result is the same as the input.
Example 2
Given the two ranges [1, 2.5] and [1.8, 4.7] then
there is : an overlap [2.5, 1.8] between the ranges and
the result is the single range [1, 4.7].
Note that order of bounds in a range is not (yet) stated.
Example 3
Given the two ranges [6.1, 7.2] and [7.2, 8.3] then
they touch at 7.2 and
the result is the single range [6.1, 8.3].
Example 4
Given the three ranges [1, 2] and [4, 8] and [2, 5]
then there is no intersection of the ranges [1, 2] and [4, 8]
but the ranges [1, 2] and [2, 5] overlap and
consolidate to produce the range [1, 5].
This range, in turn, overlaps the other range [4, 8], and
so consolidates to the final output of the single range [1, 8].
Task
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the normalized result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
See also
Set consolidation
Set of real numbers
|
#Prolog
|
Prolog
|
consolidate_ranges(Ranges, Consolidated):-
normalize(Ranges, Normalized),
sort(Normalized, Sorted),
merge(Sorted, Consolidated).
normalize([], []):-!.
normalize([r(X, Y)|Ranges], [r(Min, Max)|Normalized]):-
(X > Y -> Min = Y, Max = X; Min = X, Max = Y),
normalize(Ranges, Normalized).
merge([], []):-!.
merge([Range], [Range]):-!.
merge([r(Min1, Max1), r(Min2, Max2)|Rest], Merged):-
Min2 =< Max1,
!,
Max is max(Max1, Max2),
merge([r(Min1, Max)|Rest], Merged).
merge([Range|Ranges], [Range|Merged]):-
merge(Ranges, Merged).
write_range(r(Min, Max)):-
writef('[%w, %w]', [Min, Max]).
write_ranges([]):-!.
write_ranges([Range]):-
!,
write_range(Range).
write_ranges([Range|Ranges]):-
write_range(Range),
write(', '),
write_ranges(Ranges).
test_case([r(1.1, 2.2)]).
test_case([r(6.1, 7.2), r(7.2, 8.3)]).
test_case([r(4, 3), r(2, 1)]).
test_case([r(4, 3), r(2, 1), r(-1, -2), r(3.9, 10)]).
test_case([r(1, 3), r(-6, -1), r(-4, -5), r(8, 2), r(-6, -6)]).
main:-
forall(test_case(Ranges),
(consolidate_ranges(Ranges, Consolidated),
write_ranges(Ranges), write(' -> '),
write_ranges(Consolidated), nl)).
|
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
|
#Ol
|
Ol
|
(define (rev s)
(runes->string (reverse (string->runes s))))
; testing:
(print (rev "Hello, λ!"))
; ==> !λ ,olleH
|
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)
|
#J
|
J
|
256#.a.i.1!:11'/dev/urandom';0 4
|
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)
|
#Java
|
Java
|
import java.security.SecureRandom;
public class RandomExample {
public static void main(String[] args) {
SecureRandom rng = new SecureRandom();
/* Prints a random signed 32-bit integer. */
System.out.println(rng.nextInt());
}
}
|
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
|
#F.23
|
F#
|
// Generate 2 Random Latin Squares of order 5. Nigel Galloway: July 136th., 2019
let N=let N=System.Random() in (fun n->N.Next(n))
let rc()=let β=lN2p [|0;N 4;N 3;N 2|] [|0..4|] in Seq.item (N 56) (normLS 5) |> List.map(lN2p [|N 5;N 4;N 3;N 2|]) |> List.permute(fun n->β.[n]) |> List.iter(printfn "%A")
rc(); printfn ""; rc()
|
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 ε.)
|
#Phix
|
Phix
|
constant inf = 1e300*1e300
function rayIntersectsSegment(sequence point, sequence segment)
sequence {a, b} = segment
atom {pX,pY} = point,
{aX,aY} = a,
{bX,bY} = b,
m_red,m_blue
-- ensure {aX,aY} is the segment end-point with the smallest y coordinate
if aY>bY then
{bX,bY} = a
{aX,aY} = b
end if
if pY=aY or pY=bY then
--
-- Consider a ray passing through the top or left corner of a diamond:
-- /
-- --- or -
-- ^ \
-- In both cases it touches both edges, but ends up outside in the
-- top case, whereas it ends up inside in the left case. Just move
-- the y co-ordinate down a smidge and it'll work properly, by
-- missing one line in the left/right cases and hitting both/none
-- in the top/bottom cases.
--
pY += 0.000001
end if
if pY<aY or pY>bY then return false end if
if pX>max(aX,bX) then return false end if
if pX<min(aX,bX) then return true end if
if aX!=bX then
m_red = (bY-aY)/(bX-aX)
else
m_red = inf
end if
if aX!=pX then
m_blue = (pY-aY)/(pX-aX)
else
m_blue = inf
end if
return m_blue >= m_red
end function
function inside(sequence point, sequence poly)
bool res = false
for i=1 to length(poly) do
if rayIntersectsSegment(point,poly[i]) then
res = not res
end if
end for
return res
end function
function instr(integer flag, integer expected)
string res = {"in", "out"}[2-flag]
if flag!=expected then
res &= "*** ERROR ***"
end if
return res
end function
function instar(integer flag)
return "* "[2-flag]
end function
constant test_points = {{5,5},{5,8},{-10,5},{0,5},{10,5},{8,5},{10,10}}
--constant NAME = 1, POLY = 2, EXPECTED = 3
constant test_polygons = {
{"square", {{{0,0},{10,0}},{{10,0},{10,10}},{{10,10},{0,10}},{{0,10},{0,0}}},
{true,true,false,false,true,true,false}},
{"square hole", {{{0,0},{10,0}},{{10,0},{10,10}},{{10,10},{0,10}},{{0,10},{0,0}},
{{2.5,2.5},{7.5,2.5}},{{7.5,2.5},{7.5,7.5}},{{7.5,7.5},{2.5,7.5}},{{2.5,7.5},{2.5,2.5}}},
{false,true,false,false,true,true,false}},
{"strange", {{{0,5},{2.5,2.5}},{{2.5,2.5},{0,10}},{{0,10},{2.5,7.5}},{{2.5,7.5},{7.5,7.5}},
{{7.5,7.5},{10,10}},{{10,10},{10,0}},{{10,0},{2.5,2.5}}},
{true,false,false,false,true,true,false}},
{"exagon", {{{3,0},{7,0}},{{7,0},{10,5}},{{10,5},{7,10}},{{7,10},{3,10}},{{3,10},{0,5}},{{0,5},{3,0}}},
{true,true,false,false,true,true,false}}
}
sequence name, poly, expected, tp
for i=1 to length(test_polygons) do
{name,poly,expected} = test_polygons[i]
printf(1,"\n%12s:",{name})
for j=1 to length(test_points) do
tp = test_points[j]
printf(1," %s, %-4s",{sprint(tp),instr(inside(tp,poly),expected[j])})
end for
end for
puts(1,"\n\n\n")
for i=0 to 10 do
for j=1 to length(test_polygons) do
puts(1," ")
poly = test_polygons[j][2]
for k=0 to 10 do
puts(1,instar(inside({k+0.5,10.5-i},poly)))
end for
end for
puts(1,"\n")
end for
|
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.
|
#8080_Assembly
|
8080 Assembly
|
org 100h
lxi b,P
call A
lxi d,P
jmp B
A: ldax b
ana a
rz
call G
inx b
jmp A
B: lxi h,C
call H
mvi c,16
D: mvi a,48
call G
ldax d
call E
mvi a,104
call G
ldax d
ana a
rz
inx d
dcr c
jz B
mvi a,44
call G
jmp D
E: push psw
rlc
rlc
rlc
rlc
call F
pop psw
F: ani 15
adi 48
cpi 58
jc G
adi 7
G: push h
push d
push b
push psw
mov e,a
mvi c,2
call 5
pop psw
r: pop b
pop d
pop h
ret
H: push b
push d
push h
xchg
mvi c,9
call 5
jmp r
C: db 13,10,9,'db',9,'$'
P:
db 009h,06Fh,072h,067h,009h,031h,030h,030h,068h,00Dh,00Ah,009h,06Ch,078h,069h,009h
db 062h,02Ch,050h,00Dh,00Ah,009h,063h,061h,06Ch,06Ch,009h,041h,00Dh,00Ah,009h,06Ch
db 078h,069h,009h,064h,02Ch,050h,00Dh,00Ah,009h,06Ah,06Dh,070h,009h,042h,00Dh,00Ah
db 041h,03Ah,009h,06Ch,064h,061h,078h,009h,062h,00Dh,00Ah,009h,061h,06Eh,061h,009h
db 061h,00Dh,00Ah,009h,072h,07Ah,00Dh,00Ah,009h,063h,061h,06Ch,06Ch,009h,047h,00Dh
db 00Ah,009h,069h,06Eh,078h,009h,062h,00Dh,00Ah,009h,06Ah,06Dh,070h,009h,041h,00Dh
db 00Ah,042h,03Ah,009h,06Ch,078h,069h,009h,068h,02Ch,043h,00Dh,00Ah,009h,063h,061h
db 06Ch,06Ch,009h,048h,00Dh,00Ah,009h,06Dh,076h,069h,009h,063h,02Ch,031h,036h,00Dh
db 00Ah,044h,03Ah,009h,06Dh,076h,069h,009h,061h,02Ch,034h,038h,00Dh,00Ah,009h,063h
db 061h,06Ch,06Ch,009h,047h,00Dh,00Ah,009h,06Ch,064h,061h,078h,009h,064h,00Dh,00Ah
db 009h,063h,061h,06Ch,06Ch,009h,045h,00Dh,00Ah,009h,06Dh,076h,069h,009h,061h,02Ch
db 031h,030h,034h,00Dh,00Ah,009h,063h,061h,06Ch,06Ch,009h,047h,00Dh,00Ah,009h,06Ch
db 064h,061h,078h,009h,064h,00Dh,00Ah,009h,061h,06Eh,061h,009h,061h,00Dh,00Ah,009h
db 072h,07Ah,00Dh,00Ah,009h,069h,06Eh,078h,009h,064h,00Dh,00Ah,009h,064h,063h,072h
db 009h,063h,00Dh,00Ah,009h,06Ah,07Ah,020h,009h,042h,00Dh,00Ah,009h,06Dh,076h,069h
db 009h,061h,02Ch,034h,034h,00Dh,00Ah,009h,063h,061h,06Ch,06Ch,009h,047h,00Dh,00Ah
db 009h,06Ah,06Dh,070h,009h,044h,00Dh,00Ah,045h,03Ah,009h,070h,075h,073h,068h,009h
db 070h,073h,077h,00Dh,00Ah,009h,072h,06Ch,063h,00Dh,00Ah,009h,072h,06Ch,063h,00Dh
db 00Ah,009h,072h,06Ch,063h,00Dh,00Ah,009h,072h,06Ch,063h,00Dh,00Ah,009h,063h,061h
db 06Ch,06Ch,009h,046h,00Dh,00Ah,009h,070h,06Fh,070h,009h,070h,073h,077h,00Dh,00Ah
db 046h,03Ah,009h,061h,06Eh,069h,009h,031h,035h,00Dh,00Ah,009h,061h,064h,069h,009h
db 034h,038h,00Dh,00Ah,009h,063h,070h,069h,009h,035h,038h,00Dh,00Ah,009h,06Ah,063h
db 009h,047h,00Dh,00Ah,009h,061h,064h,069h,009h,037h,00Dh,00Ah,047h,03Ah,009h,070h
db 075h,073h,068h,009h,068h,00Dh,00Ah,009h,070h,075h,073h,068h,009h,064h,00Dh,00Ah
db 009h,070h,075h,073h,068h,009h,062h,00Dh,00Ah,009h,070h,075h,073h,068h,009h,070h
db 073h,077h,00Dh,00Ah,009h,06Dh,06Fh,076h,009h,065h,02Ch,061h,00Dh,00Ah,009h,06Dh
db 076h,069h,009h,063h,02Ch,032h,00Dh,00Ah,009h,063h,061h,06Ch,06Ch,009h,035h,00Dh
db 00Ah,009h,070h,06Fh,070h,009h,070h,073h,077h,00Dh,00Ah,072h,03Ah,009h,070h,06Fh
db 070h,009h,062h,00Dh,00Ah,009h,070h,06Fh,070h,009h,064h,00Dh,00Ah,009h,070h,06Fh
db 070h,009h,068h,00Dh,00Ah,009h,072h,065h,074h,00Dh,00Ah,048h,03Ah,009h,070h,075h
db 073h,068h,009h,062h,00Dh,00Ah,009h,070h,075h,073h,068h,009h,064h,00Dh,00Ah,009h
db 070h,075h,073h,068h,009h,068h,00Dh,00Ah,009h,078h,063h,068h,067h,00Dh,00Ah,009h
db 06Dh,076h,069h,009h,063h,02Ch,039h,00Dh,00Ah,009h,063h,061h,06Ch,06Ch,009h,035h
db 00Dh,00Ah,009h,06Ah,06Dh,070h,009h,072h,00Dh,00Ah,043h,03Ah,009h,064h,062h,009h
db 031h,033h,02Ch,031h,030h,02Ch,039h,02Ch,027h,064h,062h,027h,02Ch,039h,02Ch,027h
db 024h,027h,00Dh,00Ah,050h,03Ah,000h
|
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
|
#Action.21
|
Action!
|
SET EndProg=*
|
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
|
#Ada
|
Ada
|
with FIFO;
with Ada.Text_Io; use Ada.Text_Io;
procedure Queue_Test is
package Int_FIFO is new FIFO (Integer);
use Int_FIFO;
Queue : FIFO_Type;
Value : Integer;
begin
Push (Queue, 1);
Push (Queue, 2);
Push (Queue, 3);
Pop (Queue, Value);
Pop (Queue, Value);
Push (Queue, 4);
Pop (Queue, Value);
Pop (Queue, Value);
Push (Queue, 5);
Pop (Queue, Value);
Put_Line ("Is_Empty " & Boolean'Image (Is_Empty (Queue)));
end Queue_Test;
|
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.
|
#PL.2FM
|
PL/M
|
100H: /* READ A SPECIFIC LINE FROM A FILE */
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */
DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */
/* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */
BDOS: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
BDOS$P: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
EXIT: PROCEDURE; CALL BDOS$P( 0, 0 ); END; /* CP/M SYSTEM RESET */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, NL$CHAR, '$' ) ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
FL$EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */
DECLARE FCB ADDRESS; /* FCB EXISTS */
RETURN ( BDOS( 17, FCB ) < 4 );
END FL$EXISTS ;
FL$OPEN: PROCEDURE( FCB )BYTE; /* OPEN THE FILE WITH THE SPECIFIED FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 15, FCB ) < 4 );
END FL$OPEN;
FL$READ: PROCEDURE( FCB )BYTE; /* READ THE NEXT RECORD FROM FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 20, FCB ) = 0 );
END FL$READ;
FL$CLOSE: PROCEDURE( FCB )BYTE; /* CLOSE THE FILE WITH THE SPECIFIED FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 16, FCB ) < 4 );
END FL$CLOSE;
PR$BYTE: PROCEDURE( B ); /* PRINT B EITHER AS A CHAR OR IN HEX */
DECLARE B BYTE;
PR$HEX: PROCEDURE( H ); /* PRINT A HEX DIGIT */
DECLARE H BYTE;
IF H < 10 THEN CALL PR$CHAR( H + '0' );
ELSE CALL PR$CHAR( ( H - 10 ) + 'A' );
END PR$HEX;
IF B >= ' ' AND B < 7FH AND B <> '$' THEN DO;
/* PRINTABLE CHAR AND NOT A $, SHOW AS A CHARACTER */
CALL PR$CHAR( B );
END;
ELSE DO;
/* NON-PRINTING CHAR OR $ - SHOW IN HEX */
CALL PR$CHAR( '$' );
CALL PR$HEX( SHR( B, 4 ) );
CALL PR$HEX( B AND 0FH );
END;
END PR$BYTE;
/* I/O USES FILE CONTROL BLOCKS CONTAINING THE FILE-NAME, POSITION, ETC. */
/* WHEN THE PROGRAM IS RUN, THE CCP WILL FIRST PARSE THE COMMAND LINE AND */
/* PUT THE FIRST PARAMETER IN FCB1, THE SECOND PARAMETER IN FCB2 */
/* BUT FCB2 OVERLAYS THE END OF FCB1 AND THE DMA BUFFER OVERLAYS THE END */
/* OF FCB2, SO WE NEED TO GET THE LINE NUMBER FROM FCB2 FIRST */
DECLARE FCB$SIZE LITERALLY '36'; /* SIZE OF A FCB */
DECLARE FCB1 LITERALLY '5CH'; /* ADDRESS OF FIRST FCB */
DECLARE FCB2 LITERALLY '6CH'; /* ADDRESS OF SECOND FCB */
DECLARE DMA$BUFFER LITERALLY '80H'; /* DEFAULT DMA BUFFER ADDRESS */
DECLARE DMA$SIZE LITERALLY '128'; /* SIZE OF THE DMA BUFFER */
DECLARE F$PTR ADDRESS, F$CHAR BASED F$PTR BYTE;
/* GET THE LINE NUMBER FROM THE SECOND PARAMETER */
DECLARE LINE$NUMBER ADDRESS;
LINE$NUMBER = 0;
DO F$PTR = FCB2 + 1 TO FCB2 + 8;
IF F$CHAR >= '0' AND F$CHAR <= '9' THEN DO;
LINE$NUMBER = ( LINE$NUMBER * 10 ) + ( F$CHAR - '0' );
END;
END;
/* CLEAR THE PARTS OF FCB1 OVERLAYED BY FCB2 */
DO F$PTR = FCB1 + 12 TO FCB1 + ( FCB$SIZE - 1 );
F$CHAR = 0;
END;
/* SHOW THE REQUIRED LINE FROM THE FILE, IF THE FILE AND LINE EXIST */
IF NOT FL$EXISTS( FCB1 ) THEN DO; /* THE FILE DOES NOT EXIST */
CALL PR$STRING( .'FILE NOT FOUND$' );CALL PR$NL;
END;
ELSE IF NOT FL$OPEN( FCB1 ) THEN DO; /* UNABLE TO OPEN THE FILE */
CALL PR$STRING( .'UNABLE TO OPEN THE FILE$' );CALL PR$NL;
END;
ELSE DO; /* FILE EXISTS AND OPENED OK - ATTEMPT TO FIND THE LINE */
DECLARE LN ADDRESS, GOT$RCD BYTE, GOT$LINE BYTE, DMA$END ADDRESS;
DMA$END = DMA$BUFFER + ( DMA$SIZE - 1 );
GOT$RCD = FL$READ( FCB1 ); /* GET THE FIRST RECORD */
GOT$LINE = FALSE;
F$PTR = DMA$BUFFER;
LN = 1;
CALL PR$NUMBER( LINE$NUMBER ); CALL PR$STRING( .': <$' );
DO WHILE( GOT$RCD AND LN <= LINE$NUMBER );
IF F$PTR > DMA$END THEN DO;
/* AT THE END OF THE BUFFER - GET THE NEXT RECORD */
GOT$RCD = FL$READ( FCB1 );
F$PTR = DMA$BUFFER;
END;
ELSE IF F$CHAR = NL$CHAR THEN DO; /* END OF LINE */
LN = LN + 1;
IF LN = LINE$NUMBER THEN GOT$LINE = TRUE;
END;
ELSE IF F$CHAR = EOF$CHAR THEN GOT$RCD = FALSE; /* END OF FILE */
ELSE IF LN = LINE$NUMBER THEN CALL PR$BYTE( F$CHAR );
F$PTR = F$PTR + 1;
END;
CALL PR$CHAR( '>' ); CALL PR$NL;
/* SHOULD NOW HAVE EOF OR THE END OF THE REQUIRED LINE */
IF NOT GOT$LINE THEN DO;
/* COULDN'T READ THE SPECIFIED LINE */
CALL PR$STRING( .'CANNOT READ LINE $' );
CALL PR$NUMBER( LINE$NUMBER );
END;
/* CLOSE THE FILE */
IF NOT FL$CLOSE( FCB1 ) THEN DO;
CALL PR$STRING( .'UNABLE TO CLOSE THE FILE$' ); CALL PR$NL;
END;
END;
CALL EXIT;
EOF
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#REXX
|
REXX
|
/*REXX program demonstrates various ways to express a string of characters or numbers.*/
a= 'This is one method of including a '' (an apostrophe) within a string.'
b= "This is one method of including a ' (an apostrophe) within a string."
/*sometimes, an apostrophe is called */
/*a quote. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
c= "This is one method of including a "" (a double quote) within a string."
d= 'This is one method of including a " (a double quote) within a string.'
/*sometimes, a double quote is also */
/*called a quote, which can make for */
/*some confusion and bewilderment. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
f= 'This is one method of expressing a long literal by concatenations, the ' || ,
'trailing character of the above clause must contain a trailing ' || ,
'comma (,) === note the embedded trailing blank in the above 2 statements.'
/*──────────────────────────────────────────────────────────────────────────────────────*/
g= 'This is another method of expressing a long literal by ' ,
"abutments, the trailing character of the above clause must " ,
'contain a trailing comma (,)'
/*──────────────────────────────────────────────────────────────────────────────────────*/
h= 'This is another method of expressing a long literal by ' , /*still continued.*/
"abutments, the trailing character of the above clause must " ,
'contain a trailing comma (,) --- in this case, the comment /* ... */ is ' ,
'essentially is not considered to be "part of" the REXX clause.'
/*──────────────────────────────────────────────────────────────────────────────────────*/
i= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109
/*This is one way to express a list of */
/*numbers that don't have a sign. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
j= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109,
71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
/*This is one way to express a long */
/*list of numbers that don't have a */
/*sign. */
/*Note that this form of continuation */
/*implies a blank is abutted to first */
/*part of the REXX statement. */
/*Also note that some REXXs have a */
/*maximum clause length. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
k= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109,
71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181
/*The J and K values are identical,*/
/*superfluous and extraneous blanks are*/
/*ignored. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
l= '-2 3 +5 7 -11 13 17 19 -23 29 -31 37 -41 43 47 -53 59 -61 67 -71 73 79 -83 89 97 -101'
/*This is one way to express a list of */
/*numbers that have a sign. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
m= a b c d f g h i j k l /*this will create a list of all the */
/*listed strings used (so far) into */
/*the variable L (with an */
/*intervening blank between each */
/*variable's value. */
|
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.
|
#AppleScript
|
AppleScript
|
on quickselect(theList, l, r, k)
script o
property lst : theList's items -- Shallow copy.
end script
repeat
-- Median-of-3 pivot selection.
set leftValue to item l of o's lst
set rightValue to item r of o's lst
set pivot to item ((l + r) div 2) of o's lst
set leftGreaterThanRight to (leftValue > rightValue)
if (leftValue > pivot) then
if (leftGreaterThanRight) then
if (rightValue > pivot) then set pivot to rightValue
else
set pivot to leftValue
end if
else if (pivot > rightValue) then
if (leftGreaterThanRight) then
set pivot to leftValue
else
set pivot to rightValue
end if
end if
-- Initialise pivot store indices and swap the already compared outer values here if necessary.
set pLeft to l - 1
set pRight to r + 1
if (leftGreaterThanRight) then
set item r of o's lst to leftValue
set item l of o's lst to rightValue
if (leftValue = pivot) then
set pRight to r
else if (rightValue = pivot) then
set pLeft to l
end if
else
if (leftValue = pivot) then set pLeft to l
if (rightValue = pivot) then set pRight to r
end if
-- Continue three-way partitioning.
set i to l + 1
set j to r - 1
repeat until (i > j)
set leftValue to item i of o's lst
repeat while (leftValue < pivot)
set i to i + 1
set leftValue to item i of o's lst
end repeat
set rightValue to item j of o's lst
repeat while (rightValue > pivot)
set j to j - 1
set rightValue to item j of o's lst
end repeat
if (j > i) then
if (leftValue = pivot) then
set pRight to pRight - 1
if (pRight > j) then
set leftValue to item pRight of o's lst
set item pRight of o's lst to pivot
end if
end if
if (rightValue = pivot) then
set pLeft to pLeft + 1
if (pLeft < i) then
set rightValue to item pLeft of o's lst
set item pLeft of o's lst to pivot
end if
end if
set item j of o's lst to leftValue
set item i of o's lst to rightValue
else if (i > j) then
exit repeat
end if
set i to i + 1
set j to j - 1
end repeat
-- Swap stored pivot(s) into a central partition.
repeat with p from l to pLeft
if (j > pLeft) then
set item p of o's lst to item j of o's lst
set item j of o's lst to pivot
set j to j - 1
else
set j to p - 1
exit repeat
end if
end repeat
repeat with p from r to pRight by -1
if (i < pRight) then
set item p of o's lst to item i of o's lst
set item i of o's lst to pivot
set i to i + 1
else
set i to p + 1
exit repeat
end if
end repeat
-- If k's in either of the outer partitions, repeat for that partition. Othewise return the item in slot k.
if (k ≥ i) then
set l to i
else if (k ≤ j) then
set r to j
else
return item k of o's lst
end if
end repeat
end quickselect
-- Task code:
set theVector to {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
set selected to {}
set vectorLength to (count theVector)
repeat with i from 1 to vectorLength
set end of selected to quickselect(theVector, 1, vectorLength, i)
end repeat
return selected
|
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.
|
#J
|
J
|
mp=: +/ .* NB. matrix product
norm=: +/&.:*: NB. vector norm
normalize=: (% norm)^:(0 < norm)
dxy=. normalize@({: - {.)
pv=. -"1 {.
NB.*perpDist v Calculate perpendicular distance of points from a line
perpDist=: norm"1@(pv ([ -"1 mp"1~ */ ]) dxy) f.
rdp=: verb define
1 rdp y
:
points=. ,:^:(2 > #@$) y
epsilon=. x
if. 2 > # points do. points return. end.
NB. point with the maximum distance from line between start and end
'imax dmax'=. ((i. , ]) >./) perpDist points
if. dmax > epsilon do.
epsilon ((}:@rdp (1+imax)&{.) , (rdp imax&}.)) points
else.
({. ,: {:) points
end.
)
|
http://rosettacode.org/wiki/Ramanujan%27s_constant
|
Ramanujan's constant
|
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
|
#Phix
|
Phix
|
without javascript_semantics -- no mpfr_exp() under p2js (yet), sorry
requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed)
include mpfr.e
mpfr_set_default_precision(-120) -- (18 before, 100 after, plus 2 for kicks.)
function q(integer d)
mpfr pi = mpfr_init()
mpfr_const_pi(pi)
mpfr t = mpfr_init(d)
mpfr_sqrt(t,t)
mpfr_mul(t,pi,t)
mpfr_exp(t,t)
return t
end function
printf(1,"Ramanujan's constant to 100 decimal places is:\n")
printf(1,"%s\n", mpfr_get_fixed(q(163),100))
sequence heegners = {{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
printf(1,"\nHeegner numbers yielding 'almost' integers:\n")
mpfr t = mpfr_init(), qh
mpz c = mpz_init()
for i=1 to length(heegners) do
integer {h0,h1} = heegners[i]
qh = q(h0)
mpz_ui_pow_ui(c,h1,3)
mpz_add_ui(c,c,744)
mpfr_set_z(t,c)
mpfr_sub(t,t,qh)
string qhs = mpfr_get_fixed(qh,32),
cs = mpz_get_str(c),
ts = mpfr_get_fixed(t,32)
printf(1,"%3d: %51s ~= %18s (diff: %s)\n", {h0, qhs, cs, ts})
end for
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "") /* use comma except before first output */
#define ol (s ? 100 : 0) /* print only if not testing for length */
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 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 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#E
|
E
|
accum [] for _ in 1..1000 { _.with(entropy.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
|
#EasyLang
|
EasyLang
|
for i range 1000
a[] &= 1 + 0.5 * sqrt (-2 * logn randomf) * cos (360 * randomf)
.
print a[]
|
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.
|
#Euler_Math_Toolbox
|
Euler Math Toolbox
|
program rosetta_random
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: num
integer, allocatable :: seed(:)
integer :: un,n, istat
call random_seed(size = n)
allocate(seed(n))
! Seed with the OS random number generator
open(newunit=un, file="/dev/urandom", access="stream", &
form="unformatted", action="read", status="old", iostat=istat)
if (istat == 0) then
read(un) seed
close(un)
end if
call random_seed (put=seed)
call random_number(num)
write(*,'(E24.16)') num
end program rosetta_random
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#Factor
|
Factor
|
program rosetta_random
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: num
integer, allocatable :: seed(:)
integer :: un,n, istat
call random_seed(size = n)
allocate(seed(n))
! Seed with the OS random number generator
open(newunit=un, file="/dev/urandom", access="stream", &
form="unformatted", action="read", status="old", iostat=istat)
if (istat == 0) then
read(un) seed
close(un)
end if
call random_seed (put=seed)
call random_number(num)
write(*,'(E24.16)') num
end program rosetta_random
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#Erlang
|
Erlang
|
-module( configuration_file ).
-export( [read/1, task/0] ).
read( File ) ->
{ok, Binary} = file:read_file( File ),
Lines = [X || <<First:8, _T/binary>> = X <- binary:split(Binary, <<"\n">>, [global]), First =/= $#, First =/= $;],
[option_from_binaries(binary:split(X, <<" ">>)) || X <- Lines].
task() ->
Defaults = [{fullname, "Kalle"}, {favouritefruit, "apple"}, {needspeeling, false}, {seedsremoved, false}],
Options = read( "configuration_file" ) ++ Defaults,
[io:fwrite("~p = ~p~n", [X, proplists:get_value(X, Options)]) || X <- [fullname, favouritefruit, needspeeling, seedsremoved, otherfamily]].
option_from_binaries( [Option] ) -> {erlang:list_to_atom(string:to_lower(erlang:binary_to_list(Option))), true};
option_from_binaries( [Option, Values] ) -> {erlang:list_to_atom(string:to_lower(erlang:binary_to_list(Option))), option_from_binaries_value(binary:split(Values, <<", ">>))}.
option_from_binaries_value( [Value] ) -> erlang:binary_to_list(Value);
option_from_binaries_value( Values ) -> [erlang:binary_to_list(X) || X <- Values].
|
http://rosettacode.org/wiki/Rare_numbers
|
Rare numbers
|
Definitions and restrictions
Rare numbers are positive integers n where:
n is expressed in base ten
r is the reverse of n (decimal digits)
n must be non-palindromic (n ≠ r)
(n+r) is the sum
(n-r) is the difference and must be positive
the sum and the difference must be perfect squares
Task
find and show the first 5 rare numbers
find and show the first 8 rare numbers (optional)
find and show more rare numbers (stretch goal)
Show all output here, on this page.
References
an OEIS entry: A035519 rare numbers.
an OEIS entry: A059755 odd rare numbers.
planetmath entry: rare numbers. (some hints)
author's website: rare numbers by Shyam Sunder Gupta. (lots of hints and some observations).
|
#Perl
|
Perl
|
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Rare_numbers
use warnings;
use integer;
my $count = 0;
my @squares;
for my $large ( 0 .. 1e5 )
{
my $largesquared = $squares[$large] = $large * $large; # $large ** 2;
for my $small ( 0 .. $large - 1 )
{
my $n = $largesquared + $squares[$small];
2 * $large * $small == reverse $n or next;
printf "%12s %s\n", $n, scalar reverse $n;
$n == reverse $n and die "oops!"; # palindrome check
++$count >= 5 and exit;
}
}
|
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
|
#Clojure
|
Clojure
|
(defn split [s sep]
(defn skipFirst [[x & xs :as s]]
(cond (empty? s) [nil nil]
(= x sep) [x xs]
true [nil s]))
(loop [lst '(), s s]
(if (empty? s) (reverse lst)
(let [[hd trunc] (skipFirst s)
[word news] (split-with #(not= % sep) trunc)
cWord (cons hd word)]
(recur (cons (apply str cWord) lst)
(apply str (rest news)))))))
(defn parseRange [[x & xs :as s]]
(if (some #(= % \-) xs)
(let [[r0 r1] (split s \-)]
(range (read-string r0) (inc (read-string r1))))
(list (read-string (str s))))))
(defn rangeexpand [s]
(flatten (map parseRange (split s \,))))
> (rangeexpand "-6,-3--1,3-5,7-11,14,15,17-20")
(-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)
|
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.
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. read-file-line-by-line.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT input-file ASSIGN TO "input.txt"
ORGANIZATION LINE SEQUENTIAL
FILE STATUS input-file-status.
DATA DIVISION.
FILE SECTION.
FD input-file.
01 input-record PIC X(256).
WORKING-STORAGE SECTION.
01 input-file-status PIC 99.
88 file-is-ok VALUE 0.
88 end-of-file VALUE 10.
01 line-count PIC 9(6).
PROCEDURE DIVISION.
OPEN INPUT input-file
IF NOT file-is-ok
DISPLAY "The file could not be opened."
GOBACK
END-IF
PERFORM VARYING line-count FROM 1 BY 1 UNTIL end-of-file
READ input-file
DISPLAY line-count ": " FUNCTION TRIM(input-record)
END-PERFORM
CLOSE input-file
GOBACK
.
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Ranking (output$, orderlist) {
Open output$ for output as #k
Gosub getdata
Print #k, "Standard ranking:"
skip=true
rankval=1
oldrank=0
For i=1 to items
Read rank, name$
if skip then
skip=false
else.if oldrank<>rank then
rankval=i
end if
oldrank=rank
Print #k, Format$("{0::-5} {2} ({1})", rankval, rank, name$)
Next
Gosub getdata
Print #k, "Modified ranking:"
skip=true
rankval=Items
oldrank=0
ShiftBack 1, -items*2 ' reverse stack items
For i=items to 1
Read name$, rank
if skip then
skip=false
else.if oldrank<>rank then
rankval=i
end if
oldrank=rank
Data Format$("{0::-5} {2} ({1})", rankval, rank, name$)
Next
ShiftBack 1, -items ' reverse stack items
For i=1 to items
Print #k, letter$
Next i
Gosub getdata
Print #k, "Dense ranking:"
skip=true
Dense=Stack
acc=1
oldrank=0
For i=1 to items
Read rank, name$
if skip then
skip=false
oldrank=rank
else.if oldrank<>rank then
oldrank=rank
Gosub dense
acc=i
end if
Stack Dense {data Format$(" {0} ({1})",name$, rank)}
Next
Gosub dense
Gosub getdata
Print #k, "Ordinal ranking:"
For i=1 to items
Print #k, Format$("{0::-5} {2} ({1})", i, Number, letter$)
Next
Gosub getdata
Print #k, "Fractional ranking:"
skip=true
Frac=Stack
acc=1
oldrank=0
For i=1 to items
Read rank, name$
if skip then
skip=false
oldrank=rank
else.if oldrank<>rank then
oldrank=rank
Gosub Fractional
acc=I
end if
Stack Frac {data Format$(" {0} ({1})",name$, rank)}
Next
Gosub Fractional
Close #k
End
Fractional:
val=((len(Frac)+1)/2+(acc-1))
Stack Frac {
while not empty
Print #k, format$("{0:1:-5}{1}", val, letter$)
end while
}
Return
dense:
Stack Dense {
while not empty
Print #k, format$("{0::-5}{1}", acc, letter$)
end while
}
Return
getdata:
flush
stack stack(orderlist) // place a copy of items to current stack
items=stack.size/2
Return
}
Flush
Data 44, "Solomon", 42, "Jason", 42, "Errol"
Data 41, "Garry", 41, "Bernard", 41, "Barry"
Data 39, "Stephen"
// get all items from current stack to a new stack
alist=[]
// To screen
Ranking "", alist
// To file
Ranking "ranking.txt", alist
|
http://rosettacode.org/wiki/Range_consolidation
|
Range consolidation
|
Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then the result is that encompassing range.
If the ranges touch or intersect then the result is one new single range covering the overlapping ranges.
Otherwise the act of consolidation is to return the two non-touching ranges.
Given N ranges where N > 2 then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.
If N < 2 then range consolidation has no strict meaning and the input can be returned.
Example 1
Given the two ranges [1, 2.5] and [3, 4.2] then
there is no common region between the ranges and the result is the same as the input.
Example 2
Given the two ranges [1, 2.5] and [1.8, 4.7] then
there is : an overlap [2.5, 1.8] between the ranges and
the result is the single range [1, 4.7].
Note that order of bounds in a range is not (yet) stated.
Example 3
Given the two ranges [6.1, 7.2] and [7.2, 8.3] then
they touch at 7.2 and
the result is the single range [6.1, 8.3].
Example 4
Given the three ranges [1, 2] and [4, 8] and [2, 5]
then there is no intersection of the ranges [1, 2] and [4, 8]
but the ranges [1, 2] and [2, 5] overlap and
consolidate to produce the range [1, 5].
This range, in turn, overlaps the other range [4, 8], and
so consolidates to the final output of the single range [1, 8].
Task
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the normalized result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
See also
Set consolidation
Set of real numbers
|
#Python
|
Python
|
def normalize(s):
return sorted(sorted(bounds) for bounds in s if bounds)
def consolidate(ranges):
norm = normalize(ranges)
for i, r1 in enumerate(norm):
if r1:
for r2 in norm[i+1:]:
if r2 and r1[-1] >= r2[0]: # intersect?
r1[:] = [r1[0], max(r1[-1], r2[-1])]
r2.clear()
return [rnge for rnge in norm if rnge]
if __name__ == '__main__':
for s in [
[[1.1, 2.2]],
[[6.1, 7.2], [7.2, 8.3]],
[[4, 3], [2, 1]],
[[4, 3], [2, 1], [-1, -2], [3.9, 10]],
[[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]],
]:
print(f"{str(s)[1:-1]} => {str(consolidate(s))[1:-1]}")
|
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
|
#OOC
|
OOC
|
main: func {
"asdf" reverse() println() // prints "fdsa"
}
|
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)
|
#jq
|
jq
|
od -t x -An /dev/urandom | tr -d " " | fold -w 8 | jq -R -f uniform.jq
|
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)
|
#Julia
|
Julia
|
const rdev = "/dev/random"
rstream = try
open(rdev, "r")
catch
false
end
if isa(rstream, IOStream)
b = readbytes(rstream, 4)
close(rstream)
i = reinterpret(Int32, b)[1]
println("A hardware random number is: ", i)
else
println("The hardware random number stream, ", rdev, ", was unavailable.")
end
|
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)
|
#Kotlin
|
Kotlin
|
// version 1.1.2
import java.security.SecureRandom
fun main(args: Array<String>) {
val rng = SecureRandom()
val rn1 = rng.nextInt()
val rn2 = rng.nextInt()
val newSeed = rn1.toLong() * rn2
rng.setSeed(newSeed) // reseed using the previous 2 random numbers
println(rng.nextInt()) // get random 32-bit number and print it
}
|
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
|
#Factor
|
Factor
|
USING: arrays combinators.extras fry io kernel math.matrices
prettyprint random sequences sets ;
IN: rosetta-code.random-latin-squares
: rand-permutation ( n -- seq ) <iota> >array randomize ;
: ls? ( n -- ? ) [ all-unique? ] column-map t [ and ] reduce ;
: (ls) ( n -- m ) dup '[ _ rand-permutation ] replicate ;
: ls ( n -- m ) dup (ls) dup ls? [ nip ] [ drop ls ] if ;
: random-latin-squares ( -- ) [ 5 ls simple-table. nl ] twice ;
MAIN: random-latin-squares
|
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
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
"time"
)
type matrix [][]int
func shuffle(row []int, n int) {
rand.Shuffle(n, func(i, j int) {
row[i], row[j] = row[j], row[i]
})
}
func latinSquare(n int) {
if n <= 0 {
fmt.Println("[]\n")
return
}
latin := make(matrix, n)
for i := 0; i < n; i++ {
latin[i] = make([]int, n)
if i == n-1 {
break
}
for j := 0; j < n; j++ {
latin[i][j] = j
}
}
// first row
shuffle(latin[0], n)
// middle row(s)
for i := 1; i < n-1; i++ {
shuffled := false
shuffling:
for !shuffled {
shuffle(latin[i], n)
for k := 0; k < i; k++ {
for j := 0; j < n; j++ {
if latin[k][j] == latin[i][j] {
continue shuffling
}
}
}
shuffled = true
}
}
// last row
for j := 0; j < n; j++ {
used := make([]bool, n)
for i := 0; i < n-1; i++ {
used[latin[i][j]] = true
}
for k := 0; k < n; k++ {
if !used[k] {
latin[n-1][j] = k
break
}
}
}
printSquare(latin, n)
}
func printSquare(latin matrix, n int) {
for i := 0; i < n; i++ {
fmt.Println(latin[i])
}
fmt.Println()
}
func main() {
rand.Seed(time.Now().UnixNano())
latinSquare(5)
latinSquare(5)
latinSquare(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 ε.)
|
#PHP
|
PHP
|
<?php
function contains($bounds, $lat, $lng)
{
$count = 0;
$bounds_count = count($bounds);
for ($b = 0; $b < $bounds_count; $b++) {
$vertex1 = $bounds[$b];
$vertex2 = $bounds[($b + 1) % $bounds_count];
if (west($vertex1, $vertex2, $lng, $lat))
$count++;
}
return $count % 2;
}
function west($A, $B, $x, $y)
{
if ($A['y'] <= $B['y']) {
if ($y <= $A['y'] || $y > $B['y'] ||
$x >= $A['x'] && $x >= $B['x']) {
return false;
}
if ($x < $A['x'] && $x < $B['x']) {
return true;
}
if ($x == $A['x']) {
if ($y == $A['y']) {
$result1 = NAN;
} else {
$result1 = INF;
}
} else {
$result1 = ($y - $A['y']) / ($x - $A['x']);
}
if ($B['x'] == $A['x']) {
if ($B['y'] == $A['y']) {
$result2 = NAN;
} else {
$result2 = INF;
}
} else {
$result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);
}
return $result1 > $result2;
}
return west($B, $A, $x, $y);
}
$square = [
'name' => 'square',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]
];
$squareHole = [
'name' => 'squareHole',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]
];
$strange = [
'name' => 'strange',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]
];
$hexagon = [
'name' => 'hexagon',
'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]
];
$shapes = [$square, $squareHole, $strange, $hexagon];
$testPoints = [
['lng' => 10, 'lat' => 10],
['lng' => 10, 'lat' => 16],
['lng' => -20, 'lat' => 10],
['lng' => 0, 'lat' => 10],
['lng' => 20, 'lat' => 10],
['lng' => 16, 'lat' => 10],
['lng' => 20, 'lat' => 20]
];
for ($s = 0; $s < count($shapes); $s++) {
$shape = $shapes[$s];
for ($tp = 0; $tp < count($testPoints); $tp++) {
$testPoint = $testPoints[$tp];
echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;
}
}
|
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.
|
#ABAP
|
ABAP
|
REPORT R NO STANDARD PAGE HEADING LINE-SIZE 67.
DATA:A(440),B,C,N(3) TYPE N,I TYPE I,S.
A+000 = 'REPORT R NO STANDARD PAGE HEADING LINE-SIZE 6\7.1DATA:A'.
A+055 = '(440),B,C,N(\3) TYPE N,I TYPE I,S.?1DO 440 TIMES.3C = A'.
A+110 = '+I.3IF B = S.5IF C CA `\\\?\1\3\5\7`.7B = C.5ELSEIF C ='.
A+165 = ' `\``.7WRITE ```` NO-GAP.5ELSE.7WRITE C NO-GAP.5ENDIF.3'.
A+220 = 'ELSEIF B = `\\`.5WRITE C NO-GAP.5B = S.3ELSEIF B = `\?`'.
A+275 = '.5DO 8 TIMES.7WRITE:/ `A+` NO-GAP,N,`= ``` NO-GAP,A+N(\'.
A+330 = '5\5) NO-GAP,```.`.7N = N + \5\5.5ENDDO.5B = C.3ELSE.5WR'.
A+385 = 'ITE AT /B C NO-GAP.5B = S.3ENDIF.3I = I + \1.1ENDDO. '.
DO 440 TIMES.
C = A+I.
IF B = S.
IF C CA '\?1357'.
B = C.
ELSEIF C = '`'.
WRITE '''' NO-GAP.
ELSE.
WRITE C NO-GAP.
ENDIF.
ELSEIF B = '\'.
WRITE C NO-GAP.
B = S.
ELSEIF B = '?'.
DO 8 TIMES.
WRITE:/ 'A+' NO-GAP,N,'= ''' NO-GAP,A+N(55) NO-GAP,'''.'.
N = N + 55.
ENDDO.
B = C.
ELSE.
WRITE AT /B C NO-GAP.
B = S.
ENDIF.
I = I + 1.
ENDDO.
|
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
|
#ALGOL_68
|
ALGOL 68
|
# -*- coding: utf-8 -*- #
MODE DIETITEM = STRUCT(
STRING food, annual quantity, units, REAL cost
);
# Stigler's 1939 Diet ... #
FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$;
[]DIETITEM stigler diet = (
("Cabbage", "111","lb.", 4.11),
("Dried Navy Beans", "285","lb.", 16.80),
("Evaporated Milk", "57","cans", 3.84),
("Spinach", "23","lb.", 1.85),
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
)
|
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
|
#App_Inventor
|
App Inventor
|
on push(StackRef, value)
set StackRef's contents to {value} & StackRef's contents
return StackRef
end push
on pop(StackRef)
set R to missing value
if StackRef's contents ≠ {} then
set R to StackRef's contents's item 1
set StackRef's contents to {} & rest of StackRef's contents
end if
return R
end pop
on isStackEmpty(StackRef)
if StackRef's contents = {} then return true
return false
end isStackEmpty
set theStack to {}
repeat with i from 1 to 5
push(a reference to theStack, i)
log result
end repeat
repeat until isStackEmpty(theStack) = true
pop(a reference to theStack)
log result
end repeat
|
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.
|
#PowerShell
|
PowerShell
|
$file = Get-Content c:\file.txt
if ($file.count -lt 7)
{Write-Warning "The file is too short!"}
else
{
$file | Where Readcount -eq 7 | set-variable -name Line7
}
|
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.
|
#PureBasic
|
PureBasic
|
Structure lineLastRead
lineRead.i
line.s
EndStructure
Procedure readNthLine(file, n, *results.lineLastRead)
*results\lineRead = 0
While *results\lineRead < n And Not Eof(file)
*results\line = ReadString(file)
*results\lineRead + 1
Wend
If *results\lineRead = n
ProcedureReturn 1
EndIf
EndProcedure
Define filename.s = OpenFileRequester("Choose file to read a line from", "*.*", "All files (*.*)|*.*", 0)
If filename
Define file = ReadFile(#PB_Any, filename)
If file
Define fileReadResults.lineLastRead, lineToRead = 7
If readNthLine(file, lineToRead, fileReadResults)
MessageRequester("Results", fileReadResults\line)
Else
MessageRequester("Error", "There are less than " + Str(lineToRead) + " lines in file.")
EndIf
CloseFile(file)
Else
MessageRequester("Error", "Couldn't open file " + filename + ".")
EndIf
EndIf
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Ring
|
Ring
|
text = list(3)
text[1] = "This is 'first' example for quoting"
text[2] = "This is second 'example' for quoting"
text[3] = "This is third example 'for' quoting"
for n = 1 to len(text)
see "text for quoting: " + nl + text[n] + nl
str = substr(text[n],"'","")
see "quoted text:" + nl + str + nl + nl
next
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Smalltalk
|
Smalltalk
|
$a
$Å
$日
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
// simple string literal
System.print("Hello world!")
// string literal including an escape sequence
System.print("Hello tabbed\tworld!")
// interpolated string literal
var w = "world"
System.print("Hello interpolated %(w)!")
// 'printf' style
Fmt.print("Hello 'printf' style $s!", w)
// more complicated interpolated string literal
var h = "Hello"
System.print("%(Fmt.s(-8, h)) more complicated interpolated %(w.map { |c| "%(c + "\%")" }.join())!")
// more complicated 'printf' style
Fmt.print("$-8s more complicated 'printf' style $s\%!", h, w.join("\%"))
// raw string literal
var r = """
Hello, raw string literal which interpets a control code such as "\n" and an
interpolation such as %(h) as verbatim text.
Single (") or dual ("") double-quotes can be included without problem.
"""
System.print(r)
|
http://rosettacode.org/wiki/Quoting_constructs
|
Quoting constructs
|
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
|
#Z80_Assembly
|
Z80 Assembly
|
MyString:
byte "Hello World",0 ;a null-terminated string
LookupTable:
byte &03,&06,&09,&0C ;a pre-defined sequence of bytes (similar in concept to enum in C)
TileGfx:
incbin "Z:\game\gfx\tilemap.bmp" ;a file containing bitmap graphics data
|
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.
|
#Arturo
|
Arturo
|
quickselect: function [a k][
arr: new a
while ø [
indx: random 0 (size arr)-1
pivot: arr\[indx]
remove 'arr .index indx
left: select arr 'item -> item<pivot
right: select arr 'item -> item>pivot
case [k]
when? [= size left]-> return pivot
when? [< size left]-> arr: new left
else [
k: (k - size left) - 1
arr: new right
]
]
]
v: [9 8 7 6 5 0 1 2 3 4]
print map 0..(size v)-1 'i ->
quickselect v i
|
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.
|
#Java
|
Java
|
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
public class LineSimplification {
private static class Point extends Pair<Double, Double> {
Point(Double key, Double value) {
super(key, value);
}
@Override
public String toString() {
return String.format("(%f, %f)", getKey(), getValue());
}
}
private static double perpendicularDistance(Point pt, Point lineStart, Point lineEnd) {
double dx = lineEnd.getKey() - lineStart.getKey();
double dy = lineEnd.getValue() - lineStart.getValue();
// Normalize
double mag = Math.hypot(dx, dy);
if (mag > 0.0) {
dx /= mag;
dy /= mag;
}
double pvx = pt.getKey() - lineStart.getKey();
double pvy = pt.getValue() - lineStart.getValue();
// Get dot product (project pv onto normalized direction)
double pvdot = dx * pvx + dy * pvy;
// Scale line direction vector and subtract it from pv
double ax = pvx - pvdot * dx;
double ay = pvy - pvdot * dy;
return Math.hypot(ax, ay);
}
private static void ramerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> out) {
if (pointList.size() < 2) throw new IllegalArgumentException("Not enough points to simplify");
// Find the point with the maximum distance from line between the start and end
double dmax = 0.0;
int index = 0;
int end = pointList.size() - 1;
for (int i = 1; i < end; ++i) {
double d = perpendicularDistance(pointList.get(i), pointList.get(0), pointList.get(end));
if (d > dmax) {
index = i;
dmax = d;
}
}
// If max distance is greater than epsilon, recursively simplify
if (dmax > epsilon) {
List<Point> recResults1 = new ArrayList<>();
List<Point> recResults2 = new ArrayList<>();
List<Point> firstLine = pointList.subList(0, index + 1);
List<Point> lastLine = pointList.subList(index, pointList.size());
ramerDouglasPeucker(firstLine, epsilon, recResults1);
ramerDouglasPeucker(lastLine, epsilon, recResults2);
// build the result list
out.addAll(recResults1.subList(0, recResults1.size() - 1));
out.addAll(recResults2);
if (out.size() < 2) throw new RuntimeException("Problem assembling output");
} else {
// Just return start and end points
out.clear();
out.add(pointList.get(0));
out.add(pointList.get(pointList.size() - 1));
}
}
public static void main(String[] args) {
List<Point> pointList = List.of(
new Point(0.0, 0.0),
new Point(1.0, 0.1),
new Point(2.0, -0.1),
new Point(3.0, 5.0),
new Point(4.0, 6.0),
new Point(5.0, 7.0),
new Point(6.0, 8.1),
new Point(7.0, 9.0),
new Point(8.0, 9.0),
new Point(9.0, 9.0)
);
List<Point> pointListOut = new ArrayList<>();
ramerDouglasPeucker(pointList, 1.0, pointListOut);
System.out.println("Points remaining after simplification:");
pointListOut.forEach(System.out::println);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.