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/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Perl | Perl | use List::Util qw(sum);
use constant pi => 3.14159265;
sub legendre_pair {
my($n, $x) = @_;
if ($n == 1) { return $x, 1 }
my ($m1, $m2) = legendre_pair($n - 1, $x);
my $u = 1 - 1 / $n;
(1 + $u) * $x * $m1 - $u * $m2, $m1;
}
sub legendre {
my($n, $x) = @_;
(legendre_pair($n, $x))[0]
}
sub legendre_prime {
my($n, $x) = @_;
if ($n == 0) { return 0 }
if ($n == 1) { return 1 }
my ($m0, $m1) = legendre_pair($n, $x);
($m1 - $x * $m0) * $n / (1 - $x**2);
}
sub approximate_legendre_root {
my($n, $k) = @_;
my $t = (4*$k - 1) / (4*$n + 2);
(1 - ($n - 1) / (8 * $n**3)) * cos(pi * $t);
}
sub newton_raphson {
my($n, $r) = @_;
while (abs(my $dr = - legendre($n,$r) / legendre_prime($n,$r)) >= 2e-16) {
$r += $dr;
}
$r;
}
sub legendre_root {
my($n, $k) = @_;
newton_raphson($n, approximate_legendre_root($n, $k));
}
sub weight {
my($n, $r) = @_;
2 / ((1 - $r**2) * legendre_prime($n, $r)**2)
}
sub nodes {
my($n) = @_;
my %node;
$node{'0'} = weight($n, 0) if 0 != $n%2;
for (1 .. int $n/2) {
my $r = legendre_root($n, $_);
my $w = weight($n, $r);
$node{$r} = $w; $node{-$r} = $w;
}
return %node
}
sub quadrature {
our($n, $a, $b) = @_;
sub scale { ($_[0] * ($b - $a) + $a + $b) / 2 }
%nodes = nodes($n);
($b - $a) / 2 * sum map { $nodes{$_} * exp(scale($_)) } keys %nodes;
}
printf("Gauss-Legendre %2d-point quadrature ∫₋₃⁺³ exp(x) dx ≈ %.13f\n", $_, quadrature($_, -3, +3) )
for 5 .. 10, 20;
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Logo | Logo | make "data [
; animal inc comment
[fly 2 [I don't know why she swallowed that fly]]
[spider 2 [That wriggled and jiggled and tickled inside her]]
[bird 1 [Quite absurd, to swallow a bird]]
[cat 1 [How about that, to swallow a cat]]
[dog 1 [What a hog, to swallow a dog]]
[pig 1 [Her mouth was so big to swallow a pig]]
[goat 1 [She just opened her throat to swallow a goat.]]
[cow 1 [I don't know how she swallowed a cow.]]
[donkey 1 [It was rather wonky to swallow a donkey]]
[horse 0 [She's dead, of course!]]
]
foreach :data [
local "i make "i #
(local "animal "include "comment)
(foreach [animal include comment] ? "make)
print se [There was an old lady who swallowed a] :animal
print :comment
if greater? :include 0 [
if greater? :i 1 [
repeat difference :i 1 [
local "j make "j difference :i repcount
print (se [She swallowed the] (first item sum 1 :j :data)
[to catch the] (first item :j :data))
if greater? item 2 item :j :data 1 [print item 3 item :j :data]
]
]
print [Perhaps she'll die]
print "
]
]
bye |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Lua | Lua | animals = {"fly", "spider", "bird", "cat","dog", "goat", "cow", "horse"}
phrases = {
"",
"That wriggled and jiggled and tickled inside her",
"How absurd to swallow a bird",
"Fancy that to swallow a cat",
"What a hog, to swallow a dog",
"She just opened her throat and swallowed a goat",
"I don't know how she swallowed a cow",
" ...She's dead of course"
}
for i=0,7 do
io.write(string.format("There was an old lady who swallowed a %s\n", animals[i+1]))
if i>0 then io.write(phrases[i+1]) end
if i==7 then break end
if i>0 then
io.write("\n")
for j=i,1,-1 do
io.write(string.format("She swallowed the %s to catch the %s", animals[j+1], animals[j]))
-- if j<4 then p='.' else p=',' end
-- io.write(string.format("%s\n", p))
io.write("\n")
if j==2 then
io.write(string.format("%s!\n", phrases[2]))
end
end
end
io.write("I don't know why she swallowed a fly - Perhaps she'll die!\n\n")
end |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Tcl | Tcl | package require Tk
package require tcl3d
proc resizedWin {win w h} {
glViewport 0 0 $w $h
glMatrixMode GL_PROJECTION
glLoadIdentity
glOrtho -30.0 30.0 -30.0 30.0 -30.0 30.0
glMatrixMode GL_MODELVIEW
}
proc paintShape {win} {
glClearColor 0.0 0.0 0.0 0.5
glClear [expr {$::GL_COLOR_BUFFER_BIT+$::GL_DEPTH_BUFFER_BIT}]
glShadeModel GL_SMOOTH
glLoadIdentity
glTranslatef -15.0 -15.0 0.0
glBegin GL_TRIANGLES
glColor3f 1.0 0.0 0.0
glVertex2f 5.0 5.0
glColor3f 0.0 1.0 0.0
glVertex2f 25.0 5.0
glColor3f 0.0 0.0 1.0
glVertex2f 5.0 25.0
glEnd
$win swapbuffers
}
togl .surface -width 640 -height 480 -double true -depth true \
-displayproc paintShape -reshapeproc resizedWin
pack .surface -fill both -expand 1 |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #REXX | REXX | /*REXX program simulates reading a ten─line file, count the selection randomness. */
N= 10 /*the number of lines in pseudo-file. */
@.= 0 /*zero all the (ten) "buckets". */
do 1000000 /*perform main loop one million times.*/
?= 1
do k=1 for N /*N is the number of lines in the file*/
if random(0, 99999) / 100000 < 1/k then ?= k /*the criteria.*/
end /*k*/
@.?= @.? + 1 /*bump the count in a particular bucket*/
end /*1000000*/
do j=1 for N /*display randomness counts (buckets). */
say "number of times line" right(j, 2) "was selected:" right(@.j, 9)
end /*j*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Ring | Ring |
cnt = list(10)
for nr = 1 to 10000
cnt[oneofn(10)] += 1
next
for m = 1 to 10
see "" + m + " : " + cnt[m] + nl
next
see nl
func oneofn n
for i = 1 to n
if random(1) <= 1/i d = i ok
next
return d
|
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #XSLT | XSLT | <xsl:template name="sort">
<xsl:param name="table" />
<xsl:param name="ordering" select="'lexicographic'" />
<xsl:param name="column" select="1" />
<xsl:param name="reversed" select="false()" />
...
</xsl:template> |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Yabasic | Yabasic | sub power(n, p)
if numparams = 1 p = 2
return n^p
end sub
print power(2)
print power(2, 3) |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Rascal | Rascal | rascal>[2,1,3] < [5,2,1,3]
bool: true |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #REXX | REXX | /*REXX program determines if a list < previous list, and returns true or false. */
@.=; @.1 = 1 2 1 5 2
@.2 = 1 2 1 5 2 2
@.3 = 1 2 3 4 5
@.4 = 1 2 3 4 5
/* [↓] compare a list to previous list*/
do j=2 while @.j\==''; p= j - 1 /*P: points to previous value in list.*/
if FNorder(@.p, @.j)=='true' then is= " < " /*use a more familiar glyph.*/
else is= " ≥ " /* " " " " " */
say
say right('['@.p"]", 40) is '['@.j"]"
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
FNorder: procedure; parse arg x,y
wx= words(x); wy= words(y)
do k=1 for min(wx, wy)
a= word(x, k) /*get a value from X. */
b= word(y, k) /* " " " " Y. */
if a<b then return 'true'
else if a>b then return 'false'
end /*k*/
if wx<wy then return 'true' /*handle case of equal (so far). */
return 'false' /* " " " " " " */ |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
0 var maxlen
( ) var words
0 var f
def getword f fgets dup -1 == if drop false else -1 del endif enddef
def ordered? dup dup sort == enddef
def greater? len maxlen > enddef
"unixdict.txt" "r" fopen var f
f -1 !=
while
getword dup if
ordered? if
greater? if
len var maxlen
( ) var words
endif
len maxlen == if
words over 0 put var words
endif
endif
endif
endwhile
f fclose
words print |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Picat | Picat | go =>
Dict = "unixdict.txt",
Words = new_map([Word=Word.length : Word in read_file_lines(Dict), Word == Word.sort()]),
MaxLen = max([Len : _Word=Len in Words]),
println([Word : Word=Len in Words, Len=MaxLen].sort). |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #REXX | REXX | /*REXX pgm checks if phrase is palindromic; ignores the case of the letters. */
parse arg y /*get (optional) phrase from the C.L. */
if y='' then y='In girum imus nocte et consumimur igni' /*[↓] translation.*/
/*We walk around in the night and we are burnt by the fire (of love).*/
say 'string = ' y
if isTpal(y) then say 'The string is a true palindrome.'
else if isPal(y) then say 'The string is an inexact palindrome.'
else say "The string isn't palindromic."
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
isTpal: return reverse(arg(1))==arg(1)
isPal: return isTpal(translate(space(x,0))) |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #Wren | Wren | class Approx {
construct new(nu, sigma) {
_nu = nu
_sigma = sigma
}
static new(a) {
if (a is Approx) return Approx.new(a.nu, a.sigma)
if (a is Num) return Approx.new(a, 0)
}
nu { _nu }
sigma { _sigma }
+(a) {
if (a is Approx) return Approx.new(_nu + a.nu, (_sigma *_sigma + a.sigma*a.sigma).sqrt)
if (a is Num) return Approx.new(_nu + a, _sigma)
}
-(a) {
if (a is Approx) return Approx.new(_nu - a.nu, (_sigma *_sigma + a.sigma*a.sigma).sqrt)
if (a is Num) return Approx.new(_nu - a, _sigma)
}
*(a) {
if (a is Approx) {
var v = _nu * a.nu
return Approx.new(v, (v*v*_sigma*_sigma/(_nu*_nu) + a.sigma*a.sigma/(a.nu*a.nu)).sqrt)
}
if (a is Num) return Approx.new(_nu*a, (a*_sigma).abs)
}
/(a) {
if (a is Approx) {
var v = _nu / a.nu
return Approx.new(v, (v*v*_sigma*_sigma/(_nu*_nu) + a.sigma*a.sigma/(a.nu*a.nu)).sqrt)
}
if (a is Num) return Approx.new(_nu/a, (a*_sigma).abs)
}
pow(d) {
var v = _nu.pow(d)
return Approx.new(v, (v*d*_sigma/_nu).abs)
}
toString { "%(_nu) ±%(_sigma)" }
}
var x1 = Approx.new(100, 1.1)
var y1 = Approx.new( 50, 1.2)
var x2 = Approx.new(200, 2.2)
var y2 = Approx.new(100, 2.3)
System.print(((x1 - x2).pow(2) + (y1 - y2).pow(2)).pow(0.5)) |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Python | Python | from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
# delay action until later, in the shape of a closure
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Quackery | Quackery | [ upper dup lower != ] is letter ( c --> b )
forward is backwords ( $ --> $ )
[ [ behead
dup letter while
emit again ]
dup emit
char . !=
if backwords ] is forwords ( $ --> $ )
[ [ behead
dup letter while
swap recurse
rot emit ]
dup emit
char . !=
if forwords ] resolves backwords ( $ --> $ )
[ forwords drop cr ] is oddwords ( $ --> )
$ "we,are;not,in,kansas;any,more." oddwords
$ "what,is,the;meaning,of:life." oddwords |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #C.23 | C# | using System;
class NumberNamer {
static readonly string[] incrementsOfOne =
{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
static readonly string[] incrementsOfTen =
{ "", "", "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
const string millionName = "million",
thousandName = "thousand",
hundredName = "hundred",
andName = "and";
public static string GetName( int i ) {
string output = "";
if( i >= 1000000 ) {
output += ParseTriplet( i / 1000000 ) + " " + millionName;
i %= 1000000;
if( i == 0 ) return output;
}
if( i >= 1000 ) {
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i / 1000 ) + " " + thousandName;
i %= 1000;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i );
return output;
}
static string ParseTriplet( int i ) {
string output = "";
if( i >= 100 ) {
output += incrementsOfOne[i / 100] + " " + hundredName;
i %= 100;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " " + andName + " ";
}
if( i >= 20 ) {
output += incrementsOfTen[i / 10];
i %= 10;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " ";
}
output += incrementsOfOne[i];
return output;
}
}
class Program { // Test class
static void Main( string[] args ) {
Console.WriteLine( NumberNamer.GetName( 1 ) );
Console.WriteLine( NumberNamer.GetName( 234 ) );
Console.WriteLine( NumberNamer.GetName( 31337 ) );
Console.WriteLine( NumberNamer.GetName( 987654321 ) );
}
}
|
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. REVERSAL.
AUTHOR. Bill Gunshannon
INSTALLATION. Home.
DATE-WRITTEN. 11 December 2021
****************************************************************
** Program Abstract:
** Use a Knuth Shuffle to reate our out ot sort array.
** Use a procedure called "reverse" to pancake sort the array.
****************************************************************
DATA DIVISION.
WORKING-STORAGE SECTION.
01 RNUM PIC 9.
01 TRIES PIC 99 VALUE 0.
01 ANSWER PIC 9(9) VALUE 123456789.
01 TBL-LEN PIC 9 VALUE 9.
01 TBL.
05 TZ PIC 9(9).
05 TA REDEFINES TZ
PIC 9 OCCURS 9 TIMES.
PROCEDURE DIVISION.
MAIN-pROGRAM.
MOVE ANSWER TO TBL
CALL 'KNUTH-SHUFFLE'
USING BY REFERENCE TBL
END-CALL.
DISPLAY "TABLE after shuffle: " TBL.
PERFORM UNTIL TBL = ANSWER
ADD 1 TO TRIES
DISPLAY "How many to reverse? "
ACCEPT RNUM
CALL 'REVERSE' USING BY CONTENT RNUM,
BY REFERENCE TBL
END-CALL
DISPLAY "Try #" TRIES " " TBL
END-PERFORM.
DISPLAY "Congratulations. You did it!"
STOP RUN.
END PROGRAM REVERSAL.
IDENTIFICATION DIVISION.
PROGRAM-ID. KNUTH-SHUFFLE.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 I PIC 9(9).
01 J PIC 9(9).
01 TEMP PIC 9(9).
01 tABLE-lEN PIC 9 value 9.
LINKAGE SECTION.
01 TTABLE-AREA.
03 TTABLE PIC 9 OCCURS 9 TIMES.
PROCEDURE DIVISION USING ttable-area.
MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (11:6)) TO I
PERFORM VARYING i FROM Table-Len BY -1 UNTIL i = 0
COMPUTE j =
FUNCTION MOD(FUNCTION RANDOM * 10000, Table-Len) + 1
MOVE ttable (i) TO temp
MOVE ttable (j) TO ttable (i)
MOVE temp TO ttable (j)
END-PERFORM.
GOBACK.
END PROGRAM KNUTH-SHUFFLE.
IDENTIFICATION DIVISION.
PROGRAM-ID. REVERSE.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 I PIC 9.
01 J PIC 9.
01 X PIC 9.
01 LOOP-IDX PIC 9.
LINKAGE SECTION.
01 IDX PIC 9.
01 TTABLE-AREA.
03 TTABLE PIC 9 OCCURS 9 TIMES.
PROCEDURE DIVISION USING IDX, TTABLE-AREA.
DIVIDE IDX BY 2 GIVING LOOP-IDx
MOVE 1 TO I
MOVE IDX TO J
PERFORM LOOP-IDX TIMES
MOVE TTABLE(I) TO X
MOVE TTABLE(J) TO TTABLE(I)
MOVE X TO TTABLE(J)
ADD 1 TO I
SUBTRACT 1 FROM J
END-PERFORM.
GOBACK.
END PROGRAM REVERSE.
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
local
i: INTEGER
s: detachable STRING
do
if i = Void then
print("i = Void")
end
if s = Void then
print("s = Void")
end
end
end |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Elixir | Elixir | iex(1)> nil == :nil
true
iex(2)> is_nil(nil)
true |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #ERRE | ERRE |
PROGRAM ONEDIM_AUTOMATA
! for rosettacode.org
!
!VAR I,J,N,W,K
!$DYNAMIC
DIM X[0],X2[0]
BEGIN
DATA(20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0)
PRINT(CHR$(12);)
N=20 ! number of generation required
READ(W)
!$DIM X[W+1],X2[W+1]
FOR I=1 TO W DO
READ(X[I])
END FOR
FOR K=1 TO N DO
PRINT("Generation";K;TAB(16);)
FOR J=1 TO W DO
IF X[J]=1 THEN PRINT("#";) ELSE PRINT("_";) END IF
IF X[J-1]+X[J]+X[J+1]=2 THEN X2[J]=1 ELSE X2[J]=0 END IF
END FOR
PRINT
FOR J=1 TO W DO
X[J]=X2[J]
END FOR
END FOR
END PROGRAM
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Euphoria | Euphoria | include machine.e
function rules(integer tri)
return tri = 3 or tri = 5 or tri = 6
end function
function next_gen(atom gen)
atom new, bit
new = rules(and_bits(gen,3)*2) -- work with the first bit separately
bit = 2
while gen > 0 do
new += bit*rules(and_bits(gen,7))
gen = floor(gen/2) -- shift right
bit *= 2 -- shift left
end while
return new
end function
constant char_clear = '_', char_filled = '#'
procedure print_gen(atom gen)
puts(1, int_to_bits(gen,32) * (char_filled - char_clear) + char_clear)
puts(1,'\n')
end procedure
function s_to_gen(sequence s)
s -= char_clear
return bits_to_int(s)
end function
atom gen, prev
integer n
n = 0
prev = 0
gen = bits_to_int(rand(repeat(2,32))-1)
while gen != prev do
printf(1,"Generation %d: ",n)
print_gen(gen)
prev = gen
gen = next_gen(gen)
n += 1
end while
printf(1,"Generation %d: ",n)
print_gen(gen) |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Fortran | Fortran | elemental function elemf(x)
real :: elemf, x
elemf = f(x)
end function elemf |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Phix | Phix | with javascript_semantics
integer order = 0
sequence legendreRoots = {},
legendreWeights = {}
function legendre(integer term, atom z)
if term=0 then
return 1
elsif term=1 then
return z
else
return ((2*term-1)*z*legendre(term-1,z)-(term-1)*legendre(term-2,z))/term
end if
end function
function legendreDerivative(integer term, atom z)
if term=0
or term=1 then
return term
end if
return (term*(z*legendre(term,z)-legendre(term-1,z)))/(z*z-1)
end function
procedure getLegendreRoots()
legendreRoots = {}
for index=1 to order do
atom y = cos(PI*(index-0.25)/(order+0.5))
while 1 do
atom y1 = y
y -= legendre(order,y)/legendreDerivative(order,y)
if abs(y-y1)<2e-16 then exit end if
end while
legendreRoots &= y
end for
end procedure
procedure getLegendreWeights()
legendreWeights = {}
for index=1 to order do
atom lri = legendreRoots[index],
diff = legendreDerivative(order,lri),
weight = 2 / ((1-power(lri,2))*power(diff,2))
legendreWeights &= weight
end for
end procedure
function gaussLegendreQuadrature(integer f, lowerLimit, upperLimit, n)
order = n
getLegendreRoots()
getLegendreWeights()
atom c1 = (upperLimit - lowerLimit) / 2
atom c2 = (upperLimit + lowerLimit) / 2
atom s = 0
for i = 1 to order do
s += legendreWeights[i] * f(c1 * legendreRoots[i] + c2)
end for
return c1 * s
end function
string fmt = iff(machine_bits()=32?"%.13f":"%.14f"), res
for i=5 to 11 by 6 do
res = sprintf(fmt,{gaussLegendreQuadrature(exp, -3, 3, i)})
if i=5 then
puts(1,"roots:") ?legendreRoots
puts(1,"weights:") ?legendreWeights
end if
printf(1,"Gauss-Legendre %2d-point quadrature for exp over [-3..3] = %s\n",{order,res})
end for
res = sprintf(fmt,{exp(3)-exp(-3)})
printf(1," compared to actual = %s\n",{res})
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(V)
ENTRY TO VERSE.
TRANSFER TO VS(V+1)
VS(1) PRINT COMMENT$ I DON'T KNOW WHY SHE SWALLOWED THAT FLY$
PRINT COMMENT$ PERHAPS SHE'LL DIE$
PRINT COMMENT$ $
FUNCTION RETURN V
VS(2) PRINT COMMENT
0 $ THAT WIGGLED AND JIGGLED AND TICKLED INSIDE HER$
FUNCTION RETURN V
VS(3) PRINT COMMENT$ HOW ABSURD TO SWALLOW A BIRD!$
FUNCTION RETURN V
VS(4) PRINT COMMENT$ IMAGINE THAT - SHE SWALLOWED A CAT!$
FUNCTION RETURN V
VS(5) PRINT COMMENT$ WHAT A HOG TO SWALLOW A DOG$
FUNCTION RETURN V
VS(6) PRINT COMMENT
0 $ SHE JUST OPENED HER THROAT AND SWALLOWED THAT GOAT$
FUNCTION RETURN V
VS(7) PRINT COMMENT$ I DON'T KNOW HOW SHE SWALLOWED THAT COW$
FUNCTION RETURN V
VS(8) PRINT COMMENT$ SHE'S DEAD, OF COURSE.$
END OF FUNCTION
VECTOR VALUES ANIMAL =
0 $FLY$,$SPIDER$,$BIRD$,$CAT$,$DOG$,$GOAT$,$COW$,$HORSE$
VECTOR VALUES LADY =
0 $38HTHERE WAS AN OLD LADY WHO SWALLOWED A ,C,1H,*$
VECTOR VALUES SWALLO =
0 $18HSHE SWALLOWED THE ,C,S1,13HTO CATCH THE ,C,1H,*$
THROUGH VERSE, FOR I=0, 1, I.G.7
PRINT FORMAT LADY, ANIMAL(I)
VERSE.(I)
THROUGH VERSE, FOR J=I, -1, J.E.0 .OR. I.GE.7
PRINT FORMAT SWALLO, ANIMAL(J), ANIMAL(J-1)
VERSE WHENEVER J.LE.2, VERSE.(J-1)
END OF PROGRAM |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Maple | Maple | swallowed := ["fly", "spider", "bird", "cat", "dog", "cow", "horse"]:
phrases := ["I don't know why she swallowed a fly, perhaps she'll die!",
"That wriggled and wiggled and tiggled inside her.",
"How absurd to swallow a bird.",
"Fancy that to swallow a cat!",
"What a hog, to swallow a dog.",
"I don't know how she swallowed a cow.",
"She's dead, of course."]:
for i to numelems(swallowed) do
printf("There was an old lady who swallowed a %s.\n%s\n", swallowed[i], phrases[i]);
if i > 1 and i < 7 then
for j from i by -1 to 2 do
printf("\tShe swallowed the %s to catch the %s.\n", swallowed[j], swallowed[j-1]);
end do;
printf("%s\n\n", phrases[1]);
elif i = 1 then
printf("\n");
end if;
end do; |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Wren | Wren | /* opengl.wren */
var GL_COLOR_BUFFER_BIT = 0x4000
var GL_DEPTH_BUFFER_BIT = 0x0100
var GL_SMOOTH = 0x1d01
var GL_MODELVIEW = 0x1700
var GL_PROJECTION = 0x1701
var GL_TRIANGLES = 0x0004
var GLUT_ACTION_ON_WINDOW_CLOSE = 0x01f9
var GLUT_ACTION_GLUTMAINLOOP_RETURNS = 0x0001
class GL {
foreign static clearColor(red, green, blue, alpha)
foreign static clear(mask)
foreign static shadeModel(mode)
foreign static loadIdentity()
foreign static translatef(x, y, z)
foreign static begin(mode)
foreign static color3f(red, green, blue)
foreign static vertex2f(x, y)
foreign static end()
foreign static flush()
foreign static viewport(x, y, width, height)
foreign static matrixMode(mode)
foreign static ortho(left, right, bottom, top, nearVal, farVal)
}
class Glut {
foreign static initWindowSize(width, height)
foreign static createWindow(name)
foreign static displayFunc(clazz, signature)
foreign static reshapeFunc(clazz, signature)
foreign static setOption(eWhat, value)
}
class GLCallbacks {
static paint() {
GL.clearColor(0.3, 0.3, 0.3, 0)
GL.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
GL.shadeModel(GL_SMOOTH)
GL.loadIdentity()
GL.translatef(-15, -15, 0)
GL.begin(GL_TRIANGLES)
GL.color3f(1, 0, 0)
GL.vertex2f(0, 0)
GL.color3f(0, 1, 0)
GL.vertex2f(30, 0)
GL.color3f(0, 0, 1)
GL.vertex2f(0, 30)
GL.end()
GL.flush()
}
static reshape(width, height) {
GL.viewport(0, 0, width, height)
GL.matrixMode(GL_PROJECTION)
GL.loadIdentity()
GL.ortho(-30, 30, -30, 30, -30, 30)
GL.matrixMode(GL_MODELVIEW)
}
}
Glut.initWindowSize(640, 480)
Glut.createWindow("Triangle")
Glut.displayFunc("GLCallbacks", "paint()")
Glut.reshapeFunc("GLCallbacks", "reshape(_,_)")
Glut.setOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS) |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Ruby | Ruby | # Returns a random line from _io_, or nil if _io_ has no lines.
# # Get a random line from /etc/passwd
# line = open("/etc/passwd") {|f| random_line(f) }
def random_line(io)
choice = io.gets; count = 1
while line = io.gets
rand(count += 1).zero? and choice = line
end
choice
end
def one_of_n(n)
# Create a mock IO that provides line numbers instead of lines.
# Assumes that #random_line calls #gets.
(mock_io = Object.new).instance_eval do
@count = 0
@last = n
def self.gets
(@count < @last) ? (@count += 1) : nil
end
end
random_line(mock_io)
end
chosen = Hash.new(0)
1_000_000.times { chosen[one_of_n(10)] += 1 }
chosen.keys.sort.each do |key|
puts "#{key} chosen #{chosen[key]} times"
end |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Run_BASIC | Run BASIC | for i1 = 1 to 1000000
c = oneOfN(10)
chosen(c) = chosen(c) + 1
next
for i1 = 1 to 10
print i1;" ";chosen(i1)
next
FUNCTION oneOfN(n)
for i2 = 1 to n
IF int(rnd(1) * i2) = 0 then choice = i2
next
oneOfN = choice
END FUNCTION |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #zkl | zkl | const lex="L";
fcn mystrySort(table,ordering=lex,column=0,reverse=False,other){
vm.arglist.println();
}
mystrySort.prototype.println();
mystrySort("table");
mystrySort("table",lex,1);
mystrySort("table",lex,1,True,D("row",35,"type","foobar"));
|
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Ring | Ring |
list1 = "1, 2, 1, 5, 2"
list2 = "5, 2, 1, 5, 2, 2"
list3 = "1, 2, 3, 4, 5"
list4 = "1, 2, 3, 4, 5"
if order(list1, list2) = 0 see "list1=list2" + nl
but order(list1, list2) < 0 see "list1<list2" + nl
else see "list1>list2" + nl ok
if order(list2, list3) = 0 see "list2=list3" + nl
but order(list2, list3) < 0 see "list2<list3" + nl
else see "list2>list3" + nl ok
if order(list3, list4) = 0 see "list3=list4" + nl
but order(list3, list4) < 0 see "list3<list4" + nl
else see "list3>list4" + nl ok
func order alist, blist
return strcmp(alist, blist)
|
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Ruby | Ruby | >> ([1,2,1,3,2] <=> [1,2,0,4,4,0,0,0]) < 0
=> false |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PicoLisp | PicoLisp | (in "unixdict.txt"
(mapc prinl
(maxi '((L) (length (car L)))
(by length group
(filter '((S) (apply <= S))
(make (while (line) (link @))) ) ) ) ) ) |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Ring | Ring |
aString = "radar"
bString = ""
for i=len(aString) to 1 step -1
bString = bString + aString[i]
next
see aString
if aString = bString see " is a palindrome." + nl
else see " is not a palindrome" + nl ok
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Racket | Racket |
#!/bin/sh
#|
exec racket -tm- "$0" "$@"
|#
#lang racket
(define (even k)
(define c (read-char))
(cond [(eq? c eof) (k)]
[(not (char-alphabetic? c)) (k) (write-char c) (odd)]
[else (even (λ() (write-char c) (k)))]))
(define (odd)
(define c (read-char))
(unless (eq? c eof)
(write-char c)
(if (char-alphabetic? c) (odd) (even void))))
(provide main)
(define (main) (odd) (newline))
;; (with-input-from-string "what,is,the;meaning,of:life." main)
;; ;; -> what,si,the;gninaem,of:efil.
;; (with-input-from-string "we,are;not,in,kansas;any,more." main)
;; ;; -> we,era;not,ni,kansas;yna,more.
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Raku | Raku | my &in = { $*IN.getc // last }
loop {
ew(in);
ow(in).print;
}
multi ew ($_ where /\w/) { .print; ew(in); }
multi ew ($_) { .print; next when "\n"; }
multi ow ($_ where /\w/) { ow(in) x .print; }
multi ow ($_) { $_; } |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #C.2B.2B | C++ | #include <string>
#include <iostream>
using std::string;
const char* smallNumbers[] = {
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
string spellHundreds(unsigned n) {
string res;
if (n > 99) {
res = smallNumbers[n/100];
res += " hundred";
n %= 100;
if (n) res += " and ";
}
if (n >= 20) {
static const char* Decades[] = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
res += Decades[n/10];
n %= 10;
if (n) res += "-";
}
if (n < 20 && n > 0)
res += smallNumbers[n];
return res;
}
const char* thousandPowers[] = {
" billion", " million", " thousand", "" };
typedef unsigned long Spellable;
string spell(Spellable n) {
if (n < 20) return smallNumbers[n];
string res;
const char** pScaleName = thousandPowers;
Spellable scaleFactor = 1000000000; // 1 billion
while (scaleFactor > 0) {
if (n >= scaleFactor) {
Spellable h = n / scaleFactor;
res += spellHundreds(h) + *pScaleName;
n %= scaleFactor;
if (n) res += ", ";
}
scaleFactor /= 1000;
++pScaleName;
}
return res;
}
int main() {
#define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl;
SPELL_IT( 99);
SPELL_IT( 300);
SPELL_IT( 310);
SPELL_IT( 1501);
SPELL_IT( 12609);
SPELL_IT( 512609);
SPELL_IT(43112609);
SPELL_IT(1234567890);
return 0;
} |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Common_Lisp | Common Lisp | (defun shuffle! (vector)
(loop for i from (1- (length vector)) downto 1
do (rotatef (aref vector i)
(aref vector (random i)))))
(defun slice (vector start &optional end)
(let ((end (or end (length vector))))
(make-array (- end start)
:element-type (array-element-type vector)
:displaced-to vector
:displaced-index-offset start)))
(defun orderedp (seq)
(apply #'<= (coerce seq 'list)))
(defun prompt-integer (prompt)
(format t "~A: " prompt)
(finish-output)
(clear-input)
(parse-integer (read-line)))
(defun game ()
(let ((numbers (vector 1 2 3 4 5 6 7 8 9)))
(shuffle! numbers)
(let ((score
(do ((score 0 (1+ score)))
((orderedp numbers) score)
(format t "~A~%" numbers)
(let* ((n (prompt-integer "How many numbers to reverse"))
(slice (slice numbers 0 n)))
(replace slice (nreverse slice))))))
(format t "~A~%Congratulations, you did it in ~D reversals!~%" numbers score))))
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Erlang | Erlang | let sl : string list = [null; "abc"]
let f s =
match s with
| null -> "It is null!"
| _ -> "It's non-null: " + s
for s in sl do printfn "%s" (f s) |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #F.23 | F# | let sl : string list = [null; "abc"]
let f s =
match s with
| null -> "It is null!"
| _ -> "It's non-null: " + s
for s in sl do printfn "%s" (f s) |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Factor | Factor | USING: bit-arrays io kernel locals math sequences ;
IN: cellular
: bool-sum ( bool1 bool2 -- sum )
[ [ 2 ] [ 1 ] if ]
[ [ 1 ] [ 0 ] if ] if ;
:: neighbours ( index world -- # )
index [ 1 - ] [ 1 + ] bi [ world ?nth ] bi@ bool-sum ;
: count-neighbours ( world -- neighbours )
[ length iota ] keep [ neighbours ] curry map ;
: life-law ( alive? neighbours -- alive? )
swap [ 1 = ] [ 2 = ] if ;
: step ( world -- world' )
dup count-neighbours [ life-law ] ?{ } 2map-as ;
: print-cellular ( world -- )
[ CHAR: # CHAR: _ ? ] "" map-as print ;
: main-cellular ( -- )
?{ f t t t f t t f t f t f t f t f f t f f }
10 [ dup print-cellular step ] times print-cellular ;
MAIN: main-cellular
|
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #FreeBASIC | FreeBASIC | ' version 17-09-2015
' compile with: fbc -s console
#Define screen_width 1024
#Define screen_height 256
ScreenRes screen_width, screen_height, 8
Width screen_width\8, screen_height\16
Function f1(x As Double) As Double
Return x^3
End Function
Function f2(x As Double) As Double
Return 1/x
End Function
Function f3(x As Double) As Double
Return x
End Function
Function leftrect(a As Double, b As Double, n As Double, _
ByVal f As Function (ByVal As Double) As Double) As Double
Dim As Double sum, x = a, h = (b - a) / n
For i As UInteger = 1 To n
sum = sum + h * f(x)
x = x + h
Next
leftrect = sum
End Function
Function rightrect(a As Double, b As Double, n As Double, _
ByVal f As Function (ByVal As Double) As Double) As Double
Dim As Double sum, x = a, h = (b - a) / n
For i As UInteger = 1 To n
x = x + h
sum = sum + h * f(x)
Next
rightrect = sum
End Function
Function midrect(a As Double, b As Double, n As Double, _
ByVal f As Function (ByVal As Double) As Double) As Double
Dim As Double sum, h = (b - a) / n, x = a + h / 2
For i As UInteger = 1 To n
sum = sum + h * f(x)
x = x + h
Next
midrect = sum
End Function
Function trap(a As Double, b As Double, n As Double, _
ByVal f As Function (ByVal As Double) As Double) As Double
Dim As Double x = a, h = (b - a) / n
Dim As Double sum = h * (f(a) + f(b)) / 2
For i As UInteger = 1 To n -1
x = x + h
sum = sum + h * f(x)
Next
trap = sum
End Function
Function simpson(a As Double, b As Double, n As Double, _
ByVal f As Function (ByVal As Double) As Double) As Double
Dim As UInteger i
Dim As Double sum1, sum2
Dim As Double h = (b - a) / n
For i = 0 To n -1
sum1 = sum1 + f(a + h * i + h / 2)
Next i
For i = 1 To n -1
sum2 = sum2 + f(a + h * i)
Next i
simpson = h / 6 * (f(a) + f(b) + 4 * sum1 + 2 * sum2)
End Function
' ------=< main >=------
Dim As Double y
Dim As String frmt = " ##.##########"
Print
Print "function range steps leftrect midrect " + _
"rightrect trap simpson "
Print "f(x) = x^3 0 - 1 100";
Print Using frmt; leftrect(0, 1, 100, @f1); midrect(0, 1, 100, @f1); _
rightrect(0, 1, 100, @f1); trap(0, 1, 100, @f1); simpson(0, 1, 100, @f1)
Print "f(x) = 1/x 1 - 100 1000";
Print Using frmt; leftrect(1, 100, 1000, @f2); midrect(1, 100, 1000, @f2); _
rightrect(1, 100, 1000, @f2); trap(1, 100, 1000, @f2); _
simpson(1, 100, 1000, @f2)
frmt = " #########.###"
Print "f(x) = x 0 - 5000 5000000";
Print Using frmt; leftrect(0, 5000, 5000000, @f3); midrect(0, 5000, 5000000, @f3); _
rightrect(0, 5000, 5000000, @f3); trap(0, 5000, 5000000, @f3); _
simpson(0, 5000, 5000000, @f3)
Print "f(x) = x 0 - 6000 6000000";
Print Using frmt; leftrect(0, 6000, 6000000, @f3); midrect(0, 6000, 6000000, @f3); _
rightrect(0, 6000, 6000000, @f3); trap(0, 6000, 6000000, @f3); _
simpson(0, 6000, 6000000, @f3)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #PL.2FI | PL/I | (subscriptrange, size, fofl):
Integration_Gauss: procedure options (main);
declare (n, k) fixed binary;
declare r(*,*) float (18) controlled;
declare (z, a, b, exact) float (18);
do n = 1 to 20;
a = -3; b = 3;
if allocation(r) > 0 then free r;
allocate r(2, n); r = 0;
call gaussquad(n, r);
z = (b-a)/2 * sum(r(2,*) * exp((a+b)/2+r(1,*)*(b-a)/2));
exact = exp(3.0q0)-exp(-3.0q0);
put skip edit (n, z, z-exact) (f(5), f(25,16), e(15,2));
end;
gaussquad: procedure(n, r);
/*declare n fixed binary, r(2, n) float (18);*/
declare n fixed binary, r(2, *) float (18);/* corrected */
declare pi float (18) value (4*atan(1.0q0));
declare (x, f, df, dx) float (18);
declare (i, iter, L) fixed binary;
declare (p0(*), p1(*), tmp(*), tmp2(*)) float (18) controlled;
allocate p0(1) initial (1);
allocate p1(2) initial (1, 0);
do k = 2 to n;
allocate tmp(hbound(p1)+1); do L = 1 to hbound(p1); tmp(L) = p1(L); end; tmp(L) = 0;
allocate tmp2(hbound(p0)+2); tmp2(1), tmp2(2) = 0;
do L = 1 to hbound(p0); tmp2(L+2) = p0(L); end;
tmp = ((2*k-1)*tmp - (k-1)*tmp2)/k;
free p0; allocate p0(hbound(p1)); p0 = p1;
free p1; allocate p1(hbound(tmp)); p1 = tmp;
free tmp, tmp2;
end;
do i = 1 to n;
x = cos(pi*(i-0.25q0)/(n+0.5q0));
do iter = 1 to 10;
f = p1(1); df = 0;
do k = 2 to hbound(p1);
df = f + x*df;
f = p1(k) + x * f;
end;
dx = f / df;
x = x - dx;
if abs(dx) < 10*epsilon(dx) then leave;
end;
r(1,i) = x;
r(2,i) = 2/((1-x**2)*df**2);
end;
end gaussquad;
end Integration_Gauss;
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | animals = {"fly", "spider", "bird", "cat", "dog", "goat", "cow",
"horse"};
notes = {"", "That wiggled and jiggled and tickled inside her.\n",
"How absurd, to swallow a bird.\n",
"Imagine that. She swallowed a cat.\n",
"What a hog to swallow a dog.\n",
"She just opened her throat and swallowed that goat.\n",
"I don't know how she swallowed that cow.\n",
"She's dead, of course.",
"I don't know why she swallowed that fly.\nPerhaps she'll die.\n\n\
"};
Print[StringJoin @@ ("There was an old lady who swallowed a " <>
animals[[#]] <> ".\n" <> notes[[#]] <>
If[# == 8, "",
StringJoin @@ ("She swallowed the " <> animals[[#]] <>
" to catch the " <> animals[[# - 1]] <> ".\n" & /@
Range[#, 2, -1]) <> notes[[9]]] & /@ Range[8])]; |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Mercury | Mercury | :- module oldlady.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string.
:- type animal
---> horse
; donkey
; cow
; goat
; pig
; dog
; cat
; bird
; spider
; fly.
:- func verse(animal) = string.
verse(horse) = "She's dead, of course!".
verse(donkey) = "It was rather wonky. To swallow a donkey.".
verse(cow) = "I don't know how. To swallow a cow.".
verse(goat) = "She just opened her throat. To swallow a goat.".
verse(pig) = "Her mouth was so big. To swallow a pig.".
verse(dog) = "What a hog. To swallow a dog.".
verse(cat) = "Fancy that. To swallow a cat.".
verse(bird) = "Quite absurd. To swallow a bird.".
verse(spider) = "That wriggled and jiggled and tickled inside her.".
verse(fly) = "I don't know why she swallowed the fly.".
:- pred tocatch(animal, animal).
:- mode tocatch(in, out) is semidet.
:- mode tocatch(out, in) is semidet.
tocatch(horse, donkey).
tocatch(donkey, cow).
tocatch(cow, goat).
tocatch(goat, pig).
tocatch(pig, dog).
tocatch(dog, cat).
tocatch(cat, bird).
tocatch(bird, spider).
tocatch(spider, fly).
:- pred swallow(animal::in, io::di, io::uo) is det.
swallow(A, !IO) :-
( if tocatch(A, B) then
io.format("She swallowed the %s to catch the %s.\n",
[s(string(A)), s(string(B))], !IO),
swallow(B, !IO)
else
io.format("%s\nPerhaps she'll die.\n\n", [s(verse(fly))], !IO)
).
:- pred swallowed(animal::in, io::di, io::uo) is det.
swallowed(A, !IO) :-
io.format("I know an old lady who swallowed a %s.\n", [s(string(A))], !IO),
( if A = horse then
io.write_string("She's dead, of course!\n", !IO)
else if A = fly, tocatch(B, A) then
swallow(A, !IO),
swallowed(B, !IO)
else if tocatch(B, A) then
io.write_string(verse(A), !IO),
io.nl(!IO),
swallow(A, !IO),
swallowed(B, !IO)
else
true
).
main(!IO) :-
swallowed(fly, !IO). |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Rust | Rust | extern crate rand;
use rand::{Rng, thread_rng};
fn one_of_n<R: Rng>(rng: &mut R, n: usize) -> usize {
(1..n).fold(0, |keep, cand| {
// Note that this will break if n is larger than u32::MAX
if rng.gen_weighted_bool(cand as u32 + 1) {
cand
} else {
keep
}
})
}
fn main() {
const LINES: usize = 10;
let mut dist = [0; LINES];
let mut rng = thread_rng();
for _ in 0..1_000_000 {
let num = one_of_n(&mut rng, LINES);
dist[num] += 1;
}
println!("{:?}", dist);
}
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Scala | Scala | def one_of_n(n: Int, i: Int = 1, j: Int = 1): Int =
if (n < 1) i else one_of_n(n - 1, if (scala.util.Random.nextInt(j) == 0) n else i, j + 1)
def simulate(lines: Int, iterations: Int) = {
val counts = new Array[Int](lines)
for (_ <- 1 to iterations; i = one_of_n(lines) - 1) counts(i) = counts(i) + 1
counts
}
println(simulate(10, 1000000) mkString "\n") |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Rust | Rust | vec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0] |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Scala | Scala | def lessThan1(a: List[Int], b: List[Int]): Boolean =
if (b.isEmpty) false
else if (a.isEmpty) true
else if (a.head != b.head) a.head < b.head
else lessThan1(a.tail, b.tail) |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FI | PL/I |
order: procedure options (main); /* 24/11/2011 */
declare word character (20) varying;
declare word_list character (20) varying controlled;
declare max_length fixed binary;
declare input file;
open file (input) title ('/ORDER.DAT,TYPE(TEXT),RECSIZE(100)');
on endfile (input) go to completed_search;
max_length = 0;
do forever;
get file (input) edit (word) (L);
if length(word) > max_length then
do;
if in_order(word) then
do;
/* Get rid of any stockpiled shorter words. */
do while (allocation(word_list) > 0);
free word_list;
end;
/* Add the eligible word to the stockpile. */
allocate word_list;
word_list = word;
max_length = length(word);
end;
end;
else if max_length = length(word) then
do; /* we have an eligle word of the same (i.e., maximum) length. */
if in_order(word) then
do; /* Add it to the stockpile. */
allocate word_list;
word_list = word;
end;
end;
end;
completed_search:
put skip list ('There are ' || trim(allocation(word_list)) ||
' eligible words of length ' || trim(length(word)) || ':');
do while (allocation(word_list) > 0);
put skip list (word_list);
free word_list;
end;
/* Check that the letters of the word are in non-decreasing order of rank. */
in_order: procedure (word) returns (bit(1));
declare word character (*) varying;
declare i fixed binary;
do i = 1 to length(word)-1;
if substr(word, i, 1) > substr(word, i+1, 1) then return ('0'b);
end;
return ('1'b);
end in_order;
end order;
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Ruby | Ruby | def palindrome?(s)
s == s.reverse
end |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #REXX | REXX | /*REXX program solves the odd word problem by only using (single) byte input/output.*/
iFID_ = 'ODDWORD.IN' /*Note: numeric suffix is added later.*/
oFID_ = 'ODDWORD.' /* " " " " " " */
do case=1 for 2; #= 0 /*#: is the number of characters read.*/
iFID= iFID_ || case /*read ODDWORD.IN1 or ODDWORD.IN2 */
oFID= oFID_ || case /*write ODDWORD.1 or ODDWORD.2 */
say; say; say '════════ reading file: ' iFID "════════" /* ◄■■■■■■■■■ optional. */
do until x==. /* [↓] perform until reaching a period*/
do until \datatype(x, 'M') /* [↓] " " punctuation found*/
call rChar /*read a single character. */
call wChar /*write " " " */
end /*until \data···*/ /* [↑] read/write until punctuation. */
if x==. then leave /*is this the end─of─sentence (period)?*/
call readLetters; punct= # /*save the location of the punctuation.*/
do j=#-1 by -1 /*read some characters backwards. */
call rChar j /*read previous word (backwards). */
if \datatype(x, 'M') then leave /*Found punctuation? Then leave J. */
call wChar /*write a character (which is a letter)*/
end /*j*/ /* [↑] perform for "even" words. */
call rLett /*read letters until punctuation found.*/
call wChar; #= punct /*write a char; punctuation location. */
end /*until x==.*/
end /*case*/ /* [↑] process both of the input files*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
rLett: do until \datatype(x, 'M'); call rChar; end; return
wChar: call charout , x /*console*/; call charout oFID, x /*file*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
rChar: if arg()==0 then do; x= charin(iFID); #= #+1; end /*read next char*/
else x= charin(iFID, arg(1) ); /* " specific " */ return |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Clojure | Clojure | (clojure.pprint/cl-format nil "~R" 1234)
=> "one thousand, two hundred thirty-four" |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Crystal | Crystal |
SIZE = 9
ordered = (1..SIZE).to_a
shuffled = (1..SIZE).to_a
while shuffled == ordered
shuffled.shuffle!
end
score = 0
until shuffled == ordered
print "#{shuffled} Enter items to reverse: "
next unless guess = gets
next unless num = guess.to_i?
next if num < 2 || num > SIZE
shuffled[0, num] = shuffled[0, num].reverse
score += 1
end
puts "#{shuffled} Your score: #{score}"
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Factor | Factor | : is-f? ( obj -- ? ) f = ; |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Fantom | Fantom |
fansh> x := null
fansh> x == null
true
fansh> x = 1
1
fansh> x == null
false
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Fantom | Fantom |
class Automaton
{
static Int[] evolve (Int[] array)
{
return array.map |Int x, Int i -> Int|
{
if (i == 0)
return ( (x + array[1] == 2) ? 1 : 0)
else if (i == array.size-1)
return ( (x + array[-2] == 2) ? 1 : 0)
else if (x + array[i-1] + array[i+1] == 2)
return 1
else
return 0
}
}
public static Void main ()
{
Int[] array := [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]
echo (array.join(""))
Int[] newArray := evolve(array)
while (newArray != array)
{
echo (newArray.join(""))
array = newArray
newArray = evolve(array)
}
}
}
|
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Go | Go | package main
import (
"fmt"
"math"
)
// specification for an integration
type spec struct {
lower, upper float64 // bounds for integration
n int // number of parts
exact float64 // expected answer
fs string // mathematical description of function
f func(float64) float64 // function to integrate
}
// test cases per task description
var data = []spec{
spec{0, 1, 100, .25, "x^3", func(x float64) float64 { return x * x * x }},
spec{1, 100, 1000, float64(math.Log(100)), "1/x",
func(x float64) float64 { return 1 / x }},
spec{0, 5000, 5e5, 12.5e6, "x", func(x float64) float64 { return x }},
spec{0, 6000, 6e6, 18e6, "x", func(x float64) float64 { return x }},
}
// object for associating a printable function name with an integration method
type method struct {
name string
integrate func(spec) float64
}
// integration methods implemented per task description
var methods = []method{
method{"Rectangular (left) ", rectLeft},
method{"Rectangular (right) ", rectRight},
method{"Rectangular (midpoint)", rectMid},
method{"Trapezium ", trap},
method{"Simpson's ", simpson},
}
func rectLeft(t spec) float64 {
var a adder
r := t.upper - t.lower
nf := float64(t.n)
x0 := t.lower
for i := 0; i < t.n; i++ {
x1 := t.lower + float64(i+1)*r/nf
// x1-x0 better than r/nf.
// (with r/nf, the represenation error accumulates)
a.add(t.f(x0) * (x1 - x0))
x0 = x1
}
return a.total()
}
func rectRight(t spec) float64 {
var a adder
r := t.upper - t.lower
nf := float64(t.n)
x0 := t.lower
for i := 0; i < t.n; i++ {
x1 := t.lower + float64(i+1)*r/nf
a.add(t.f(x1) * (x1 - x0))
x0 = x1
}
return a.total()
}
func rectMid(t spec) float64 {
var a adder
r := t.upper - t.lower
nf := float64(t.n)
// there's a tiny gloss in the x1-x0 trick here. the correct way
// would be to compute x's at division boundaries, but we don't need
// those x's for anything else. (the function is evaluated on x's
// at division midpoints rather than division boundaries.) so, we
// reuse the midpoint x's, knowing that they will average out just
// as well. we just need one extra point, so we use lower-.5.
x0 := t.lower - .5*r/nf
for i := 0; i < t.n; i++ {
x1 := t.lower + (float64(i)+.5)*r/nf
a.add(t.f(x1) * (x1 - x0))
x0 = x1
}
return a.total()
}
func trap(t spec) float64 {
var a adder
r := t.upper - t.lower
nf := float64(t.n)
x0 := t.lower
f0 := t.f(x0)
for i := 0; i < t.n; i++ {
x1 := t.lower + float64(i+1)*r/nf
f1 := t.f(x1)
a.add((f0 + f1) * .5 * (x1 - x0))
x0, f0 = x1, f1
}
return a.total()
}
func simpson(t spec) float64 {
var a adder
r := t.upper - t.lower
nf := float64(t.n)
// similar to the rectangle midpoint logic explained above,
// we play a little loose with the values used for dx and dx0.
dx0 := r / nf
a.add(t.f(t.lower) * dx0)
a.add(t.f(t.lower+dx0*.5) * dx0 * 4)
x0 := t.lower + dx0
for i := 1; i < t.n; i++ {
x1 := t.lower + float64(i+1)*r/nf
xmid := (x0 + x1) * .5
dx := x1 - x0
a.add(t.f(x0) * dx * 2)
a.add(t.f(xmid) * dx * 4)
x0 = x1
}
a.add(t.f(t.upper) * dx0)
return a.total() / 6
}
func sum(v []float64) float64 {
var a adder
for _, e := range v {
a.add(e)
}
return a.total()
}
type adder struct {
sum, e float64
}
func (a *adder) total() float64 {
return a.sum + a.e
}
func (a *adder) add(x float64) {
sum := a.sum + x
e := sum - a.sum
a.e += a.sum - (sum - e) + (x - e)
a.sum = sum
}
func main() {
for _, t := range data {
fmt.Println("Test case: f(x) =", t.fs)
fmt.Println("Integration from", t.lower, "to", t.upper,
"in", t.n, "parts")
fmt.Printf("Exact result %.7e Error\n", t.exact)
for _, m := range methods {
a := m.integrate(t)
e := a - t.exact
if e < 0 {
e = -e
}
fmt.Printf("%s %.7e %.7e\n", m.name, a, e)
}
fmt.Println("")
}
} |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Python | Python | from numpy import *
##################################################################
# Recursive generation of the Legendre polynomial of order n
def Legendre(n,x):
x=array(x)
if (n==0):
return x*0+1.0
elif (n==1):
return x
else:
return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n
##################################################################
# Derivative of the Legendre polynomials
def DLegendre(n,x):
x=array(x)
if (n==0):
return x*0
elif (n==1):
return x*0+1.0
else:
return (n/(x**2-1.0))*(x*Legendre(n,x)-Legendre(n-1,x))
##################################################################
# Roots of the polynomial obtained using Newton-Raphson method
def LegendreRoots(polyorder,tolerance=1e-20):
if polyorder<2:
err=1 # bad polyorder no roots can be found
else:
roots=[]
# The polynomials are alternately even and odd functions. So we evaluate only half the number of roots.
for i in range(1,int(polyorder)/2 +1):
x=cos(pi*(i-0.25)/(polyorder+0.5))
error=10*tolerance
iters=0
while (error>tolerance) and (iters<1000):
dx=-Legendre(polyorder,x)/DLegendre(polyorder,x)
x=x+dx
iters=iters+1
error=abs(dx)
roots.append(x)
# Use symmetry to get the other roots
roots=array(roots)
if polyorder%2==0:
roots=concatenate( (-1.0*roots, roots[::-1]) )
else:
roots=concatenate( (-1.0*roots, [0.0], roots[::-1]) )
err=0 # successfully determined roots
return [roots, err]
##################################################################
# Weight coefficients
def GaussLegendreWeights(polyorder):
W=[]
[xis,err]=LegendreRoots(polyorder)
if err==0:
W=2.0/( (1.0-xis**2)*(DLegendre(polyorder,xis)**2) )
err=0
else:
err=1 # could not determine roots - so no weights
return [W, xis, err]
##################################################################
# The integral value
# func : the integrand
# a, b : lower and upper limits of the integral
# polyorder : order of the Legendre polynomial to be used
#
def GaussLegendreQuadrature(func, polyorder, a, b):
[Ws,xs, err]= GaussLegendreWeights(polyorder)
if err==0:
ans=(b-a)*0.5*sum( Ws*func( (b-a)*0.5*xs+ (b+a)*0.5 ) )
else:
# (in case of error)
err=1
ans=None
return [ans,err]
##################################################################
# The integrand - change as required
def func(x):
return exp(x)
##################################################################
#
order=5
[Ws,xs,err]=GaussLegendreWeights(order)
if err==0:
print "Order : ", order
print "Roots : ", xs
print "Weights : ", Ws
else:
print "Roots/Weights evaluation failed"
# Integrating the function
[ans,err]=GaussLegendreQuadrature(func , order, -3,3)
if err==0:
print "Integral : ", ans
else:
print "Integral evaluation failed" |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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 OldLady;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE
AA = ARRAY[0..7] OF ARRAY[0..7] OF CHAR;
VA = ARRAY[0..7] OF ARRAY[0..63] OF CHAR;
VAR
buf : ARRAY[0..127] OF CHAR;
animals : AA;
verses : VA;
i,j : INTEGER;
BEGIN
FormatString("I don't know why she swallowed that fly.\nPerhaps she'll die\n", buf);
animals := AA{"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"};
verses := VA{
"I don't know why she swallowed that fly.",
"That wiggled and jiggled and tickled inside her",
"How absurd, to swallow a bird",
"Imagine that. She swallowed a cat",
"What a hog to swallow a dog",
"She just opened her throat and swallowed that goat",
"I don't know how she swallowed that cow",
"She's dead of course"
};
FOR i:=0 TO 7 DO
FormatString("There was an old lady who swallowed a %s\n%s\n", buf, animals[i], verses[i]);
WriteString(buf);
IF i=0 THEN
WriteString("Perhaps she'll die");
WriteLn;
WriteLn;
END;
j := i;
WHILE (j>0) AND (i<7) DO
FormatString("She swallowed the %s to catch the %s\n", buf, animals[j], animals[j-1]);
WriteString(buf);
IF j=1 THEN
WriteString(verses[0]);
WriteLn;
WriteString("Perhaps she'll die");
WriteLn;
WriteLn
END;
DEC(j)
END;
END;
ReadChar
END OldLady. |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: one_of_n (in integer: n) is func
result
var integer: r is 1;
local
var integer: i is 0;
begin
for i range 2 to n do
if rand(1, i) = 1 then
r := i;
end if;
end for;
end func;
const proc: main is func
local
var array integer: r is 10 times 0;
var integer: i is 0;
begin
for i range 1 to 1000000 do
incr(r[one_of_n(10)]);
end for;
for i range 1 to 10 do
write(r[i] <& " ");
end for;
writeln;
end func; |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Sidef | Sidef | func one_of_n(n) {
var choice
n.times { |i|
choice = i if (1 > i.rand)
}
choice - 1
}
func one_of_n_test(n = 10, trials = 1_000_000) {
var bins = []
trials.times {
bins[one_of_n(n)] := 0 ++
}
bins
}
say one_of_n_test() |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Scheme | Scheme | (define (lex<? a b)
(cond ((null? b) #f)
((null? a) #t)
((= (car a) (car b)) (lex<? (cdr a) (cdr b)))
(else (< (car a) (car b))))) |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln([] (1) < [] (1, 2)); # If the first list runs out of elements the result is TRUE.
writeln([] (1, 2) < [] (1)); # If the second list runs out of elements the result is FALSE.
writeln([] (1, 2) < [] (1, 2)); # If both lists run out of elements the result is FALSE.
writeln([] (1, 2, 3) < [] (1, 1, 3)); # The second element is greater than --> FALSE
writeln([] (1, 2, 3) < [] (1, 3, 3)); # The second element is less than --> TRUE
writeln(0 times 0 < [] (1)); # The empty list is less than any nonempty list --> TRUE
writeln([] (1) < 0 times 0); # Any nonempty list is not less than the empty list --> FALSE
writeln(0 times 0 < 0 times 0); # The empty list is not less than the empty list --> FALSE
end func; |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PowerShell | PowerShell |
$url = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
(New-Object System.Net.WebClient).DownloadFile($url, "$env:TEMP\unixdict.txt")
$ordered = Get-Content -Path "$env:TEMP\unixdict.txt" |
ForEach-Object {if (($_.ToCharArray() | Sort-Object) -join '' -eq $_) {$_}} |
Group-Object -Property Length |
Sort-Object -Property Name |
Select-Object -Property @{Name="WordCount" ; Expression={$_.Count}},
@{Name="WordLength"; Expression={[int]$_.Name}},
@{Name="Words" ; Expression={$_.Group}} -Last 1
"There are {0} ordered words of the longest word length ({1} characters):`n`n{2}" -f $ordered.WordCount,
$ordered.WordLength,
($ordered.Words -join ", ")
Remove-Item -Path "$env:TEMP\unixdict.txt" -Force -ErrorAction SilentlyContinue
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Run_BASIC | Run BASIC | data "My dog has fleas", "Madam, I'm Adam.", "1 on 1", "In girum imus nocte et consumimur igni"
for i = 1 to 4
read w$
print w$;" is ";isPalindrome$(w$);" Palindrome"
next
FUNCTION isPalindrome$(str$)
for i = 1 to len(str$)
a$ = upper$(mid$(str$,i,1))
if (a$ >= "A" and a$ <= "Z") or (a$ >= "0" and a$ <= "9") then b$ = b$ + a$: c$ = a$ + c$
next i
if b$ <> c$ then isPalindrome$ = "not" |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Ring | Ring |
# Project : Odd word problem
test = "what,is,the;meaning,of:life."
n1 = 1
testarr = []
testorigin = test
test = substr(test, ",", " ")
test = substr(test, ";", " ")
test = substr(test, ":", " ")
test = substr(test, ".", " ")
while true
n2 = substring(test, " ", n1)
n3 = substring(test, " ", n2 + 1)
if n2>0 and n3>0
strcut = substr(test, n2 + 1, n3 - n2)
strcut = trim(strcut)
if strcut != ""
add(testarr, strcut)
n1 = n3 + 1
else
exit
ok
ok
end
for n = 1 to len(testarr)
strrev = revstr(testarr[n])
testorigin = substr(testorigin, testarr[n], strrev)
next
see testorigin + nl
func Substring str,substr,n
newstr=right(str,len(str)-n+1)
nr = substr(newstr, substr)
return n + nr -1
func revstr(cStr)
cStr2 = ""
for x = len(cStr) to 1 step -1
cStr2 += cStr[x]
next
return cStr2
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Ruby | Ruby | f, r = nil
fwd = proc {|c|
c =~ /[[:alpha:]]/ ? [(print c), fwd[Fiber.yield f]][1] : c }
rev = proc {|c|
c =~ /[[:alpha:]]/ ? [rev[Fiber.yield r], (print c)][0] : c }
(f = Fiber.new { loop { print fwd[Fiber.yield r] }}).resume
(r = Fiber.new { loop { print rev[Fiber.yield f] }}).resume
coro = f
until $stdin.eof?
coro = coro.resume($stdin.getc)
end |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #CoffeeScript | CoffeeScript |
spell_integer = (n) ->
tens = [null, null, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
small = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
bl = [null, null, "m", "b", "tr", "quadr",
"quint", "sext", "sept", "oct", "non", "dec"]
divmod = (n, d) ->
[Math.floor(n / d), n % d]
nonzero = (c, n) ->
if n == 0
""
else
c + spell_integer n
big = (e, n) ->
if e == 0
spell_integer n
else if e == 1
spell_integer(n) + " thousand"
else
spell_integer(n) + " " + bl[e] + "illion"
base1000_rev = (n) ->
# generates the value of the digits of n in base 1000
# (i.e. 3-digit chunks), in reverse.
chunks = []
while n != 0
[n, r] = divmod n, 1000
chunks.push r
chunks
if n < 0
throw Error "spell_integer: negative input"
else if n < 20
small[n]
else if n < 100
[a, b] = divmod n, 10
tens[a] + nonzero("-", b)
else if n < 1000
[a, b] = divmod n, 100
small[a] + " hundred" + nonzero(" ", b)
else
chunks = (big(exp, x) for x, exp in base1000_rev(n) when x)
chunks.reverse().join ', '
# example
console.log spell_integer 1278
console.log spell_integer 1752
console.log spell_integer 2010
console.log spell_integer 4000123007913
|
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #D | D | import std.stdio, std.random, std.string, std.conv, std.algorithm,
std.range;
void main() {
auto data = iota(1, 10).array;
do data.randomShuffle;
while (data.isSorted);
int trial;
while (!data.isSorted) {
writef("%d: %s How many numbers to flip? ", ++trial, data);
data[0 .. readln.strip.to!uint].reverse;
}
writefln("\nYou took %d attempts.", trial);
} |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Forth | Forth | 'FB 1.05.0 Win64
' FreeBASIC does not have a NULL keyword but it's possible to create one using a macro
#Define NULL CPtr(Any Ptr, 0) '' Any Ptr is implicitly convertible to pointers of other types
Type Dog
name As String
age As Integer
End Type
Dim d As Dog Ptr = New Dog
d->Name = "Rover"
d->Age = 5
Print d->Name, d->Age
Delete d
d = NULL '' guard against 'd' being used accidentally in future
' in practice many FB developers would simply have written: d = 0 above
Sleep |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #FreeBASIC | FreeBASIC | 'FB 1.05.0 Win64
' FreeBASIC does not have a NULL keyword but it's possible to create one using a macro
#Define NULL CPtr(Any Ptr, 0) '' Any Ptr is implicitly convertible to pointers of other types
Type Dog
name As String
age As Integer
End Type
Dim d As Dog Ptr = New Dog
d->Name = "Rover"
d->Age = 5
Print d->Name, d->Age
Delete d
d = NULL '' guard against 'd' being used accidentally in future
' in practice many FB developers would simply have written: d = 0 above
Sleep |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #FOCAL | FOCAL | 1.1 S OLD(2)=1; S OLD(3)=1; S OLD(4)=1; S OLD(6)=1; S OLD(7)=1
1.2 S OLD(9)=1; S OLD(11)=1; S OLD(13)=1; S OLD(15)=1; S OLD(18)=1
1.3 F N=1,10; D 2
1.4 Q
2.1 F X=1,20; D 3
2.2 F X=1,20; D 6
2.3 F X=1,20; S OLD(X)=NEW(X)
2.4 T !
3.1 I (OLD(X-1)+OLD(X)+OLD(X+1)-2)4.1,5.1,4.1
4.1 S NEW(X)=0
5.1 S NEW(X)=1
6.1 I (-OLD(X))7.1,8.1,8.1
7.1 T "#"
8.1 T "." |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Forth | Forth | : init ( bits count -- )
0 do dup 1 and c, 2/ loop drop ;
20 constant size
create state $2556e size init 0 c,
: .state
cr size 0 do
state i + c@ if ." #" else space then
loop ;
: ctable create does> + c@ ;
ctable rules $68 8 init
: gen
state c@ ( window )
size 0 do
2* state i + 1+ c@ or 7 and
dup rules state i + c!
loop drop ;
: life1d ( n -- )
.state 1 do gen .state loop ;
10 life1d |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Groovy | Groovy | def assertBounds = { List bounds, int nRect ->
assert (bounds.size() == 2) && (bounds[0] instanceof Double) && (bounds[1] instanceof Double) && (nRect > 0)
}
def integral = { List bounds, int nRectangles, Closure f, List pointGuide, Closure integralCalculator->
double a = bounds[0], b = bounds[1], h = (b - a)/nRectangles
def xPoints = pointGuide.collect { double it -> a + it*h }
def fPoints = xPoints.collect { x -> f(x) }
integralCalculator(h, fPoints)
}
def leftRectIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, (0..<nRect)) { h, fPoints -> h*fPoints.sum() }
}
def rightRectIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, (1..nRect)) { h, fPoints -> h*fPoints.sum() }
}
def midRectIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, ((0.5d)..nRect)) { h, fPoints -> h*fPoints.sum() }
}
def trapezoidIntegral = { List bounds, int nRect, Closure f ->
assertBounds(bounds, nRect)
integral(bounds, nRect, f, (0..nRect)) { h, fPoints ->
def fLeft = fPoints[0..<nRect]
def fRight = fPoints[1..nRect]
h/2*(fLeft + fRight).sum()
}
}
def simpsonsIntegral = { List bounds, int nSimpRect, Closure f ->
assertBounds(bounds, nSimpRect)
integral(bounds, nSimpRect*2, f, (0..(nSimpRect*2))) { h, fPoints ->
def fLeft = fPoints[(0..<nSimpRect*2).step(2)]
def fMid = fPoints[(1..<nSimpRect*2).step(2)]
def fRight = fPoints[(2..nSimpRect*2).step(2)]
h/3*((fLeft + fRight).sum() + 4*(fMid.sum()))
}
} |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Racket | Racket |
(define (LegendreP n x)
(let compute ([n n] [Pn-1 x] [Pn-2 1])
(case n
[(0) Pn-2]
[(1) Pn-1]
[else (compute (- n 1)
(/ (- (* (- (* 2 n) 1) x Pn-1)
(* (- n 1) Pn-2)) n)
Pn-1)])))
(define (LegendreP′ n x)
(* (/ n (- (* x x) 1))
(- (* x (LegendreP n x))
(LegendreP (- n 1) x))))
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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 | reason = {"She swallowed the ", " to catch the "}
creatures = {"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"}
comments = {"I don't know why she swallowed that fly.\nPerhaps she'll die\n",\
"That wiggled and jiggled and tickled inside her",\
"How absurd, to swallow a bird",\
"Imagine that. She swallowed a cat",\
"What a hog to swallow a dog",\
"She just opened her throat and swallowed that goat",\
"I don't know how she swallowed that cow",\
"She's dead of course"}
max = len(creatures)
for i in range(0, max - 1)
println "There was an old lady who swallowed a " + creatures[i]
println comments[i]
for (j = i) ((j > 0) && (i < (max - 1))) (j -= 1)
println reason[0] + creatures[j] + reason[1] + creatures[j - 1]
if j = 1
println comments[j - 1]
end
end
end
input() |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import zip/zlib, base64
const b64 = """
eNrtVE1rwzAMvedXaKdeRn7ENrb21rHCzmrs1m49K9gOJv9+cko/HBcGg0LHcpOfnq2np0QL
2FuKgBbICDAoeoiKwEc0hqIUgLAxfV0tQJCdhQM7qh68kheswKeBt5ROYetTemYMCC3rii//
WMS3WkhXVyuFAaLT261JuBWwu4iDbvYp1tYzHVS68VEIObwFgaDB0KizuFs38aSdqKv3TgcJ
uPYdn2B1opwIpeKE53qPftxRd88Y6uoVbdPzWxznrQ3ZUi3DudQ/bcELbevqM32iCIrj3IIh
W6plOJf6L6xaajZjzqW/qAsKIvITBGs9Nm3glboZzkVP5l6Y+0bHLnedD0CttIyrpEU5Kv7N
Mz3XkPBc/TSN3yxGiqMiipHRekycK0ZwMhM8jerGC9zuZaoTho3kMKSfJjLaF8v8wLzmXMqM
zJvGew/jnZPzclA08yAkikegDTTUMfzwDXBcwoE="""
echo b64.decode.uncompress() |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Swift | Swift | func one_of_n(n: Int) -> Int {
var result = 1
for i in 2...n {
if arc4random_uniform(UInt32(i)) < 1 {
result = i
}
}
return result
}
var counts = [0,0,0,0,0,0,0,0,0,0]
for _ in 1..1_000_000 {
counts[one_of_n(10)-1]++
}
println(counts) |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Tcl | Tcl | package require Tcl 8.5
proc 1ofN {n} {
for {set line 1} {$line <= $n} {incr line} {
if {rand() < 1.0/[incr fraction]} {
set result $line
}
}
return $result
}
for {set i 0} {$i < 1000000} {incr i} {
incr count([1ofN 10])
}
parray count; # Alphabetic order, but convenient |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Sidef | Sidef | func ordered(a, b) {
(a <=> b) < 0
}
for p in [
Pair([1,2,4], [1,2,4]),
Pair([1,2,4], [1,2] ),
Pair([1,2], [1,2,4]),
] {
var a = p.first
var b = p.second
var before = ordered(a, b)
say "#{a} comes before #{b} : #{before}"
} |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Prolog | Prolog | :- use_module(library( http/http_open )).
ordered_words :-
% we read the URL of the words
http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', In, []),
read_file(In, [], Out),
close(In),
% we get a list of pairs key-value where key = Length and value = <list-of-its-codes>
% this list must be sorted
msort(Out, MOut),
group_pairs_by_key(MOut, POut),
% we sorted this list in decreasing order of the length of values
predsort(my_compare, POut, [_N-V | _OutSort]),
maplist(mwritef, V).
mwritef(V) :-
writef('%s\n', [V]).
read_file(In, L, L1) :-
read_line_to_codes(In, W),
( W == end_of_file ->
% the file is read
L1 = L
;
% we sort the list of codes of the line
% and keep only the "goods word"
( msort(W, W) ->
length(W, N), L2 = [N-W | L], (len = 6 -> writef('%s\n', [W]); true)
;
L2 = L
),
% and we have the pair Key-Value in the result list
read_file(In, L2, L1)).
% predicate for sorting list of pairs Key-Values
% if the lentgh of values is the same
% we sort the keys in alhabetic order
my_compare(R, K1-_V1, K2-_V2) :-
( K1 < K2 -> R = >; K1 > K2 -> R = <; =).
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Rust | Rust | fn is_palindrome(string: &str) -> bool {
let half_len = string.len() / 2;
string
.chars()
.take(half_len)
.eq(string.chars().rev().take(half_len))
}
macro_rules! test {
( $( $x:tt ),* ) => { $( println!("'{}': {}", $x, is_palindrome($x)); )* };
}
fn main() {
test!(
"",
"a",
"ada",
"adad",
"ingirumimusnocteetconsumimurigni",
"人人為我,我為人人",
"Я иду с мечем, судия",
"아들딸들아",
"The quick brown fox"
);
} |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Run_BASIC | Run BASIC | open "oddWord.txt" for input as #f ' read input stream
while not(eof(#f))
line input #f, a$
oddW$ = "" ' begin the result oddW with blank
px = 0 ' begin word search location with 0
count = 0 ' begin the word count to 0
while x < len(a$) ' look at each character
x = instr(a$,",",px) ' search for comma (,)
if x = 0 then x = len(a$) ' no more commas?
x1 = instr(a$,";",px) ' search for (;)
x2 = instr(a$,":",px) ' search for (:)
if x1 <> 0 then x = min(x,x1) ' what came first the , ; or :
if x2 <> 0 then x = min(x,x2)
w$ = mid$(a$,px,x - px) ' get the word seperated by , ; or :
if count and 1 then ' is it the odd word
w1$ = ""
for i = len(w$) to 1 step -1
w1$ = w1$ + mid$(w$,i,1) ' reverse odd words
next i
w$ = w1$
end if
oddW$ = oddW$ + w$ + mid$(a$,x,1) ' add the word to the end of oddW$
px = x + 1 ' bump word search location for next while
count = count + 1 ' count the words
wend
print a$;" -> ";oddW$ ' print the original and result
next ii
wend
close #f |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Scala | Scala | import scala.io.Source
import java.io.PrintStream
def process(s: Source, p: PrintStream, w: Int = 0): Unit = if (s.hasNext) s.next match {
case '.' => p append '.'
case c if !Character.isAlphabetic(c) => p append c; reverse(s, p, w + 1)
case c => p append c; process(s, p, w)
}
def reverse(s: Source, p: PrintStream, w: Int = 0, x: Char = '.'): Char = s.next match {
case c if !Character.isAlphabetic(c) => p append x; c
case c => val n = reverse(s, p, w, c);
if (x == '.') {p append n; process(s, p, w + 1)} else p append x; n
}
process(Source.fromString("what,is,the;meaning,of:life."), System.out); println
process(Source.fromString("we,are;not,in,kansas;any,more."), System.out); println |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Commodore_BASIC | Commodore BASIC | 10 print chr$(147);chr$(14)
20 dim s$(11),ts$(11),t$(11),o$(11):co=39
30 for i=0 to 11:read s$(i),ts$(i),t$(i),o$(i):next
40 print "Enter a number";:input n$
45 ou$=""
50 if len(n$)>36 then print:print "Too long.":print:goto 40
51 print
55 rem check for negative
56 if left$(n$,1)="-" then n$=right$(n$,len(n$)-1):ou$="negative ":gosub 500
60 no=int((len(n$)-1)/3)
70 rem pad left side
71 p=(no+1)*3-len(n$)
75 if p>0 then n$="0"+n$:p=p-1:goto 75
77 if val(n$)=0 then ou$=s$(0):gosub 500:goto 125
80 rem calculate left to right
81 for i=no to 0 step -1:oi=no-i
85 ch$=mid$(n$,1+(oi*3),3)
90 h=val(mid$(ch$,1,1)):t=val(mid$(ch$,2,1)):s=val(mid$(ch$,3,1))
93 if h=0 and t=0 and s=0 then goto 120
95 if h>0 then ou$=s$(h)+" hundred ":gosub 500
100 if t>1 then ou$=t$(t)+mid$("- ",abs(s=0)+1,1):gosub 500
105 if t=1 then ou$=ts$(s)+" ":gosub 500
110 if t<>1 and s>0 then ou$=s$(s)+" ":gosub 500
115 ou$=o$(i)+" ":gosub 500
120 next i
125 print:print
130 print "Another? (y/n) ";
140 get k$:ifk$<>"y" and k$<>"n" then 140
145 print k$
150 if k$="y" then print:goto 40
200 end
500 rem print with word wrapping
505 cp=pos(0):nl=len(ou$)
510 if cp>co-nl then print
520 print ou$;
599 return
1000 data zero,ten,"",""
1001 data one,eleven,ten,thousand
1002 data two,twelve,twenty,million
1003 data three,thirteen,thirty,billion
1004 data four,fourteen,forty,trillion
1005 data five,fifteen,fifty,quadrillion
1006 data six,sixteen,sixty,quintillion
1007 data seven,seventeen,seventy,sextillion
1008 data eight,eighteen,eighty,septillion
1009 data nine,nineteen,ninety,octillion
1010 data "","","",nonillion
1011 data "","","",decillion |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Egel | Egel |
import "prelude.eg"
import "io.ego"
import "random.ego"
using System
using IO
using List
using Math
def swap =
[ (I J) XX -> insert I (nth J XX) (insert J (nth I XX) XX) ]
def shuffle =
[ XX ->
let INDICES = reverse (fromto 0 ((length XX) - 1)) in
let SWAPS = map [ I -> I (between 0 I) ] INDICES in
foldr [I J -> swap I J] XX SWAPS ]
def prompt =
[ XX TURN ->
let _ = print TURN ". " in
let _ = map [ X -> print X " " ] XX in
let _ = print " : " in
toint getline ]
def game =
[ GOAL SHUFFLE TURN ->
if SHUFFLE == GOAL then
let _ = print "the goal was " in
let _ = map [ X -> print X " " ] GOAL in
print "\nit took you " TURN " turns\n"
else
let N = prompt SHUFFLE TURN in
let YY = (reverse (take N SHUFFLE)) ++ (drop N SHUFFLE) in
game GOAL YY (TURN + 1) ]
def main =
let XX = fromto 1 9 in game XX (shuffle XX) 0 |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Go | Go |
package main
import "fmt"
var (
s []int // slice type
p *int // pointer type
f func() // function type
i interface{} // interface type
m map[int]int // map type
c chan int // channel type
)
func main() {
fmt.Println(s == nil)
fmt.Println(p == nil)
fmt.Println(f == nil)
fmt.Println(i == nil)
fmt.Println(m == nil)
fmt.Println(c == nil)
}
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Haskell | Haskell | undefined -- undefined value provided by the standard library
error "oops" -- another undefined value
head [] -- undefined, you can't take the head of an empty list |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Fortran | Fortran | PROGRAM LIFE_1D
IMPLICIT NONE
LOGICAL :: cells(20) = (/ .FALSE., .TRUE., .TRUE., .TRUE., .FALSE., .TRUE., .TRUE., .FALSE., .TRUE., .FALSE., &
.TRUE., .FALSE., .TRUE., .FALSE., .TRUE., .FALSE., .FALSE., .TRUE., .FALSE., .FALSE. /)
INTEGER :: i
DO i = 0, 9
WRITE(*, "(A,I0,A)", ADVANCE = "NO") "Generation ", i, ": "
CALL Drawgen(cells)
CALL Nextgen(cells)
END DO
CONTAINS
SUBROUTINE Nextgen(cells)
LOGICAL, INTENT (IN OUT) :: cells(:)
LOGICAL :: left, centre, right
INTEGER :: i
left = .FALSE.
DO i = 1, SIZE(cells)-1
centre = cells(i)
right = cells(i+1)
IF (left .AND. right) THEN
cells(i) = .NOT. cells(i)
ELSE IF (.NOT. left .AND. .NOT. right) THEN
cells(i) = .FALSE.
END IF
left = centre
END DO
cells(SIZE(cells)) = left .AND. right
END SUBROUTINE Nextgen
SUBROUTINE Drawgen(cells)
LOGICAL, INTENT (IN OUT) :: cells(:)
INTEGER :: i
DO i = 1, SIZE(cells)
IF (cells(i)) THEN
WRITE(*, "(A)", ADVANCE = "NO") "#"
ELSE
WRITE(*, "(A)", ADVANCE = "NO") "_"
END IF
END DO
WRITE(*,*)
END SUBROUTINE Drawgen
END PROGRAM LIFE_1D |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Haskell | Haskell | approx f xs ws = sum [w * f x | (x,w) <- zip xs ws] |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Raku | Raku | multi legendre-pair( 1 , $x) { $x, 1 }
multi legendre-pair(Int $n, $x) {
my ($m1, $m2) = legendre-pair($n - 1, $x);
my \u = 1 - 1 / $n;
(1 + u) * $x * $m1 - u * $m2, $m1;
}
multi legendre( 0 , $ ) { 1 }
multi legendre(Int $n, $x) { legendre-pair($n, $x)[0] }
multi legendre-prime( 0 , $ ) { 0 }
multi legendre-prime( 1 , $ ) { 1 }
multi legendre-prime(Int $n, $x) {
my ($m0, $m1) = legendre-pair($n, $x);
($m1 - $x * $m0) * $n / (1 - $x**2);
}
sub approximate-legendre-root(Int $n, Int $k) {
# Approximation due to Francesco Tricomi
my \t = (4*$k - 1) / (4*$n + 2);
(1 - ($n - 1) / (8 * $n**3)) * cos(pi * t);
}
sub newton-raphson(&f, &f-prime, $r is copy, :$eps = 2e-16) {
while abs(my \dr = - f($r) / f-prime($r)) >= $eps {
$r += dr;
}
$r;
}
sub legendre-root(Int $n, Int $k) {
newton-raphson(&legendre.assuming($n), &legendre-prime.assuming($n),
approximate-legendre-root($n, $k));
}
sub weight(Int $n, $r) { 2 / ((1 - $r**2) * legendre-prime($n, $r)**2) }
sub nodes(Int $n) {
flat gather {
take 0 => weight($n, 0) if $n !%% 2;
for 1 .. $n div 2 {
my $r = legendre-root($n, $_);
my $w = weight($n, $r);
take $r => $w, -$r => $w;
}
}
}
sub quadrature(Int $n, &f, $a, $b, :@nodes = nodes($n)) {
sub scale($x) { ($x * ($b - $a) + $a + $b) / 2 }
($b - $a) / 2 * [+] @nodes.map: { .value * f(scale(.key)) }
}
say "Gauss-Legendre $_.fmt('%2d')-point quadrature ∫₋₃⁺³ exp(x) dx ≈ ",
quadrature($_, &exp, -3, +3) for flat 5 .. 10, 20; |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #OCaml | OCaml | let d = [|
"I know an old lady who swallowed a "; "fly"; ".\n";
"I don't know why she swallowed the fly.\nPerhaps she'll die.\n\n";
"spider"; "That wriggled and jiggled and tickled inside her";
"She swallowed the "; " to catch the "; "Bird"; "Quite absurd";
". To swallow a "; "Cat"; "Fancy that"; "Dog"; "What a hog"; "Pig";
"Her mouth was so big"; "Goat"; "She just opened her throat"; "Cow";
"I don't know how"; "Donkey"; "It was rather wonky";
"I know an old lady who swallowed a Horse.\nShe's dead, of course!\n";
|]
let s0 = [6;4;7;1;2;3]
let s1 = [6;8;7;4;2] @ s0
let s2 = [6;11;7;8;2] @ s1
let s3 = [6;13;7;11;2] @ s2
let s4 = [6;15;7;13;2] @ s3
let s5 = [6;17;7;15;2] @ s4
let s6 = [6;19;7;17;2] @ s5
let s7 = [6;21;7;19;2] @ s6
let s =
[0;1;2;3;0;4;2;5;2] @ s0 @
[0;8;2;9;10;8;2] @ s1 @
[0;11;2;12;10;11;2] @ s2 @
[0;13;2;14;10;13;2] @ s3 @
[0;15;2;16;10;15;2] @ s4 @
[0;17;2;18;10;17;2] @ s5 @
[0;19;2;20;10;19;2] @ s6 @
[0;21;2;22;10;21;2] @ s7 @
[23] ;;
List.iter (fun i -> print_string d.(i)) s |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #VBScript | VBScript |
Dim chosen(10)
For j = 1 To 1000000
c = one_of_n(10)
chosen(c) = chosen(c) + 1
Next
For k = 1 To 10
WScript.StdOut.WriteLine k & ". " & chosen(k)
Next
Function one_of_n(n)
Randomize
For i = 1 To n
If Rnd(1) < 1/i Then
one_of_n = i
End If
Next
End Function
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var oneOfN = Fn.new { |n|
var choice = 1
for (i in 2..n) {
if (rand.float() < 1/i) choice = i
}
return choice
}
var n = 10
var freqs = List.filled(n, 0)
var reps = 1e6
for (i in 0...reps) {
var num = oneOfN.call(n)
freqs[num-1] = freqs[num-1] + 1
}
for (i in 1..n) Fmt.print("Line $-2d = $,7d", i, freqs[i-1]) |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Standard_ML | Standard ML | - List.collate Int.compare ([1,2,1,3,2], [1,2,0,4,4,0,0,0]) = LESS;
val it = false : bool |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Swift | Swift | let a = [1,2,1,3,2]
let b = [1,2,0,4,4,0,0,0]
println(lexicographicalCompare(a, b)) // this is "less than" |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #PureBasic | PureBasic | Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted
Protected Dim letters.c(wordLength)
Protected *letAdr = @letters()
CopyMemoryString(*word, @*letAdr)
SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1)
ProcedureReturn PeekS(@letters(), wordLength)
EndProcedure
Structure orderedWord
word.s
length.i
EndStructure
Define filename.s = "unixdict.txt", fileNum = 0, word.s
If OpenConsole()
NewList orderedWords.orderedWord()
If ReadFile(fileNum, filename)
While Not Eof(fileNum)
word = ReadString(fileNum)
If word = sortLetters(@word, Len(word))
AddElement(orderedWords())
orderedWords()\word = word
orderedWords()\length = Len(word)
EndIf
Wend
Else
MessageRequester("Error", "Unable to find dictionary '" + filename + "'")
End
EndIf
SortStructuredList(orderedWords(), #PB_Sort_Ascending, OffsetOf(orderedWord\word), #PB_String)
SortStructuredList(orderedWords(), #PB_Sort_Descending, OffsetOf(orderedWord\length), #PB_Integer)
Define maxLength
FirstElement(orderedWords())
maxLength = orderedWords()\length
ForEach orderedWords()
If orderedWords()\length = maxLength
Print(orderedWords()\word + " ")
EndIf
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #SAS | SAS |
The macro "palindro" has two parameters: string and ignorewhitespace.
string is the expression to be checked.
ignorewhitespace, (Y/N), determines whether or not to ignore blanks and punctuation.
This macro was written in SAS 9.2. If you use a version before SAS 9.1.3,
the compress function options will not work.
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Scheme | Scheme | (define (odd)
(let ((c (read-char)))
(if (char-alphabetic? c)
(let ((r (odd)))
(write-char c)
r)
(lambda () (write-char c) (char=? c #\.)))))
(define (even)
(let ((c (read-char)))
(write-char c)
(if (char-alphabetic? c)
(even)
(char=? c #\.))))
(let loop ((i #f))
(if (if i ((odd)) (even))
(exit)
(loop (not i)))) |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.