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/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 ε.)
|
#Haskell
|
Haskell
|
import Data.Ratio
type Point = (Rational, Rational)
type Polygon = [Point]
data Line = Sloped {lineSlope, lineYIntercept :: Rational} |
Vert {lineXIntercept :: Rational}
polygonSides :: Polygon -> [(Point, Point)]
polygonSides poly@(p1 : ps) = zip poly $ ps ++ [p1]
intersects :: Point -> Line -> Bool
{- @intersects (px, py) l@ is true if the ray {(x, py) | x ≥ px}
intersects l. -}
intersects (px, _) (Vert xint) = px <= xint
intersects (px, py) (Sloped m b) | m < 0 = py <= m * px + b
| otherwise = py >= m * px + b
onLine :: Point -> Line -> Bool
{- Is the point on the line? -}
onLine (px, _) (Vert xint) = px == xint
onLine (px, py) (Sloped m b) = py == m * px + b
carrier :: (Point, Point) -> Line
{- Finds the line containing the given line segment. -}
carrier ((ax, ay), (bx, by)) | ax == bx = Vert ax
| otherwise = Sloped slope yint
where slope = (ay - by) / (ax - bx)
yint = ay - slope * ax
between :: Ord a => a -> a -> a -> Bool
between x a b | a > b = b <= x && x <= a
| otherwise = a <= x && x <= b
inPolygon :: Point -> Polygon -> Bool
inPolygon p@(px, py) = f 0 . polygonSides
where f n [] = odd n
f n (side : sides) | far = f n sides
| onSegment = True
| rayIntersects = f (n + 1) sides
| otherwise = f n sides
where far = not $ between py ay by
onSegment | ay == by = between px ax bx
| otherwise = p `onLine` line
rayIntersects =
intersects p line &&
(py /= ay || by < py) &&
(py /= by || ay < py)
((ax, ay), (bx, by)) = side
line = carrier side
|
http://rosettacode.org/wiki/Random_sentence_from_book
|
Random sentence from book
|
Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep account of what words follow two words and how many times it is seen, (again treating sentence terminators as words too).
Assume that a sentence starts with a not to be shown full-stop character then use a weighted random choice of the possible words that may follow a full-stop to add to the sentence.
Then repeatedly add words to the sentence based on weighted random choices of what words my follow the last two words to extend the sentence.
Stop after adding a sentence ending punctuation character.
Tidy and then print the sentence.
Show examples of random sentences generated.
Related task
Markov_chain_text_generator
|
#Phix
|
Phix
|
-- demo/rosetta/RandomSentence.exw
include builtins\libcurl.e
constant url = "http://www.gutenberg.org/files/36/36-0.txt",
filename = "war_of_the_worlds.txt",
fsent = "No one would have believed",
lasts = "End of the Project Gutenberg EBook",
unicodes = {utf32_to_utf8({#2019}), -- rsquo
utf32_to_utf8({#2014})}, -- hyphen
asciis = {"'","-"},
aleph = tagset('Z','A')&tagset('z','a')&tagset('9','0')&",'.?! ",
follow = new_dict(), -- {word} -> {words,counts}
follow2 = new_dict() -- {word,word} -> {words,counts}
if not file_exists(filename) then
printf(1,"Downloading %s...\n",{filename})
CURLcode res = curl_easy_get_file(url,"",filename)
if res!=CURLE_OK then crash("cannot download") end if
end if
string text = get_text(filename)
text = text[match(fsent,text)..match(lasts,text)-1]
text = substitute_all(text,unicodes,asciis)
text = substitute_all(text,".?!-\n",{" ."," ? "," ! "," "," "})
text = filter(text,"in",aleph)
sequence words = split(text)
procedure account(sequence words)
string next = words[$]
words = words[1..$-1]
for i=length(words) to 1 by -1 do
integer d = {follow,follow2}[i]
sequence t = getdd(words,{{},{}},d)
integer tk = find(next,t[1])
if tk=0 then
t[1] = append(t[1],next)
t[2] = append(t[2],1)
else
t[2][tk] += 1
end if
setd(words,t,d)
words = words[2..$]
if words!={"."} then exit end if -- (may as well quit)
end for
end procedure
for i=2 to length(words) do
if find(words[i],{".","?","!"})
and i<length(words) then
words[i+1] = lower(words[i+1])
end if
account(words[max(1,i-2)..i])
end for
function weighted_random_pick(sequence words, integer dict)
sequence t = getd(words,dict)
integer total = sum(t[2]),
r = rand(total)
for i=1 to length(t[2]) do
r -= t[2][i]
if r<=0 then
return t[1][i]
end if
end for
end function
for i=1 to 5 do
sequence sentence = {".",weighted_random_pick({"."},follow)}
while true do
string next = weighted_random_pick(sentence[-2..-1],follow2)
sentence = append(sentence,next)
if find(next,{".","?","!"}) then exit end if
end while
sentence[2][1] = upper(sentence[2][1])
printf(1,"%s\n",{join(sentence[2..$-1])&sentence[$]})
end for
{} = wait_key()
|
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.
|
#Lua
|
Lua
|
function fileLine (lineNum, fileName)
local count = 0
for line in io.lines(fileName) do
count = count + 1
if count == lineNum then return line end
end
error(fileName .. " has fewer than " .. lineNum .. " lines.")
end
print(fileLine(7, "test.txt"))
|
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
|
#BBC_BASIC
|
BBC BASIC
|
BOOL = 1
NAME = 2
ARRAY = 3
optfile$ = "options.cfg"
fullname$ = FNoption(optfile$, "FULLNAME", NAME)
favouritefruit$ = FNoption(optfile$, "FAVOURITEFRUIT", NAME)
needspeeling% = FNoption(optfile$, "NEEDSPEELING", BOOL)
seedsremoved% = FNoption(optfile$, "SEEDSREMOVED", BOOL)
!^otherfamily$() = FNoption(optfile$, "OTHERFAMILY", ARRAY)
PRINT "fullname = " fullname$
PRINT "favouritefruit = " favouritefruit$
PRINT "needspeeling = "; : IF needspeeling% PRINT "true" ELSE PRINT "false"
PRINT "seedsremoved = "; : IF seedsremoved% PRINT "true" ELSE PRINT "false"
PRINT "otherfamily(1) = " otherfamily$(1)
PRINT "otherfamily(2) = " otherfamily$(2)
END
DEF FNoption(file$, key$, type%)
LOCAL file%, opt$, comma%, bool%, name$, size%, !^array$()
file% = OPENIN(file$)
IF file% = 0 THEN = 0
WHILE NOT EOF#file%
opt$ = GET$#file%
WHILE RIGHT$(opt$) = " " opt$ = LEFT$(opt$) : ENDWHILE
IF opt$ = key$ OR LEFT$(opt$, LEN(key$)+1) = key$ + " " THEN
opt$ = MID$(opt$, LEN(key$) + 1)
WHILE LEFT$(opt$,1) = " " opt$ = MID$(opt$,2) : ENDWHILE
CASE type% OF
WHEN BOOL: bool% = TRUE : EXIT WHILE
WHEN NAME: name$ = opt$ : EXIT WHILE
WHEN ARRAY:
REPEAT
comma% = INSTR(opt$, ",", comma%+1)
IF comma% size% += 1
UNTIL comma% = 0
DIM array$(size% + 1)
size% = 0
REPEAT
comma% = INSTR(opt$, ",")
IF comma% THEN
size% += 1
array$(size%) = LEFT$(opt$, comma%-1)
opt$ = MID$(opt$, comma%+1)
WHILE LEFT$(opt$,1) = " " opt$ = MID$(opt$,2) : ENDWHILE
ENDIF
UNTIL comma% = 0
array$(size% + 1) = opt$
EXIT WHILE
ENDCASE
ENDIF
ENDWHILE
CLOSE #file%
CASE type% OF
WHEN BOOL: = bool%
WHEN NAME: = name$
WHEN ARRAY: = !^array$()
ENDCASE
= 0
|
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).
|
#D
|
D
|
import std.algorithm;
import std.array;
import std.conv;
import std.datetime.stopwatch;
import std.math;
import std.stdio;
struct Term {
ulong coeff;
byte ix1, ix2;
}
enum maxDigits = 16;
ulong toUlong(byte[] digits, bool reverse) {
ulong sum = 0;
if (reverse) {
for (int i = digits.length - 1; i >= 0; --i) {
sum = sum * 10 + digits[i];
}
} else {
for (size_t i = 0; i < digits.length; ++i) {
sum = sum * 10 + digits[i];
}
}
return sum;
}
bool isSquare(ulong n) {
if ((0x202021202030213 & (1 << (n & 63))) != 0) {
auto root = cast(ulong)sqrt(cast(double)n);
return root * root == n;
}
return false;
}
byte[] seq(byte from, byte to, byte step) {
byte[] res;
for (auto i = from; i <= to; i += step) {
res ~= i;
}
return res;
}
string commatize(ulong n) {
auto s = n.to!string;
auto le = s.length;
for (int i = le - 3; i >= 1; i -= 3) {
s = s[0..i] ~ "," ~ s[i..$];
}
return s;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
ulong pow = 1;
writeln("Aggregate timings to process all numbers up to:");
// terms of (n-r) expression for number of digits from 2 to maxDigits
Term[][] allTerms = uninitializedArray!(Term[][])(maxDigits - 1);
for (auto r = 2; r <= maxDigits; r++) {
Term[] terms;
pow *= 10;
ulong pow1 = pow;
ulong pow2 = 1;
byte i1 = 0;
byte i2 = cast(byte)(r - 1);
while (i1 < i2) {
terms ~= Term(pow1 - pow2, i1, i2);
pow1 /= 10;
pow2 *= 10;
i1++;
i2--;
}
allTerms[r - 2] = terms;
}
// map of first minus last digits for 'n' to pairs giving this value
byte[][][byte] fml = [
0: [[2, 2], [8, 8]],
1: [[6, 5], [8, 7]],
4: [[4, 0]],
6: [[6, 0], [8, 2]]
];
// map of other digit differences for 'n' to pairs giving this value
byte[][][byte] dmd;
for (byte i = 0; i < 100; i++) {
byte[] a = [i / 10, i % 10];
auto d = a[0] - a[1];
dmd[cast(byte)d] ~= a;
}
byte[] fl = [0, 1, 4, 6];
auto dl = seq(-9, 9, 1); // all differences
byte[] zl = [0]; // zero diferences only
auto el = seq(-8, 8, 2); // even differences only
auto ol = seq(-9, 9, 2); // odd differences only
auto il = seq(0, 9, 1);
ulong[] rares;
byte[][][] lists = uninitializedArray!(byte[][][])(4);
foreach (i, f; fl) {
lists[i] = [[f]];
}
byte[] digits;
int count = 0;
// Recursive closure to generate (n+r) candidates from (n-r) candidates
// and hence find Rare numbers with a given number of digits.
void fnpr(byte[] cand, byte[] di, byte[][] dis, byte[][] indicies, ulong nmr, int nd, int level) {
if (level == dis.length) {
digits[indicies[0][0]] = fml[cand[0]][di[0]][0];
digits[indicies[0][1]] = fml[cand[0]][di[0]][1];
auto le = di.length;
if (nd % 2 == 1) {
le--;
digits[nd / 2] = di[le];
}
foreach (i, d; di[1..le]) {
digits[indicies[i + 1][0]] = dmd[cand[i + 1]][d][0];
digits[indicies[i + 1][1]] = dmd[cand[i + 1]][d][1];
}
auto r = toUlong(digits, true);
auto npr = nmr + 2 * r;
if (!isSquare(npr)) {
return;
}
count++;
writef(" R/N %2d:", count);
auto ms = sw.peek();
writef(" %9s", ms);
auto n = toUlong(digits, false);
writef(" (%s)\n", commatize(n));
rares ~= n;
} else {
foreach (num; dis[level]) {
di[level] = num;
fnpr(cand, di, dis, indicies, nmr, nd, level + 1);
}
}
}
// Recursive closure to generate (n-r) candidates with a given number of digits.
void fnmr(byte[] cand, byte[][] list, byte[][] indicies, int nd, int level) {
if (level == list.length) {
ulong nmr, nmr2;
foreach (i, t; allTerms[nd - 2]) {
if (cand[i] >= 0) {
nmr += t.coeff * cand[i];
} else {
nmr2 += t.coeff * -cast(int)(cand[i]);
if (nmr >= nmr2) {
nmr -= nmr2;
nmr2 = 0;
} else {
nmr2 -= nmr;
nmr = 0;
}
}
}
if (nmr2 >= nmr) {
return;
}
nmr -= nmr2;
if (!isSquare(nmr)) {
return;
}
byte[][] dis;
dis ~= seq(0, cast(byte)(fml[cand[0]].length - 1), 1);
for (auto i = 1; i < cand.length; i++) {
dis ~= seq(0, cast(byte)(dmd[cand[i]].length - 1), 1);
}
if (nd % 2 == 1) {
dis ~= il;
}
byte[] di = uninitializedArray!(byte[])(dis.length);
fnpr(cand, di, dis, indicies, nmr, nd, 0);
} else {
foreach (num; list[level]) {
cand[level] = num;
fnmr(cand, list, indicies, nd, level + 1);
}
}
}
for (int nd = 2; nd <= maxDigits; nd++) {
digits = uninitializedArray!(byte[])(nd);
if (nd == 4) {
lists[0] ~= zl;
lists[1] ~= ol;
lists[2] ~= el;
lists[3] ~= ol;
} else if (allTerms[nd - 2].length > lists[0].length) {
for (int i = 0; i < 4; i++) {
lists[i] ~= dl;
}
}
byte[][] indicies;
foreach (t; allTerms[nd - 2]) {
indicies ~= [t.ix1, t.ix2];
}
foreach (list; lists) {
byte[] cand = uninitializedArray!(byte[])(list.length);
fnmr(cand, list, indicies, nd, 0);
}
auto ms = sw.peek();
writefln(" %2d digits: %9s", nd, ms);
}
rares.sort;
writefln("\nThe rare numbers with up to %d digits are:", maxDigits);
foreach (i, rare; rares) {
writefln(" %2d: %25s", i + 1, commatize(rare));
}
}
|
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
|
#Action.21
|
Action!
|
BYTE FUNC Find(CHAR ARRAY text CHAR c BYTE start)
BYTE i
i=start
WHILE i<=text(0)
DO
IF text(i)=c THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
PROC ProcessItem(CHAR ARRAY text INT ARRAY res INT POINTER size)
BYTE pos
INT start,end,i
CHAR ARRAY tmp(200)
pos=Find(text,'-,2)
IF pos=0 THEN
res(size^)=ValI(text)
size^==+1
ELSE
SCopyS(tmp,text,1,pos-1)
start=ValI(tmp)
SCopyS(tmp,text,pos+1,text(0))
end=ValI(tmp)
FOR i=start TO end
DO
res(size^)=i
size^==+1
OD
FI
RETURN
PROC RangeExtraction(CHAR ARRAY text INT ARRAY res INT POINTER size)
BYTE i,pos
CHAR ARRAY tmp(200)
i=1 size^=0
WHILE i<=text(0)
DO
pos=Find(text,',,i)
IF pos=0 THEN
SCopyS(tmp,text,i,text(0))
i=text(0)+1
ELSE
SCopyS(tmp,text,i,pos-1)
i=pos+1
FI
ProcessItem(tmp,res,size)
OD
RETURN
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC Main()
INT ARRAY res(100)
INT size
RangeExtraction("-6,-3--1,3-5,7-11,14,15,17-20",res,@size)
PrintArray(res,size)
RETURN
|
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.
|
#ALGOL_68
|
ALGOL 68
|
#!/usr/local/bin/a68g --script #
FILE foobar;
INT errno = open(foobar, "Read_a_file_line_by_line.a68", stand in channel);
STRING line;
FORMAT line fmt = $gl$;
PROC mount next tape = (REF FILE file)BOOL: (
print("Please mount next tape or q to quit");
IF read char = "q" THEN done ELSE TRUE FI
);
on physical file end(foobar, mount next tape);
on logical file end(foobar, (REF FILE skip)BOOL: done);
FOR count DO
getf(foobar, (line fmt, line));
printf(($g(0)": "$, count, line fmt, line))
OD;
done: SKIP
|
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.
|
#Factor
|
Factor
|
USING: arrays assocs formatting fry generalizations io kernel
math math.ranges math.statistics math.vectors sequences
splitting.monotonic ;
IN: rosetta-code.ranking
CONSTANT: ranks {
{ 44 "Solomon" } { 42 "Jason" } { 42 "Errol" }
{ 41 "Garry" } { 41 "Bernard" } { 41 "Barry" }
{ 39 "Stephen" }
}
: rank ( seq quot -- seq' )
'[ [ = ] monotonic-split [ length ] map dup @ [ <array> ]
2map concat ] call ; inline
: standard ( seq -- seq' ) [ cum-sum0 1 v+n ] rank ;
: modified ( seq -- seq' ) [ cum-sum ] rank ;
: dense ( seq -- seq' ) [ length [1,b] ] rank ;
: ordinal ( seq -- seq' ) length [1,b] ;
: fractional ( seq -- seq' )
[ dup cum-sum swap [ dupd - [a,b) mean ] 2map ] rank ;
: .rank ( quot -- )
[ ranks dup keys ] dip call swap
[ first2 "%5u %d %s\n" printf ] 2each ; inline
: ranking-demo ( -- )
"Standard ranking" [ standard ]
"Modified ranking" [ modified ]
"Dense ranking" [ dense ]
"Ordinal ranking" [ ordinal ]
"Fractional ranking" [ fractional ]
[ [ print ] [ .rank nl ] bi* ] 2 5 mnapply ;
MAIN: ranking-demo
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
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
Given an Array, derive a sequence of elements in which all duplicates are removed.
There are basically three approaches seen here:
Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
|
#XPL0
|
XPL0
|
code Text=12; \built-in routine to display a string of characters
string 0; \use zero-terminated strings (not MSb terminated)
func StrLen(S); \Return number of characters in an ASCIIZ string
char S;
int I;
for I:= 0, -1>>1-1 do \(limit = 2,147,483,646 if 32 bit, or 32766 if 16 bit)
if S(I) = 0 then return I;
func Unique(S); \Remove duplicate bytes from string
char S;
int I, J, K, L;
[L:= StrLen(S); \string length
for I:= 0 to L-1 do \for all characters in string...
for J:= I+1 to L-1 do \scan rest of string for duplicates
if S(I) = S(J) then \if duplicate then
[for K:= J+1 to L do \ shift rest of string down (including
S(K-1):= S(K); \ terminating zero)
L:= L-1 \ string is now one character shorter
];
return S; \return pointer to string
];
Text(0, Unique("Pack my box with five dozen liquor jugs."))
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
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
Given an Array, derive a sequence of elements in which all duplicates are removed.
There are basically three approaches seen here:
Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
|
#Yabasic
|
Yabasic
|
data "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "the", "party.", ""
do
read p$
if p$ = "" break
if not instr(r$, p$) r$ = r$ + p$ + " "
loop
print r$
|
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
|
#Factor
|
Factor
|
USING: arrays combinators formatting kernel math.combinatorics
math.order math.statistics sequences sets sorting ;
: overlaps? ( pair pair -- ? )
2dup swap [ [ first2 between? ] curry any? ] 2bi@ or ;
: merge ( seq -- newseq ) concat minmax 2array 1array ;
: merge1 ( seq -- newseq )
dup 2 [ first2 overlaps? ] find-combination
[ [ without ] keep merge append ] when* ;
: normalize ( seq -- newseq ) [ natural-sort ] map ;
: consolidate ( seq -- newseq )
normalize [ merge1 ] to-fixed-point natural-sort ;
{
{ { 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 } }
} [ dup consolidate "%49u => %u\n" printf ] each
|
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
|
#FreeBASIC
|
FreeBASIC
|
Dim Shared As Integer i
Dim Shared As Single items, temp = 10^30
Sub ordenar(tabla() As Single)
Dim As Integer t1, t2
Dim As Boolean s
Do
s = True
For i = 1 To Ubound(tabla)-1
If tabla(i, 1) > tabla(i+1, 1) Then
t1 = tabla(i, 1) : t2 = tabla(i, 2)
tabla(i, 1) = tabla(i + 1, 1) : tabla(i, 2) = tabla(i + 1, 2)
tabla(i + 1, 1) = t1 : tabla(i + 1, 2) = t2
s = False
End If
Next i
Loop Until(s)
End Sub
Sub normalizar(tabla() As Single)
Dim As Integer t
For i = 1 To Ubound(tabla)
If tabla(i, 1) > tabla(i, 2) Then
t = tabla(i, 1)
tabla(i, 1) = tabla(i, 2)
tabla(i, 2) = t
End If
Next i
ordenar(tabla())
End Sub
Sub consolidar(tabla() As Single)
normalizar(tabla())
For i = 1 To Ubound(tabla)-1
If tabla(i + 1, 1) <= tabla(i, 2) Then
tabla(i + 1, 1) = tabla(i, 1)
If tabla(i + 1, 2) <= tabla(i, 2) Then
tabla(i + 1, 2) = tabla(i, 2)
End If
tabla(i, 1) = temp : tabla(i, 2) = temp
End If
Next i
End Sub
Data 1, 1.1, 2.2
Data 2, 6.1, 7.2, 7.2, 8.3
Data 2, 4, 3, 2, 1
Data 4, 4, 3, 2, 1, -1, -2, 3.9, 10
Data 5, 1,3, -6,-1, -4,-5, 8,2, -6,-6
For j As Byte = 1 To 5
Read items
Dim As Single tabla(items, 2)
For i = 1 To items
Read tabla(i, 1), tabla(i, 2)
Next i
consolidar(tabla())
For i = 1 To items
If tabla(i, 1) <> temp Then Print "[";tabla(i, 1); ", "; tabla(i, 2); "] ";
Next i
Print
Next j
Sleep
|
http://rosettacode.org/wiki/Rate_counter
|
Rate counter
|
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth of jobs and/or Y jobs.
Report at least three distinct times.
Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.
See also: System time, Time a function
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int N, I, T0, Time;
[for N:= 1, 3 do
[T0:= GetTime;
for I:= 1 to 100 do
[while port($3DA) & $08 do []; \wait for vertical retrace to go away
repeat until port($3DA) & $08; \wait for vertical retrace signal
];
Time:= GetTime - T0;
IntOut(0, Time); Text(0, " microseconds for 100 samples = ");
RlOut(0, 100.0e6/float(Time)); Text(0, "Hz"); CrLf(0);
];
]
|
http://rosettacode.org/wiki/Rate_counter
|
Rate counter
|
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth of jobs and/or Y jobs.
Report at least three distinct times.
Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.
See also: System time, Time a function
|
#Yabasic
|
Yabasic
|
iterations = 100000
for j = 2 to 4
a = peek("millisrunning")
for i = 1 to iterations
void = i + j^2
next
dif = peek("millisrunning") - a
print "take ", dif, " ms";
print " or ", iterations / dif * 1000 using "########", " sums per second"
next
|
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
|
#NewLISP
|
NewLISP
|
(reverse "!dlroW olleH")
|
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 ε.)
|
#J
|
J
|
NB.*crossPnP v point in closed polygon, crossing number
NB. bool=. points crossPnP polygon
crossPnP=: 4 : 0"2
'X Y'=. |:x
'x0 y0 x1 y1'=. |:2 ,/\^:(2={:@$@]) y
p1=. ((y0<:/Y)*. y1>/Y) +. (y0>/Y)*. y1<:/Y
p2=. (x0-/X) < (x0-x1) * (y0-/Y) % (y0 - y1)
2|+/ p1*.p2
)
|
http://rosettacode.org/wiki/Random_sentence_from_book
|
Random sentence from book
|
Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep account of what words follow two words and how many times it is seen, (again treating sentence terminators as words too).
Assume that a sentence starts with a not to be shown full-stop character then use a weighted random choice of the possible words that may follow a full-stop to add to the sentence.
Then repeatedly add words to the sentence based on weighted random choices of what words my follow the last two words to extend the sentence.
Stop after adding a sentence ending punctuation character.
Tidy and then print the sentence.
Show examples of random sentences generated.
Related task
Markov_chain_text_generator
|
#Python
|
Python
|
from urllib.request import urlopen
import re
from string import punctuation
from collections import Counter, defaultdict
import random
# The War of the Worlds, by H. G. Wells
text_url = 'http://www.gutenberg.org/files/36/36-0.txt'
text_start = 'No one would have believed'
sentence_ending = '.!?'
sentence_pausing = ',;:'
def read_book(text_url, text_start) -> str:
with urlopen(text_url) as book:
text = book.read().decode('utf-8')
return text[text.index(text_start):]
def remove_punctuation(text: str, keep=sentence_ending+sentence_pausing)-> str:
"Remove punctuation, keeping some"
to_remove = ''.join(set(punctuation) - set(keep))
text = text.translate(str.maketrans(to_remove, ' ' * len(to_remove))).strip()
text = re.sub(fr"[^a-zA-Z0-9{keep}\n ]+", ' ', text)
# Remove duplicates and put space around remaining punctuation
if keep:
text = re.sub(f"([{keep}])+", r" \1 ", text).strip()
if text[-1] not in sentence_ending:
text += ' .'
return text.lower()
def word_follows_words(txt_with_pauses_and_endings):
"return dict of freq of words following one/two words"
words = ['.'] + txt_with_pauses_and_endings.strip().split()
# count of what word follows this
word2next = defaultdict(lambda :defaultdict(int))
word2next2 = defaultdict(lambda :defaultdict(int))
for lh, rh in zip(words, words[1:]):
word2next[lh][rh] += 1
for lh, mid, rh in zip(words, words[1:], words[2:]):
word2next2[(lh, mid)][rh] += 1
return dict(word2next), dict(word2next2)
def gen_sentence(word2next, word2next2) -> str:
s = ['.']
s += random.choices(*zip(*word2next[s[-1]].items()))
while True:
s += random.choices(*zip(*word2next2[(s[-2], s[-1])].items()))
if s[-1] in sentence_ending:
break
s = ' '.join(s[1:]).capitalize()
s = re.sub(fr" ([{sentence_ending+sentence_pausing}])", r'\1', s)
s = re.sub(r" re\b", "'re", s)
s = re.sub(r" s\b", "'s", s)
s = re.sub(r"\bi\b", "I", s)
return s
if __name__ == "__main__":
txt_with_pauses_and_endings = remove_punctuation(read_book(text_url, text_start))
word2next, word2next2 = word_follows_words(txt_with_pauses_and_endings)
#%%
sentence = gen_sentence(word2next, word2next2)
print(sentence)
|
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.
|
#Maple
|
Maple
|
path := "file.txt":
specificLine := proc(path, num)
local i, input:
for i to num do
input := readline(path):
if input = 0 then break; end if:
end do:
if i = num+1 then printf("Line %d, %s", num, input):
elif i <= num then printf ("Line number %d is not reached",num): end if:
end proc:
|
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]
|
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
|
#11l
|
11l
|
F range_extract(lst)
[[Int]] r
V lenlst = lst.len
V i = 0
L i < lenlst
V low = lst[i]
L i < lenlst - 1 & lst[i] + 1 == lst[i + 1]
i++
V hi = lst[i]
I hi - low >= 2
r [+]= [low, hi]
E I hi - low == 1
r [+]= [low]
r [+]= [hi]
E
r [+]= [low]
i++
R r
F printr(ranges)
print(ranges.map(r -> (I r.len == 2 {r[0]‘-’r[1]} E String(r[0]))).join(‘,’))
L(lst) [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[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]]
printr(range_extract(lst))
|
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
|
#Ada
|
Ada
|
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Normal_Random is
function Normal_Distribution
( Seed : Generator;
Mu : Float := 1.0;
Sigma : Float := 0.5
) return Float is
begin
return
Mu + (Sigma * Sqrt (-2.0 * Log (Random (Seed), 10.0)) * Cos (2.0 * Pi * Random (Seed)));
end Normal_Distribution;
Seed : Generator;
Distribution : array (1..1_000) of Float;
begin
Reset (Seed);
for I in Distribution'Range loop
Distribution (I) := Normal_Distribution (Seed);
end loop;
end Normal_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.
|
#11l
|
11l
|
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a :=
¢ the next pseudo-random ℒ integral value after 'a' from a
uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;
¢ the real value corresponding to 'a' according to some mapping of
integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1)
i.e. such that -0 <= x < 1 such that the sequence of real
values so produced preserves the properties of pseudo-randomness
and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #;
PROC ℒ random = ℒ REAL: ℒ next random(ℒ last 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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <confini.h>
#define rosetta_uint8_t unsigned char
#define FALSE 0
#define TRUE 1
#define CONFIGS_TO_READ 5
#define INI_ARRAY_DELIMITER ','
/* Assume that the config file represent a struct containing all the parameters to load */
struct configs {
char *fullname;
char *favouritefruit;
rosetta_uint8_t needspeeling;
rosetta_uint8_t seedsremoved;
char **otherfamily;
size_t otherfamily_len;
size_t _configs_left_;
};
static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {
/* Allocate a new array of strings and populate it from the stringified source */
*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);
char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;
if (!dest) { return NULL; }
memcpy(dest + *arrlen, src, buffsize);
char * iter = (char *) (dest + *arrlen);
for (size_t idx = 0; idx < *arrlen; idx++) {
dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);
ini_string_parse(dest[idx], ini_format);
}
return dest;
}
static int configs_member_handler (IniDispatch *this, void *v_confs) {
struct configs *confs = (struct configs *) v_confs;
if (this->type != INI_KEY) {
return 0;
}
if (ini_string_match_si("FULLNAME", this->data, this->format)) {
if (confs->fullname) { return 0; }
this->v_len = ini_string_parse(this->value, this->format); /* Remove all quotes, if any */
confs->fullname = strndup(this->value, this->v_len);
confs->_configs_left_--;
} else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) {
if (confs->favouritefruit) { return 0; }
this->v_len = ini_string_parse(this->value, this->format); /* Remove all quotes, if any */
confs->favouritefruit = strndup(this->value, this->v_len);
confs->_configs_left_--;
} else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) {
if (~confs->needspeeling & 0x80) { return 0; }
confs->needspeeling = ini_get_bool(this->value, TRUE);
confs->_configs_left_--;
} else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) {
if (~confs->seedsremoved & 0x80) { return 0; }
confs->seedsremoved = ini_get_bool(this->value, TRUE);
confs->_configs_left_--;
} else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) {
if (confs->otherfamily) { return 0; }
this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); /* Save memory (not strictly needed) */
confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);
confs->_configs_left_--;
}
/* Optimization: stop reading the INI file when we have all we need */
return !confs->_configs_left_;
}
static int populate_configs (struct configs * confs) {
/* Define the format of the configuration file */
IniFormat config_format = {
.delimiter_symbol = INI_ANY_SPACE,
.case_sensitive = FALSE,
.semicolon_marker = INI_IGNORE,
.hash_marker = INI_IGNORE,
.multiline_nodes = INI_NO_MULTILINE,
.section_paths = INI_NO_SECTIONS,
.no_single_quotes = FALSE,
.no_double_quotes = FALSE,
.no_spaces_in_names = TRUE,
.implicit_is_not_empty = TRUE,
.do_not_collapse_values = FALSE,
.preserve_empty_quotes = FALSE,
.disabled_after_space = TRUE,
.disabled_can_be_implicit = FALSE
};
*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };
if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {
fprintf(stderr, "Sorry, something went wrong :-(\n");
return 1;
}
confs->needspeeling &= 0x7F;
confs->seedsremoved &= 0x7F;
return 0;
}
int main () {
struct configs confs;
ini_global_set_implicit_value("YES", 0);
if (populate_configs(&confs)) {
return 1;
}
/* Print the configurations parsed */
printf(
"Full name: %s\n"
"Favorite fruit: %s\n"
"Need spelling: %s\n"
"Seeds removed: %s\n",
confs.fullname,
confs.favouritefruit,
confs.needspeeling ? "True" : "False",
confs.seedsremoved ? "True" : "False"
);
for (size_t idx = 0; idx < confs.otherfamily_len; idx++) {
printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]);
}
/* Free the allocated memory */
#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }
FREE_NON_NULL(confs.fullname);
FREE_NON_NULL(confs.favouritefruit);
FREE_NON_NULL(confs.otherfamily);
return 0;
}
|
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).
|
#F.23
|
F#
|
// Find all Rare numbers with a digits. Nigel Galloway: September 18th., 2019.
let rareNums a=
let tN=set[1L;4L;5L;6L;9L]
let izPS g=let n=(float>>sqrt>>int64)g in n*n=g
let n=[for n in [0..a/2-1] do yield ((pown 10L (a-n-1))-(pown 10L n))]|>List.rev
let rec fN i g e=seq{match e with 0->yield g |e->for n in i do yield! fN [-9L..9L] (n::g) (e-1)}|>Seq.filter(fun g->let g=Seq.map2(*) n g|>Seq.sum in g>0L && izPS g)
let rec fG n i g e l=seq{
match l with
h::t->for l in max 0L (0L-h)..min 9L (9L-h) do if e>1L||l=0L||tN.Contains((2L*l+h)%10L) then yield! fG (n+l*e+(l+h)*g) (i+l*g+(l+h)*e) (g/10L) (e*10L) t
|_->if n>(pown 10L (a-1)) then for l in (if a%2=0 then [0L] else [0L..9L]) do let g=l*(pown 10L (a/2)) in if izPS (n+i+2L*g) then yield (i+g,n+g)}
fN [0L..9L] [] (a/2) |> Seq.collect(List.rev >> fG 0L 0L (pown 10L (a-1)) 1L)
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Range_Expansion is
type Sequence is array (Positive range <>) of Integer;
function Expand (Text : String) return Sequence is
To : Integer := Text'First;
Count : Natural := 0;
Low : Integer;
function Get return Integer is
From : Integer := To;
begin
if Text (To) = '-' then
To := To + 1;
end if;
while To <= Text'Last loop
case Text (To) is
when ',' | '-' => exit;
when others => To := To + 1;
end case;
end loop;
return Integer'Value (Text (From..To - 1));
end Get;
begin
while To <= Text'Last loop -- Counting items of the list
Low := Get;
if To > Text'Last or else Text (To) = ',' then
Count := Count + 1;
else
To := To + 1;
Count := Count + Get - Low + 1;
end if;
To := To + 1;
end loop;
return Result : Sequence (1..Count) do
Count := 0;
To := Text'First;
while To <= Text'Last loop -- Filling the list
Low := Get;
if To > Text'Last or else Text (To) = ',' then
Count := Count + 1;
Result (Count) := Low;
else
To := To + 1;
for Item in Low..Get loop
Count := Count + 1;
Result (Count) := Item;
end loop;
end if;
To := To + 1;
end loop;
end return;
end Expand;
procedure Put (S : Sequence) is
First : Boolean := True;
begin
for I in S'Range loop
if First then
First := False;
else
Put (',');
end if;
Put (Integer'Image (S (I)));
end loop;
end Put;
begin
Put (Expand ("-6,-3--1,3-5,7-11,14,15,17-20"));
end Test_Range_Expansion;
|
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.
|
#APL
|
APL
|
⍝⍝ GNU APL Version
∇listFile fname ;fileHandle;maxLineLen;line
maxLineLen ← 128
fileHandle ← ⎕FIO['fopen'] fname
readLoop:
→(0=⍴(line ← maxLineLen ⎕FIO['fgets'] fileHandle))/eof
⍞ ← ⎕AV[1+line] ⍝⍝ bytes to ASCII
→ readLoop
eof:
⊣⎕FIO['fclose'] fileHandle
⊣⎕FIO['errno'] fileHandle
∇
listFile 'corpus/sample1.txt'
This is some sample text.
The text itself has multiple lines, and
the text has some words that occur multiple times
in the text.
This is the end of the text.
|
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.
|
#Amazing_Hopper
|
Amazing Hopper
|
#include <hopper.h>
main:
.ctrlc
fd=0
fopen(OPEN_READ,"archivo.txt")(fd)
if file error?
{"Error open file: "},file error
else
line read=0
while( not(feof(fd)))
fread line(1000)(fd), ++line read
println
wend
{"Total read lines : ",line read}
fclose(fd)
endif
println
exit(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.
|
#FreeBASIC
|
FreeBASIC
|
Data 44,"Solomon", 42,"Jason", 42,"Errol", 41,"Garry"
Data 41,"Bernard", 41,"Barry", 39,"Stephen"
Dim Shared As Integer n = 7
Dim Shared As Integer puntos(n), i
Dim Shared As Single ptosnom(n)
Dim Shared As String nombre(n)
Print "Puntuaciones a clasificar (mejores primero):"
For i = 1 To n
Read puntos(i), nombre(i)
Print Using " ##, \ \"; puntos(i); nombre(i)
Next i
Print
Sub MostarTabla
For i = 1 To n
Print Using " \ \ ##, \ \"; Str(ptosnom(i)); puntos(i); nombre(i)
Next i
Print
End Sub
Print "--- Standard ranking ---"
ptosnom(1) = 1
For i = 2 To n
If puntos(i) = puntos(i-1) Then ptosnom(i) = ptosnom(i-1) Else ptosnom(i) = i
Next i
MostarTabla
Print "--- Modified ranking ---"
ptosnom(n) = n
For i = n-1 To 1 Step -1
If puntos(i) = puntos(i+1) Then ptosnom(i) = ptosnom(i+1) Else ptosnom(i) = i
Next i
MostarTabla
Print "--- Dense ranking ---"
ptosnom(1) = 1
For i = 2 To n
ptosnom(i) = ptosnom(i-1) - (puntos(i) <> puntos(i-1))
Next i
MostarTabla
Print "--- Ordinal ranking ---"
For i = 1 To n
ptosnom(i) = i
Next i
MostarTabla
Print "--- Fractional ranking ---"
i = 1
Dim As Integer j = 2
Do
If j <= n Then If (puntos(j-1) = puntos(j)) Then j += 1
For k As Integer = i To j-1
ptosnom(k) = (i+j-1) / 2
Next k
i = j
j += 1
Loop While i <= n
MostarTabla
Sleep
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
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
Given an Array, derive a sequence of elements in which all duplicates are removed.
There are basically three approaches seen here:
Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
|
#zkl
|
zkl
|
zkl: Utils.Helpers.listUnique(T(1,3,2,9,1,2,3,8,8,"8",1,0,2,"8"))
L(1,3,2,9,8,"8",0)
zkl: "1,3,2,9,1,2,3,8,8,1,0,2".unique()
,012389
|
http://rosettacode.org/wiki/Remove_duplicate_elements
|
Remove duplicate elements
|
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
Given an Array, derive a sequence of elements in which all duplicates are removed.
There are basically three approaches seen here:
Put the elements into a hash table which does not allow duplicates. The complexity is O(n) on average, and O(n2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(n log n). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(n2). The up-shot is that this always works on any type (provided that you can test for equality).
|
#Zoea
|
Zoea
|
program: remove_duplicate_elements
input: [1,2,1,3,2,4,1]
output: [1,2,3,4]
|
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
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
"sort"
)
type Range struct{ Lower, Upper float64 }
func (r Range) Norm() Range {
if r.Lower > r.Upper {
return Range{r.Upper, r.Lower}
}
return r
}
func (r Range) String() string {
return fmt.Sprintf("[%g, %g]", r.Lower, r.Upper)
}
func (r1 Range) Union(r2 Range) []Range {
if r1.Upper < r2.Lower {
return []Range{r1, r2}
}
r := Range{r1.Lower, math.Max(r1.Upper, r2.Upper)}
return []Range{r}
}
func consolidate(rs []Range) []Range {
for i := range rs {
rs[i] = rs[i].Norm()
}
le := len(rs)
if le < 2 {
return rs
}
sort.Slice(rs, func(i, j int) bool {
return rs[i].Lower < rs[j].Lower
})
if le == 2 {
return rs[0].Union(rs[1])
}
for i := 0; i < le-1; i++ {
for j := i + 1; j < le; j++ {
ru := rs[i].Union(rs[j])
if len(ru) == 1 {
rs[i] = ru[0]
copy(rs[j:], rs[j+1:])
rs = rs[:le-1]
le--
i--
break
}
}
}
return rs
}
func main() {
rss := [][]Range{
{{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}},
}
for _, rs := range rss {
s := fmt.Sprintf("%v", rs)
fmt.Printf("%40s => ", s[1:len(s)-1])
rs2 := consolidate(rs)
s = fmt.Sprintf("%v", rs2)
fmt.Println(s[1 : len(s)-1])
}
}
|
http://rosettacode.org/wiki/Rate_counter
|
Rate counter
|
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth of jobs and/or Y jobs.
Report at least three distinct times.
Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.
See also: System time, Time a function
|
#zkl
|
zkl
|
fcn rateCounter(f,timeNRuns,secsToRun=Void){
now:=Time.Clock.time;
if(secsToRun){
then:=now + secsToRun;
N:=0; do{ f(); N+=1; }while(Time.Clock.time<then);
t:=Time.Clock.time - now;
println("%d runs in %s seconds = %.3f sec/run"
.fmt(N,Time.Date.toHMSString(0,0,t),t.toFloat()/N));
}
else{
do(timeNRuns){ f() }
t:=Time.Clock.time - now;
println("%s seconds to run %d times = %.3f sec/run"
.fmt(Time.Date.toHMSString(0,0,t),timeNRuns,
t.toFloat()/timeNRuns));
t
}
}
|
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
|
#Nial
|
Nial
|
reverse 'asdf'
=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)
|
#AArch64_Assembly
|
AArch64 Assembly
|
.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_GETRANDOM, 278
.equ SVC_EXIT, 93
.text
.global _start
_start:
stp x29, x30, [sp, -32]! // allocate buffer space at [sp]
mov x29, sp
mov x0, sp
mov x1, #4
bl _getrandom // getrandom(&tmp, 4);
ldr w0, [sp]
bl print_uint64 // print_uint64(tmp);
ldp x29, x30, [sp], 32
mov x0, #0
b _exit // exit(0);
// void print_uint64(uint64_t x) - print an unsigned integer in base 10.
print_uint64:
// x0 = remaining number to convert
// x1 = pointer to most significant digit
// x2 = 10
// x3 = x0 / 10
// x4 = x0 % 10
// compute x0 divmod 10, store a digit, repeat if x0 > 0
ldr x1, =strbuf_end
mov x2, #10
1: udiv x3, x0, x2
msub x4, x3, x2, x0
add x4, x4, #48
mov x0, x3
strb w4, [x1, #-1]!
cbnz x0, 1b
// compute the number of digits to print, then call write()
ldr x3, =strbuf_end_newline
sub x2, x3, x1
mov x0, #STDOUT
b _write
.data
strbuf:
.space 31
strbuf_end:
.ascii "\n"
strbuf_end_newline:
.align 4
.text
//////////////// system call wrappers
// ssize_t _write(int fd, void *buf, size_t count)
_write:
mov x8, #SVC_WRITE
svc #0
ret
// ssize_t getrandom(void *buf, size_t buflen, unsigned int flags=0)
_getrandom:
mov x2, #0
mov x8, #SVC_GETRANDOM
svc #0
ret
// void _exit(int retval)
_exit:
mov x8, #SVC_EXIT
svc #0
|
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 ε.)
|
#Java
|
Java
|
import static java.lang.Math.*;
public class RayCasting {
static boolean intersects(int[] A, int[] B, double[] P) {
if (A[1] > B[1])
return intersects(B, A, P);
if (P[1] == A[1] || P[1] == B[1])
P[1] += 0.0001;
if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))
return false;
if (P[0] < min(A[0], B[0]))
return true;
double red = (P[1] - A[1]) / (double) (P[0] - A[0]);
double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);
return red >= blue;
}
static boolean contains(int[][] shape, double[] pnt) {
boolean inside = false;
int len = shape.length;
for (int i = 0; i < len; i++) {
if (intersects(shape[i], shape[(i + 1) % len], pnt))
inside = !inside;
}
return inside;
}
public static void main(String[] a) {
double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},
{20, 10}, {16, 10}, {20, 20}};
for (int[][] shape : shapes) {
for (double[] pnt : testPoints)
System.out.printf("%7s ", contains(shape, pnt));
System.out.println();
}
}
final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};
final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},
{5, 5}, {15, 5}, {15, 15}, {5, 15}};
final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},
{20, 20}, {20, 0}};
final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},
{6, 20}, {0, 10}};
final static int[][][] shapes = {square, squareHole, strange, hexagon};
}
|
http://rosettacode.org/wiki/Random_sentence_from_book
|
Random sentence from book
|
Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep account of what words follow two words and how many times it is seen, (again treating sentence terminators as words too).
Assume that a sentence starts with a not to be shown full-stop character then use a weighted random choice of the possible words that may follow a full-stop to add to the sentence.
Then repeatedly add words to the sentence based on weighted random choices of what words my follow the last two words to extend the sentence.
Stop after adding a sentence ending punctuation character.
Tidy and then print the sentence.
Show examples of random sentences generated.
Related task
Markov_chain_text_generator
|
#Raku
|
Raku
|
my $text = '36-0.txt'.IO.slurp.subst(/.+ '*** START OF THIS' .+? \n (.*?) 'End of the Project Gutenberg EBook' .*/, {$0} );
$text.=subst(/ <+punct-[.!?\’,]> /, ' ', :g);
$text.=subst(/ (\s) '’' (\s) /, '', :g);
$text.=subst(/ (\w) '’' (\s) /, {$0~$1}, :g);
$text.=subst(/ (\s) '’' (\w) /, {$0~$1}, :g);
my (%one, %two);
for $text.comb(/[\w+(\’\w+)?]','?|<punct>/).rotor(3 => -2) {
%two{.[0]}{.[1]}{.[2]}++;
%one{.[0]}{.[1]}++;
}
sub weightedpick (%hash) { %hash.keys.map( { $_ xx %hash{$_} } ).pick }
sub sentence {
my @sentence = <. ! ?>.roll;
@sentence.push: weightedpick( %one{ @sentence[0] } );
@sentence.push: weightedpick( %two{ @sentence[*-2] }{ @sentence[*-1] } // %('.' => 1) )[0]
until @sentence[*-1] ∈ <. ! ?>;
@sentence.=squish;
shift @sentence;
redo if @sentence < 7;
@sentence.join(' ').tc.subst(/\s(<:punct>)/, {$0}, :g);
}
say sentence() ~ "\n" for ^10;
|
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.
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
eln = 7; % extract line number 7
line = '';
fid = fopen('foobar.txt','r');
if (fid < 0)
printf('Error:could not open file\n')
else
n = 0;
while ~feof(fid),
n = n + 1;
if (n ~= eln),
fgetl(fid);
else
line = fgetl(fid);
end
end;
fclose(fid);
end;
printf('line %i: %s\n',eln,line);
|
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
|
#Action.21
|
Action!
|
INT FUNC FindRange(INT ARRAY a INT len,start)
INT count
count=1
WHILE start<len-1
DO
IF a(start)+1#a(start+1) THEN
EXIT
FI
start==+1
count==+1
OD
RETURN (count)
PROC Append(CHAR ARRAY text,suffix)
BYTE POINTER srcPtr,dstPtr
BYTE len
len=suffix(0)
IF text(0)+len>255 THEN
len=255-text(0)
FI
IF len THEN
srcPtr=suffix+1
dstPtr=text+text(0)+1
MoveBlock(dstPtr,srcPtr,len)
text(0)==+suffix(0)
FI
RETURN
PROC RangeToStr(INT ARRAY a INT len CHAR ARRAY res)
INT i,count
CHAR ARRAY tmp(10)
i=0
res(0)=0
WHILE i<len
DO
count=FindRange(a,len,i)
StrI(a(i),tmp) Append(res,tmp)
IF count=2 THEN
Append(res,",")
StrI(a(i+1),tmp) Append(res,tmp)
ELSEIF count>2 THEN
Append(res,"-")
StrI(a(i+count-1),tmp) Append(res,tmp)
FI
i==+count
IF i<len THEN
Append(res,",")
FI
OD
RETURN
PROC Main()
INT ARRAY a=[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]
INT ARRAY b=[65530 65533 65534 65535
0 1 3 4 5 7 8 9 10 11 14 15 17 18 19 20]
CHAR ARRAY res(256)
RangeToStr(a,33,res)
PrintE(res) PutE()
RangeToStr(b,20,res)
PrintE(res)
RETURN
|
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
|
#ALGOL_68
|
ALGOL 68
|
PROC random normal = REAL: # normal distribution, centered on 0, std dev 1 #
(
sqrt(-2*log(random)) * cos(2*pi*random)
);
test:(
[1000]REAL rands;
FOR i TO UPB rands DO
rands[i] := 1 + random normal/2
OD;
INT limit=10;
printf(($"("n(limit-1)(-d.6d",")-d.5d" ... )"$, rands[:limit]))
)
|
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
|
#Arturo
|
Arturo
|
rnd: function []-> (random 0 10000)//10000
rands: map 1..1000 'x [
1 + (sqrt neg 2 * ln rnd) * (cos 2 * pi * rnd)
]
print rands
|
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.
|
#8th
|
8th
|
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a :=
¢ the next pseudo-random ℒ integral value after 'a' from a
uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;
¢ the real value corresponding to 'a' according to some mapping of
integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1)
i.e. such that -0 <= x < 1 such that the sequence of real
values so produced preserves the properties of pseudo-randomness
and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #;
PROC ℒ random = ℒ REAL: ℒ next random(ℒ last 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.
|
#ActionScript
|
ActionScript
|
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a :=
¢ the next pseudo-random ℒ integral value after 'a' from a
uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;
¢ the real value corresponding to 'a' according to some mapping of
integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1)
i.e. such that -0 <= x < 1 such that the sequence of real
values so produced preserves the properties of pseudo-randomness
and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #;
PROC ℒ random = ℒ REAL: ℒ next random(ℒ last 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.
|
#Ada
|
Ada
|
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a :=
¢ the next pseudo-random ℒ integral value after 'a' from a
uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;
¢ the real value corresponding to 'a' according to some mapping of
integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1)
i.e. such that -0 <= x < 1 such that the sequence of real
values so produced preserves the properties of pseudo-randomness
and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #;
PROC ℒ random = ℒ REAL: ℒ next random(ℒ last 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
|
#C.2B.2B
|
C++
|
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> sep(" ","#;,");
//Assume that the config file represent a struct containing all the parameters to load
struct configs{
string fullname;
string favoritefruit;
bool needspelling;
bool seedsremoved;
vector<string> otherfamily;
} conf;
void parseLine(const string &line, configs &conf)
{
if (line[0] == '#' || line.empty())
return;
Tokenizer tokenizer(line, sep);
vector<string> tokens;
for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)
tokens.push_back(*iter);
if (tokens[0] == ";"){
algorithm::to_lower(tokens[1]);
if (tokens[1] == "needspeeling")
conf.needspelling = false;
if (tokens[1] == "seedsremoved")
conf.seedsremoved = false;
}
algorithm::to_lower(tokens[0]);
if (tokens[0] == "needspeeling")
conf.needspelling = true;
if (tokens[0] == "seedsremoved")
conf.seedsremoved = true;
if (tokens[0] == "fullname"){
for (unsigned int i=1; i<tokens.size(); i++)
conf.fullname += tokens[i] + " ";
conf.fullname.erase(conf.fullname.size() -1, 1);
}
if (tokens[0] == "favouritefruit")
for (unsigned int i=1; i<tokens.size(); i++)
conf.favoritefruit += tokens[i];
if (tokens[0] == "otherfamily"){
unsigned int i=1;
string tmp;
while (i<=tokens.size()){
if ( i == tokens.size() || tokens[i] ==","){
tmp.erase(tmp.size()-1, 1);
conf.otherfamily.push_back(tmp);
tmp = "";
i++;
}
else{
tmp += tokens[i];
tmp += " ";
i++;
}
}
}
}
int _tmain(int argc, TCHAR* argv[])
{
if (argc != 2)
{
wstring tmp = argv[0];
wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl;
return -1;
}
ifstream file (argv[1]);
if (file.is_open())
while(file.good())
{
char line[255];
file.getline(line, 255);
string linestring(line);
parseLine(linestring, conf);
}
else
{
cout << "Unable to open the file" << endl;
return -2;
}
cout << "Fullname= " << conf.fullname << endl;
cout << "Favorite Fruit= " << conf.favoritefruit << endl;
cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl;
cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl;
string otherFamily;
for (unsigned int i = 0; i < conf.otherfamily.size(); i++)
otherFamily += conf.otherfamily[i] + ", ";
otherFamily.erase(otherFamily.size()-2, 2);
cout << "Other Family= " << otherFamily << endl;
return 0;
}
|
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).
|
#FreeBASIC
|
FreeBASIC
|
Function revn(n As ULongInt, nd As ULongInt) As ULongInt
Dim As ULongInt r
For i As UInteger = 1 To nd
r = r * 10 + n Mod 10
n = n \ 10
Next i
Return r
End Function
Dim As UInteger nd = 2, count, lim = 90, n = 20
Do
n += 1
Dim As ULongInt r = revn(n,nd)
If r < n Then
Dim As ULongInt s = n + r, d = n - r
If nd And 1 Then
If d Mod 1089 <> 0 Then GoTo jump
Else
If s Mod 121 <> 0 Then GoTo jump
End If
If Frac(Sqr(s)) = 0 And Frac(Sqr(d)) = 0 Then
count += 1
Print count; ": "; n
If count = 5 Then Exit Do : End If
End If
End If
jump:
If n = lim Then
lim = lim * 10
nd += 1
n = (lim \ 9) * 2
End If
Loop
Print
Print "Done"
Sleep
|
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
|
#Aime
|
Aime
|
list l;
file().b_affix("-6,-3--1,3-5,7-11,14,15,17-20").news(l, 0, 0, ",");
for (, text s in l) {
integer a, b, p;
p = b_frame(s, '-');
if (p < 1) {
o_(s, ",");
} else {
p -= s[p - 1] == '-' ? 1 : 0;
a = s.cut(0, p).atoi;
b = s.erase(0, p).atoi;
do {
o_(a, ",");
} while ((a += 1) <= b);
}
}
o_("\n");
|
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
|
#ALGOL_68
|
ALGOL 68
|
MODE YIELDINT = PROC(INT)VOID;
MODE RANGE = STRUCT(INT lwb, upb);
MODE RANGEINT = UNION(RANGE, INT);
OP SIZEOF = ([]RANGEINT list)INT: (
# determine the length of the output array #
INT upb := LWB list - 1;
FOR key FROM LWB list TO UPB list DO
CASE list[key] IN
(RANGE value): upb +:= upb OF value - lwb OF value + 1,
(INT): upb +:= 1
ESAC
OD;
upb
);
PROC gen range expand = ([]RANGEINT list, YIELDINT yield)VOID:
FOR key FROM LWB list TO UPB list DO
CASE list[key] IN
(RANGE range): FOR value FROM lwb OF range TO upb OF range DO yield(value) OD,
(INT int): yield(int)
ESAC
OD;
PROC range expand = ([]RANGEINT list)[]INT: (
[LWB list: LWB list + SIZEOF list - 1]INT out;
INT upb := LWB out - 1;
# FOR INT value IN # gen range expand(list, # ) DO #
## (INT value)VOID:
out[upb +:= 1] := value
# OD #);
out
);
#
test:(
[]RANGEINT list = (-6, RANGE(-3, -1), RANGE(3, 5), RANGE(7, 11), 14, 15, RANGE(17, 20));
print((range expand(list), new line))
)
#
# converts string containing a comma-separated list of ranges and values to a []RANGEINT #
OP TORANGE = ( STRING s )[]RANGEINT:
BEGIN
# counts the number of elements - one more than the number of commas #
# and so assumes there is always at least one element #
PROC count elements = INT:
BEGIN
INT elements := 1;
FOR pos FROM LWB s TO UPB s
DO
IF s[ pos ] = ","
THEN
elements +:= 1
FI
OD;
# RESULT #
elements
END; # count elements #
REF[]RANGEINT result = HEAP [ 1 : count elements ]RANGEINT;
# does the actual parsing - assumes the string is syntatically valid and doesn't check for errors #
# - in particular, a string with no elements will cause problems, as will space characters in the string #
PROC parse range string = []RANGEINT:
BEGIN
INT element := 0;
INT str pos := 1;
PROC next = VOID: str pos +:= 1;
PROC curr char = CHAR: IF str pos > UPB s THEN "?" ELSE s[ str pos ] FI;
PROC have minus = BOOL: curr char = "-";
PROC have digit = BOOL: curr char >= "0" AND curr char <= "9";
# parses a number out of the string #
# the number must be a sequence of digits with an optional leading minus sign #
PROC get number = INT:
BEGIN
INT number := 0;
INT sign multiplier = IF have minus
THEN
# negaive number #
# skip the sign #
next;
-1
ELSE
# positive number #
1
FI;
WHILE curr char >= "0" AND curr char <= "9"
DO
number *:= 10;
number +:= ( ABS curr char - ABS "0" );
next
OD;
# RESULT #
number * sign multiplier
END; # get number #
# main parsing #
WHILE str pos <= UPB s
DO
CHAR c = curr char;
IF have minus OR have digit
THEN
# have the start of a number #
INT from value = get number;
element +:= 1;
IF NOT have minus
THEN
# not a range #
result[ element ] := from value
ELSE
# have a range #
next;
INT to value = get number;
result[ element ] := RANGE( from value, to value )
FI
ELSE
# should be a comma #
next
FI
OD;
# RESULT #
result
END; # parse range string #
# RESULT #
parse range string
END; # TORANGE #
# converts a []INT to a comma separated string of the elements #
OP TOSTRING = ( []INT values )STRING:
BEGIN
STRING result := "";
STRING separator := "";
FOR pos FROM LWB values TO UPB values
DO
result +:= ( separator + whole( values[ pos ], 0 ) );
separator := ","
OD;
# RESULT #
result
END; # TOSTRING #
test:(
print( ( TOSTRING range expand( TORANGE "-6,-3--1,3-5,7-11,14,15,17-20" ), newline ) )
)
|
http://rosettacode.org/wiki/Read_a_file_line_by_line
|
Read a file line by line
|
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
|
#ARM_Assembly
|
ARM Assembly
|
/* ARM assembly Raspberry PI */
/* program readfile.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ OPEN, 5
.equ CLOSE, 6
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ BUFFERSIZE, 100
.equ LINESIZE, 100
/*******************************************/
/* Structures */
/********************************************/
/* structure read file*/
.struct 0
readfile_Fd: @ File descriptor
.struct readfile_Fd + 4
readfile_buffer: @ read buffer
.struct readfile_buffer + 4
readfile_buffersize: @ buffer size
.struct readfile_buffersize + 4
readfile_line: @ line buffer
.struct readfile_line + 4
readfile_linesize: @ line buffer size
.struct readfile_linesize + 4
readfile_pointer:
.struct readfile_pointer + 4 @ read pointer (init to buffer size + 1)
readfile_end:
/* Initialized data */
.data
szFileName: .asciz "fictest.txt"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
szMessErr: .ascii "Error code hexa : "
sHexa: .space 9,' '
.ascii " decimal : "
sDeci: .space 15,' '
.asciz "\n"
/* UnInitialized data */
.bss
sBuffer: .skip BUFFERSIZE @ buffer result
szLineBuffer: .skip LINESIZE
.align 4
stReadFile: .skip readfile_end
/* code section */
.text
.global main
main:
ldr r0,iAdrszFileName @ File name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ open file
svc #0
cmp r0,#0 @ error ?
ble error
ldr r1,iAdrstReadFile @ init struture readfile
str r0,[r1,#readfile_Fd] @ save FD in structure
ldr r0,iAdrsBuffer @ buffer address
str r0,[r1,#readfile_buffer]
mov r0,#BUFFERSIZE @ buffer size
str r0,[r1,#readfile_buffersize]
ldr r0,iAdrszLineBuffer @ line buffer address
str r0,[r1,#readfile_line]
mov r0,#LINESIZE @ line buffer size
str r0,[r1,#readfile_linesize]
mov r0,#BUFFERSIZE + 1 @ init read pointer
str r0,[r1,#readfile_pointer]
1: @ begin read loop
mov r0,r1
bl readLineFile
cmp r0,#0
beq end @ end loop
blt error
ldr r0,iAdrszLineBuffer @ display line
bl affichageMess
ldr r0,iAdrszCarriageReturn @ display line return
bl affichageMess
b 1b @ and loop
end:
ldr r1,iAdrstReadFile
ldr r0,[r1,#readfile_Fd] @ load FD to structure
mov r7, #CLOSE @ call system close file
svc #0
cmp r0,#0
blt error
mov r0,#0 @ return code
b 100f
error:
ldr r1,iAdrszMessErreur @ error message
bl displayError
mov r0,#1 @ return error code
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrsBuffer: .int sBuffer
iAdrszFileName: .int szFileName
iAdrszMessErreur: .int szMessErreur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrstReadFile: .int stReadFile
iAdrszLineBuffer: .int szLineBuffer
/******************************************************************/
/* sub strings index start number of characters */
/******************************************************************/
/* r0 contains the address of the structure */
/* r0 returns number of characters or -1 if error */
readLineFile:
push {r1-r8,lr} @ save registers
mov r4,r0 @ save structure
ldr r1,[r4,#readfile_buffer]
ldr r2,[r4,#readfile_buffersize]
ldr r5,[r4,#readfile_pointer]
ldr r6,[r4,#readfile_linesize]
ldr r7,[r4,#readfile_buffersize]
ldr r8,[r4,#readfile_line]
mov r3,#0 @ line pointer
strb r3,[r8,r3] @ store zéro in line buffer
cmp r5,r2 @ pointer buffer < buffer size ?
ble 2f @ no file read
1: @ loop read file
ldr r0,[r4,#readfile_Fd]
mov r7,#READ @ call system read file
svc 0
cmp r0,#0 @ error read or end ?
ble 100f
mov r7,r0 @ number of read characters
mov r5,#0 @ init buffer pointer
2: @ begin loop copy characters
ldrb r0,[r1,r5] @ load 1 character read buffer
cmp r0,#0x0A @ end line ?
beq 4f
strb r0,[r8,r3] @ store character in line buffer
add r3,#1 @ increment pointer line
cmp r3,r6
movgt r0,#-2 @ line buffer too small -> error
bgt 100f
add r5,#1 @ increment buffer pointer
cmp r5,r2 @ end buffer ?
bge 1b @ yes new read
cmp r5,r7 @ read characters ?
blt 2b @ no loop
@ final
cmp r3,#0 @ no characters in line buffer ?
beq 100f
4:
mov r0,#0
strb r0,[r8,r3] @ store zéro final
add r5,#1
str r5,[r4,#readfile_pointer] @ store pointer in structure
str r7,[r4,#readfile_buffersize] @ store number of last characters
mov r0,r3 @ return length of line
100:
pop {r1-r8,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* display error message */
/***************************************************/
/* r0 contains error code r1 : message address */
displayError:
push {r0-r2,lr} @ save registers
mov r2,r0 @ save error code
mov r0,r1
bl affichageMess
mov r0,r2 @ error code
ldr r1,iAdrsHexa
bl conversion16 @ conversion hexa
mov r0,r2 @ error code
ldr r1,iAdrsDeci @ result address
bl conversion10S @ conversion decimale
ldr r0,iAdrszMessErr @ display error message
bl affichageMess
100:
pop {r0-r2,lr} @ restaur registers
bx lr @ return
iAdrszMessErr: .int szMessErr
iAdrsHexa: .int sHexa
iAdrsDeci: .int sDeci
/******************************************************************/
/* Converting a register to hexadecimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion16:
push {r1-r4,lr} @ save registers
mov r2,#28 @ start bit position
mov r4,#0xF0000000 @ mask
mov r3,r0 @ save entry value
1: @ start loop
and r0,r3,r4 @ value register and mask
lsr r0,r2 @ move right
cmp r0,#10 @ compare value
addlt r0,#48 @ <10 ->digit
addge r0,#55 @ >10 ->letter A-F
strb r0,[r1],#1 @ store digit on area and + 1 in area address
lsr r4,#4 @ shift mask 4 positions
subs r2,#4 @ counter bits - 4 <= zero ?
bge 1b @ no -> loop
100:
pop {r1-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 @ debut zone stockage
mov r3,#'+' @ par defaut le signe est +
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionpar10U
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"sort"
)
type rankable interface {
Len() int
RankEqual(int, int) bool
}
func StandardRank(d rankable) []float64 {
r := make([]float64, d.Len())
var k int
for i := range r {
if i == 0 || !d.RankEqual(i, i-1) {
k = i + 1
}
r[i] = float64(k)
}
return r
}
func ModifiedRank(d rankable) []float64 {
r := make([]float64, d.Len())
for i := range r {
k := i + 1
for j := i + 1; j < len(r) && d.RankEqual(i, j); j++ {
k = j + 1
}
r[i] = float64(k)
}
return r
}
func DenseRank(d rankable) []float64 {
r := make([]float64, d.Len())
var k int
for i := range r {
if i == 0 || !d.RankEqual(i, i-1) {
k++
}
r[i] = float64(k)
}
return r
}
func OrdinalRank(d rankable) []float64 {
r := make([]float64, d.Len())
for i := range r {
r[i] = float64(i + 1)
}
return r
}
func FractionalRank(d rankable) []float64 {
r := make([]float64, d.Len())
for i := 0; i < len(r); {
var j int
f := float64(i + 1)
for j = i + 1; j < len(r) && d.RankEqual(i, j); j++ {
f += float64(j + 1)
}
f /= float64(j - i)
for ; i < j; i++ {
r[i] = f
}
}
return r
}
type scores []struct {
score int
name string
}
func (s scores) Len() int { return len(s) }
func (s scores) RankEqual(i, j int) bool { return s[i].score == s[j].score }
func (s scores) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s scores) Less(i, j int) bool {
if s[i].score != s[j].score {
return s[i].score > s[j].score
}
return s[i].name < s[j].name
}
var data = scores{
{44, "Solomon"},
{42, "Jason"},
{42, "Errol"},
{41, "Garry"},
{41, "Bernard"},
{41, "Barry"},
{39, "Stephen"},
}
func main() {
show := func(name string, fn func(rankable) []float64) {
fmt.Println(name, "Ranking:")
r := fn(data)
for i, d := range data {
fmt.Printf("%4v - %2d %s\n", r[i], d.score, d.name)
}
}
sort.Sort(data)
show("Standard", StandardRank)
show("\nModified", ModifiedRank)
show("\nDense", DenseRank)
show("\nOrdinal", OrdinalRank)
show("\nFractional", FractionalRank)
}
|
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
|
#Haskell
|
Haskell
|
import Data.List (intercalate, maximumBy, sort)
import Data.Ord (comparing)
------------------- RANGE CONSOLIDATION ------------------
consolidated :: [(Float, Float)] -> [(Float, Float)]
consolidated = foldr go [] . sort . fmap ab
where
go xy [] = [xy]
go xy@(x, y) abetc@((a, b) : etc)
| y >= b = xy : etc
| y >= a = (x, b) : etc
| otherwise = xy : abetc
ab (a, b)
| a <= b = (a, b)
| otherwise = (b, a)
--------------------------- TEST -------------------------
tests :: [[(Float, Float)]]
tests =
[ [],
[(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)]
]
main :: IO ()
main =
putStrLn $
tabulated
"Range consolidations:"
showPairs
showPairs
consolidated
tests
-------------------- DISPLAY FORMATTING ------------------
tabulated ::
String ->
(a -> String) ->
(b -> String) ->
(a -> b) ->
[a] ->
String
tabulated s xShow fxShow f xs =
let w =
length $
maximumBy
(comparing length)
(xShow <$> xs)
rjust n c s = drop (length s) (replicate n c <> s)
in unlines $
s :
fmap
( ((<>) . rjust w ' ' . xShow)
<*> ((" -> " <>) . fxShow . f)
)
xs
showPairs :: [(Float, Float)] -> String
showPairs xs
| null xs = "[]"
| otherwise =
'[' :
intercalate
", "
(showPair <$> xs)
<> "]"
showPair :: (Float, Float) -> String
showPair (a, b) =
'(' :
showNum a
<> ", "
<> showNum b
<> ")"
showNum :: Float -> String
showNum n
| 0 == (n - fromIntegral (round n)) = show (round n)
| otherwise = show n
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Nim
|
Nim
|
import unicode
proc reverse(s: var string) =
for i in 0 .. s.high div 2:
swap(s[i], s[s.high - i])
proc reversed(s: string): string =
result = newString(s.len)
for i,c in s:
result[s.high - i] = c
proc uniReversed(s: string): string =
result = newStringOfCap(s.len)
var tmp: seq[Rune] = @[]
for r in runes(s):
tmp.add(r)
for i in countdown(tmp.high, 0):
result.add(toUtf8(tmp[i]))
proc isComb(r: Rune): bool =
(r >=% Rune(0x300) and r <=% Rune(0x36f)) or
(r >=% Rune(0x1dc0) and r <=% Rune(0x1dff)) or
(r >=% Rune(0x20d0) and r <=% Rune(0x20ff)) or
(r >=% Rune(0xfe20) and r <=% Rune(0xfe2f))
proc uniReversedPreserving(s: string): string =
result = newStringOfCap(s.len)
var tmp: seq[Rune] = @[]
for r in runes(s):
if isComb(r): tmp.insert(r, tmp.high)
else: tmp.add(r)
for i in countdown(tmp.high, 0):
result.add(toUtf8(tmp[i]))
for str in ["Reverse This!", "as⃝df̅"]:
echo "Original string: ", str
echo "Reversed: ", reversed(str)
echo "UniReversed: ", uniReversed(str)
echo "UniReversedPreserving: ", uniReversedPreserving(str)
|
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)
|
#Ada
|
Ada
|
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
procedure Random is
Number : Integer;
Random_File : Ada.Streams.Stream_IO.File_Type;
begin
Ada.Streams.Stream_IO.Open (File => Random_File,
Mode => Ada.Streams.Stream_IO.In_File,
Name => "/dev/random");
Integer'Read (Ada.Streams.Stream_IO.Stream (Random_File), Number);
Ada.Streams.Stream_IO.Close (Random_File);
Ada.Text_IO.Put_Line ("Number:" & Integer'Image (Number));
end Random;
|
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)
|
#ARM_Assembly
|
ARM Assembly
|
/* ARM assembly Raspberry PI */
/* program urandom.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ OPEN, 5
.equ CLOSE, 6
.equ O_RDONLY, 0 @ open for reading only
.equ BUFFERSIZE, 4 @ random number 32 bits
/* Initialized data */
.data
szFileName: .asciz "/dev/urandom" @ see linux doc
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
szMessErr: .ascii "Error code hexa : "
sHexa: .space 9,' '
.ascii " decimal : "
sDeci: .space 15,' '
.asciz "\n"
/* datas message display */
szMessResult: .ascii "Random number :"
sValue: .space 12,' '
.asciz "\n"
/* UnInitialized data */
.bss
sBuffer: .skip BUFFERSIZE @ buffer result
/* code section */
.text
.global main
main:
ldr r0,iAdrszFileName @ File name
mov r1,#O_RDONLY @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ open file
svc #0
cmp r0,#0 @ error ?
ble error
mov r8,r0 @ save FD
mov r4,#0 @ loop counter
1:
mov r0,r8 @ File Descriptor
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ call system read file
svc 0
cmp r0,#0 @ read error ?
ble error
ldr r1,iAdrsBuffer @ buffer address
ldr r0,[r1] @ display buffer value
ldr r1,iAdrsValue
bl conversion10
ldr r0,iAdrszMessResult
bl affichageMess
add r4,#1 @ increment counter
cmp r4,#10 @ maxi ?
blt 1b @ no -> loop
end:
mov r0,r8
mov r7, #CLOSE @ call system close file
svc #0
cmp r0,#0
blt error
mov r0,#0 @ return code
b 100f
error:
ldr r1,iAdrszMessErreur @ error message
bl displayError
mov r0,#1 @ return error code
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrsBuffer: .int sBuffer
iAdrsValue: .int sValue
iAdrszMessResult: .int szMessResult
iAdrszFileName: .int szFileName
iAdrszMessErreur: .int szMessErreur
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* display error message */
/***************************************************/
/* r0 contains error code r1 : message address */
displayError:
push {r0-r2,lr} @ save registers
mov r2,r0 @ save error code
mov r0,r1
bl affichageMess
mov r0,r2 @ error code
ldr r1,iAdrsHexa
bl conversion16 @ conversion hexa
mov r0,r2 @ error code
ldr r1,iAdrsDeci @ result address
bl conversion10S @ conversion decimale
ldr r0,iAdrszMessErr @ display error message
bl affichageMess
100:
pop {r0-r2,lr} @ restaur registers
bx lr @ return
iAdrszMessErr: .int szMessErr
iAdrsHexa: .int sHexa
iAdrsDeci: .int sDeci
/******************************************************************/
/* Converting a register to hexadecimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion16:
push {r1-r4,lr} @ save registers
mov r2,#28 @ start bit position
mov r4,#0xF0000000 @ mask
mov r3,r0 @ save entry value
1: @ start loop
and r0,r3,r4 @ value register and mask
lsr r0,r2 @ move right
cmp r0,#10 @ compare value
addlt r0,#48 @ <10 ->digit
addge r0,#55 @ >10 ->letter A-F
strb r0,[r1],#1 @ store digit on area and + 1 in area address
lsr r4,#4 @ shift mask 4 positions
subs r2,#4 @ counter bits - 4 <= zero ?
bge 1b @ no -> loop
100:
pop {r1-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 @ debut zone stockage
mov r3,#'+' @ par defaut le signe est +
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionpar10U
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
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 ε.)
|
#JavaScript
|
JavaScript
|
/**
* @return {boolean} true if (lng, lat) is in bounds
*/
function contains(bounds, lat, lng) {
//https://rosettacode.org/wiki/Ray-casting_algorithm
var count = 0;
for (var b = 0; b < bounds.length; b++) {
var vertex1 = bounds[b];
var vertex2 = bounds[(b + 1) % bounds.length];
if (west(vertex1, vertex2, lng, lat))
++count;
}
return count % 2;
/**
* @return {boolean} true if (x,y) is west of the line segment connecting A and B
*/
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;
} else if (x < A.x && x < B.x) {
return true;
} else {
return (y - A.y) / (x - A.x) > (B.y - A.y) / (B.x - A.x);
}
} else {
return west(B, A, x, y);
}
}
}
var square = {name: 'square', bounds: [{x: 0, y: 0}, {x: 20, y: 0}, {x: 20, y: 20}, {x: 0, y: 20}]};
var 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}]
};
var 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}]
};
var 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}]
};
var shapes = [square, squareHole, strange, hexagon];
var 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 (var s = 0; s < shapes.length; s++) {
var shape = shapes[s];
for (var tp = 0; tp < testPoints.length; tp++) {
var testPoint = testPoints[tp];
console.log(JSON.stringify(testPoint) + '\tin ' + shape.name + '\t' + contains(shape.bounds, testPoint.lat, testPoint.lng));
}
}
|
http://rosettacode.org/wiki/Random_sentence_from_book
|
Random sentence from book
|
Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep account of what words follow two words and how many times it is seen, (again treating sentence terminators as words too).
Assume that a sentence starts with a not to be shown full-stop character then use a weighted random choice of the possible words that may follow a full-stop to add to the sentence.
Then repeatedly add words to the sentence based on weighted random choices of what words my follow the last two words to extend the sentence.
Stop after adding a sentence ending punctuation character.
Tidy and then print the sentence.
Show examples of random sentences generated.
Related task
Markov_chain_text_generator
|
#Wren
|
Wren
|
import "io" for File
import "random" for Random
import "/seq" for Lst
// puctuation to keep (also keep hyphen and apostrophe but don't count as words)
var ending = ".!?"
var pausing = ",:;"
// puctuation to remove
var removing = "\"#$\%&()*+/<=>@[\\]^_`{|}~“”"
// read in book
var fileName = "36-0.txt" // local copy of http://www.gutenberg.org/files/36/36-0.txt
var text = File.read(fileName)
// skip to start
var ix = text.indexOf("No one would have believed")
text = text[ix..-1]
// remove extraneous punctuation
for (r in removing) text = text.replace(r, "")
// replace EM DASH (unicode 8212) with a space
text = text.replace("—", " ")
// split into words
var words = text.split(" ").where { |w| w != "" }.toList
// treat 'ending' and 'pausing' punctuation as words
for (i in 0...words.count) {
var w = words[i]
for (p in ending + pausing) if (w.endsWith(p)) words[i] = [w[0...-1], w[-1]]
}
words = Lst.flatten(words)
// Keep account of what words follow words and how many times it is seen
var dict1 = {}
for (i in 0...words.count-1) {
var w1 = words[i]
var w2 = words[i+1]
if (dict1[w1]) {
dict1[w1].add(w2)
} else {
dict1[w1] = [w2]
}
}
for (key in dict1.keys) dict1[key] = [dict1[key].count, Lst.individuals(dict1[key])]
// Keep account of what words follow two words and how many times it is seen
var dict2 = {}
for (i in 0...words.count-2) {
var w12 = words[i] + " " + words[i+1]
var w3 = words[i+2]
if (dict2[w12]) {
dict2[w12].add(w3)
} else {
dict2[w12] = [w3]
}
}
for (key in dict2.keys) dict2[key] = [dict2[key].count, Lst.individuals(dict2[key])]
var rand = Random.new()
var weightedRandomChoice = Fn.new { |value|
var n = value[0]
var indivs = value[1]
var r = rand.int(n)
var sum = 0
for (indiv in indivs) {
sum = sum + indiv[1]
if (r < sum) return indiv[0]
}
}
// build 5 random sentences say
for (i in 1..5) {
var sentence = weightedRandomChoice.call(dict1["."])
var lastOne = sentence
var lastTwo = ". " + sentence
while (true) {
var nextOne = weightedRandomChoice.call(dict2[lastTwo])
sentence = sentence + " " + nextOne
if (ending.contains(nextOne)) break // stop on reaching ending punctuation
lastTwo = lastOne + " " + nextOne
lastOne = nextOne
}
// tidy up sentence
for (p in ending + pausing) sentence = sentence.replace(" %(p)", "%(p)")
sentence = sentence.replace("\n", " ")
System.print(sentence)
System.print()
}
|
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.
|
#MoonScript
|
MoonScript
|
iter = io.lines 'test.txt'
for i=0, 5
error 'Not 7 lines in file' if not iter!
print iter!
|
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.
|
#Nanoquery
|
Nanoquery
|
def getline(fname, linenum)
contents = null
try
contents = new(Nanoquery.IO.File).read()
return contents[linenum]
catch
if contents = null
throw new(Exception, "unable to read from file '" + fname + "'")
else
throw new(Exception, "unable to retrieve line " + linenum + " from file: not enough lines")
end
end
end
|
http://rosettacode.org/wiki/Range_extraction
|
Range extraction
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
Show the output of your program.
Related task
Range expansion
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Range_Extraction is
type Sequence is array (Positive range <>) of Integer;
function Image (S : Sequence) return String is
Result : Unbounded_String;
From : Integer;
procedure Flush (To : Integer) is
begin
if Length (Result) > 0 then
Append (Result, ',');
end if;
Append (Result, Trim (Integer'Image (From), Ada.Strings.Left));
if From < To then
if From+1 = To then
Append (Result, ',');
else
Append (Result, '-');
end if;
Append (Result, Trim (Integer'Image (To), Ada.Strings.Left));
end if;
end Flush;
begin
if S'Length > 0 then
From := S (S'First);
for I in S'First + 1..S'Last loop
if S (I - 1) + 1 /= S (I) then
Flush (S (I - 1));
From := S (I);
end if;
end loop;
Flush (S (S'Last));
end if;
return To_String (Result);
end Image;
begin
Put_Line
( Image
( ( 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
) ) );
end Range_Extraction;
|
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
|
#AutoHotkey
|
AutoHotkey
|
Loop 40
R .= RandN(1,0.5) "`n" ; mean = 1.0, standard deviation = 0.5
MsgBox %R%
RandN(m,s) { ; Normally distributed random numbers of mean = m, std.dev = s by Box-Muller method
Static i, Y
If (i := !i) { ; every other call
Random U, 0, 1.0
Random V, 0, 6.2831853071795862
U := sqrt(-2*ln(U))*s
Y := m + U*sin(V)
Return m + U*cos(V)
}
Return Y
}
|
http://rosettacode.org/wiki/Random_numbers
|
Random numbers
|
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
|
#Avail
|
Avail
|
Method "U(_,_)" is
[
lower : number,
upper : number
|
divisor ::= ((1<<32)) ÷ (upper - lower)→double;
map a pRNG through [i : integer | (i ÷ divisor) + lower]
];
Method "a Marsaglia polar sampler" is
[
generator for
[
yield : [double]→⊤
|
source ::= U(-1, 1);
Repeat [
x ::= take 1 from source[1];
y ::= take 1 from source[1];
s ::= x^2 + y^2;
If 0 < s < 1 then
[
factor ::= ((-2 × ln s) ÷ s) ^ 0.5;
yield(x × factor);
yield(y × factor);
];
]
]
];
// the default distribution has mean 0 and std dev 1.0, so we scale the values
sampler ::= map a Marsaglia polar sampler through [d : double | d ÷ 2.0 + 1.0];
values ::= take 1000 from sampler;
|
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.
|
#ALGOL_68
|
ALGOL 68
|
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a :=
¢ the next pseudo-random ℒ integral value after 'a' from a
uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;
¢ the real value corresponding to 'a' according to some mapping of
integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1)
i.e. such that -0 <= x < 1 such that the sequence of real
values so produced preserves the properties of pseudo-randomness
and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #;
PROC ℒ random = ℒ REAL: ℒ next random(ℒ last 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.
|
#Arturo
|
Arturo
|
#include <stdio.h>
#include <stdlib.h>
/* Flip a coin, 10 times. */
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#AutoHotkey
|
AutoHotkey
|
#include <stdio.h>
#include <stdlib.h>
/* Flip a coin, 10 times. */
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#Clojure
|
Clojure
|
(ns read-conf-file.core
(:require [clojure.java.io :as io]
[clojure.string :as str])
(:gen-class))
(def conf-keys ["fullname"
"favouritefruit"
"needspeeling"
"seedsremoved"
"otherfamily"])
(defn get-lines
"Read file returning vec of lines."
[file]
(try
(with-open [rdr (io/reader file)]
(into [] (line-seq rdr)))
(catch Exception e (.getMessage e))))
(defn parse-line
"Parse passed line returning vec: token, vec of values."
[line]
(if-let [[_ k v] (re-matches #"(?i)^\s*([a-z]+)(?:\s+|=)?(.+)?$" line)]
(let [k (str/lower-case k)]
(if v
[k (str/split v #",\s*")]
[k [true]]))))
(defn mk-conf
"Build configuration map from lines."
[lines]
(->> (map parse-line lines)
(filter (comp not nil?))
(reduce (fn
[m [k v]]
(assoc m k v)) {})))
(defn output
[conf-keys conf]
(doseq [k conf-keys]
(let [v (get conf k)]
(if v
(println (format "%s = %s" k (str/join ", " v)))
(println (format "%s = %s" k "false"))))))
(defn -main
[filename]
(output conf-keys (mk-conf (get-lines filename))))
|
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).
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
"sort"
"time"
)
type term struct {
coeff uint64
ix1, ix2 int8
}
const maxDigits = 19
func toUint64(digits []int8, reverse bool) uint64 {
sum := uint64(0)
if !reverse {
for i := 0; i < len(digits); i++ {
sum = sum*10 + uint64(digits[i])
}
} else {
for i := len(digits) - 1; i >= 0; i-- {
sum = sum*10 + uint64(digits[i])
}
}
return sum
}
func isSquare(n uint64) bool {
if 0x202021202030213&(1<<(n&63)) != 0 {
root := uint64(math.Sqrt(float64(n)))
return root*root == n
}
return false
}
func seq(from, to, step int8) []int8 {
var res []int8
for i := from; i <= to; i += step {
res = append(res, i)
}
return res
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
start := time.Now()
pow := uint64(1)
fmt.Println("Aggregate timings to process all numbers up to:")
// terms of (n-r) expression for number of digits from 2 to maxDigits
allTerms := make([][]term, maxDigits-1)
for r := 2; r <= maxDigits; r++ {
var terms []term
pow *= 10
pow1, pow2 := pow, uint64(1)
for i1, i2 := int8(0), int8(r-1); i1 < i2; i1, i2 = i1+1, i2-1 {
terms = append(terms, term{pow1 - pow2, i1, i2})
pow1 /= 10
pow2 *= 10
}
allTerms[r-2] = terms
}
// map of first minus last digits for 'n' to pairs giving this value
fml := map[int8][][]int8{
0: {{2, 2}, {8, 8}},
1: {{6, 5}, {8, 7}},
4: {{4, 0}},
6: {{6, 0}, {8, 2}},
}
// map of other digit differences for 'n' to pairs giving this value
dmd := make(map[int8][][]int8)
for i := int8(0); i < 100; i++ {
a := []int8{i / 10, i % 10}
d := a[0] - a[1]
dmd[d] = append(dmd[d], a)
}
fl := []int8{0, 1, 4, 6}
dl := seq(-9, 9, 1) // all differences
zl := []int8{0} // zero differences only
el := seq(-8, 8, 2) // even differences only
ol := seq(-9, 9, 2) // odd differences only
il := seq(0, 9, 1)
var rares []uint64
lists := make([][][]int8, 4)
for i, f := range fl {
lists[i] = [][]int8{{f}}
}
var digits []int8
count := 0
// Recursive closure to generate (n+r) candidates from (n-r) candidates
// and hence find Rare numbers with a given number of digits.
var fnpr func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int)
fnpr = func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) {
if level == len(dis) {
digits[indices[0][0]] = fml[cand[0]][di[0]][0]
digits[indices[0][1]] = fml[cand[0]][di[0]][1]
le := len(di)
if nd%2 == 1 {
le--
digits[nd/2] = di[le]
}
for i, d := range di[1:le] {
digits[indices[i+1][0]] = dmd[cand[i+1]][d][0]
digits[indices[i+1][1]] = dmd[cand[i+1]][d][1]
}
r := toUint64(digits, true)
npr := nmr + 2*r
if !isSquare(npr) {
return
}
count++
fmt.Printf(" R/N %2d:", count)
ms := uint64(time.Since(start).Milliseconds())
fmt.Printf(" %9s ms", commatize(ms))
n := toUint64(digits, false)
fmt.Printf(" (%s)\n", commatize(n))
rares = append(rares, n)
} else {
for _, num := range dis[level] {
di[level] = num
fnpr(cand, di, dis, indices, nmr, nd, level+1)
}
}
}
// Recursive closure to generate (n-r) candidates with a given number of digits.
var fnmr func(cand []int8, list [][]int8, indices [][2]int8, nd, level int)
fnmr = func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) {
if level == len(list) {
var nmr, nmr2 uint64
for i, t := range allTerms[nd-2] {
if cand[i] >= 0 {
nmr += t.coeff * uint64(cand[i])
} else {
nmr2 += t.coeff * uint64(-cand[i])
if nmr >= nmr2 {
nmr -= nmr2
nmr2 = 0
} else {
nmr2 -= nmr
nmr = 0
}
}
}
if nmr2 >= nmr {
return
}
nmr -= nmr2
if !isSquare(nmr) {
return
}
var dis [][]int8
dis = append(dis, seq(0, int8(len(fml[cand[0]]))-1, 1))
for i := 1; i < len(cand); i++ {
dis = append(dis, seq(0, int8(len(dmd[cand[i]]))-1, 1))
}
if nd%2 == 1 {
dis = append(dis, il)
}
di := make([]int8, len(dis))
fnpr(cand, di, dis, indices, nmr, nd, 0)
} else {
for _, num := range list[level] {
cand[level] = num
fnmr(cand, list, indices, nd, level+1)
}
}
}
for nd := 2; nd <= maxDigits; nd++ {
digits = make([]int8, nd)
if nd == 4 {
lists[0] = append(lists[0], zl)
lists[1] = append(lists[1], ol)
lists[2] = append(lists[2], el)
lists[3] = append(lists[3], ol)
} else if len(allTerms[nd-2]) > len(lists[0]) {
for i := 0; i < 4; i++ {
lists[i] = append(lists[i], dl)
}
}
var indices [][2]int8
for _, t := range allTerms[nd-2] {
indices = append(indices, [2]int8{t.ix1, t.ix2})
}
for _, list := range lists {
cand := make([]int8, len(list))
fnmr(cand, list, indices, nd, 0)
}
ms := uint64(time.Since(start).Milliseconds())
fmt.Printf(" %2d digits: %9s ms\n", nd, commatize(ms))
}
sort.Slice(rares, func(i, j int) bool { return rares[i] < rares[j] })
fmt.Printf("\nThe rare numbers with up to %d digits are:\n", maxDigits)
for i, rare := range rares {
fmt.Printf(" %2d: %25s\n", i+1, commatize(rare))
}
}
|
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
|
#APL
|
APL
|
range←{
aplnum←{⍎('¯',⎕D)[('-',⎕D)⍳⍵]}
∊{ 0::('Invalid range: ''',⍵,'''')⎕SIGNAL 11
n←aplnum¨(~<\(⊢≠∨\)⍵∊⎕D)⊆⍵
1=≢n:n
s e←n
(s+(⍳e-s-1))-1
}¨(⍵≠',')⊆⍵
}
|
http://rosettacode.org/wiki/Range_expansion
|
Range expansion
|
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range syntax is to be used only for, and for every range that expands to more than two values.
Example
The list of integers:
-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
Is accurately expressed by the range expression:
-6,-3-1,3-5,7-11,14,15,17-20
(And vice-versa).
Task
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the range from minus 3 to minus 1.
Related task
Range extraction
|
#AppleScript
|
AppleScript
|
-- Each comma-delimited string is mapped to a list of integers,
-- and these integer lists are concatenated together into a single list
---------------------- RANGE EXPANSION ---------------------
-- expansion :: String -> [Int]
on expansion(strExpr)
-- The string (between commas) is split on hyphens,
-- and this segmentation is rewritten to ranges or minus signs
-- and evaluated to lists of integer values
-- signedRange :: String -> [Int]
script signedRange
-- After the first character, numbers preceded by an
-- empty string (resulting from splitting on hyphens)
-- and interpreted as negative
-- signedIntegerAppended:: [Int] -> String -> Int -> [Int] -> [Int]
on signedIntegerAppended(acc, strNum, iPosn, xs)
if strNum ≠ "" then
if iPosn > 1 then
set strSign to |λ|(0 < length of (item (iPosn - 1) of xs)) ¬
of bool("", "-")
else
set strSign to "+"
end if
acc & ((strSign & strNum) as integer)
else
acc
end if
end signedIntegerAppended
on |λ|(strHyphenated)
tupleRange(foldl(signedIntegerAppended, {}, ¬
splitOn("-", strHyphenated)))
end |λ|
end script
concatMap(signedRange, splitOn(",", strExpr))
end expansion
---------------------------- TEST --------------------------
on run
expansion("-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}
end run
--------------------- GENERIC FUNCTIONS --------------------
-- bool :: a -> a -> Bool -> a
on bool(tf, ff)
-- The evaluation of either tf or ff,
-- depending on a boolean value.
script
on |λ|(bln)
if bln then
set e to tf
else
set e to ff
end if
set c to class of e
if {script, handler} contains c then
|λ|() of mReturn(e)
else
e
end if
end |λ|
end script
end bool
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
script append
on |λ|(a, b)
a & b
end |λ|
end script
foldl(append, {}, map(f, xs))
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- splitOn :: Text -> Text -> [Text]
on splitOn(strDelim, strMain)
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
set xs to text items of strMain
set my text item delimiters to dlm
return xs
end splitOn
-- range :: (Int, Int) -> [Int]
on tupleRange(tuple)
if tuple = {} then
{}
else if length of tuple > 1 then
enumFromTo(item 1 of tuple, item 2 of tuple)
else
item 1 of tuple
end if
end tupleRange
|
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.
|
#Astro
|
Astro
|
for line in lines open('input.txt'):
print line
|
http://rosettacode.org/wiki/Read_a_file_line_by_line
|
Read a file line by line
|
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
|
#AutoHotkey
|
AutoHotkey
|
; --> Prompt the user to select the file being read
FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes
If Errorlevel ; If no file selected
ExitApp
; --> Main loop: Input (File), Output (Text)
Loop
{
FileReadLine, Line, %File%, %A_Index% ; Reads line N (where N is loop iteration)
if Errorlevel ; If line does not exist, break loop
break
Text .= A_Index ". " Line . "`n" ; Appends the line to the variable "Text", adding line number before & new line after
}
; --> Delivers the output as a text file
FileDelete, Output.txt ; Makes sure output is clear before writing
FileAppend, %Text%, Output.txt ; Writes the result to Output.txt
Run Output.txt ; Shows the created file
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#Haskell
|
Haskell
|
import Data.List (groupBy, sortBy, intercalate)
type Item = (Int, String)
type ItemList = [Item]
type ItemGroups = [ItemList]
type RankItem a = (a, Int, String)
type RankItemList a = [RankItem a]
-- make sure the input is ordered and grouped by score
prepare :: ItemList -> ItemGroups
prepare = groupBy gf . sortBy (flip compare)
where
gf (a, _) (b, _) = a == b
-- give an item a rank
rank
:: Num a
=> a -> Item -> RankItem a
rank n (a, b) = (n, a, b)
-- ranking methods
standard, modified, dense, ordinal :: ItemGroups -> RankItemList Int
standard = ms 1
where
ms _ [] = []
ms n (x:xs) = (rank n <$> x) ++ ms (n + length x) xs
modified = md 1
where
md _ [] = []
md n (x:xs) =
let l = length x
nl = n + l
nl1 = nl - 1
in (rank nl1 <$> x) ++ md (n + l) xs
dense = md 1
where
md _ [] = []
md n (x:xs) = map (rank n) x ++ md (n + 1) xs
ordinal = zipWith rank [1 ..] . concat
fractional :: ItemGroups -> RankItemList Double
fractional = mf 1.0
where
mf _ [] = []
mf n (x:xs) =
let l = length x
o = take l [n ..]
ld = fromIntegral l
a = sum o / ld
in map (rank a) x ++ mf (n + ld) xs
-- sample data
test :: ItemGroups
test =
prepare
[ (44, "Solomon")
, (42, "Jason")
, (42, "Errol")
, (41, "Garry")
, (41, "Bernard")
, (41, "Barry")
, (39, "Stephen")
]
-- print rank items nicely
nicePrint
:: Show a
=> String -> RankItemList a -> IO ()
nicePrint xs items = do
putStrLn xs
mapM_ np items
putStr "\n"
where
np (a, b, c) = putStrLn $ intercalate "\t" [show a, show b, c]
main :: IO ()
main = do
nicePrint "Standard:" $ standard test
nicePrint "Modified:" $ modified test
nicePrint "Dense:" $ dense test
nicePrint "Ordinal:" $ ordinal test
nicePrint "Fractional:" $ fractional test
|
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
|
#J
|
J
|
ensure2D=: ,:^:(1 = #@$) NB. if list make 1 row table
normalise=: ([: /:~ /:~"1)@ensure2D NB. normalises list of ranges
merge=: ,:`(<.&{. , >.&{:)@.(>:/&{: |.) NB. merge ranges x and y
consolidate=: (}.@] ,~ (merge {.)) ensure2D
|
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
|
#NS-HUBASIC
|
NS-HUBASIC
|
10 STRING$="THIS TEXT IS REVERSED."
20 REVERSED$=""
30 FOR I=1 TO LEN(STRING$)
40 REVERSED$=MID$(STRING$,I,1)+REVERSED$
50 NEXT
60 PRINT REVERSED$
|
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)
|
#Batch_File
|
Batch File
|
@echo %random%
|
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)
|
#BBC_BASIC
|
BBC BASIC
|
SYS "SystemFunction036", ^random%, 4
PRINT ~random%
|
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)
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define RANDOM_PATH "/dev/urandom"
int main(void)
{
unsigned char buf[4];
unsigned long v;
FILE *fin;
if ((fin = fopen(RANDOM_PATH, "r")) == NULL) {
fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH);
return EXIT_FAILURE;
}
if (fread(buf, 1, sizeof buf, fin) != sizeof buf) {
fprintf(stderr, "%s: not enough bytes (expected %u)\n",
RANDOM_PATH, (unsigned) sizeof buf);
return EXIT_FAILURE;
}
fclose(fin);
v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL;
printf("%lu\n", v);
return 0;
}
|
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 ε.)
|
#Julia
|
Julia
|
module RayCastings
export Point
struct Point{T}
x::T
y::T
end
Base.show(io::IO, p::Point) = print(io, "($(p.x), $(p.y))")
const Edge = Tuple{Point{T}, Point{T}} where T
Base.show(io::IO, e::Edge) = print(io, "$(e[1]) ∘-∘ $(e[2])")
function rayintersectseg(p::Point{T}, edge::Edge{T}) where T
a, b = edge
if a.y > b.y
a, b = b, a
end
if p.y ∈ (a.y, b.y)
p = Point(p.x, p.y + eps(p.y))
end
rst = false
if (p.y > b.y || p.y < a.y) || (p.x > max(a.x, b.x))
return false
end
if p.x < min(a.x, b.x)
rst = true
else
mred = (b.y - a.y) / (b.x - a.x)
mblu = (p.y - a.y) / (p.x - a.x)
rst = mblu ≥ mred
end
return rst
end
isinside(poly::Vector{Tuple{Point{T}, Point{T}}}, p::Point{T}) where T =
isodd(count(edge -> rayintersectseg(p, edge), poly))
connect(a::Point{T}, b::Point{T}...) where T =
[(a, b) for (a, b) in zip(vcat(a, b...), vcat(b..., a))]
end # module RayCastings
|
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.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref symbols nobinary
parse arg inFileName lineNr .
if inFileName = '' | inFileName = '.' then inFileName = './data/input.txt'
if lineNr = '' | lineNr = '.' then lineNr = 7
do
lineTxt = readLine(inFileName, lineNr)
say '<textline number="'lineNr.right(5, 0)'">'lineTxt'</textline>'
catch ex = Exception
ex.printStackTrace()
end
return
-- =============================================================================
-- NetRexx/Java programs don't have a special mechanism to seek to a specified line number
-- the simple solution is to iterate through file. (Costly for very large files)
method readLine(inFileName, lineNr) public static signals IOException, FileNotFoundException
lineReader = LineNumberReader(FileReader(File(inFileName)))
notFound = isTrue
lineTxt = ''
loop label reading forever
line = lineReader.readLine()
select
when lineReader.getLineNumber() = lineNr then do
lineTxt = line
notFound = isFalse
leave reading -- terminate I/O loop
end
when line = null then do
leave reading -- terminate I/O loop
end
otherwise nop
end
finally
lineReader.close()
end reading
if notFound then signal RuntimeException('File' inFileName 'does not contain line' lineNr.right(5))
return lineTxt
-- =============================================================================
method isTrue() public static returns boolean
return 1 == 1
-- =============================================================================
method isFalse() public static returns boolean
return \(1 == 1)
|
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.
|
#11l
|
11l
|
F rdp(l, ε) -> [(Float, Float)]
V x = 0
V dMax = -1.0
V p1 = l[0]
V p2 = l.last
V p21 = p2 - p1
L(p) l[1.<(len)-1]
V d = abs(cross(p, p21) + cross(p2, p1))
I d > dMax
x = L.index + 1
dMax = d
I dMax > ε
R rdp(l[0..x], ε) [+] rdp(l[x..], ε)[1..]
R [l[0], l.last]
print(rdp([(0.0, 0.0),
(1.0, 0.1),
(2.0,-0.1),
(3.0, 5.0),
(4.0, 6.0),
(5.0, 7.0),
(6.0, 8.1),
(7.0, 9.0),
(8.0, 9.0),
(9.0, 9.0)], 1.0))
|
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.
|
#C.2B.2B
|
C++
|
#include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
|
http://rosettacode.org/wiki/Ramanujan_primes/twins
|
Ramanujan primes/twins
|
In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins.
Related Task
Twin primes
|
#F.23
|
F#
|
// Twin Ramanujan primes. Nigel Galloway: September 9th., 2021
printfn $"There are %d{rP 1000000|>Seq.pairwise|>Seq.filter(fun(n,g)->n=g-2)|>Seq.length} twins in the first million Ramanujan primes"
|
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
|
#Aime
|
Aime
|
rp(list l)
{
integer a, i;
data b;
index x;
a = l[0];
x[a] = a;
for (, a in l) {
x[a == x.back + 1 ? x.high : a] = a;
}
for (i, a in x) {
b.form(a - i < 2 ? a - i ? "~,~," : "~," : "~-~,", i, a);
}
b.delete(-1);
}
main(void)
{
o_(rp(list(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)),
"\n");
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
|
#AWK
|
AWK
|
$ awk 'func r(){return sqrt(-2*log(rand()))*cos(6.2831853*rand())}BEGIN{for(i=0;i<1000;i++)s=s" "1+0.5*r();print s}'
|
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
|
#BASIC
|
BASIC
|
RANDOMIZE TIMER 'seeds random number generator with the system time
pi = 3.141592653589793#
DIM a(1 TO 1000) AS DOUBLE
CLS
FOR i = 1 TO 1000
a(i) = 1 + SQR(-2 * LOG(RND)) * COS(2 * pi * RND)
NEXT i
|
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.
|
#AWK
|
AWK
|
#include <stdio.h>
#include <stdlib.h>
/* Flip a coin, 10 times. */
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
|
http://rosettacode.org/wiki/Random_number_generator_(included)
|
Random number generator (included)
|
The task is to:
State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
|
#BASIC
|
BASIC
|
#include <stdio.h>
#include <stdlib.h>
/* Flip a coin, 10 times. */
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#COBOL
|
COBOL
|
identification division.
program-id. ReadConfiguration.
environment division.
configuration section.
repository.
function all intrinsic.
input-output section.
file-control.
select config-file assign to "Configuration.txt"
organization line sequential.
data division.
file section.
fd config-file.
01 config-record pic is x(128).
working-storage section.
77 idx pic 9(3).
77 pos pic 9(3).
77 last-pos pic 9(3).
77 config-key pic x(32).
77 config-value pic x(64).
77 multi-value pic x(64).
77 full-name pic x(64).
77 favourite-fruit pic x(64).
77 other-family pic x(64) occurs 10.
77 need-speeling pic x(5) value "false".
77 seeds-removed pic x(5) value "false".
procedure division.
main.
open input config-file
perform until exit
read config-file
at end
exit perform
end-read
move trim(config-record) to config-record
if config-record(1:1) = "#" or ";" or spaces
exit perform cycle
end-if
unstring config-record delimited by spaces into config-key
move trim(config-record(length(trim(config-key)) + 1:)) to config-value
if config-value(1:1) = "="
move trim(config-value(2:)) to config-value
end-if
evaluate upper-case(config-key)
when "FULLNAME"
move config-value to full-name
when "FAVOURITEFRUIT"
move config-value to favourite-fruit
when "NEEDSPEELING"
if config-value = spaces
move "true" to config-value
end-if
if config-value = "true" or "false"
move config-value to need-speeling
end-if
when "SEEDSREMOVED"
if config-value = spaces
move "true" to config-value
end-if,
if config-value = "true" or "false"
move config-value to seeds-removed
end-if
when "OTHERFAMILY"
move 1 to idx, pos
perform until exit
unstring config-value delimited by "," into multi-value with pointer pos
on overflow
move trim(multi-value) to other-family(idx)
move pos to last-pos
not on overflow
if config-value(last-pos:) <> spaces
move trim(config-value(last-pos:)) to other-family(idx)
end-if,
exit perform
end-unstring
add 1 to idx
end-perform
end-evaluate
end-perform
close config-file
display "fullname = " full-name
display "favouritefruit = " favourite-fruit
display "needspeeling = " need-speeling
display "seedsremoved = " seeds-removed
perform varying idx from 1 by 1 until idx > 10
if other-family(idx) <> low-values
display "otherfamily(" idx ") = " other-family(idx)
end-if
end-perform
.
|
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).
|
#J
|
J
|
rare =: ( np@:] *. (nbrPs rr) ) b10
np =: -.@:(-: |.) NB. Not palindromic
nbrPs =: > *. sdPs NB. n is Bigger than R and the perfect square constraint is satisfied
sdPs =: + *.&:ps - NB. n > rr and both their sum and difference are perfect squares
ps =: 0 = 1 | %: NB. Perfect square (integral sqrt)
rr =: 10&#.@:|. NB. Do note we do reverse the digits twice (once here, once in np)
b10 =: 10&#.^:_1 NB. Base 10 digits
|
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
|
#Arturo
|
Arturo
|
expandRange: function [rng][
flatten @ to :block
join.with:" " map split.by:"," rng 'x ->
replace replace replace x
{/^\-(\d+)/} "(neg $1)" {/\-\-(\d+)/}
"-(neg $1)" "-" ".."
]
print expandRange {-6,-3--1,3-5,7-11,14,15,17-20}
|
http://rosettacode.org/wiki/Read_a_file_line_by_line
|
Read a file line by line
|
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
|
#AWK
|
AWK
|
awk '{ print $0 }' filename
|
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.
|
#BASIC
|
BASIC
|
' Read a file line by line
filename$ = "readlines.bac"
OPEN filename$ FOR READING AS fh
READLN fl$ FROM fh
WHILE ISFALSE(ENDFILE(fh))
INCR lines
READLN fl$ FROM fh
WEND
PRINT lines, " lines in ", filename$
CLOSE FILE fh
|
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.
|
#J
|
J
|
competitors=:<;._1;._2]0 :0
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
)
scores=: {."1
standard=: 1+i.~
modified=: 1+i:~
dense=: #/.~ # #\@~.
ordinal=: #\
fractional=: #/.~ # ] (+/%#)/. #\
rank=:1 :'<"0@u@: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
|
#Java
|
Java
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class RangeConsolidation {
public static void main(String[] args) {
displayRanges( Arrays.asList(new Range(1.1, 2.2)));
displayRanges( Arrays.asList(new Range(6.1, 7.2), new Range(7.2, 8.3)));
displayRanges( Arrays.asList(new Range(4, 3), new Range(2, 1)));
displayRanges( Arrays.asList(new Range(4, 3), new Range(2, 1), new Range(-1, -2), new Range(3.9, 10)));
displayRanges( Arrays.asList(new Range(1, 3), new Range(-6, -1), new Range(-4, -5), new Range(8, 2), new Range(-6, -6)));
displayRanges( Arrays.asList(new Range(1, 1), new Range(1, 1)));
displayRanges( Arrays.asList(new Range(1, 1), new Range(1, 2)));
displayRanges( Arrays.asList(new Range(1, 2), new Range(3, 4), new Range(1.5, 3.5), new Range(1.2, 2.5)));
}
private static final void displayRanges(List<Range> ranges) {
System.out.printf("ranges = %-70s, colsolidated = %s%n", ranges, Range.consolidate(ranges));
}
private static final class RangeSorter implements Comparator<Range> {
@Override
public int compare(Range o1, Range o2) {
return (int) (o1.left - o2.left);
}
}
private static class Range {
double left;
double right;
public Range(double left, double right) {
if ( left <= right ) {
this.left = left;
this.right = right;
}
else {
this.left = right;
this.right = left;
}
}
public Range consolidate(Range range) {
// no overlap
if ( this.right < range.left ) {
return null;
}
// no overlap
if ( range.right < this.left ) {
return null;
}
// contained
if ( this.left <= range.left && this.right >= range.right ) {
return this;
}
// contained
if ( range.left <= this.left && range.right >= this.right ) {
return range;
}
// overlap
if ( this.left <= range.left && this.right <= range.right ) {
return new Range(this.left, range.right);
}
// overlap
if ( this.left >= range.left && this.right >= range.right ) {
return new Range(range.left, this.right);
}
throw new RuntimeException("ERROR: Logic invalid.");
}
@Override
public String toString() {
return "[" + left + ", " + right + "]";
}
private static List<Range> consolidate(List<Range> ranges) {
List<Range> consolidated = new ArrayList<>();
Collections.sort(ranges, new RangeSorter());
for ( Range inRange : ranges ) {
Range r = null;
Range conRange = null;
for ( Range conRangeLoop : consolidated ) {
r = inRange.consolidate(conRangeLoop);
if (r != null ) {
conRange = conRangeLoop;
break;
}
}
if ( r == null ) {
consolidated.add(inRange);
}
else {
consolidated.remove(conRange);
consolidated.add(r);
}
}
Collections.sort(consolidated, new RangeSorter());
return consolidated;
}
}
}
|
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
|
#Oberon
|
Oberon
|
MODULE reverse;
IMPORT Out, Strings;
VAR s: ARRAY 12 + 1 OF CHAR;
PROCEDURE Swap(VAR c, d: CHAR);
VAR oldC: CHAR;
BEGIN
oldC := c; c := d; d := oldC
END Swap;
PROCEDURE Reverse(VAR s: ARRAY OF CHAR);
VAR len, i: INTEGER;
BEGIN
len := Strings.Length(s);
FOR i := 0 TO len DIV 2 DO
Swap(s[i], s[len - 1 - i])
END
END Reverse;
BEGIN
s := "hello, world";
Reverse(s);
Out.String(s);
Out.Ln
END 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)
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::uniform_int_distribution<long> dist; // long is guaranteed to be 32 bits
std::cout << "Random Number: " << dist(rd) << std::endl;
}
|
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)
|
#C.23
|
C#
|
using System;
using System.Security.Cryptography;
private static int GetRandomInt()
{
int result = 0;
var rng = new RNGCryptoServiceProvider();
var buffer = new byte[4];
rng.GetBytes(buffer);
result = BitConverter.ToInt32(buffer, 0);
return result;
}
|
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
|
#11l
|
11l
|
F _transpose(matrix)
assert(matrix.len == matrix[0].len)
V r = [[0] * matrix.len] * matrix.len
L(i) 0 .< matrix.len
L(j) 0 .< matrix.len
r[i][j] = matrix[j][i]
R r
F _shuffle_transpose_shuffle(matrix)
V square = copy(matrix)
random:shuffle(&square)
V trans = _transpose(square)
random:shuffle(&trans)
R trans
F _rls(&symbols)
V n = symbols.len
I n == 1
R [symbols]
E
V sym = random:choice(symbols)
symbols.remove(sym)
V square = _rls(&symbols)
square.append(copy(square[0]))
L(i) 0 .< n
square[i].insert(i, sym)
R square
F rls(n)
V symbols = Array(0 .< n)
V square = _rls(&symbols)
R _shuffle_transpose_shuffle(square)
F _check_rows(square)
V set_row0 = Set(square[0])
R all(square.map(row -> row.len == Set(row).len & Set(row) == @set_row0))
F _check(square)
V transpose = _transpose(square)
assert(_check_rows(square) & _check_rows(transpose), ‘Not a Latin square’)
L(i) [3, 3, 5, 5]
V square = rls(i)
print(square.map(row -> row.join(‘ ’)).join("\n"))
_check(square)
print()
|
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 ε.)
|
#Kotlin
|
Kotlin
|
import java.lang.Double.MAX_VALUE
import java.lang.Double.MIN_VALUE
import java.lang.Math.abs
data class Point(val x: Double, val y: Double)
data class Edge(val s: Point, val e: Point) {
operator fun invoke(p: Point) : Boolean = when {
s.y > e.y -> Edge(e, s).invoke(p)
p.y == s.y || p.y == e.y -> invoke(Point(p.x, p.y + epsilon))
p.y > e.y || p.y < s.y || p.x > Math.max(s.x, e.x) -> false
p.x < Math.min(s.x, e.x) -> true
else -> {
val blue = if (abs(s.x - p.x) > MIN_VALUE) (p.y - s.y) / (p.x - s.x) else MAX_VALUE
val red = if (abs(s.x - e.x) > MIN_VALUE) (e.y - s.y) / (e.x - s.x) else MAX_VALUE
blue >= red
}
}
val epsilon = 0.00001
}
class Figure(val name: String, val edges: Array<Edge>) {
operator fun contains(p: Point) = edges.count({ it(p) }) % 2 != 0
}
object Ray_casting {
fun check(figures : Array<Figure>, points : List<Point>) {
println("points: " + points)
figures.forEach { f ->
println("figure: " + f.name)
f.edges.forEach { println(" " + it) }
println("result: " + (points.map { it in f }))
}
}
}
|
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.
|
#Nim
|
Nim
|
import strformat
proc readLine(f: File; num: Positive): string =
for n in 1..num:
try:
result = f.readLine()
except EOFError:
raise newException(IOError, &"Not enough lines in file; expected {num}, found {n - 1}.")
let f = open("test.txt", fmRead)
echo f.readLine(7)
f.close()
|
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.
|
#OCaml
|
OCaml
|
let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let nth_line n filename =
let ic = open_in filename in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i = n then begin
close_in ic;
(line)
end else aux (succ i)
| None ->
close_in ic;
failwith "end of file reached"
in
aux 1
let () =
print_endline (nth_line 7 Sys.argv.(1))
|
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.
|
#C
|
C
|
#include <assert.h>
#include <math.h>
#include <stdio.h>
typedef struct point_tag {
double x;
double y;
} point_t;
// Returns the distance from point p to the line between p1 and p2
double perpendicular_distance(point_t p, point_t p1, point_t p2) {
double dx = p2.x - p1.x;
double dy = p2.y - p1.y;
double d = sqrt(dx * dx + dy * dy);
return fabs(p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.x)/d;
}
// Simplify an array of points using the Ramer–Douglas–Peucker algorithm.
// Returns the number of output points.
size_t douglas_peucker(const point_t* points, size_t n, double epsilon,
point_t* dest, size_t destlen) {
assert(n >= 2);
assert(epsilon >= 0);
double max_dist = 0;
size_t index = 0;
for (size_t i = 1; i + 1 < n; ++i) {
double dist = perpendicular_distance(points[i], points[0], points[n - 1]);
if (dist > max_dist) {
max_dist = dist;
index = i;
}
}
if (max_dist > epsilon) {
size_t n1 = douglas_peucker(points, index + 1, epsilon, dest, destlen);
if (destlen >= n1 - 1) {
destlen -= n1 - 1;
dest += n1 - 1;
} else {
destlen = 0;
}
size_t n2 = douglas_peucker(points + index, n - index, epsilon, dest, destlen);
return n1 + n2 - 1;
}
if (destlen >= 2) {
dest[0] = points[0];
dest[1] = points[n - 1];
}
return 2;
}
void print_points(const point_t* points, size_t n) {
for (size_t i = 0; i < n; ++i) {
if (i > 0)
printf(" ");
printf("(%g, %g)", points[i].x, points[i].y);
}
printf("\n");
}
int main() {
point_t points[] = {
{0,0}, {1,0.1}, {2,-0.1}, {3,5}, {4,6},
{5,7}, {6,8.1}, {7,9}, {8,9}, {9,9}
};
const size_t len = sizeof(points)/sizeof(points[0]);
point_t out[len];
size_t n = douglas_peucker(points, len, 1.0, out, len);
print_points(out, n);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.