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/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).
|
#Tcl
|
Tcl
|
set result [lsort -unique $listname]
|
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).
|
#True_BASIC
|
True BASIC
|
OPTION BASE 1
LET max = 10
DIM dat(10), res(10)
FOR i = 1 TO max
READ dat(i)
NEXT i
DATA 1, 2, 1, 4, 5, 2, 15, 1, 3, 4
LET res(1) = dat(1)
LET count = 1
LET posic = 1
DO WHILE posic < max
LET posic = posic + 1
LET esnuevo = 1
LET indice = 1
DO WHILE (indice <= count) AND esnuevo = 1
IF dat(posic) = res(indice) THEN LET esnuevo = 0
LET indice = indice + 1
LOOP
IF esnuevo = 1 THEN
LET count = count + 1
LET res(count) = dat(posic)
END IF
LOOP
FOR i = 1 TO count
PRINT res(i);
NEXT i
END
|
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
|
#Racket
|
Racket
|
#lang racket
;; Racket has a useful `time*' macro that does just what's requested:
;; run some expression N times, and produce timing results
(require unstable/time)
;; Sample use:
(define (fib n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(time* 10 (fib 38))
;; But of course, can be used to measure external processes too:
(time* 10 (system "sleep 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
|
#Raku
|
Raku
|
sub runrate($N where $N > 0, &todo) {
my $n = $N;
my $start = now;
todo() while --$n;
my $end = now;
say "Start time: ", DateTime.new($start).Str;
say "End time: ", DateTime.new($end).Str;
my $elapsed = $end - $start;
say "Elapsed time: $elapsed seconds";
say "Rate: { ($N / $elapsed).fmt('%.2f') } per second\n";
}
sub factorial($n) { (state @)[$n] //= $n < 2 ?? 1 !! $n * factorial($n-1) }
runrate 10000, { state $n = 1; factorial($n++) }
runrate 10000, { state $n = 1; factorial($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
|
#min
|
min
|
("" split reverse "" join) :reverse-str
|
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 ε.)
|
#AutoHotkey
|
AutoHotkey
|
Points :=[{x: 5.0, y: 5.0}
, {x: 5.0, y: 8.0}
, {x:-10.0, y: 5.0}
, {x: 0.0, y: 5.0}
, {x: 10.0, y: 5.0}
, {x: 8.0, y: 5.0}
, {x: 10.0, y:10.0}]
Square :=[{x: 0.0, y: 0.0}, {x:10.0, y: 0.0}
, {x:10.0, y: 0.0}, {x:10.0, y:10.0}
, {x:10.0, y:10.0}, {x: 0.0, y:10.0}
, {x: 0.0, y:10.0}, {x: 0.0, y: 0.0}]
Sq_Hole:=[{x: 0.0, y: 0.0}, {x:10.0, y: 0.0}
, {x:10.0, y: 0.0}, {x:10.0, y:10.0}
, {x:10.0, y:10.0}, {x: 0.0, y:10.0}
, {x: 0.0, y:10.0}, {x: 0.0, y: 0.0}
, {x: 2.5, y: 2.5}, {x: 7.5, y: 2.5}
, {x: 7.5, y: 2.5}, {x: 7.5, y: 7.5}
, {x: 7.5, y: 7.5}, {x: 2.5, y: 7.5}
, {x: 2.5, y: 7.5}, {x: 2.5, y: 2.5}]
Strange:=[{x: 0.0, y: 0.0}, {x: 2.5, y: 2.5}
, {x: 2.5, y: 2.5}, {x: 0.0, y:10.0}
, {x: 0.0, y:10.0}, {x: 2.5, y: 7.5}
, {x: 2.5, y: 7.5}, {x: 7.5, y: 7.5}
, {x: 7.5, y: 7.5}, {x:10.0, y:10.0}
, {x:10.0, y:10.0}, {x:10.0, y: 0.0}
, {x:10.0, y: 0.0}, {x: 2.5, y: 2.5}]
Exagon :=[{x: 3.0, y: 0.0}, {x: 7.0, y: 0.0}
, {x: 7.0, y: 0.0}, {x:10.0, y: 5.0}
, {x:10.0, y: 5.0}, {x: 7.0, y:10.0}
, {x: 7.0, y:10.0}, {x: 3.0, y:10.0}
, {x: 3.0, y:10.0}, {x: 0.0, y: 5.0}
, {x: 0.0, y: 5.0}, {x: 3.0, y: 0.0}]
Polygons := {"Square":Square, "Sq_Hole":Sq_Hole, "Strange":Strange, "Exagon":Exagon}
For j, Poly in Polygons
For i, Point in Points
If (point_in_polygon(Point,Poly))
s.= j " does contain point " i "`n"
Else
s.= j " doesn't contain point " i "`n"
Msgbox %s%
point_in_polygon(Point,Poly) {
n:=Poly.MaxIndex()
count:=0
loop, %n% {
if (ray_intersects_segment(Point,Poly[A_Index],Poly[mod(A_Index,n)+1])) {
count++
}
}
if (mod(count,2)) { ; true = inside, false = outside
return true ; P is in the polygon
} else {
return false ; P isn't in the polygon
}
}
ray_intersects_segment(P,A,B) {
;P = the point from which the ray starts
;A = the end-point of the segment with the smallest y coordinate
;B = the end-point of the segment with the greatest y coordinate
if (A.y > B.y) {
temp:=A
A:=B
B:=temp
}
if (P.y = A.y or P.y = B.y) {
P.y += 0.000001
}
if (P.y < A.y or P.y > B.y) {
return false
} else if (P.x > A.x && P.x > B.x) {
return false
} else {
if (P.x < A.x && P.x < B.x) {
return true
} else {
if (A.x != B.x) {
m_red := (B.y - A.y)/(B.x - A.x)
} else {
m_red := "inf"
}
if (A.x != P.x) {
m_blue := (P.y - A.y)/(P.x - A.x)
} else {
m_blue := "inf"
}
if (m_blue >= m_red) {
return true
} else {
return false
}
}
}
}
|
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.
|
#Go
|
Go
|
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
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.
|
#AutoHotkey
|
AutoHotkey
|
Rank(data, opt:=1){ ; opt = 1 Standard (default), 2 Modified, 3 Dense, 4 Ordinal, 5 Fractional
for index, val in StrSplit(data, "`n", "`r") {
RegExMatch(val, "^(\d+)\s+(.*)", Match)
if !(Match1=prev)
n := index
prev := Match1
Res1 .= n "`t" Match "`n"
Res4 .= index "`t" Match "`n"
Temp .= n ":" index " " Match "`n"
}
n:=0
while pos := RegExMatch(Temp, "`asm)^(\d+).*?\R(?!\1)|.+", Match, pos?pos+StrLen(Match):1) {
n += StrSplit(Trim(Match, "`r`n"), "`n", "`r").MaxIndex()
Res2 .= RegExReplace(Match, "`am)^\d+:\d+", n "`t")
Res3 .= RegExReplace(Match, "`am)^\d+:\d+", A_Index "`t")
R := 0
for index, val in StrSplit(Match, "`n", "`r")
R += StrSplit(val, ":").2
Res5 .= RegExReplace(Match, "`am)^\d+:\d+", RegExReplace(R / StrSplit(Trim(Match, "`r`n"), "`n", "`r").MaxIndex(), "\.?0+$") "`t")
}
return Res%opt%
}
|
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).
|
#TSE_SAL
|
TSE SAL
|
//
// 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.
//
INTEGER PROC FNBlockGetUniqueAllToBufferB( INTEGER bufferI )
INTEGER B = FALSE
INTEGER downB = TRUE
STRING s[255] = ""
IF ( NOT ( IsBlockInCurrFile() ) ) Warn( "Please mark a block" ) B = FALSE RETURN( B ) ENDIF // return from the current procedure if no block is marked
PushPosition()
PushBlock()
GotoBlockBegin()
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
s = GetText( 1, MAXSTRINGLEN )
PushPosition()
PushBlock()
GotoBufferId( bufferI )
IF NOT LFind( s, "" )
AddLine( s )
ENDIF
PopBlock()
PopPosition()
downB = Down()
ENDWHILE
PopPosition()
PopBlock()
B = TRUE
RETURN( B )
END
//
PROC Main()
INTEGER bufferI = 0
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
Message( FNBlockGetUniqueAllToBufferB( bufferI ) ) // gives e.g. TRUE
GotoBufferId( bufferI )
END
|
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
|
#REXX
|
REXX
|
/*REXX program reports on the amount of elapsed time 4 different tasks use (wall clock).*/
time.= /*nullify times for all the tasks below*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
call time 'Reset' /*reset the REXX (elapsed) clock timer.*/
/*show pi in hex to 2,000 dec. digits.*/
task.1= 'base(pi,16) ;;; lowercase digits 2k echoOptions'
call '$CALC' task.1 /*perform task number one (via $CALC).*/
time.1=time('E') /*get and save the time used by task 1.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
call time 'Reset' /*reset the REXX (elapsed) clock timer.*/
/*get primes 40000 ──► 40800 and */
/*show their differences. */
task.2= 'diffs[ prime(40k, 40.8k) ] ;;; GRoup 20'
call '$CALC' task.2 /*perform task number two (via $CALC).*/
time.2=time('E') /*get and save the time used by task 2.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
call time 'Reset' /*reset the REXX (elapsed) clock timer.*/
/*show the Collatz sequence for a */
/*stupidly gihugeic number. */
task.3= 'Collatz(38**8) ;;; Horizontal'
call '$CALC' task.3 /*perform task number three (via $CALC)*/
time.3=time('E') /*get and save the time used by task 3.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
call time 'Reset' /*reset the REXX (elapsed) clock timer.*/
/*plot SINE in ½ degree increments.*/
/*using five decimal digits (¬ 60). */
task.4= 'sinD(-180, +180, 0.5) ;;; Plot DIGits 5 echoOptions'
call '$CALC' task.4 /*perform task number four (via $CALC).*/
time.4=time('E') /*get and save the time used by task 4.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
say
do j=1 while time.j\==''
say 'time used for task' j "was" right(format(time.j,,0),4) 'seconds.'
end /*j*/
/*stick a fork in it, we're all done. */
|
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
|
#MiniScript
|
MiniScript
|
str = "This is a string"
print "Forward: " + str
newStr = ""
for i in range(str.len-1, 0)
newStr = newStr + str[i]
end for
print "Reversed: " + newStr
|
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 ε.)
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;
#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}
#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }
BIN_V(sub, a.x - b.x, a.y - b.y);
BIN_V(add, a.x + b.x, a.y + b.y);
BIN_S(dot, a.x * b.x + a.y * b.y);
BIN_S(cross, a.x * b.y - a.y * b.x);
/* return a + s * b */
vec vmadd(vec a, double s, vec b)
{
vec c;
c.x = a.x + s * b.x;
c.y = a.y + s * b.y;
return c;
}
/* check if x0->x1 edge crosses y0->y1 edge. dx = x1 - x0, dy = y1 - y0, then
solve x0 + a * dx == y0 + b * dy with a, b in real
cross both sides with dx, then: (remember, cross product is a scalar)
x0 X dx = y0 X dx + b * (dy X dx)
similarly,
x0 X dy + a * (dx X dy) == y0 X dy
there is an intersection iff 0 <= a <= 1 and 0 <= b <= 1
returns: 1 for intersect, -1 for not, 0 for hard to say (if the intersect
point is too close to y0 or y1)
*/
int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)
{
vec dx = vsub(x1, x0), dy = vsub(y1, y0);
double d = vcross(dy, dx), a;
if (!d) return 0; /* edges are parallel */
a = (vcross(x0, dx) - vcross(y0, dx)) / d;
if (sect)
*sect = vmadd(y0, a, dy);
if (a < -tol || a > 1 + tol) return -1;
if (a < tol || a > 1 - tol) return 0;
a = (vcross(x0, dy) - vcross(y0, dy)) / d;
if (a < 0 || a > 1) return -1;
return 1;
}
/* distance between x and nearest point on y0->y1 segment. if the point
lies outside the segment, returns infinity */
double dist(vec x, vec y0, vec y1, double tol)
{
vec dy = vsub(y1, y0);
vec x1, s;
int r;
x1.x = x.x + dy.y; x1.y = x.y - dy.x;
r = intersect(x, x1, y0, y1, tol, &s);
if (r == -1) return HUGE_VAL;
s = vsub(s, x);
return sqrt(vdot(s, s));
}
#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)
/* returns 1 for inside, -1 for outside, 0 for on edge */
int inside(vec v, polygon p, double tol)
{
/* should assert p->n > 1 */
int i, k, crosses, intersectResult;
vec *pv;
double min_x, max_x, min_y, max_y;
for (i = 0; i < p->n; i++) {
k = (i + 1) % p->n;
min_x = dist(v, p->v[i], p->v[k], tol);
if (min_x < tol) return 0;
}
min_x = max_x = p->v[0].x;
min_y = max_y = p->v[1].y;
/* calculate extent of polygon */
for_v(i, pv, p) {
if (pv->x > max_x) max_x = pv->x;
if (pv->x < min_x) min_x = pv->x;
if (pv->y > max_y) max_y = pv->y;
if (pv->y < min_y) min_y = pv->y;
}
if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)
return -1;
max_x -= min_x; max_x *= 2;
max_y -= min_y; max_y *= 2;
max_x += max_y;
vec e;
while (1) {
crosses = 0;
/* pick a rand point far enough to be outside polygon */
e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;
e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;
for (i = 0; i < p->n; i++) {
k = (i + 1) % p->n;
intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);
/* picked a bad point, ray got too close to vertex.
re-pick */
if (!intersectResult) break;
if (intersectResult == 1) crosses++;
}
if (i == p->n) break;
}
return (crosses & 1) ? 1 : -1;
}
int main()
{
vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10},
{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};
polygon_t sq = { 4, vsq }, /* outer square */
sq_hole = { 8, vsq }; /* outer and inner square, ie hole */
vec c = { 10, 5 }; /* on edge */
vec d = { 5, 5 };
printf("%d\n", inside(c, &sq, 1e-10));
printf("%d\n", inside(c, &sq_hole, 1e-10));
printf("%d\n", inside(d, &sq, 1e-10)); /* in */
printf("%d\n", inside(d, &sq_hole, 1e-10)); /* out (in the hole) */
return 0;
}
|
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
|
Read a specific line from a file
|
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
|
#Groovy
|
Groovy
|
def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
line = currentLine
}
}
println "Line 7 = $line"
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#APL
|
APL
|
standard ← ∊∘(⌊\¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢
modified ← ∊∘(⌈\∘⌽¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢
dense ← (+\1,2≠/1⌷[2]⊢),⊢
ordinal ← ⍳∘≢,⊢
fractional ← ∊∘((≢(/∘⊢)+/÷≢)¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢
|
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).
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
list_old="b'A'A'5'1'2'3'2'3'4"
list_sort=MIXED_SORT (list_old)
list_new=REDUCE (list_sort)
PRINT list_old
PRINT list_new
|
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
|
#11l
|
11l
|
F consolidate(ranges)
F normalize(s)
R sorted(s.filter(bounds -> !bounds.empty).map(bounds -> sorted(bounds)))
V norm = normalize(ranges)
L(&r1) norm
V i = L.index
I !r1.empty
L(j) i + 1 .< norm.len
V& r2 = norm[j]
I !r2.empty & r1.last >= r2[0]
r1 = [r1[0], max(r1.last, r2.last)]
r2.clear()
R norm.filter(rnge -> !rnge.empty)
L(s) [[[1.1, 2.2]],
[[6.1, 7.2], [7.2, 8.3]],
[[4.0, 3.0], [2.0, 1.0]],
[[4.0, 3.0], [2.0, 1.0], [-1.0, -2.0], [3.9, 10.0]],
[[1.0, 3.0], [-6.0, -1.0], [-4.0, -5.0], [8.0, 2.0], [-6.0, -6.0]]]
print(String(s)[1 .< (len)-1]‘ => ’String(consolidate(s))[1 .< (len)-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
|
#Ring
|
Ring
|
# Project : Rate counter
see "method 1: calculate reciprocal of elapsed time:" + nl
for trial = 1 to 3
start = clock()
tasktomeasure()
finish = clock()
see "rate = " + 100 / (finish-start) + " per second" + nl
next
see "method 2: count completed tasks in one second:" + nl
for trial = 1 to 3
runs = 0
finish = clock() + 100
while clock() < finish
tasktomeasure()
if clock() < finish
runs = runs + 1
ok
end
see "rate = " + runs + " per second" + nl
next
func tasktomeasure
for i = 1 to 100000
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
|
#MIPS_Assembly
|
MIPS Assembly
|
# First, it gets the length of the original string
# Then, it allocates memory from the copy
# Then it copies the pointer to the original string, and adds the strlen
# subtract 1, then that new pointer is at the last char.
# while(strlen)
# copy char
# decrement strlen
# decrement source pointer
# increment target pointer
.text
strcpy:
addi $sp, $sp, -4
sw $s0, 0($sp)
add $s0, $zero, $zero
L1:
add $t1, $s0, $a1
lb $t2, 0($t1)
add $t3, $s0, $a0
sb $t2, 0($t3)
beq $t2, $zero, L2
addi $s0, $s0, 1
j L1
L2:
lw $s0, 0($sp)
addi $sp, $sp, 4
jr $ra
.data
ex_msg_og: .asciiz "Original string:\n"
ex_msg_cpy: .asciiz "\nCopied string:\n"
string: .asciiz "Nice string you got there!\n"
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
using namespace std;
const double epsilon = numeric_limits<float>().epsilon();
const numeric_limits<double> DOUBLE;
const double MIN = DOUBLE.min();
const double MAX = DOUBLE.max();
struct Point { const double x, y; };
struct Edge {
const Point a, b;
bool operator()(const Point& p) const
{
if (a.y > b.y) return Edge{ b, a }(p);
if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });
if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;
if (p.x < min(a.x, b.x)) return true;
auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;
auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;
return blue >= red;
}
};
struct Figure {
const string name;
const initializer_list<Edge> edges;
bool contains(const Point& p) const
{
auto c = 0;
for (auto e : edges) if (e(p)) c++;
return c % 2 != 0;
}
template<unsigned char W = 3>
void check(const initializer_list<Point>& points, ostream& os) const
{
os << "Is point inside figure " << name << '?' << endl;
for (auto p : points)
os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl;
os << endl;
}
};
int main()
{
const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };
const Figure square = { "Square",
{ {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }
};
const Figure square_hole = { "Square hole",
{ {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},
{{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}
}
};
const Figure strange = { "Strange",
{ {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},
{{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}
}
};
const Figure exagon = { "Exagon",
{ {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},
{{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}
}
};
for(auto f : {square, square_hole, strange, exagon})
f.check(points, cout);
return EXIT_SUCCESS;
}
|
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.
|
#Haskell
|
Haskell
|
main :: IO ()
main = do contents <- readFile filename
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
where filename = "testfile"
|
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.
|
#AWK
|
AWK
|
##
## Dense ranking in file: ranking_d.awk
##
BEGIN{ lastresult = "!"; lastrank = 0 }
function d_rank(){
if($1==lastresult){
print lastrank, $0
}else{
lastresult = $1
print ++lastrank, $0 }
}
//{d_rank() }
##
## Fractional ranking in file: ranking_f.awk
##
BEGIN{
last = "!"
flen = 0 }
function f_rank(){
item = $0
if($1!=last){
if(flen){
sum = 0
for(fl=0; fl < flen;){
$0 = fifo[fl++]
sum += $1 }
mean = sum / flen
for(fl=0; fl < flen;){
$0 = fifo[fl++]
$1 = ""
printf("%3g %s\n", mean, $0) }
flen = 0
}}
$0 = item
last = $1
fifo[flen++] = sprintf("%i %s", FNR, item)
}
//{f_rank()}
END{ if(flen){
sum = 0
for(fl=0; fl < flen;){
$0 = fifo[fl++]
sum += $1 }
mean = sum / flen
for(fl=0; fl < flen;){
$0 = fifo[fl++]
$1 = ""
printf("%3g %s\n", mean, $0) }}}
##
## Modified competition ranking in file: ranking_mc.awk
##
BEGIN{
lastresult = "!"
flen = 0 }
function mc_rank(){
if($1==lastresult){
fifo[flen++] = $0
}else{
for(fl=0; fl < flen;){
print FNR-1, fifo[fl++]}
flen = 0
fifo[flen++] = $0
lastresult = $1}
}
//{mc_rank()}
END{ for(fl=0; fl < flen;){
print FNR, fifo[fl++]} }
##
## Ordinal ranking in file: ranking_o.awk
##
function o_rank(){ print FNR, $0 }
//{o_rank() }
##
## Standard competition ranking in file: ranking_sc.awk
##
BEGIN{ lastresult = lastrank = "!" }
function sc_rank(){
if($1==lastresult){
print lastrank, $0
}else{
print FNR, $0
lastresult = $1
lastrank = FNR}
}
//{sc_rank()}
|
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).
|
#UnixPipes
|
UnixPipes
|
bash$ # original list
bash$ printf '6\n2\n3\n6\n4\n2\n'
6
2
3
6
4
2
bash$ # made uniq
bash$ printf '6\n2\n3\n6\n4\n2\n'|sort -n|uniq
2
3
4
6
bash$
|
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
|
#Action.21
|
Action!
|
INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
DEFINE RANGESIZE="12"
DEFINE LOW_="+0"
DEFINE HIGH_="+6"
TYPE Range=[CARD l1,l2,l3,h1,h2,h3]
PROC Inverse(Range POINTER r)
REAL tmp
RealAssign(r LOW_,tmp)
RealAssign(r HIGH_,r LOW_)
RealAssign(tmp,r HIGH_)
RETURN
PROC Normalize(Range POINTER r)
IF RealLess(r HIGH_,r LOW_) THEN
Inverse(r)
FI
RETURN
INT FUNC Compare(Range Pointer r1,r2)
IF RealLess(r1 LOW_,r2 LOW_) THEN
RETURN (-1)
ELSEIF RealLess(r2 LOW_,r1 LOW_) THEN
RETURN (1)
ELSEIF RealLess(r1 HIGH_,r2 HIGH_) THEN
RETURN (-1)
ELSEIF RealLess(r2 HIGH_,r1 HIGH_) THEN
RETURN (1)
FI
RETURN (0)
PTR FUNC GetItemAddr(PTR data INT index)
RETURN (data+index*RANGESIZE)
PROC Swap(Range POINTER r1,r2)
REAL tmp
RealAssign(r1 LOW_,tmp)
RealAssign(r2 LOW_,r1 LOW_)
RealAssign(tmp, r2 LOW_)
RealAssign(r1 HIGH_,tmp)
RealAssign(r2 HIGH_,r1 HIGH_)
RealAssign(tmp, r2 HIGH_)
RETURN
PROC Sort(PTR data INT count)
INT i,j,minpos
Range POINTER r1,r2
FOR i=0 TO count-2
DO
minpos=i
FOR j=i+1 TO count-1
DO
r1=GetItemAddr(data,minpos)
r2=GetItemAddr(data,j)
IF Compare(r1,r2)>0 THEN
minpos=j
FI
OD
IF minpos#i THEN
r1=GetItemAddr(data,minpos)
r2=GetItemAddr(data,i)
Swap(r1,r2)
FI
OD
RETURN
PROC Consolidate(PTR data INT POINTER count)
INT i,j,newCount
Range POINTER r1,r2
FOR i=0 TO count^-1
DO
r1=GetItemAddr(data,i)
Normalize(r1)
OD
Sort(data,count^)
newCount=0 i=0
WHILE i<count^
DO
j=i+1
WHILE j<count^
DO
r1=GetItemAddr(data,i)
r2=GetItemAddr(data,j)
IF RealLess(r1 HIGH_,r2 LOW_) THEN
EXIT
ELSEIF RealLess(r1 HIGH_,r2 HIGH_) THEN
RealAssign(r2 HIGH_,r1 HIGH_)
FI
j==+1
OD
r1=GetItemAddr(data,i)
r2=GetItemAddr(data,newCount)
RealAssign(r1 LOW_,r2 LOW_)
RealAssign(r1 HIGH_,r2 HIGH_)
newCount==+1
i=j
OD
count^=newCount
RETURN
PROC PrintRanges(PTR data INT count)
INT i
Range POINTER r
FOR i=0 TO count-1
DO
IF i>0 THEN Put(' ) FI
r=GetItemAddr(data,i)
Put('[) PrintR(r LOW_)
Put(',) PrintR(r HIGH_) Put('])
OD
RETURN
PROC Append(PTR data INT POINTER count
CHAR ARRAY sLow,sHigh)
Range POINTER r
r=GetItemAddr(data,count^)
ValR(sLow,r LOW_)
ValR(sHigh,r High_)
count^=count^+1
RETURN
INT FUNC InitData(BYTE case PTR data)
INT count
count=0
IF case=0 THEN
Append(data,@count,"1.1","2.2")
ELSEIF case=1 THEN
Append(data,@count,"6.1","7.2")
Append(data,@count,"7.2","8.3")
ELSEIF case=2 THEN
Append(data,@count,"4","3")
Append(data,@count,"2","1")
ELSEIF case=3 THEN
Append(data,@count,"4","3")
Append(data,@count,"2","1")
Append(data,@count,"-1","-2")
Append(data,@count,"3.9","10")
ELSEIF case=4 THEN
Append(data,@count,"1","3")
Append(data,@count,"-6","-1")
Append(data,@count,"-4","-5")
Append(data,@count,"8","2")
Append(data,@count,"-6","-6")
FI
RETURN (count)
PROC Main()
BYTE ARRAY data(100)
INT count
BYTE i
Put(125) PutE() ;clear the screen
FOR i=0 TO 4
DO
count=InitData(i,data)
PrintRanges(data,count)
Print(" -> ")
Consolidate(data,@count)
PrintRanges(data,count)
PutE() PutE()
OD
RETURN
|
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
|
#Ruby
|
Ruby
|
require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
documents_h = {}
1.upto(10_000) do |n|
d = Document.new(n)
documents_a << d
documents_h[d.id] = d
end
searchlist = Array.new(1000){ rand(10_000)+1 }
Benchmark.bm(10) do |x|
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }
x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} }
end
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Mirah
|
Mirah
|
def reverse(s:string)
StringBuilder.new(s).reverse
end
puts reverse('reversed')
|
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 ε.)
|
#CoffeeScript
|
CoffeeScript
|
Point = (@x,@y) ->
pointInPoly = (point,poly) ->
segments = for pointA, index in poly
pointB = poly[(index + 1) % poly.length]
[pointA,pointB]
intesected = (segment for segment in segments when rayIntesectsSegment(point,segment))
intesected.length % 2 != 0
rayIntesectsSegment = (p,segment) ->
[p1,p2] = segment
[a,b] = if p1.y < p2.y
[p1,p2]
else
[p2,p1]
if p.y == b.y || p.y == a.y
p.y += Number.MIN_VALUE
if p.y > b.y || p.y < a.y
false
else if p.x > a.x && p.x > b.x
false
else if p.x < a.x && p.x < b.x
true
else
mAB = (b.y - a.y) / (b.x - a.x)
mAP = (p.y - a.y) / (p.x - a.x)
mAP > mAB
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
write(readline("foo.bar.txt",7)|"failed")
end
procedure readline(f,n) # return n'th line of file f
f := open(\f,"r") | fail # open file
every i := n & line := |read(f) \ n do i -:= 1 # <== here
close(f)
if i = 0 then return line
end
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#11l
|
11l
|
F readconf(fname)
[String = String] ret
L(=line) File(fname).read_lines()
line = line.trim((‘ ’, "\t", "\r", "\n"))
I line == ‘’ | line.starts_with(‘#’)
L.continue
V boolval = 1B
I line.starts_with(‘;’)
line = line.ltrim(‘;’)
I line.split_py().len != 1
L.continue
boolval = 0B
V bits = line.split(‘ ’, 2, group_delimiters' 1B)
String k, v
I bits.len == 1
k = bits[0]
v = String(boolval)
E
(k, v) = bits
ret[k.lowercase()] = v
R ret
V conf = readconf(‘config.txt’)
L(k, v) sorted(conf.items())
print(k‘ = ’v)
|
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.
|
#BASIC
|
BASIC
|
10 READ N
20 DIM S(N),N$(N),R(N)
30 FOR I=1 TO N: READ S(I),N$(I): NEXT
40 PRINT "--- Standard ranking ---": GOSUB 100: GOSUB 400
50 PRINT "--- Modified ranking ---": GOSUB 150: GOSUB 400
60 PRINT "--- Dense ranking ---": GOSUB 200: GOSUB 400
70 PRINT "--- Ordinal ranking ---": GOSUB 250: GOSUB 400
80 PRINT "--- Fractional ranking ---": GOSUB 300: GOSUB 400
90 END
100 REM
101 REM ** Ordinal ranking **
110 R(1)=1
120 FOR I=2 TO N
130 IF S(I)=S(I-1) THEN R(I)=R(I-1) ELSE R(I)=I
140 NEXT: RETURN
150 REM
151 REM ** Modified ranking **
160 R(N)=N
170 FOR I=N-1 TO 1 STEP -1
180 IF S(I)=S(I+1) THEN R(I)=R(I+1) ELSE R(I)=I
190 NEXT: RETURN
200 REM
201 REM ** Dense ranking **
210 R(1)=1
220 FOR I=2 TO N: R(I)=R(I-1)-(S(I)<>S(I-1)): NEXT
230 RETURN
250 REM
251 REM ** Ordinal ranking **
260 FOR I=1 TO N: R(I)=I: NEXT: RETURN
300 REM
301 REM ** Fractional ranking **
310 I=1: J=2
320 IF J<=N THEN IF S(J-1)=S(J) THEN J=J+1: GOTO 320
330 FOR K=I TO J-1: R(K) = (I+J-1)/2: NEXT
340 I=J: J=J+1: IF I<=N THEN 320
350 RETURN
400 REM
401 REM ** Print the table ***
410 FOR I=1 TO N
420 PRINT USING "\ \ ##, \ \";STR$(R(I));S(I);N$(I)
430 NEXT
440 PRINT: RETURN
500 DATA 7
510 DATA 44,Solomon
520 DATA 42,Jason
530 DATA 42,Errol
540 DATA 41,Garry
550 DATA 41,Bernard
560 DATA 41,Barry
570 DATA 39,Stephen
|
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).
|
#Ursala
|
Ursala
|
#cast %s
example = |=hS& 'mississippi'
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Range_Consolidation is
type Set_Type is record
Left, Right : Float;
end record;
package Set_Vectors is
new Ada.Containers.Vectors (Positive, Set_Type);
procedure Normalize (Set : in out Set_Vectors.Vector) is
function Less_Than (Left, Right : Set_Type) return Boolean is
begin Return Left.Left < Right.Left; end;
package Set_Sorting is
new Set_Vectors.Generic_Sorting (Less_Than);
begin
for Elem of Set loop
Elem := (Left => Float'Min (Elem.Left, Elem.Right),
Right => Float'Max (Elem.Left, Elem.Right));
end loop;
Set_Sorting.Sort (Set);
end Normalize;
procedure Consolidate (Set : in out Set_Vectors.Vector) is
use Set_Vectors;
First : Cursor := Set.First;
Last : Cursor := Next (First);
begin
while Last /= No_Element loop
if Element (First).Right < Element (Last).Left then -- non-overlap
First := Last;
Last := Next (Last);
elsif Element (First).Right >= Element (Last).Left then -- overlap
Replace_Element (Set, First, (Left => Element (First).Left,
Right => Float'Max (Element (First).Right,
Element (Last) .Right)));
Delete (Set, Last);
Last := Next (First);
end if;
end loop;
end Consolidate;
procedure Put (Set : in Set_Vectors.Vector) is
package Float_IO is
new Ada.Text_IO.Float_IO (Float);
begin
Float_IO.Default_Exp := 0;
Float_IO.Default_Aft := 1;
Float_IO.Default_Fore := 3;
for Elem of Set loop
Ada.Text_IO.Put ("(");
Float_IO.Put (Elem.Left);
Float_IO.Put (Elem.Right);
Ada.Text_IO.Put (") ");
end loop;
end Put;
procedure Show (Set : in out Set_Vectors.Vector) is
use Ada.Text_IO;
begin
Put (Set);
Normalize (Set);
Consolidate (Set);
Set_Col (70);
Put (Set);
New_Line;
end Show;
use Set_Vectors;
Set_0 : Set_Vectors.Vector := Empty_Vector;
Set_1 : Set_Vectors.Vector := Empty_Vector & (1.1, 2.2);
Set_2 : Set_Vectors.Vector := (6.1, 7.2) & (7.2, 8.3);
Set_3 : Set_Vectors.Vector := (4.0, 3.0) & (2.0, 1.0);
Set_4 : Set_Vectors.Vector := (4.0, 3.0) & (2.0, 1.0) & (-1.0, -2.0) & (3.9, 10.0);
Set_5 : Set_Vectors.Vector := (1.0, 3.0) & (-6.0, -1.0) & (-4.0, -5.0) & (8.0, 2.0) & (-6.0, -6.0);
begin
Show (Set_0);
Show (Set_1);
Show (Set_2);
Show (Set_3);
Show (Set_4);
Show (Set_5);
end Range_Consolidation;
|
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
|
#Run_BASIC
|
Run BASIC
|
html "<table bgcolor=wheat border=1><tr><td align=center colspan=2>Rate Counter</td></tr>
<tr><td>Run Job Times</td><td>"
textbox #runTimes,"10",3
html "</tr><tr><td align=center colspan=2>"
button #r,"Run", [runIt]
html " "
button #a, "Average", [ave]
html "</td></tr></table>"
wait
[runIt]
runTimes = min(10,val(#runTimes contents$()))
count = count + 1
print "-------- Run Number ";count;" ----------------"
print "Run jobs";runTimes;" times, reporting each"
for i = 1 to runTimes
' -----------------------------------------------------------------
' Normally we use a RUN() command to run another program
' but for test pruporse we have a routine that simply loops a bunch
' -----------------------------------------------------------------
begTime = time$("ms")
theRun = bogusProg()
endTime = time$("ms")
lapsTime = endTime - begTime
print "Job #";i;" Elapsed time, ms ";lapsTime;" ";1000/lapsTime; " ticks per second"
next
aveTime = (endTime-startTime)/runTimes
totAveTime = totAveTime + aveTime
print "Average time, ms, is ";aveTime;" "; 1000/((endTime-startTime)/runTimes); " ticks per second"
wait
[ave]
print "---------------------------------"
print "Total average time:";aveTime/count
function bogusProg()
for i = 1 to 10000
sini = sini + sin(i)
tani = tani + tan(i)
cpsi = cosi + cos(i)
next
end function
|
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
|
#Modula-2
|
Modula-2
|
MODULE ReverseStr;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE ReverseStr(in : ARRAY OF CHAR; VAR out : ARRAY OF CHAR);
VAR ip,op : INTEGER;
BEGIN
ip := 0;
op := 0;
WHILE in[ip] # 0C DO
INC(ip)
END;
DEC(ip);
WHILE ip>=0 DO
out[op] := in[ip];
INC(op);
DEC(ip)
END
END ReverseStr;
TYPE A = ARRAY[0..63] OF CHAR;
VAR is,os : A;
BEGIN
is := "Hello World";
ReverseStr(is, os);
WriteString(is);
WriteLn;
WriteString(os);
WriteLn;
ReadChar
END ReverseStr.
|
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 ε.)
|
#Common_Lisp
|
Common Lisp
|
(defun point-in-polygon (point polygon)
(do ((in-p nil)) ((endp polygon) in-p)
(when (ray-intersects-segment point (pop polygon))
(setf in-p (not in-p)))))
(defun ray-intersects-segment (point segment &optional (epsilon .001))
(destructuring-bind (px . py) point
(destructuring-bind ((ax . ay) . (bx . by)) segment
(when (< ay by)
(rotatef ay by)
(rotatef ax bx))
(when (or (= py ay) (= py by))
(incf py epsilon))
(cond
;; point is above, below, or to the right of the rectangle
;; determined by segment; ray does not intesect the segment.
((or (> px (max ax bx)) (> py (max ay by)) (< py (min ay by)))
nil)
;; point is to left of the rectangle; ray intersects segment
((< px (min ax bx))
t)
;; point is within the rectangle...
(t (let ((m-red (if (= ax bx) nil
(/ (- by ay) (- bx ax))))
(m-blue (if (= px ax) nil
(/ (- py ay) (- px ax)))))
(cond
((null m-blue) t)
((null m-red) nil)
(t (>= m-blue m-red)))))))))
|
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.
|
#J
|
J
|
readLine=: 4 :0
(x-1) {:: <;.2 ] 1!:1 boxxopen y
)
|
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
|
#Ada
|
Ada
|
with Config; use Config;
with Ada.Text_IO; use Ada.Text_IO;
procedure Rosetta_Read_Cfg is
cfg: Configuration:= Init("rosetta_read.cfg", Case_Sensitive => False, Variable_Terminator => ' ');
fullname : String := cfg.Value_Of("*", "fullname");
favouritefruit : String := cfg.Value_Of("*", "favouritefruit");
needspeeling : Boolean := cfg.Is_Set("*", "needspeeling");
seedsremoved : Boolean := cfg.Is_Set("*", "seedsremoved");
otherfamily : String := cfg.Value_Of("*", "otherfamily");
begin
Put_Line("fullname = " & fullname);
Put_Line("favouritefruit = " & favouritefruit);
Put_Line("needspeeling = " & Boolean'Image(needspeeling));
Put_Line("seedsremoved = " & Boolean'Image(seedsremoved));
Put_Line("otherfamily = " & otherfamily);
end;
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#C
|
C
|
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int score;
char name[100];
}entry;
void ordinalRanking(entry* list,int len){
int i;
printf("\n\nOrdinal Ranking\n---------------");
for(i=0;i<len;i++)
printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name);
}
void standardRanking(entry* list,int len){
int i,j=1;
printf("\n\nStandard Ranking\n----------------");
for(i=0;i<len;i++){
printf("\n%d\t%d\t%s",j,list[i].score,list[i].name);
if(list[i+1].score<list[i].score)
j = i+2;
}
}
void denseRanking(entry* list,int len){
int i,j=1;
printf("\n\nDense Ranking\n-------------");
for(i=0;i<len;i++){
printf("\n%d\t%d\t%s",j,list[i].score,list[i].name);
if(list[i+1].score<list[i].score)
j++;
}
}
void modifiedRanking(entry* list,int len){
int i,j,count;
printf("\n\nModified Ranking\n----------------");
for(i=0;i<len-1;i++){
if(list[i].score!=list[i+1].score){
printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name);
count = 1;
for(j=i+1;list[j].score==list[j+1].score && j<len-1;j++)
count ++;
for(j=0;j<count-1;j++)
printf("\n%d\t%d\t%s",i+count+1,list[i+j+1].score,list[i+j+1].name);
i += (count-1);
}
}
printf("\n%d\t%d\t%s",len,list[len-1].score,list[len-1].name);
}
void fractionalRanking(entry* list,int len){
int i,j,count;
float sum = 0;
printf("\n\nFractional Ranking\n------------------");
for(i=0;i<len;i++){
if(i==len-1 || list[i].score!=list[i+1].score)
printf("\n%.1f\t%d\t%s",(float)(i+1),list[i].score,list[i].name);
else if(list[i].score==list[i+1].score){
sum = i;
count = 1;
for(j=i;list[j].score==list[j+1].score;j++){
sum += (j+1);
count ++;
}
for(j=0;j<count;j++)
printf("\n%.1f\t%d\t%s",sum/count + 1,list[i+j].score,list[i+j].name);
i += (count-1);
}
}
}
void processFile(char* fileName){
FILE* fp = fopen(fileName,"r");
entry* list;
int i,num;
fscanf(fp,"%d",&num);
list = (entry*)malloc(num*sizeof(entry));
for(i=0;i<num;i++)
fscanf(fp,"%d%s",&list[i].score,list[i].name);
fclose(fp);
ordinalRanking(list,num);
standardRanking(list,num);
denseRanking(list,num);
modifiedRanking(list,num);
fractionalRanking(list,num);
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage %s <score list file>");
else
processFile(argV[1]);
return 0;
}
|
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).
|
#VBA
|
VBA
|
Option Explicit
Sub Main()
Dim myArr() As Variant, i As Long
myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))
'return :
For i = LBound(myArr) To UBound(myArr)
Debug.Print myArr(i)
Next
End Sub
Private Function Remove_Duplicate(Arr As Variant) As Variant()
Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long
ReDim Temp(UBound(Arr))
For i = LBound(Arr) To UBound(Arr)
On Error Resume Next
myColl.Add CStr(Arr(i)), CStr(Arr(i))
If Err.Number > 0 Then
On Error GoTo 0
Else
Temp(cpt) = Arr(i)
cpt = cpt + 1
End If
Next i
ReDim Preserve Temp(cpt - 1)
Remove_Duplicate = Temp
End Function
|
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
|
#AutoHotkey
|
AutoHotkey
|
RangeConsolidation(arr){
arr1 := [], arr2 := [], result := []
for i, obj in arr
arr1[i,1] := min(arr[i]*), arr1[i,2] := max(arr[i]*) ; sort each range individually
for i, obj in arr1
if (obj.2 > arr2[obj.1])
arr2[obj.1] := obj.2 ; creates helper array sorted by range
i := 1
for start, stop in arr2
if (i = 1) || (start > result[i-1, 2]) ; first or non overlapping range
result[i, 1] := start, result[i, 2] := stop, i++
else ; overlapping range
result[i-1, 2] := stop > result[i-1, 2] ? stop : result[i-1, 2]
return result
}
|
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
|
#Scala
|
Scala
|
def task(n: Int) = Thread.sleep(n * 1000)
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
val cnt1 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt2 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt3 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
println("%d jobs in 5 seconds" format cnt1)
println("%d jobs in 10 seconds" format cnt2)
println("%d jobs in 15 seconds" format cnt3)
}
rate(List.fill(30)(() => task(scala.util.Random.nextInt(10)+1)))
|
http://rosettacode.org/wiki/Reverse_a_string
|
Reverse a string
|
Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Modula-3
|
Modula-3
|
MODULE Reverse EXPORTS Main;
IMPORT IO, Text;
PROCEDURE String(item: TEXT): TEXT =
VAR result: TEXT := "";
BEGIN
FOR i := Text.Length(item) - 1 TO 0 BY - 1 DO
result := Text.Cat(result, Text.FromChar(Text.GetChar(item, i)));
END;
RETURN result;
END String;
BEGIN
IO.Put(String("Foobarbaz") & "\n");
END Reverse.
|
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 ε.)
|
#D
|
D
|
import std.stdio, std.math, std.algorithm;
immutable struct Point { double x, y; }
immutable struct Edge { Point a, b; }
immutable struct Figure {
string name;
Edge[] edges;
}
bool contains(in Figure poly, in Point p) pure nothrow @safe @nogc {
static bool raySegI(in Point p, in Edge edge)
pure nothrow @safe @nogc {
enum double epsilon = 0.00001;
with (edge) {
if (a.y > b.y)
//swap(a, b); // if edge is mutable
return raySegI(p, Edge(b, a));
if (p.y == a.y || p.y == b.y)
//p.y += epsilon; // if p is mutable
return raySegI(Point(p.x, p.y + epsilon), edge);
if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x))
return false;
if (p.x < min(a.x, b.x))
return true;
immutable blue = (abs(a.x - p.x) > double.min_normal) ?
((p.y - a.y) / (p.x - a.x)) :
double.max;
immutable red = (abs(a.x - b.x) > double.min_normal) ?
((b.y - a.y) / (b.x - a.x)) :
double.max;
return blue >= red;
}
}
return poly.edges.count!(e => raySegI(p, e)) % 2;
}
void main() {
immutable Figure[] polys = [
{"Square", [
{{ 0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}},
{{10.0, 10.0}, { 0.0, 10.0}}, {{ 0.0, 10.0}, { 0.0, 0.0}}]},
{"Square hole", [
{{ 0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}},
{{10.0, 10.0}, { 0.0, 10.0}}, {{ 0.0, 10.0}, { 0.0, 0.0}},
{{ 2.5, 2.5}, { 7.5, 2.5}}, {{ 7.5, 2.5}, { 7.5, 7.5}},
{{ 7.5, 7.5}, { 2.5, 7.5}}, {{ 2.5, 7.5}, { 2.5, 2.5}}]},
{"Strange", [
{{ 0.0, 0.0}, { 2.5, 2.5}}, {{ 2.5, 2.5}, { 0.0, 10.0}},
{{ 0.0, 10.0}, { 2.5, 7.5}}, {{ 2.5, 7.5}, { 7.5, 7.5}},
{{ 7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}},
{{10.0, 0}, { 2.5, 2.5}}]},
{"Exagon", [
{{ 3.0, 0.0}, { 7.0, 0.0}}, {{ 7.0, 0.0}, {10.0, 5.0}},
{{10.0, 5.0}, { 7.0, 10.0}}, {{ 7.0, 10.0}, { 3.0, 10.0}},
{{ 3.0, 10.0}, { 0.0, 5.0}}, {{ 0.0, 5.0}, { 3.0, 0.0}}]}
];
immutable Point[] testPoints = [{ 5, 5}, {5, 8}, {-10, 5}, {0, 5},
{10, 5}, {8, 5}, { 10, 10}];
foreach (immutable poly; polys) {
writefln(`Is point inside figure "%s"?`, poly.name);
foreach (immutable p; testPoints)
writefln(" (%3s, %2s): %s", p.x, p.y, contains(poly, p));
writeln;
}
}
|
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.
|
#Java
|
Java
|
package linenbr7;
import java.io.*;
public class LineNbr7 {
public static void main(String[] args) throws Exception {
File f = new File(args[0]);
if (!f.isFile() || !f.canRead())
throw new IOException("can't read " + args[0]);
BufferedReader br = new BufferedReader(new FileReader(f));
try (LineNumberReader lnr = new LineNumberReader(br)) {
String line = null;
int lnum = 0;
while ((line = lnr.readLine()) != null
&& (lnum = lnr.getLineNumber()) < 7) {
}
switch (lnum) {
case 0:
System.out.println("the file has zero length");
break;
case 7:
boolean empty = "".equals(line);
System.out.println("line 7: " + (empty ? "empty" : line));
break;
default:
System.out.println("the file has only " + lnum + " line(s)");
}
}
}
}
|
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
|
#Aime
|
Aime
|
record r, s;
integer c;
file f;
list l;
text an, d, k;
an = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
f.affix("tmp/config");
while ((c = f.peek) ^ -1) {
integer removed;
f.side(" \t\r");
c = f.peek;
removed = c == ';';
if (removed) {
f.pick;
f.side(" \t\r");
c = f.peek;
}
c = place(an, c);
if (-1 < c && c < 52) {
f.near(an, k);
if (removed) {
r[k] = "false";
} else {
f.side(" \t\r");
if (f.peek == '=') {
f.pick;
f.side(" \t\r");
}
f.ever(",#\n", d);
d = bb_drop(d, " \r\t");
if (f.peek != ',') {
r[k] = ~d ? d : "true";
} else {
f.news(l, 0, 0, ",");
lf_push(l, d);
for (c, d in l) {
l[c] = bb_drop(d, " \r\t").bf_drop(" \r\t").string;
}
s.put(k, l);
f.seek(-1, SEEK_CURRENT);
}
}
}
f.slip;
}
r.wcall(o_, 0, 2, ": ", "\n");
for (k, l in s) {
o_(k, ": ");
l.ucall(o_, 0, ", ");
o_("\n");
}
|
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.
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace RankingMethods {
class Program {
static void Main(string[] args) {
Dictionary<string, int> scores = new Dictionary<string, int> {
["Solomon"] = 44,
["Jason"] = 42,
["Errol"] = 42,
["Gary"] = 41,
["Bernard"] = 41,
["Barry"] = 41,
["Stephen"] = 39,
};
StandardRank(scores);
ModifiedRank(scores);
DenseRank(scores);
OrdinalRank(scores);
FractionalRank(scores);
}
static void StandardRank(Dictionary<string, int> data) {
Console.WriteLine("Standard Rank");
var list = data.Values.Distinct().ToList();
list.Sort((a, b) => b.CompareTo(a));
int rank = 1;
foreach (var value in list) {
int temp = rank;
foreach (var k in data.Keys) {
if (data[k] == value) {
Console.WriteLine("{0} {1} {2}", temp, value, k);
rank++;
}
}
}
Console.WriteLine();
}
static void ModifiedRank(Dictionary<string, int> data) {
Console.WriteLine("Modified Rank");
var list = data.Values.Distinct().ToList();
list.Sort((a, b) => b.CompareTo(a));
int rank = 0;
foreach (var value in list) {
foreach (var k in data.Keys) {
if (data[k] == value) {
rank++;
}
}
foreach (var k in data.Keys) {
if (data[k] == value) {
Console.WriteLine("{0} {1} {2}", rank, data[k], k);
}
}
}
Console.WriteLine();
}
static void DenseRank(Dictionary<string, int> data) {
Console.WriteLine("Dense Rank");
var list = data.Values.Distinct().ToList();
list.Sort((a, b) => b.CompareTo(a));
int rank = 1;
foreach (var value in list) {
foreach (var k in data.Keys) {
if (data[k] == value) {
Console.WriteLine("{0} {1} {2}", rank, data[k], k);
}
}
rank++;
}
Console.WriteLine();
}
static void OrdinalRank(Dictionary<string, int> data) {
Console.WriteLine("Ordinal Rank");
var list = data.Values.Distinct().ToList();
list.Sort((a, b) => b.CompareTo(a));
int rank = 1;
foreach (var value in list) {
foreach (var k in data.Keys) {
if (data[k] == value) {
Console.WriteLine("{0} {1} {2}", rank, data[k], k);
rank++;
}
}
}
Console.WriteLine();
}
static void FractionalRank(Dictionary<string, int> data) {
Console.WriteLine("Fractional Rank");
var list = data.Values.Distinct().ToList();
list.Sort((a, b) => b.CompareTo(a));
int rank = 0;
foreach (var value in list) {
double avg = 0;
int cnt = 0;
foreach (var k in data.Keys) {
if (data[k] == value) {
rank++;
cnt++;
avg += rank;
}
}
avg /= cnt;
foreach (var k in data.Keys) {
if (data[k] == value) {
Console.WriteLine("{0:F1} {1} {2}", avg, data[k], k);
}
}
}
Console.WriteLine();
}
}
}
|
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).
|
#VBScript
|
VBScript
|
Function remove_duplicates(list)
arr = Split(list,",")
Set dict = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(arr)
If dict.Exists(arr(i)) = False Then
dict.Add arr(i),""
End If
Next
For Each key In dict.Keys
tmp = tmp & key & ","
Next
remove_duplicates = Left(tmp,Len(tmp)-1)
End Function
WScript.Echo remove_duplicates("a,a,b,b,c,d,e,d,f,f,f,g,h")
|
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
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct range_tag {
double low;
double high;
} range_t;
void normalize_range(range_t* range) {
if (range->high < range->low) {
double tmp = range->low;
range->low = range->high;
range->high = tmp;
}
}
int range_compare(const void* p1, const void* p2) {
const range_t* r1 = p1;
const range_t* r2 = p2;
if (r1->low < r2->low)
return -1;
if (r1->low > r2->low)
return 1;
if (r1->high < r2->high)
return -1;
if (r1->high > r2->high)
return 1;
return 0;
}
void normalize_ranges(range_t* ranges, size_t count) {
for (size_t i = 0; i < count; ++i)
normalize_range(&ranges[i]);
qsort(ranges, count, sizeof(range_t), range_compare);
}
// Consolidates an array of ranges in-place. Returns the
// number of ranges after consolidation.
size_t consolidate_ranges(range_t* ranges, size_t count) {
normalize_ranges(ranges, count);
size_t out_index = 0;
for (size_t i = 0; i < count; ) {
size_t j = i;
while (++j < count && ranges[j].low <= ranges[i].high) {
if (ranges[i].high < ranges[j].high)
ranges[i].high = ranges[j].high;
}
ranges[out_index++] = ranges[i];
i = j;
}
return out_index;
}
void print_range(const range_t* range) {
printf("[%g, %g]", range->low, range->high);
}
void print_ranges(const range_t* ranges, size_t count) {
if (count == 0)
return;
print_range(&ranges[0]);
for (size_t i = 1; i < count; ++i) {
printf(", ");
print_range(&ranges[i]);
}
}
void test_consolidate_ranges(range_t* ranges, size_t count) {
print_ranges(ranges, count);
printf(" -> ");
count = consolidate_ranges(ranges, count);
print_ranges(ranges, count);
printf("\n");
}
#define LENGTHOF(a) sizeof(a)/sizeof(a[0])
int main() {
range_t test1[] = { {1.1, 2.2} };
range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} };
range_t test3[] = { {4, 3}, {2, 1} };
range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} };
range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} };
test_consolidate_ranges(test1, LENGTHOF(test1));
test_consolidate_ranges(test2, LENGTHOF(test2));
test_consolidate_ranges(test3, LENGTHOF(test3));
test_consolidate_ranges(test4, LENGTHOF(test4));
test_consolidate_ranges(test5, LENGTHOF(test5));
return 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
|
#Sidef
|
Sidef
|
var benchmark = frequire('Benchmark');
func job1 {
#...job1 code...
}
func job2 {
#...job2 code...
}
const COUNT = -1; # run for one CPU second
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2));
|
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
|
#MUMPS
|
MUMPS
|
REVERSE
;Take in a string and reverse it using the built in function $REVERSE
NEW S
READ:30 "Enter a string: ",S
WRITE !,$REVERSE(S)
QUIT
|
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 ε.)
|
#Factor
|
Factor
|
USING: kernel prettyprint sequences arrays math math.vectors ;
IN: raycasting
: between ( a b x -- ? ) [ last ] tri@ [ < ] curry bi@ xor ;
: lincomb ( a b x -- w )
3dup [ last ] tri@
[ - ] curry bi@
[ drop ] 2dip
neg 2dup + [ / ] curry bi@
[ [ v*n ] curry ] bi@ bi* v+ ;
: leftof ( a b x -- ? ) dup [ lincomb ] dip [ first ] bi@ > ;
: ray ( a b x -- ? ) [ between ] [ leftof ] 3bi and ;
: raycast ( poly x -- ? )
[ dup first suffix [ rest-slice ] [ but-last-slice ] bi ] dip
[ ray ] curry 2map
f [ xor ] reduce ;
|
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.
|
#jq
|
jq
|
# Input - a line number to read, counting from 1
# Output - a stream with 0 or 1 items
def read_line:
. as $in
| label $top
| foreach inputs as $line
(0; .+1; if . == $in then $line, break $top else empty end) ;
|
http://rosettacode.org/wiki/Read_a_configuration_file
|
Read a configuration file
|
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
# This is the fullname parameter
FULLNAME Foo Barber
# This is a favourite fruit
FAVOURITEFRUIT banana
# This is a boolean that should be set
NEEDSPEELING
# This boolean is commented out
; SEEDSREMOVED
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
OTHERFAMILY Rhu Barber, Harry Barber
For the task we need to set four variables according to the configuration entries as follows:
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
We also have an option that contains multiple parameters. These may be stored in an array.
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
Related tasks
Update a configuration file
|
#Arturo
|
Arturo
|
parseConfig: function [f][
lines: split.lines read f
lines: select map lines 'line [strip replace line {/[#;].*/} ""]
'line [not? empty? line]
result: #[]
fields: loop lines 'line [
field: first match line {/^[A-Z]+/}
rest: strip replace line field ""
parts: select map split.by:"," rest => strip 'part -> not? empty? part
val: null
case [(size parts)]
when? [= 0] -> val: true
when? [= 1] -> val: first parts
else -> val: parts
result\[lower field]: val
]
return result
]
loop parseConfig relative "config.file" [k,v][
if? block? v -> print [k "->" join.with:", " v]
else -> print [k "->" v]
]
|
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.
|
#360_Assembly
|
360 Assembly
|
* Read a file line by line 12/06/2016
READFILE CSECT
SAVE (14,12) save registers on entry
PRINT NOGEN
BALR R12,0 establish addressability
USING *,R12 set base register
ST R13,SAVEA+4 link mySA->prevSA
LA R11,SAVEA mySA
ST R11,8(R13) link prevSA->mySA
LR R13,R11 set mySA pointer
OPEN (INDCB,INPUT) open the input file
OPEN (OUTDCB,OUTPUT) open the output file
LOOP GET INDCB,PG read record
CLI EOFFLAG,C'Y' eof reached?
BE EOF
PUT OUTDCB,PG write record
B LOOP
EOF CLOSE (INDCB) close input
CLOSE (OUTDCB) close output
L R13,SAVEA+4 previous save area addrs
RETURN (14,12),RC=0 return to caller with rc=0
INEOF CNOP 0,4 end-of-data routine
MVI EOFFLAG,C'Y' set the end-of-file flag
BR R14 return to caller
SAVEA DS 18F save area for chaining
INDCB DCB DSORG=PS,MACRF=PM,DDNAME=INDD,LRECL=80, *
RECFM=FB,EODAD=INEOF
OUTDCB DCB DSORG=PS,MACRF=PM,DDNAME=OUTDD,LRECL=80, *
RECFM=FB
EOFFLAG DC C'N' end-of-file flag
PG DS CL80 buffer
YREGS
END READFILE
|
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.
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& print(std::ostream& os, const T& src) {
auto it = src.cbegin();
auto end = src.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
typedef std::map<std::string, int> Map;
typedef Map::value_type MapEntry;
void standardRank(const Map& scores) {
std::cout << "Standard Rank" << std::endl;
std::vector<int> list;
for (auto& elem : scores) {
list.push_back(elem.second);
}
std::sort(list.begin(), list.end(), std::greater<int>{});
list.erase(std::unique(list.begin(), list.end()), list.end());
int rank = 1;
for (auto value : list) {
int temp = rank;
for (auto& e : scores) {
if (e.second == value) {
std::cout << temp << " " << value << " " << e.first.c_str() << std::endl;
rank++;
}
}
}
std::cout << std::endl;
}
void modifiedRank(const Map& scores) {
std::cout << "Modified Rank" << std::endl;
std::vector<int> list;
for (auto& elem : scores) {
list.push_back(elem.second);
}
std::sort(list.begin(), list.end(), std::greater<int>{});
list.erase(std::unique(list.begin(), list.end()), list.end());
int rank = 0;
for (auto value : list) {
rank += std::count_if(scores.begin(), scores.end(), [value](const MapEntry& e) { return e.second == value; });
for (auto& e : scores) {
if (e.second == value) {
std::cout << rank << " " << value << " " << e.first.c_str() << std::endl;
}
}
}
std::cout << std::endl;
}
void denseRank(const Map& scores) {
std::cout << "Dense Rank" << std::endl;
std::vector<int> list;
for (auto& elem : scores) {
list.push_back(elem.second);
}
std::sort(list.begin(), list.end(), std::greater<int>{});
list.erase(std::unique(list.begin(), list.end()), list.end());
int rank = 1;
for (auto value : list) {
for (auto& e : scores) {
if (e.second == value) {
std::cout << rank << " " << value << " " << e.first.c_str() << std::endl;
}
}
rank++;
}
std::cout << std::endl;
}
void ordinalRank(const Map& scores) {
std::cout << "Ordinal Rank" << std::endl;
std::vector<int> list;
for (auto& elem : scores) {
list.push_back(elem.second);
}
std::sort(list.begin(), list.end(), std::greater<int>{});
list.erase(std::unique(list.begin(), list.end()), list.end());
int rank = 1;
for (auto value : list) {
for (auto& e : scores) {
if (e.second == value) {
std::cout << rank++ << " " << value << " " << e.first.c_str() << std::endl;
}
}
}
std::cout << std::endl;
}
void fractionalRank(const Map& scores) {
std::cout << "Ordinal Rank" << std::endl;
std::vector<int> list;
for (auto& elem : scores) {
list.push_back(elem.second);
}
std::sort(list.begin(), list.end(), std::greater<int>{});
list.erase(std::unique(list.begin(), list.end()), list.end());
int rank = 0;
for (auto value : list) {
double avg = 0.0;
int cnt = 0;
for (auto& e : scores) {
if (e.second == value) {
rank++;
cnt++;
avg += rank;
}
}
avg /= cnt;
for (auto& e : scores) {
if (e.second == value) {
std::cout << std::setprecision(1) << std::fixed << avg << " " << value << " " << e.first.c_str() << std::endl;
}
}
}
std::cout << std::endl;
}
int main() {
using namespace std;
map<string, int> scores{
{"Solomon", 44},
{"Jason", 42},
{"Errol", 42},
{"Gary", 41},
{"Bernard", 41},
{"Barry", 41},
{"Stephen", 39}
};
standardRank(scores);
modifiedRank(scores);
denseRank(scores);
ordinalRank(scores);
fractionalRank(scores);
return 0;
}
|
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).
|
#Vedit_macro_language
|
Vedit macro language
|
Sort(0, File_Size) // sort the data
While(Replace("^(.*)\N\1$", "\1", REGEXP+BEGIN+NOERR)){} // remove duplicates
|
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).
|
#Vim_Script
|
Vim Script
|
call filter(list, 'count(list, v:val) == 1')
|
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
|
#C.23
|
C#
|
using static System.Math;
using System.Linq;
using System;
public static class RangeConsolidation
{
public static void Main() {
foreach (var list in new [] {
new[] { (1.1, 2.2) }.ToList(),
new[] { (6.1, 7.2), (7.2, 8.3) }.ToList(),
new[] { (4d, 3d), (2, 1) }.ToList(),
new[] { (4d, 3d), (2, 1), (-1, 2), (3.9, 10) }.ToList(),
new[] { (1d, 3d), (-6, -1), (-4, -5), (8, 2), (-6, -6) }.ToList()
})
{
for (int z = list.Count-1; z >= 1; z--) {
for (int y = z - 1; y >= 0; y--) {
if (Overlap(list[z], list[y])) {
list[y] = Consolidate(list[z], list[y]);
list.RemoveAt(z);
break;
}
}
}
Console.WriteLine(string.Join(", ", list.Select(Normalize).OrderBy(range => range.s)));
}
}
private static bool Overlap((double s, double e) left, (double s, double e) right) =>
Max(left.s, left.e) > Max(right.s, right.e)
? Max(right.s, right.e) >= Min(left.s, left.e)
: Max(left.s, left.e) >= Min(right.s, right.e);
private static (double s, double e) Consolidate((double s, double e) left, (double s, double e) right) =>
(Min(Min(left.s, left.e), Min(right.s, right.e)), Max(Max(left.s, left.e), Max(right.s, right.e)));
private static (double s, double e) Normalize((double s, double e) range) =>
(Min(range.s, range.e), Max(range.s, range.e));
}
|
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
|
#Smalltalk
|
Smalltalk
|
|times|
times := Bag new.
1 to: 10 do: [:n| times add:
(Time millisecondsToRun: [3000 factorial])].
Transcript show: times average asInteger.
|
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
|
#Nanoquery
|
Nanoquery
|
def reverse(string)
l = ""
for char in list(str(string)).reverse()
l += char
end
return l
end
|
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 ε.)
|
#Fortran
|
Fortran
|
module Polygons
use Points_Module
implicit none
type polygon
type(point), dimension(:), allocatable :: points
integer, dimension(:), allocatable :: vertices
end type polygon
contains
function create_polygon(pts, vt)
type(polygon) :: create_polygon
type(point), dimension(:), intent(in) :: pts
integer, dimension(:), intent(in) :: vt
integer :: np, nv
np = size(pts,1)
nv = size(vt,1)
allocate(create_polygon%points(np), create_polygon%vertices(nv))
create_polygon%points = pts
create_polygon%vertices = vt
end function create_polygon
subroutine free_polygon(pol)
type(polygon), intent(inout) :: pol
deallocate(pol%points, pol%vertices)
end subroutine free_polygon
end module Polygons
|
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
|
#ALGOL_68
|
ALGOL 68
|
# generate random sentences using text from a book as a basis #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
# returns s with chars removed #
PRIO REMOVE = 1;
OP REMOVE = ( STRING s, chars )STRING:
BEGIN
[ LWB s : UPB s ]CHAR result;
INT r pos := LWB result - 1;
FOR s pos FROM LWB s TO UPB s DO
IF NOT char in string( s[ s pos ], NIL, chars ) THEN
# have a character that needn't be removed #
r pos +:= 1;
result[ r pos ] := s[ s pos ]
FI
OD;
result[ LWB s : r pos ]
END # REMOVE # ;
# returns text converted to an INT or -1 if text is not a number #
OP TOINT = ( STRING text )INT:
BEGIN
INT result := 0;
BOOL is numeric := TRUE;
FOR ch pos FROM LWB text TO UPB text WHILE is numeric DO
CHAR c = text[ ch pos ];
is numeric := ( c >= "0" AND c <= "9" );
IF is numeric THEN ( result *:= 10 ) +:= ABS c - ABS "0" FI
OD;
IF is numeric THEN result ELSE -1 FI
END # TOINT # ;
# get the file name and number of words for the prefix and #
# max number of words and sentences from the command line #
STRING file name := "twotw.txt";
STRING start word := "";
INT prefix length := 2;
INT number of sentences := 10;
INT max words := 1 000 000;
FOR arg pos TO argc - 1 DO
STRING arg upper := argv( arg pos );
FOR ch pos FROM LWB arg upper TO UPB arg upper DO
IF is lower( arg upper[ ch pos ] ) THEN arg upper[ ch pos ] := to upper( arg upper[ ch pos ] ) FI
OD;
IF arg upper = "FILE" THEN
file name := argv( arg pos + 1 )
ELIF arg upper = "PREFIX" THEN
prefix length := TOINT argv( arg pos + 1 )
ELIF arg upper = "SENTENCES" THEN
number of sentences := TOINT argv( arg pos + 1 )
ELIF arg upper = "MAXWORDS" THEN
max words := TOINT argv( arg pos + 1 )
ELIF arg upper = "STARTWORD" THEN
start word := argv( arg pos + 1 )
FI
OD;
# delimiter for separating suffixes - must not appear in the text #
CHAR suffix delimiter = REPR 1; # ^A #
STRING punctuation = """'@,/;:(){}[]*&^%$£";
IF FILE input file;
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
BOOL at eol := FALSE;
# set the EOF handler for the file #
on logical file end( input file
, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the #
# latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
# set the end-of-line handler for the file so get word can see line boundaries #
on line end( input file
, ( REF FILE f )BOOL:
BEGIN
# note we reached end-of-line #
at eol := TRUE;
# return FALSE to use the default eol handling #
# i.e. just get the next charactefr #
FALSE
END
);
CHAR c := " ";
# returns the next word from input file #
# a word is any sequence of characters separated by spaces and #
# suffix delimiters, or one of the characters ".", "!" or "?" #
PROC get word = STRING:
IF at eof THEN ""
ELSE # not at end of file #
STRING word := "";
at eol := FALSE;
IF c = "." OR c = "!" OR c = "?" THEN
# sentence ending "word" #
word := c;
get( input file, ( c ) )
ELSE
# "normal" word #
WHILE ( c = " " OR c = suffix delimiter ) AND NOT at eof DO get( input file, ( c ) ) OD;
WHILE c /= " "
AND c /= "."
AND c /= "!"
AND c /= "?"
AND c /= suffix delimiter
AND NOT at eol
AND NOT at eof
DO
word +:= c;
get( input file, ( c ) )
OD
FI;
at eol := FALSE;
word
FI # get word # ;
# returns a random number between 1 and n inclusive #
PROC random choice = ( INT n )INT: IF n < 2 THEN n ELSE ENTIER ( ( next random * n ) + 1 ) FI;
# chooses a suffix at random to continue a sentence #
PROC choose suffix = ( STRING sfxs )STRING:
BEGIN
# count the number of suffixes #
INT suffix max := 0;
FOR s pos FROM LWB sfxs TO UPB sfxs DO
IF sfxs[ s pos ] = suffix delimiter THEN suffix max +:= 1 FI
OD;
# select a random suffix to continue the text with #
STRING sfx := "";
INT prev pos := LWB sfxs - 1;
INT suffix count := random choice( suffix max );
FOR s pos FROM LWB sfxs TO UPB sfxs WHILE suffix count > 0 DO
IF sfxs[ s pos ] = suffix delimiter THEN
# found the end of a suffix #
sfx := sfxs[ prev pos + 1 : s pos - 1 @ 1 ];
prev pos := s pos;
suffix count -:= 1
FI
OD;
sfx
END # choose suffix # ;
# skip to the start word, if there is one #
IF start word /= "" THEN WHILE NOT at eof AND get word /= start word DO SKIP OD FI;
# get the first prefix from the file #
[ prefix length ]STRING prefix;
FOR p pos TO prefix length WHILE NOT at eof DO prefix[ p pos ] := get word OD;
IF at eof THEN
# not enough words in the file #
print( ( file name, " contains less than ", whole( prefix length, 0 ), " words", newline ) )
ELSE
# have some words #
INT word count := prefix length;
# store the prefixes and suffixes in the associatibe array #
# we store the suffix as a single concatenated #
# string delimited by suffix delimiters, the string will #
# have a leading delimiter #
# suffixes that appear multiple times in the input text will #
# appear multiple time in the array, this will allow them to #
# have a higher probability than suffixes that appear fewer #
# times #
# this will use more memory than storing the sufixes and a #
# count, but simplifies the generation #
# with a prefix length of 2 (as required by the task), #
# the War Of The Worlds can be processed - for longer prefix #
# lengths a less memory hungry algorithm would be needed #
REF AARRAY suffixes := INIT LOC AARRAY;
INT prefix count := 0;
WHILE NOT at eof AND word count <= max words
DO
# concatenate the prefix words to a single string #
STRING prefix text := prefix[ 1 ];
FOR p pos FROM 2 TO prefix length DO prefix text +:= ( " " + prefix[ p pos ] ) OD;
STRING suffix := get word;
# if the prefix has no lower case, ignore it as it is #
# probably a chapter heading or similar #
IF BOOL has lowercase := FALSE;
FOR s pos FROM LWB prefix text TO UPB prefix text
WHILE NOT ( has lowercase := is lower( prefix text[ s pos ] ) )
DO SKIP OD;
has lowercase
THEN
# the prefix contains some lower case #
# store the suffixes associated with the prefix #
IF NOT ( suffixes CONTAINSKEY prefix text ) THEN
# first time this prefix has appeared #
prefix count +:= 1
FI;
IF prefix[ 1 ] = "." OR prefix[ 1 ] = "!" OR prefix[ 1 ] = "?" THEN
# have the start of a sentence #
suffixes // "*." +:= ( suffix delimiter + prefix text )
FI;
STRING prefix without punctuation = prefix text REMOVE punctuation;
IF prefix without punctuation /= "" THEN prefix text := prefix without punctuation FI;
suffixes // prefix text +:= ( suffix delimiter + suffix )
FI;
# shuffle the prefixes down one and add the new suffix #
# as the final prefix #
FOR p pos FROM 2 TO prefix length DO prefix[ p pos - 1 ] := prefix[ p pos ] OD;
prefix[ prefix length ] := suffix;
IF NOT at eof THEN word count +:= 1 FI
OD;
# generate text #
TO number of sentences DO
print( ( newline ) );
# start with a random prefix #
STRING pfx := choose suffix( suffixes // "*." );
STRING line := pfx[ @ 1 ][ 3 : ]; # remove the leading #
# ". " from the line #
pfx := pfx REMOVE punctuation;
BOOL finished := FALSE;
WHILE NOT finished DO
IF STRING sfxs := ( suffixes // pfx );
IF LWB sfxs <= UPB sfxs THEN
IF sfxs[ LWB sfxs ] = suffix delimiter THEN sfxs := sfxs[ LWB sfxs + 1 : ] FI
FI;
sfxs +:= suffix delimiter;
sfxs = suffix delimiter
THEN
# no suffix - reached the end of the generated text #
line +:= " (" + pfx + " has no suffix)";
finished := TRUE
ELSE
# can continue to generate text #
STRING sfx = choose suffix( sfxs );
IF sfx = "." OR sfx = "!" OR sfx = "?"
THEN
# reached the end of a sentence #
finished := TRUE;
# if the line ends with ",;:", remove it #
INT line end := UPB line;
IF CHAR c = line[ line end ]; c = "," OR c = ";" OR c = ":" THEN
line end -:= 1
FI;
# remove trailing spaces #
WHILE line[ line end ] = " " AND line end > LWB line DO line end -:= 1 OD;
line := line[ LWB line : line end ] + sfx
ELSE
# not at the end of the sentence #
line +:= " " + sfx;
# remove the first word from the prefix and add #
# the suffix #
IF INT space pos := 0;
NOT char in string( " ", space pos, pfx )
THEN
# the prefix is only one word #
pfx := sfx
ELSE
# have multiple words #
pfx := ( pfx[ space pos + 1 : ] + " " + sfx )[ @ 1 ]
FI;
STRING pfx without punctuation = pfx REMOVE punctuation;
IF pfx without punctuation /= "" THEN pfx := pfx without punctuation FI
FI
FI
OD;
print( ( line, newline ) )
OD
FI;
close( input file )
FI
|
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.
|
#Julia
|
Julia
|
open(readlines, "path/to/file")[7]
|
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.
|
#Kotlin
|
Kotlin
|
// version 1.1.2
import java.io.File
fun main(args: Array<String>) {
/* The following code reads the whole file into memory
and so should not be used for large files
which should instead be read line by line until the
desired line is reached */
val lines = File("input.txt").readLines()
if (lines.size < 7)
println("There are only ${lines.size} lines in the file")
else {
val line7 = lines[6].trim()
if (line7.isEmpty())
println("The seventh line is empty")
else
println("The seventh line is : $line7")
}
}
/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/
|
http://rosettacode.org/wiki/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
|
#AutoHotkey
|
AutoHotkey
|
; Author: AlephX, Aug 18 2011
data = %A_scriptdir%\rosettaconfig.txt
comma := ","
Loop, Read, %data%
{
if NOT (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "")
{
if instr(A_LoopReadLine, ";") == 1
{
parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "")
%parameter% = "1"
}
else
{
parameter := RegExReplace(A_LoopReadLine, "^[ \s]+|[ \s]+$", "")
if instr(parameter, A_Space)
{
value := substr(parameter, instr(parameter, A_Space)+1,999)
parameter := substr(parameter, 1, instr(parameter, A_Space)-1)
if (instr(value, ",") <> 0)
{
Loop, Parse, value, %comma% ,%A_Space%
%parameter%%A_Index% := A_Loopfield
}
else
%parameter% = %value%
}
else
%parameter% = "0"
}
}
}
msgbox, FULLNAME %fullname%`nFAVOURITEFRUIT %FAVOURITEFRUIT%`nNEEDSPEELING %NEEDSPEELING%`nSEEDSREMOVED %SEEDSREMOVED%`nOTHERFAMILY %OTHERFAMILY1% + %OTHERFAMILY2%
|
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.
|
#8th
|
8th
|
"path/to/file" f:open ( . cr ) f:eachline f:close
|
http://rosettacode.org/wiki/Read_a_file_line_by_line
|
Read a file line by line
|
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
|
#AArch64_Assembly
|
AArch64 Assembly
|
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readfile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 1000
.equ LINESIZE, 100
/*******************************************/
/* Structures */
/********************************************/
/* structure read file*/
.struct 0
readfile_Fd: // File descriptor
.struct readfile_Fd + 8
readfile_buffer: // read buffer
.struct readfile_buffer + 8
readfile_buffersize: // buffer size
.struct readfile_buffersize + 8
readfile_line: // line buffer
.struct readfile_line + 8
readfile_linesize: // line buffer size
.struct readfile_linesize + 8
readfile_pointer:
.struct readfile_pointer + 8 // read pointer (init to buffer size + 1)
readfile_end:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szFileName: .asciz "fictest.txt"
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessError: .asciz "Error detected : @ \n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sBuffer: .skip BUFFERSIZE // buffer result
szLineBuffer: .skip LINESIZE
.align 4
stReadFile: .skip readfile_end
sZoneConv: .skip 24
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
mov x0,AT_FDCWD
ldr x1,qAdrszFileName // File name
mov x2,O_RDWR // flags
mov x3,0 // mode
mov x8,OPEN // open file
svc 0
cmp x0,0 // error ?
ble error
ldr x21,qAdrstReadFile // init struture readfile
str x0,[x21,readfile_Fd] // save FD in structure
ldr x0,qAdrsBuffer // buffer address
str x0,[x21,readfile_buffer]
mov x0,BUFFERSIZE // buffer size
str x0,[x21,readfile_buffersize]
ldr x0,qAdrszLineBuffer // line buffer address
str x0,[x21,readfile_line]
mov x0,LINESIZE // line buffer size
str x0,[x21,readfile_linesize]
mov x0,BUFFERSIZE + 1 // init read pointer
str x0,[x21,readfile_pointer]
1: // begin read loop
mov x0,x21
bl readLineFile
cmp x0,0
beq end // end loop
blt error
ldr x0,qAdrszLineBuffer // display line
bl affichageMess
ldr x0,qAdrszCarriageReturn // display line return
bl affichageMess
b 1b // and loop
end:
ldr x1,qAdrstReadFile
ldr x0,[x1,readfile_Fd] // load FD to structure
mov x8,CLOSE // call system close file
svc 0
cmp x0,0
blt error
mov x0,0 // return code
b 100f
error:
ldr x1,qAdrsZoneConv
bl conversion10S
ldr x0,qAdrszMessError // error message
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
mov x0,1 // return error code
100: // standard end of the program
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrsBuffer: .quad sBuffer
qAdrszFileName: .quad szFileName
qAdrszMessError: .quad szMessError
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrstReadFile: .quad stReadFile
qAdrszLineBuffer: .quad szLineBuffer
/******************************************************************/
/* sub strings index start number of characters */
/******************************************************************/
/* x0 contains the address of the structure */
/* x0 returns number of characters or -1 if error */
readLineFile:
stp x1,lr,[sp,-16]! // save registers
mov x14,x0 // save structure
ldr x11,[x14,#readfile_buffer]
ldr x12,[x14,#readfile_buffersize]
ldr x15,[x14,#readfile_pointer]
ldr x16,[x14,#readfile_linesize]
ldr x18,[x14,#readfile_buffersize]
ldr x10,[x14,#readfile_line]
mov x13,0
strb wzr,[x10,x13] // store zéro in line buffer
cmp x15,x12 // pointer buffer < buffer size ?
ble 2f // no file read
1: // loop read file
ldr x0,[x14,#readfile_Fd]
mov x1,x11 // buffer address
mov x2,x12 // buffer size
mov x8,READ // call system read file
svc 0
cmp x0,#0 // error read or end ?
ble 100f
mov x18,x0 // number of read characters
mov x15,#0 // init buffer pointer
2: // begin loop copy characters
ldrb w0,[x11,x15] // load 1 character read buffer
cmp x0,0x0A // end line ?
beq 4f
strb w0,[x10,x13] // store character in line buffer
add x13,x13,1 // increment pointer line
cmp x13,x16
bgt 99f // error
add x15,x15,1 // increment buffer pointer
cmp x15,x12 // end buffer ?
bge 1b // yes new read
cmp x15,x18 // read characters ?
blt 2b // no loop
// final
cmp x13,0 // no characters in line buffer ?
beq 100f
4:
strb wzr,[x10,x13] // store zéro final
add x15,x15,#1
str x15,[x14,#readfile_pointer] // store pointer in structure
str x18,[x14,#readfile_buffersize] // store number of last characters
mov x0,x13 // return length of line
b 100f
99:
mov x0,#-2 // line buffer too small -> error
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
# List of competitors
record Competitor is
score: uint8;
name: [uint8];
end record;
var cs: Competitor[] := {
{44, "Solomon"},
{42, "Jason"},
{42, "Errol"},
{41, "Garry"},
{41, "Bernard"},
{41, "Barry"},
{39, "Stephen"}
};
# Rank competitors given ranking method
interface Ranking(c: [Competitor],
n: intptr,
len: intptr,
last: uint16): (rank: uint16);
sub Rank(cs: [Competitor], num: intptr, r: Ranking) is
var last: uint16 := 0;
var idx: intptr := 0;
while idx < num loop
last := r(cs, idx, num, last);
if last < 100 then
print_i16(last);
else
# print fixed-point rank nicely
print_i16(last / 100);
print_char('.');
print_i16((last % 100) / 10);
print_i16(last % 10);
end if;
print(". ");
print_i8(cs.score);
print(", ");
print(cs.name);
print_nl();
idx := idx + 1;
cs := @next cs;
end loop;
end sub;
# Standard ranking
var stdcount: uint16 := 0;
sub Standard implements Ranking is
if n==0 then stdcount := 0; end if;
stdcount := stdcount + 1;
if n>0 and c.score == [@prev c].score then
rank := last;
else
rank := stdcount;
end if;
end sub;
# Modified ranking
sub Modified implements Ranking is
rank := last;
if n == 0 or c.score != [@prev c].score then
while n < len loop
rank := rank + 1;
c := @next c;
if c.score != [@prev c].score then
break;
end if;
n := n + 1;
end loop;
end if;
end sub;
# Dense ranking
sub Dense implements Ranking is
if n>0 and c.score == [@prev c].score then
rank := last;
else
rank := last + 1;
end if;
end sub;
# Ordinal ranking
sub Ordinal implements Ranking is
rank := last + 1;
end sub;
# Fractional ranking (with fixed point arithmetic)
sub Fractional implements Ranking is
rank := last;
if n==0 or c.score != [@prev c].score then
var sum: uint16 := 0;
var ct: uint16 := 0;
while n < len loop
sum := sum + (n as uint16 + 1);
ct := ct + 1;
c := @next c;
if c.score != [@prev c].score then
break;
end if;
n := n + 1;
end loop;
rank := (sum * 100) / (ct as uint16);
end if;
end sub;
record Method is
name: [uint8];
method: Ranking;
end record;
var methods: Method[] := {
{"Standard", Standard},
{"Modified", Modified},
{"Dense", Dense},
{"Ordinal", Ordinal},
{"Fractional", Fractional}
};
var n: @indexof methods := 0;
while n < @sizeof methods loop
print("--- ");
print(methods[n].name);
print(" ---\n");
Rank(&cs[0], @sizeof cs, methods[n].method);
print_nl();
n := n + 1;
end loop;
|
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).
|
#Visual_FoxPro
|
Visual FoxPro
|
LOCAL i As Integer, n As Integer, lcOut As String
CLOSE DATABASES ALL
CLEAR
CREATE CURSOR nums (num I)
INDEX ON num TAG num COLLATE "Machine"
SET ORDER TO 0
n = 50
RAND(-1)
FOR i = 1 TO n
INSERT INTO nums VALUES (RanInt(1, 10))
ENDFOR
SELECT num, COUNT(num) As cnt FROM nums ;
GROUP BY num INTO CURSOR grouped
LIST OFF TO FILE grouped.txt NOCONSOLE
lcOut = ""
SCAN
lcOut = lcOut + TRANSFORM(num) + ","
ENDSCAN
lcOut = LEFT(lcOut, LEN(lcOut)-1)
? lcOut
FUNCTION RanInt(tnLow As Integer, tnHigh As Integer) As Integer
RETURN INT((tnHigh - tnLow + 1)*RAND() + tnLow)
ENDFUNC
|
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).
|
#Wart
|
Wart
|
def (dedup l)
let exists (table)
collect+each x l
unless exists.x
yield x
exists.x <- 1
|
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
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
// A range is represented as std::pair<from, to>
template <typename iterator>
void normalize_ranges(iterator begin, iterator end) {
for (iterator i = begin; i != end; ++i) {
if (i->second < i->first)
std::swap(i->first, i->second);
}
std::sort(begin, end);
}
// Merges a range of ranges in-place. Returns an iterator to the
// end of the resulting range, similarly to std::remove.
template <typename iterator>
iterator merge_ranges(iterator begin, iterator end) {
iterator out = begin;
for (iterator i = begin; i != end; ) {
iterator j = i;
while (++j != end && j->first <= i->second)
i->second = std::max(i->second, j->second);
*out++ = *i;
i = j;
}
return out;
}
template <typename iterator>
iterator consolidate_ranges(iterator begin, iterator end) {
normalize_ranges(begin, end);
return merge_ranges(begin, end);
}
template <typename pair>
void print_range(std::ostream& out, const pair& range) {
out << '[' << range.first << ", " << range.second << ']';
}
template <typename iterator>
void print_ranges(std::ostream& out, iterator begin, iterator end) {
if (begin != end) {
print_range(out, *begin++);
for (; begin != end; ++begin) {
out << ", ";
print_range(out, *begin);
}
}
}
int main() {
std::vector<std::pair<double, double>> test_cases[] = {
{ {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 (auto&& ranges : test_cases) {
print_ranges(std::cout, std::begin(ranges), std::end(ranges));
std::cout << " -> ";
auto i = consolidate_ranges(std::begin(ranges), std::end(ranges));
print_ranges(std::cout, std::begin(ranges), i);
std::cout << '\n';
}
return 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
|
#Tcl
|
Tcl
|
set iters 10
# A silly example task
proc theTask {} {
for {set a 0} {$a < 100000} {incr a} {
expr {$a**3+$a**2+$a+1}
}
}
# Measure the time taken $iters times
for {set i 1} {$i <= $iters} {incr i} {
set t [lindex [time {
theTask
}] 0]
puts "task took $t microseconds on iteration $i"
}
|
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
|
#Neko
|
Neko
|
/* Reverse a string, in Neko */
var reverse = function(s) {
var len = $ssize(s)
if len < 2 return s
var reverse = $smake(len)
var pos = 0
while len > 0 $sset(reverse, pos ++= 1, $sget(s, len -= 1))
return reverse
}
var str = "never odd or even"
$print(str, "\n")
$print(reverse(str), "\n\n")
str = "abcdefghijklmnopqrstuvwxyz"
$print(str, "\n")
$print(reverse(str), "\n\n")
$print("single test\n")
str = "a"
$print(str, "\n")
$print(reverse(str), "\n\n")
$print("empty test\n")
str = ""
$print(str, "\n")
$print(reverse(str), "\n")
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#FreeBASIC
|
FreeBASIC
|
Type Point
As Single x,y
End Type
Function inpolygon(p1() As Point,p2 As Point) As Integer
#Macro isleft2(L,p)
-Sgn( (L(1).x-L(2).x)*(p.y-L(2).y) - (p.x-L(2).x)*(L(1).y-L(2).y))
#EndMacro
Dim As Integer index,nextindex
Dim k As Integer=UBound(p1)+1
Dim send (1 To 2) As Point
Dim wn As Integer=0
For n As Integer=1 To UBound(p1)
index=n Mod k:nextindex=(n+1) Mod k
If nextindex=0 Then nextindex=1
send(1).x=p1(index).x:send(2).x=p1(nextindex).x
send(1).y=p1(index).y:send(2).y=p1(nextindex).y
If p1(index).y<=p2.y Then
If p1(nextindex).y>p2.y Then
If isleft2(send,p2)>=0 Then '=
wn=wn+1
End If
End If
Else
If p1(nextindex).y<=p2.y Then
If isleft2(send,p2)<=0 Then'=
wn=wn-1
End If
End If
End If
Next n
Return wn
End Function
Dim As Point square(1 To 4) ={(0,0),(10,0),(10,10),(0,10)}
Dim As Point hole(1 To 4) ={(2.5,2.5),(7.5,2.5),(7.5,7.5),(2.5,7.5)}
Dim As Point strange(1 To 8) ={(0,0),(2.5,2.5),(0,10),(2.5,7.5),_
(7.5,7.5),(10,10),(10,0),(2.5,2.5)}
Dim As Point exagon(1 To 6) ={(3,0),(7,0),(10,5),(7,10),(3,10),(0,5)}
'printouts
For z As Integer=1 To 4
Select Case z
Case 1: Print "squared"
Print "(5,5) " ;Tab(12);
If inpolygon(square(),Type<Point>(5,5)) Then Print "in" Else Print "out"
Print "(5,8) " ;Tab(12);
If inpolygon(square(),Type<Point>(5,8)) Then Print "in" Else Print "out"
Print "(-10,5) " ;Tab(12);
If inpolygon(square(),Type<Point>(-10,5)) Then Print "in" Else Print "out"
Print "(0,5) " ;Tab(12);
If inpolygon(square(),Type<Point>(0,5)) Then Print "in" Else Print "out"
Print "(10,5) " ;Tab(12);
If inpolygon(square(),Type<Point>(10,5)) Then Print "in" Else Print "out"
Print "(8,5) " ;Tab(12);
If inpolygon(square(),Type<Point>(8,5)) Then Print "in" Else Print "out"
Print "(10,10) " ;Tab(12);
If inpolygon(square(),Type<Point>(10,10)) Then Print "in" Else Print "out"
Print
Case 2:Print "squared hole"
Print "(5,5) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(5,5)) And inpolygon(square(),Type<Point>(5,5)) Then Print "in" Else Print "out"
Print "(5,8) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(5,8)) And inpolygon(square(),Type<Point>(5,8))Then Print "in" Else Print "out"
Print "(-10,5) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(-10,5))And inpolygon(square(),Type<Point>(-10,5)) Then Print "in" Else Print "out"
Print "(0,5) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(0,5))And inpolygon(square(),Type<Point>(0,5)) Then Print "in" Else Print "out"
Print "(10,5) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(10,5))And inpolygon(square(),Type<Point>(10,5)) Then Print "in" Else Print "out"
Print "(8,5) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(8,5))And inpolygon(square(),Type<Point>(8,5)) Then Print "in" Else Print "out"
Print "(10,10) " ;Tab(12);
If Not inpolygon(hole(),Type<Point>(10,10))And inpolygon(square(),Type<Point>(10,10)) Then Print "in" Else Print "out"
Print
Case 3:Print "strange"
Print "(5,5) " ;Tab(12);
If inpolygon(strange(),Type<Point>(5,5)) Then Print "in" Else Print "out"
Print "(5,8) " ;Tab(12);
If inpolygon(strange(),Type<Point>(5,8)) Then Print "in" Else Print "out"
Print "(-10,5) " ;Tab(12);
If inpolygon(strange(),Type<Point>(-10,5)) Then Print "in" Else Print "out"
Print "(0,5) " ;Tab(12);
If inpolygon(strange(),Type<Point>(0,5)) Then Print "in" Else Print "out"
Print "(10,5) " ;Tab(12);
If inpolygon(strange(),Type<Point>(10,5)) Then Print "in" Else Print "out"
Print "(8,5) " ;Tab(12);
If inpolygon(strange(),Type<Point>(8,5)) Then Print "in" Else Print "out"
Print "(10,10) " ;Tab(12);
If inpolygon(strange(),Type<Point>(10,10)) Then Print "in" Else Print "out"
Print
Case 4:Print "exagon"
Print "(5,5) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(5,5)) Then Print "in" Else Print "out"
Print "(5,8) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(5,8)) Then Print "in" Else Print "out"
Print "(-10,5) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(-10,5)) Then Print "in" Else Print "out"
Print "(0,5) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(0,5)) Then Print "in" Else Print "out"
Print "(10,5) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(10,5)) Then Print "in" Else Print "out"
Print "(8,5) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(8,5)) Then Print "in" Else Print "out"
Print "(10,10) " ;Tab(12);
If inpolygon(exagon(),Type<Point>(10,10)) Then Print "in" Else Print "out"
Print
End Select
Next z
Sleep
|
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
|
#Julia
|
Julia
|
""" weighted random pick of items in a Dict{String, Int} where keys are words, values counts """
function weightedrandompick(dict, total)
n = rand(1:total)
for (key, value) in dict
n -= value
if n <= 0
return key
end
end
return last(keys(dict))
end
let
""" Read in the book "The War of the Worlds", by H. G. Wells. """
wotw_uri = "http://www.gutenberg.org/files/36/36-0.txt"
wfile = "war_of_the_worlds.txt"
stat(wfile).size == 0 && download(wotw_uri, wfile) # download if file not here already
text = read(wfile, String)
"""skip to start of book and prune end """
startphrase, endphrase = "No one would have believed", "she has counted me, among the dead"
text = text[findfirst(startphrase, text).start:findlast(endphrase, text).stop]
""" Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? """
text = replace(replace(text, r"[^01-9a-zA-Z\.\?\!’,]" => " "), r"([.?!])" => s" \1")
words = split(text, r"\s+")
for (i, w) in enumerate(words)
w != "I" && i > 1 && words[i - 1] in [".", "?", "!"] && (words[i] = lowercase(words[i]))
end
""" 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.
"""
follows, follows2 = Dict{String, Dict{String, Int}}(), Dict{String, Dict{String, Int}}()
afterstop, wlen = Dict{String, Int}(), length(words)
for (i, w) in enumerate(@view words[1:end-1])
d = get!(follows, w, Dict(words[i + 1] => 0))
get!(d, words[i + 1], 0)
d[words[i + 1]] += 1
if w in [".", "?", "!"]
d = get!(afterstop, words[i + 1], 0)
afterstop[words[i + 1]] += 1
end
(i > wlen - 2) && continue
w2 = w * " " * words[i + 1]
d = get!(follows2, w2, Dict(words[i + 2] => 0))
get!(d, words[i + 2], 0)
d[words[i + 2]] += 1
end
followsums = Dict(key => sum(values(follows[key])) for key in keys(follows))
follow2sums = Dict(key => sum(values(follows2[key])) for key in keys(follows2))
afterstopsum = sum(values(afterstop))
""" 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.
"""
function makesentence()
firstword = weightedrandompick(afterstop, afterstopsum)
sentencewords = [firstword, weightedrandompick(follows[firstword], followsums[firstword])]
while !(sentencewords[end] in [".", "?", "!"])
w2 = sentencewords[end-1] * " " * sentencewords[end]
if haskey(follows2, w2)
push!(sentencewords, weightedrandompick(follows2[w2], follow2sums[w2]))
else
push!(sentencewords, weightedrandompick(afterstop, afterstopsum))
end
end
sentencewords[1] = uppercase(firstword[1]) * (length(firstword) > 1 ? firstword[2:end] : "")
println(join(sentencewords[1:end-1], " ") * sentencewords[end] * "\n")
end
# Print 3 weighted random pick sentences
makesentence(); makesentence(); makesentence()
end
|
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
|
#Nim
|
Nim
|
import random, sequtils, strutils, tables
from unicode import utf8
const StopChars = [".", "?", "!"]
proc weightedChoice(choices: CountTable[string]; totalCount: int): string =
## Return a string from "choices" key using counts as weights.
var n = rand(1..totalCount)
for word, count in choices.pairs:
dec n, count
if n <= 0: return word
assert false, "internal error"
proc finalFilter(words: seq[string]): seq[string] =
## Eliminate words of length one (except those of a given list)
## and words containing only uppercase letters (words from titles).
for word in words:
if word in [".", "?", "!", "I", "A", "a"]:
result.add word
elif word.len > 1 and any(word, isLowerAscii):
result.add word
randomize()
var text = readFile("The War of the Worlds.txt")
# Extract the actual text from the book.
const
StartText = "BOOK ONE\r\nTHE COMING OF THE MARTIANS"
EndText = "End of the Project Gutenberg EBook"
let startIndex = text.find(StartText)
let endIndex = text.find(EndText)
text = text[startIndex..<endIndex]
# Clean the text by removing some characters and replacing others.
# As there are some non ASCII characters, we have to apply special rules.
var processedText: string
for uchar in text.utf8():
if uchar.len == 1:
# ASCII character.
let ch = uchar[0]
case ch
of '0'..'9', 'a'..'z', 'A'..'Z', ' ': processedText.add ch # Keep as is.
of '\n': processedText.add ' ' # Replace with a space.
of '.', '?', '!': processedText.add ' ' & ch # Make sure these characters are isolated.
else: discard # Remove others.
else:
# Some UTF-8 representation of a non ASCII character.
case uchar
of "—": processedText.add ' ' # Replace EM DASH with space.
of "ç", "æ", "’": processedText.add uchar # Keep these characters as they are parts of words.
of "“", "”", "‘": discard # Removed these ones.
else: echo "encountered: ", uchar # Should not go here.
# Extract words and filter them.
let words = processedText.splitWhitespace().finalFilter()
# Build count tables.
var followCount, followCount2: Table[string, CountTable[string]]
for i in 1..words.high:
followCount.mgetOrPut(words[i - 1], initCountTable[string]()).inc(words[i])
for i in 2..words.high:
followCount2.mgetOrPut(words[i - 2] & ' ' & words[i - 1], initCountTable[string]()).inc words[i]
# Build sum tables.
var followSum, followSum2: CountTable[string]
for key in followCount.keys:
for count in followCount[key].values:
followSum.inc key, count
for key in followCount2.keys:
for count in followCount2[key].values:
followSum2.inc key, count
# Build table of starting words and compute the sum.
var
startingWords: CountTable[string]
startingSum: int
for stopChar in StopChars:
for word, count in followCount[stopChar].pairs:
startingWords.inc word, count
inc startingSum, count
# Build a sentence.
let firstWord = weightedChoice(startingWords, startingSum)
var sentence = @[firstWord]
var lastWord = weightedChoice(followCount[firstWord], followSum[firstWord])
while lastWord notin StopChars:
sentence.add lastWord
let key = sentence[^2] & ' ' & lastWord
lastWord = if key in followCount2:
weightedChoice(followCount2[key], followSum2[key])
else:
weightedChoice(followCount[lastWord], followSum[lastWord])
echo sentence.join(" ") & lastWord
|
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.
|
#Lasso
|
Lasso
|
local(f) = file('unixdict.txt')
handle => { #f->close }
local(this_line = string,line = 0)
#f->forEachLine => {
#line++
#line == 7 ? #this_line = #1
#line == 7 ? loop_abort
}
#this_line // 6th, which is the 7th line in the file
|
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
|
#AWK
|
AWK
|
# syntax: GAWK -f READ_A_CONFIGURATION_FILE.AWK
BEGIN {
fullname = favouritefruit = ""
needspeeling = seedsremoved = "false"
fn = "READ_A_CONFIGURATION_FILE.INI"
while (getline rec <fn > 0) {
tmp = tolower(rec)
if (tmp ~ /^ *fullname/) { fullname = extract(rec) }
else if (tmp ~ /^ *favouritefruit/) { favouritefruit = extract(rec) }
else if (tmp ~ /^ *needspeeling/) { needspeeling = "true" }
else if (tmp ~ /^ *seedsremoved/) { seedsremoved = "true" }
else if (tmp ~ /^ *otherfamily/) { split(extract(rec),otherfamily,",") }
}
close(fn)
printf("fullname=%s\n",fullname)
printf("favouritefruit=%s\n",favouritefruit)
printf("needspeeling=%s\n",needspeeling)
printf("seedsremoved=%s\n",seedsremoved)
for (i=1; i<=length(otherfamily); i++) {
sub(/^ +/,"",otherfamily[i]) # remove leading spaces
sub(/ +$/,"",otherfamily[i]) # remove trailing spaces
printf("otherfamily(%d)=%s\n",i,otherfamily[i])
}
exit(0)
}
function extract(rec, pos,str) {
sub(/^ +/,"",rec) # remove leading spaces before parameter name
pos = match(rec,/[= ]/) # determine where data begins
str = substr(rec,pos) # extract the data
gsub(/^[= ]+/,"",str) # remove leading "=" and spaces
sub(/ +$/,"",str) # remove trailing spaces
return(str)
}
|
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).
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using UI = System.UInt64;
using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;
using Lst = System.Collections.Generic.List<sbyte>;
using DT = System.DateTime;
class Program {
const sbyte MxD = 19;
public struct term { public UI coeff; public sbyte a, b;
public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } }
static int[] digs; static List<UI> res; static sbyte count = 0;
static DT st; static List<List<term>> tLst; static List<LST> lists;
static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il;
static bool odd; static int nd, nd2; static LST ixs;
static int[] cnd, di; static LST dis; static UI Dif;
// converts digs array to the "difference"
static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++)
r = r * 10 + (uint)digs[i]; return r; }
// converts digs array to the "sum"
static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--)
r = r * 10 + (uint)digs[i]; return Dif + (r << 1); }
// determines if the nmbr is square or not
static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0)
{ UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; }
// returns sequence of sbytes
static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst();
for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; }
// Recursive closure to generate (n+r) candidates from (n-r) candidates
static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0];
digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1;
if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) {
digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; }
if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine("{0,16:n0}{1,4} ({2:n0})",
(DT.Now - st).TotalMilliseconds, ++count, res.Last()); }
else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } }
// Recursive closure to generate (n-r) candidates with a given number of digits.
static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0;
foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]);
else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return;
dis = new LST { Seq(0, fml[cnd[0]].Count - 1) };
foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1));
if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0);
} else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } }
static void init() { UI pow = 1;
// terms of (n-r) expression for number of digits from 2 to maxDigits
tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) {
List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1;
for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) {
terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; }
tLst.Add(terms); }
// map of first minus last digits for 'n' to pairs giving this value
fml = new Dictionary<int, LST> {
[0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } },
[1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } },
[4] = new LST { new Lst { 4, 0 } },
[6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } };
// map of other digit differences for 'n' to pairs giving this value
dmd = new Dictionary<int, LST>();
for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) {
if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j });
else dmd[d] = new LST { new Lst { i, j } }; }
dl = Seq(-9, 9); // all differences
zl = Seq( 0, 0); // zero differences only
el = Seq(-8, 8, 2); // even differences only
ol = Seq(-9, 9, 2); // odd differences only
il = Seq( 0, 9); lists = new List<LST>();
foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); }
static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0;
WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Unordered Rare Numbers");
for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd];
if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); }
else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl);
ixs = new LST();
foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b });
foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); }
WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds); }
res.Sort();
WriteLine("\nThe {0} rare numbers with up to {1} digits are:", res.Count, MxD);
count = 0; foreach (var rare in res) WriteLine("{0,2}:{1,27:n0}", ++count, rare);
if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }
}
|
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
|
#11l
|
11l
|
F rangeexpand(txt)
[Int] lst
L(r) txt.split(‘,’)
I ‘-’ C r[1..]
V rr = r[1..].split(‘-’, 2)
lst [+]= Int(r[0]‘’rr[0]) .. Int(rr[1])
E
lst.append(Int(r))
R lst
print(rangeexpand(‘-6,-3--1,3-5,7-11,14,15,17-20’))
|
http://rosettacode.org/wiki/Read_a_file_line_by_line
|
Read a file line by line
|
Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
|
#Action.21
|
Action!
|
char array TXT
Proc Main()
Open (1,"D:FILENAME.TXT",4,0)
Do
InputSD(1,TXT)
PrintE(TXT)
Until EOF(1)
Od
Close(1)
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.
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Line_By_Line is
File : File_Type;
begin
Open (File => File,
Mode => In_File,
Name => "line_by_line.adb");
While not End_Of_File (File) Loop
Put_Line (Get_Line (File));
end loop;
Close (File);
end Line_By_Line;
|
http://rosettacode.org/wiki/Ranking_methods
|
Ranking methods
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition.
The numerical rank of a competitor can be assigned in several different ways.
Task
The following scores are accrued for all competitors of a competition (in best-first order):
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen
For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers:
Standard. (Ties share what would have been their first ordinal number).
Modified. (Ties share what would have been their last ordinal number).
Dense. (Ties share the next available integer).
Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise).
Fractional. (Ties share the mean of what would have been their ordinal numbers).
See the wikipedia article for a fuller description.
Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
|
#D
|
D
|
import std.algorithm;
import std.stdio;
void main() {
immutable scores = [
"Solomon": 44,
"Jason": 42,
"Errol": 42,
"Garry": 41,
"Bernard": 41,
"Barry": 41,
"Stephen": 39
];
scores.standardRank;
scores.modifiedRank;
scores.denseRank;
scores.ordinalRank;
scores.fractionalRank;
}
/*
Standard ranking
1 44 Solomon
2 42 Jason
2 42 Errol
4 41 Garry
4 41 Bernard
4 41 Barry
7 39 Stephen
*/
void standardRank(const int[string] data) {
writeln("Standard Rank");
int rank = 1;
foreach (value; data.values.dup.sort!"a>b".uniq) {
int temp = rank;
foreach(k,v; data) {
if (v==value) {
writeln(temp, " ", v, " ", k);
rank++;
}
}
}
writeln;
}
/*
Modified ranking
1 44 Solomon
3 42 Jason
3 42 Errol
6 41 Garry
6 41 Bernard
6 41 Barry
7 39 Stephen
*/
void modifiedRank(const int[string] data) {
writeln("Modified Rank");
int rank = 0;
foreach (value; data.values.dup.sort!"a>b".uniq) {
foreach(k,v; data) {
if (v==value) {
rank++;
}
}
foreach(k,v; data) {
if (v==value) {
writeln(rank, " ", v, " ", k);
}
}
}
writeln;
}
/*
Dense ranking
1 44 Solomon
2 42 Jason
2 42 Errol
3 41 Garry
3 41 Bernard
3 41 Barry
4 39 Stephen
*/
void denseRank(const int[string] data) {
writeln("Dense Rank");
int rank = 1;
foreach (value; data.values.dup.sort!"a>b".uniq) {
foreach(k,v; data) {
if (v==value) {
writeln(rank, " ", v, " ", k);
}
}
rank++;
}
writeln;
}
/*
Ordinal ranking
1 44 Solomon
2 42 Jason
3 42 Errol
4 41 Garry
5 41 Bernard
6 41 Barry
7 39 Stephen
*/
void ordinalRank(const int[string] data) {
writeln("Ordinal Rank");
int rank = 1;
foreach (value; data.values.dup.sort!"a>b".uniq) {
foreach(k,v; data) {
if (v==value) {
writeln(rank, " ", v, " ", k);
rank++;
}
}
}
writeln;
}
/*
Fractional ranking
1,0 44 Solomon
2,5 42 Jason
2,5 42 Errol
5,0 41 Garry
5,0 41 Bernard
5,0 41 Barry
7,0 39 Stephen
*/
void fractionalRank(const int[string] data) {
writeln("Fractional Rank");
int rank = 0;
foreach (value; data.values.dup.sort!"a>b".uniq) {
real avg = 0;
int cnt;
foreach(k,v; data) {
if (v==value) {
rank++;
cnt++;
avg+=rank;
}
}
avg /= cnt;
foreach(k,v; data) {
if (v==value) {
writef("%0.1f ", avg);
writeln(v, " ", k);
}
}
}
writeln;
}
|
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).
|
#Wortel
|
Wortel
|
@uniq [1 2 3 2 1 2 3] ; returns [1 2 3]
|
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).
|
#Wren
|
Wren
|
import "/sort" for Sort
// Using a map - order of distinct items is undefined.
var removeDuplicates1 = Fn.new { |a|
if (a.count <= 1) return a
var m = {}
for (e in a) m[e] = true
return m.keys.toList
}
// Sort elements and remove consecutive duplicates.
var removeDuplicates2 = Fn.new { |a|
if (a.count <= 1) return a
Sort.insertion(a)
for (i in a.count-1..1) {
if (a[i] == a[i-1]) a.removeAt(i)
}
return a
}
// Iterate through list and for each element check if it occurs later in the list.
// If it does, discard it.
var removeDuplicates3 = Fn.new { |a|
if (a.count <= 1) return a
var i = 0
while (i < a.count-1) {
var j = i + 1
while(j < a.count) {
if (a[i] == a[j]) {
a.removeAt(j)
} else {
j = j + 1
}
}
i = i + 1
}
return a
}
var a = [1,2,3,4,1,2,3,5,1,2,3,4,5]
System.print("Original: %(a)")
System.print("Method 1: %(removeDuplicates1.call(a.toList))") // copy original each time
System.print("Method 2: %(removeDuplicates2.call(a.toList))")
System.print("Method 3: %(removeDuplicates3.call(a.toList))")
|
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
|
#Clojure
|
Clojure
|
(defn normalize [r]
(let [[n1 n2] r]
[(min n1 n2) (max n1 n2)]))
(defn touch? [r1 r2]
(let [[lo1 hi1] (normalize r1)
[lo2 hi2] (normalize r2)]
(or (<= lo2 lo1 hi2)
(<= lo2 hi1 hi2))))
(defn consolidate-touching-ranges [rs]
(let [lows (map #(apply min %) rs)
highs (map #(apply max %) rs)]
[ (apply min lows) (apply max highs) ]))
(defn consolidate-ranges [rs]
(loop [res []
rs rs]
(if (empty? rs)
res
(let [r0 (first rs)
touching (filter #(touch? r0 %) rs)
remove-used (fn [rs used]
(remove #(contains? (set used) %) rs))]
(recur (conj res (consolidate-touching-ranges touching))
(remove-used (rest rs) touching))))))
|
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
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/bash
while : ; do
task && echo >> .fc
done
|
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
|
#Vlang
|
Vlang
|
import rand
import time
// representation of time.Time is nanosecond, actual resolution system specific
struct RateStateS {
mut:
last_flush time.Time
period time.Duration
tick_count int
}
fn (mut p_rate RateStateS) tic_rate() {
p_rate.tick_count++
now := time.now()
if now-p_rate.last_flush >= p_rate.period {
// TPS Report
mut tps := 0.0
if p_rate.tick_count > 0 {
tps = f64(p_rate.tick_count) / (now-p_rate.last_flush).seconds()
}
println("$tps tics per second.")
// Reset
p_rate.tick_count = 0
p_rate.last_flush = now
}
}
fn something_we_do() {
time.sleep(time.Duration(i64(9e7) + rand.i64n(i64(2e7)) or {i64(0)})) // sleep about .1 second.
}
fn main() {
start := time.now()
mut rate_watch := RateStateS{
last_flush: start,
period: 5 * time.second,
}
// Loop for twenty seconds
mut latest := start
for latest-start < 20*time.second {
something_we_do()
rate_watch.tic_rate()
latest = time.now()
}
}
|
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
|
#Nemerle
|
Nemerle
|
ncc -reference:System.Windows.Forms reverse.n
|
http://rosettacode.org/wiki/Ray-casting_algorithm
|
Ray-casting algorithm
|
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.
A pseudocode can be simply:
count ← 0
foreach side in polygon:
if ray_intersects_segment(P,side) then
count ← count + 1
if is_odd(count) then
return inside
else
return outside
Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.
An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).
So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.
Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).
So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.
Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).
Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so.
An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):
ray_intersects_segment:
P : the point from which the ray starts
A : the end-point of the segment with the smallest y coordinate
(A must be "below" B)
B : the end-point of the segment with the greatest y coordinate
(B must be "above" A)
if Py = Ay or Py = By then
Py ← Py + ε
end if
if Py < Ay or Py > By then
return false
else if Px >= max(Ax, Bx) then
return false
else
if Px < min(Ax, Bx) then
return true
else
if Ax ≠ Bx then
m_red ← (By - Ay)/(Bx - Ax)
else
m_red ← ∞
end if
if Ax ≠ Px then
m_blue ← (Py - Ay)/(Px - Ax)
else
m_blue ← ∞
end if
if m_blue ≥ m_red then
return true
else
return false
end if
end if
end if
(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity ε.)
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
type xy struct {
x, y float64
}
type seg struct {
p1, p2 xy
}
type poly struct {
name string
sides []seg
}
func inside(pt xy, pg poly) (i bool) {
for _, side := range pg.sides {
if rayIntersectsSegment(pt, side) {
i = !i
}
}
return
}
func rayIntersectsSegment(p xy, s seg) bool {
var a, b xy
if s.p1.y < s.p2.y {
a, b = s.p1, s.p2
} else {
a, b = s.p2, s.p1
}
for p.y == a.y || p.y == b.y {
p.y = math.Nextafter(p.y, math.Inf(1))
}
if p.y < a.y || p.y > b.y {
return false
}
if a.x > b.x {
if p.x > a.x {
return false
}
if p.x < b.x {
return true
}
} else {
if p.x > b.x {
return false
}
if p.x < a.x {
return true
}
}
return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
var (
p1 = xy{0, 0}
p2 = xy{10, 0}
p3 = xy{10, 10}
p4 = xy{0, 10}
p5 = xy{2.5, 2.5}
p6 = xy{7.5, 2.5}
p7 = xy{7.5, 7.5}
p8 = xy{2.5, 7.5}
p9 = xy{0, 5}
p10 = xy{10, 5}
p11 = xy{3, 0}
p12 = xy{7, 0}
p13 = xy{7, 10}
p14 = xy{3, 10}
)
var tpg = []poly{
{"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},
{"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},
{p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},
{"strange", []seg{{p1, p5},
{p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},
{"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13},
{p13, p14}, {p14, p9}, {p9, p11}}},
}
var tpt = []xy{
// test points common in other solutions on this page
{5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},
// test points that show the problem with "strange"
{1, 2}, {2, 1},
}
func main() {
for _, pg := range tpg {
fmt.Printf("%s:\n", pg.name)
for _, pt := range tpt {
fmt.Println(pt, inside(pt, pg))
}
}
}
|
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
|
#Perl
|
Perl
|
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Random_sentence_from_book
use warnings;
my $book = do { local (@ARGV, $/) = 'waroftheworlds.txt'; <> };
my (%one, %two);
s/^.*?START OF THIS\N*\n//s, s/END OF THIS.*//s,
tr/a-zA-Z.!?/ /c, tr/ / /s for $book;
my $qr = qr/(\b\w+\b|[.!?])/;
$one{$1}{$2}++, $two{$1}{$2}{$3}++ while $book =~ /$qr(?= *$qr *$qr)/g;
sub weightedpick
{
my $href = shift;
my @weightedpick = map { ($_) x $href->{$_} } keys %$href;
$weightedpick[rand @weightedpick];
}
sub sentence
{
my @sentence = qw( . ! ? )[rand 3];
push @sentence, weightedpick( $one{ $sentence[0] } );
push @sentence, weightedpick( $two{ $sentence[-2] }{ $sentence[-1] } )
while $sentence[-1] =~ /\w/;
shift @sentence;
"@sentence\n\n" =~ s/\w\K (?=[st]\b)/'/gr =~ s/ (?=[.!?]\n)//r
=~ s/.{60,}?\K /\n/gr;
}
print sentence() for 1 .. 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.
|
#Liberty_BASIC
|
Liberty BASIC
|
fileName$ ="F:\sample.txt"
requiredLine =7
open fileName$ for input as #i
f$ =input$( #i, lof( #i))
close #i
line7$ =word$( f$, 7, chr$( 13))
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."
print line7$
|
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
|
#BASIC
|
BASIC
|
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Read a Configuration File V1.0 '
' '
' Developed by A. David Garza Marín in VB-DOS for '
' RosettaCode. December 2, 2016. '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
OPTION EXPLICIT ' For VB-DOS, PDS 7.1
' OPTION _EXPLICIT ' For QB64
' SUBs and FUNCTIONs
DECLARE FUNCTION ErrorMessage$ (WhichError AS INTEGER)
DECLARE FUNCTION YorN$ ()
DECLARE FUNCTION FileExists% (WhichFile AS STRING)
DECLARE FUNCTION ReadConfFile% (NameOfConfFile AS STRING)
DECLARE FUNCTION getVariable$ (WhichVariable AS STRING)
DECLARE FUNCTION getArrayVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER)
' Register for values located
TYPE regVarValue
VarName AS STRING * 20
VarType AS INTEGER ' 1=String, 2=Integer, 3=Real
VarValue AS STRING * 30
END TYPE
' Var
DIM rVarValue() AS regVarValue, iErr AS INTEGER, i AS INTEGER, iHMV AS INTEGER
DIM otherfamily(1 TO 2) AS STRING
DIM fullname AS STRING, favouritefruit AS STRING, needspeeling AS INTEGER, seedsremoved AS INTEGER
CONST ConfFileName = "config.fil"
' ------------------- Main Program ------------------------
CLS
PRINT "This program reads a configuration file and shows the result."
PRINT
PRINT "Default file name: "; ConfFileName
PRINT
iErr = ReadConfFile(ConfFileName)
IF iErr = 0 THEN
iHMV = UBOUND(rVarValue)
PRINT "Variables found in file:"
FOR i = 1 TO iHMV
PRINT RTRIM$(rVarValue(i).VarName); " = "; RTRIM$(rVarValue(i).VarValue); " (";
SELECT CASE rVarValue(i).VarType
CASE 0: PRINT "Undefined";
CASE 1: PRINT "String";
CASE 2: PRINT "Integer";
CASE 3: PRINT "Real";
END SELECT
PRINT ")"
NEXT i
PRINT
' Sets required variables
fullname = getVariable$("FullName")
favouritefruit = getVariable$("FavouriteFruit")
needspeeling = VAL(getVariable$("NeedSpeeling"))
seedsremoved = VAL(getVariable$("SeedsRemoved"))
FOR i = 1 TO 2
otherfamily(i) = getArrayVariable$("OtherFamily", i)
NEXT i
PRINT "Variables requested to set values:"
PRINT "fullname = "; fullname
PRINT "favouritefruit = "; favouritefruit
PRINT "needspeeling = ";
IF needspeeling = 0 THEN PRINT "false" ELSE PRINT "true"
PRINT "seedsremoved = ";
IF seedsremoved = 0 THEN PRINT "false" ELSE PRINT "true"
FOR i = 1 TO 2
PRINT "otherfamily("; i; ") = "; otherfamily(i)
NEXT i
ELSE
PRINT ErrorMessage$(iErr)
END IF
' --------- End of Main Program -----------------------
END
FileError:
iErr = ERR
RESUME NEXT
FUNCTION ErrorMessage$ (WhichError AS INTEGER)
' Var
DIM sError AS STRING
SELECT CASE WhichError
CASE 0: sError = "Everything went ok."
CASE 1: sError = "Configuration file doesn't exist."
CASE 2: sError = "There are no variables in the given file."
END SELECT
ErrorMessage$ = sError
END FUNCTION
FUNCTION FileExists% (WhichFile AS STRING)
' Var
DIM iFile AS INTEGER
DIM iItExists AS INTEGER
SHARED iErr AS INTEGER
ON ERROR GOTO FileError
iFile = FREEFILE
iErr = 0
OPEN WhichFile FOR BINARY AS #iFile
IF iErr = 0 THEN
iItExists = LOF(iFile) > 0
CLOSE #iFile
IF NOT iItExists THEN
KILL WhichFile
END IF
END IF
ON ERROR GOTO 0
FileExists% = iItExists
END FUNCTION
FUNCTION getArrayVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER)
' Var
DIM i AS INTEGER, iHMV AS INTEGER, iCount AS INTEGER
DIM sVar AS STRING, sVal AS STRING, sWV AS STRING
SHARED rVarValue() AS regVarValue
' Looks for a variable name and returns its value
iHMV = UBOUND(rVarValue)
sWV = UCASE$(LTRIM$(RTRIM$(WhichVariable)))
sVal = ""
DO
i = i + 1
sVar = UCASE$(RTRIM$(rVarValue(i).VarName))
IF sVar = sWV THEN
iCount = iCount + 1
IF iCount = WhichIndex THEN
sVal = LTRIM$(RTRIM$(rVarValue(i).VarValue))
END IF
END IF
LOOP UNTIL i >= iHMV OR sVal <> ""
' Found it or not, it will return the result.
' If the result is "" then it didn't found the requested variable.
getArrayVariable$ = sVal
END FUNCTION
FUNCTION getVariable$ (WhichVariable AS STRING)
' Var
DIM i AS INTEGER, iHMV AS INTEGER
DIM sVal AS STRING
' For a single variable, looks in the first (and only)
' element of the array that contains the name requested.
sVal = getArrayVariable$(WhichVariable, 1)
getVariable$ = sVal
END FUNCTION
FUNCTION ReadConfFile% (NameOfConfFile AS STRING)
' Var
DIM iFile AS INTEGER, iType AS INTEGER, iVar AS INTEGER, iHMV AS INTEGER
DIM iVal AS INTEGER, iCurVar AS INTEGER, i AS INTEGER, iErr AS INTEGER
DIM dValue AS DOUBLE
DIM sLine AS STRING, sVar AS STRING, sValue AS STRING
SHARED rVarValue() AS regVarValue
' This procedure reads a configuration file with variables
' and values separated by the equal sign (=) or a space.
' It needs the FileExists% function.
' Lines begining with # or blank will be ignored.
IF FileExists%(NameOfConfFile) THEN
iFile = FREEFILE
REDIM rVarValue(1 TO 10) AS regVarValue
OPEN NameOfConfFile FOR INPUT AS #iFile
WHILE NOT EOF(iFile)
LINE INPUT #iFile, sLine
sLine = RTRIM$(LTRIM$(sLine))
IF LEN(sLine) > 0 THEN ' Does it have any content?
IF LEFT$(sLine, 1) <> "#" THEN ' Is not a comment?
IF LEFT$(sLine,1) = ";" THEN ' It is a commented variable
sLine = LTRIM$(MID$(sLine, 2))
END IF
iVar = INSTR(sLine, "=") ' Is there an equal sign?
IF iVar = 0 THEN iVar = INSTR(sLine, " ") ' if not then is there a space?
GOSUB AddASpaceForAVariable
iCurVar = iHMV
IF iVar > 0 THEN ' Is a variable and a value
rVarValue(iHMV).VarName = LEFT$(sLine, iVar - 1)
ELSE ' Is just a variable name
rVarValue(iHMV).VarName = sLine
rVarValue(iHMV).VarValue = ""
END IF
IF iVar > 0 THEN ' Get the value(s)
sLine = LTRIM$(MID$(sLine, iVar + 1))
DO ' Look for commas
iVal = INSTR(sLine, ",")
IF iVal > 0 THEN ' There is a comma
rVarValue(iHMV).VarValue = RTRIM$(LEFT$(sLine, iVal - 1))
GOSUB AddASpaceForAVariable
rVarValue(iHMV).VarName = rVarValue(iHMV - 1).VarName ' Repeats the variable name
sLine = LTRIM$(MID$(sLine, iVal + 1))
END IF
LOOP UNTIL iVal = 0
rVarValue(iHMV).VarValue = sLine
' Determine the variable type of each variable found in this step
FOR i = iCurVar TO iHMV
GOSUB DetermineVariableType
NEXT i
END IF
END IF
END IF
WEND
CLOSE iFile
IF iHMV > 0 THEN
REDIM PRESERVE rVarValue(1 TO iHMV) AS regVarValue
iErr = 0 ' Everything ran ok.
ELSE
REDIM rVarValue(1 TO 1) AS regVarValue
iErr = 2 ' No variables found in configuration file
END IF
ELSE
iErr = 1 ' File doesn't exist
END IF
ReadConfFile = iErr
EXIT FUNCTION
AddASpaceForAVariable:
iHMV = iHMV + 1
IF UBOUND(rVarValue) < iHMV THEN ' Are there space for a new one?
REDIM PRESERVE rVarValue(1 TO iHMV + 9) AS regVarValue
END IF
RETURN
DetermineVariableType:
sValue = RTRIM$(rVarValue(i).VarValue)
IF ASC(LEFT$(sValue, 1)) < 48 OR ASC(LEFT$(sValue, 1)) > 57 THEN
rVarValue(i).VarType = 1 ' String
ELSE
dValue = VAL(sValue)
IF CLNG(dValue) = dValue THEN
rVarValue(i).VarType = 2 ' Integer
ELSE
rVarValue(i).VarType = 3 ' Real
END IF
END IF
RETURN
END FUNCTION
|
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).
|
#C.2B.2B
|
C++
|
// Rare Numbers : Nigel Galloway - December 20th., 2019;
// Nigel Galloway/Enter your username - January 4th., 2021 (see discussion page.
#include <functional>
#include <bitset>
#include <cmath>
using namespace std;
using Z2 = optional<long long>; using Z1 = function<Z2()>;
// powers of 10 array
constexpr auto pow10 = [] { array <long long, 19> n {1}; for (int j{0}, i{1}; i < 19; j = i++) n[i] = n[j] * 10; return n; } ();
long long acc, l;
bool izRev(int n, unsigned long long i, unsigned long long g) {
return (i / pow10[n - 1] != g % 10) ? false : n < 2 ? true : izRev(n - 1, i % pow10[n - 1], g / 10);
}
const Z1 fG(Z1 n, int start, int end, int reset, const long long step, long long &l) {
return [n, i{step * start}, g{step * end}, e{step * reset}, &l, step] () mutable {
while (i<g){i+=step; return Z2(l+=step);}
l-=g-(i=e); return n();};
}
struct nLH {
vector<unsigned long long>even{}, odd{};
nLH(const Z1 a, const vector<long long> b, long long llim){while (auto i = a()) for (auto ng : b)
if(ng>0 | *i>llim){unsigned long long sq{ng+ *i}, r{sqrt(sq)}; if (r*r == sq) ng&1 ? odd.push_back(sq) : even.push_back(sq);}}
};
const double fac = 3.94;
const int mbs = (int)sqrt(fac * pow10[9]), mbt = (int)sqrt(fac * fac * pow10[9]) >> 3;
const bitset<100000>bs {[]{bitset<100000>n{false}; for(int g{3};g<mbs;++g) n[(g*g)%100000]=true; return n;}()};
constexpr array<const int, 7>li{1,3,0,0,1,1,1},lin{0,-7,0,0,-8,-3,-9},lig{0,9,0,0,8,7,9},lil{0,2,0,0,2,10,2};
const nLH makeL(const int n){
constexpr int r{9}; acc=0; Z1 g{[]{return Z2{};}}; int s{-r}, q{(n>11)*5}; vector<long long> w{};
for (int i{1};i<n/2-q+1;++i){l=pow10[n-i-q]-pow10[i+q-1]; s-=i==n/2-q; g=fG(g,s,r,-r,l,acc+=l*s);}
if(q){long long g0{0}, g1{0}, g2{0}, g3{0}, g4{0}, l3{pow10[n-5]}; while (g0<7){const long long g{-10000*g4-1000*g3-100*g2-10*g1-g0};
if (bs[(g+1000000000000LL)%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);
if(g4<r) ++g4; else{g4= -r; if(g3<r) ++g3; else{g3= -r; if(g2<r) ++g2; else{g2= -r; if(g1<lig[g0]) g1+=lil[g0]; else {g0+=li[g0];g1=lin[g0];}}}}}}
return q ? nLH(g,w,0) : nLH(g,{0},0);
}
const bitset<100000>bt {[]{bitset<100000>n{false}; for(int g{11};g<mbt;++g) n[(g*g)%100000]=true; return n;}()};
constexpr array<const int, 17>lu{0,0,0,0,2,0,4,0,0,0,1,4,0,0,0,1,1},lun{0,0,0,0,0,0,1,0,0,0,9,1,0,0,0,1,0},lug{0,0,0,0,18,0,17,0,0,0,9,17,0,0,0,11,18},lul{0,0,0,0,2,0,2,0,0,0,0,2,0,0,0,10,2};
const nLH makeH(const int n){
acc= -pow10[n>>1]-pow10[(n-1)>>1]; Z1 g{[]{ return Z2{};}}; int q{(n>11)*5}; vector<long long> w {};
for (int i{1}; i<(n>>1)-q+1; ++i) g = fG(g,0,18,0,pow10[n-i-q]+pow10[i+q-1], acc);
if (n & 1){l=pow10[n>>1]<<1; g=fG(g,0,9,0,l,acc+=l);}
if(q){long long g0{4}, g1{0}, g2{0}, g3{0}, g4{0},l3{pow10[n-5]}; while (g0<17){const long long g{g4*10000+g3*1000+g2*100+g1*10+g0};
if (bt[g%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);
if (g4<18) ++g4; else{g4=0; if(g3<18) ++g3; else{g3=0; if(g2<18) ++g2; else{g2=0; if(g1<lug[g0]) g1+=lul[g0]; else{g0+=lu[g0];g1=lun[g0];}}}}}}
return q ? nLH(g,w,0) : nLH(g,{0},pow10[n-1]<<2);
}
#include <chrono>
using namespace chrono; using VU = vector<unsigned long long>; using VS = vector<string>;
template <typename T> // concatenates vectors
vector<T>& operator +=(vector<T>& v, const vector<T>& w) { v.insert(v.end(), w.begin(), w.end()); return v; }
int c{0}; // solution counter
auto st{steady_clock::now()}, st0{st}, tmp{st}; // for determining elasped time
// formats elasped time
string dFmt(duration<double> et, int digs) {
string res{""}; double dt{et.count()};
if (dt > 60.0) { int m = (int)(dt / 60.0); dt -= m * 60.0; res = to_string(m) + "m"; }
res += to_string(dt); return res.substr(0, digs - 1) + 's';
}
// combines list of square differences with list of square sums, reports compatible results
VS dump(int nd, VU lo, VU hi) {
VS res {};
for (auto l : lo) for (auto h : hi) {
auto r { (h - l) >> 1 }, z { h - r };
if (izRev(nd, r, z)) {
char buf[99]; sprintf(buf, "%20llu %11lu %10lu", z, (long long)sqrt(h), (long long)sqrt(l));
res.push_back(buf); } } return res;
}
// reports one block of digits
void doOne(int n, nLH L, nLH H) {
VS lines = dump(n, L.even, H.even); lines += dump(n, L.odd , H.odd); sort(lines.begin(), lines.end());
duration<double> tet = (tmp = steady_clock::now()) - st; int ls = lines.size();
if (ls-- > 0)
for (int i{0}; i <= ls; ++i)
printf("%3d %s%s", ++c, lines[i].c_str(), i == ls ? "" : "\n");
else printf("%s", string(47, ' ').c_str());
printf(" %2d: %s %s\n", n, dFmt(tmp - st0, 8).c_str(), dFmt(tet, 8).c_str()); st0 = tmp;
}
void Rare(int n) { doOne(n, makeL(n), makeH(n)); }
int main(int argc, char *argv[]) {
int max{argc > 1 ? stoi(argv[1]) : 19}; if (max < 2) max = 2; if (max > 19 ) max = 19;
printf("%4s %19s %11s %10s %5s %11s %9s\n", "nth", "forward", "rt.sum", "rt.diff", "digs", "block.et", "total.et");
for (int nd{2}; nd <= max; ++nd) Rare(nd);
}
|
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
|
#8th
|
8th
|
\ Given a low and high limit, create an array containing the numbers in the
\ range, inclusive:
: n:gen-range \ low hi -- a
\ make sure they are in order:
2dup n:> if swap then
\ fill the array with the values:
[] ' a:push
2swap loop ;
\ Take a string, either "X" or "X-Y", and correctly return either a number (if
\ "X") or an array of numbers (if "X-Y"):
: n:expand-one \ s -- n | a[n,..m]
\ First see if we can parse a number. This works in the "X" case:
dup >n null? if
\ Failed >n because it's (possibly) "X-Y"
drop
\ not a valid number, might be a range
\ We'll use a capturing regex to handle the different cases correctly:
/(-?[0-9]+)-(-?[0-9]+)/ tuck r:match
\ If the regex matches three (the whole string, plus the two captured
\ expressions) then it's a valid "X-Y":
3 n:= if
1 r:@ >n swap 2 r:@ >n nip
\ generate the range:
n:gen-range
else
\ The regex didn't match, so we got garbage. Therefore, return a 'null':
drop null
then
else
\ It was a "X", just drop the original string:
nip
then
;
\ Take an array (possibly) containing other arrays, and flatten any contained
\ arrays so the result is a simple array:
: a:flatten \ a1 -- a2
[] >r
(
nip
array? if
a:flatten r> swap a:+ >r
else
r> swap a:push >r
then
) a:each drop r> ;
\ Take a comma-delimited string of ranges, and expand it into an array of
\ numbers:
: n:range-expand \ str -- a
"," s:/
' n:expand-one a:map
a:flatten ;
\ Process a list:
"-6,-3--1,3-5,7-11,14,15,17-20"
n:range-expand
\ print the expanded list:
. cr bye
|
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.
|
#Aime
|
Aime
|
file f;
text s;
f.affix("src/aime.c");
while (f.line(s) != -1) {
o_text(s);
o_byte('\n');
}
|
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.
|
#Elixir
|
Elixir
|
defmodule Ranking do
def methods(data) do
IO.puts "stand.\tmod.\tdense\tord.\tfract."
Enum.group_by(data, fn {score,_name} -> score end)
|> Enum.map(fn {score,pairs} ->
names = Enum.map(pairs, fn {_,name} -> name end) |> Enum.reverse
{score, names}
end)
|> Enum.sort_by(fn {score,_} -> -score end)
|> Enum.with_index
|> Enum.reduce({1,0,0}, fn {{score, names}, i}, {s_rnk, m_rnk, o_rnk} ->
d_rnk = i + 1
m_rnk = m_rnk + length(names)
f_rnk = ((s_rnk + m_rnk) / 2) |> to_string |> String.replace(".0","")
o_rnk = Enum.reduce(names, o_rnk, fn name,acc ->
IO.puts "#{s_rnk}\t#{m_rnk}\t#{d_rnk}\t#{acc+1}\t#{f_rnk}\t#{score} #{name}"
acc + 1
end)
{s_rnk+length(names), m_rnk, o_rnk}
end)
end
end
~w"44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen"
|> Enum.chunk(2)
|> Enum.map(fn [score,name] -> {String.to_integer(score),name} end)
|> Ranking.methods
|
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).
|
#XBS
|
XBS
|
func RemoveDuplicates(Array){
set NewArray = [];
foreach(k,v as Array){
if (NewArray->includes(v)){
Array->splice(toint(k),1);
} else {
NewArray->push(v);
}
}
}
set Arr = ["Hello",1,2,"Hello",3,1];
log(Arr);
RemoveDuplicates(Arr);
log(Arr);
|
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
|
#Dyalect
|
Dyalect
|
type Pt(s, e) with Lookup
func Pt.Min() => min(this.s, this.e)
func Pt.Max() => max(this.s, this.e)
func Pt.ToString() => "(\(this.s), \(this.e))"
let rng = [
[ Pt(1.1, 2.2) ],
[ Pt(6.1, 7.2), Pt(7.2, 8.3) ],
[ Pt(4.0, 3.0), Pt(2, 1) ],
[ Pt(4.0, 3.0), Pt(2, 1), Pt(-1, 2), Pt(3.9, 10) ],
[ Pt(1.0, 3.0), Pt(-6, -1), Pt(-4, -5), Pt(8, 2), Pt(-6, -6) ]
]
func overlap(left, right) =>
left.Max() > right.Max() ? right.Max() >= left.Min()
: left.Max() >= right.Min()
func consolidate(left, right) => Pt(min(left.Min(), right.Min()), max(left.Max(), right.Max()))
func normalize(range) => Pt(range.Min(), range.Max())
for list in rng {
var z = list.Length() - 1
while z >= 1 {
for y in (z - 1)^-1..0 when overlap(list[z], list[y]) {
list[y] = consolidate(list[z], list[y])
break list.RemoveAt(z)
}
z -= 1
}
for i in list.Indices() {
list[i] = normalize(list[i])
}
list.Sort((x,y) => x.s - y.s)
print(list)
}
|
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
|
#Wren
|
Wren
|
var cube = Fn.new { |n| n * n * n }
var benchmark = Fn.new { |n, func, arg, calls|
var times = List.filled(n, 0)
for (i in 0...n) {
var m = System.clock
for (j in 0...calls) func.call(arg)
times[i] = ((System.clock - m) * 1000).round // milliseconds
}
return times
}
System.print("Timings (milliseconds) : ")
for (time in benchmark.call(10, cube, 5, 1e6)) System.print(time)
|
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
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
reverseThis = 'asdf'
sihTesrever = reverseThis.reverse
say reverseThis
say sihTesrever
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.