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/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
| #Cowgol | Cowgol | include "cowgol.coh";
var animals: [uint8][] := {
"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"
};
var verses: [uint8][] := {
"I don't know why she swallowed that fly - Perhaps 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."
};
var i: uint8 := 0;
while i < @sizeof animals loop
print("There was an old lady who swallowed a ");
print(animals[i]);
print(",\n");
print(verses[i]);
print_nl();
var j: uint8 := i;
while j > 0 and i < @sizeof animals-1 loop
print("She swallowed the ");
print(animals[j]);
print(" to catch the ");
print(animals[j-1]);
print(",\n");
if j <= 2 then
print(verses[j-1]);
print_nl();
end if;
j := j - 1;
end loop;
i := i + 1;
end loop; |
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
| #D | D | import core.stdc.stdio;
immutable data = [
"_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,/What a hog"~
"_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just opened her throat_f_"~
"r;_icow,/_mhow she_ga cow;_k_o,/It_qrather wonky_f_o;_a_o_bcow,_khorse.."~
"./She's dead, of course!/","_a_p_b_e ","/S_t "," to catch the ","fly,/Bu"~
"t _mwhy s_t fly,/Perhaps she'll die!//_ha","_apig_bdog,_l`","spider,/Tha"~
"t wr_nj_ntickled inside her;_aspider_b_c",", to_s a ","_sed ","There_qan"~
" old lady who_g","_a_r_bpig,_d","_acat_b_p,_","_acow_b_r,_i","_adog_bcat"~
",_j","I don't know ","iggled and ","donkey","bird"," was ","goat"," swal"~
"low","he_gthe"];
bool oldLady(in string part, bool s=false) nothrow @nogc {
foreach (immutable ch; part) {
if (s)
s = oldLady(data[ch - '_'], false);
else if (ch == '_')
s = true;
else
putchar(ch == '/' ? '\n' : ch);
}
return s;
}
void main() {
data[0].oldLady;
} |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Raku | Raku | convert(1, 'meter');
say '*' x 40, "\n";
convert(1, 'milia');
sub convert (Real $magnitude, $unit) {
my %factor =
tochka => 0.000254,
liniya => 0.00254,
diuym => 0.0254,
vershok => 0.04445,
piad => 0.1778,
fut => 0.3048,
arshin => 0.7112,
sazhen => 2.1336,
versta => 1066.8,
milia => 7467.6,
centimeter => 0.01,
meter => 1.0,
kilometer => 1000.0,
;
my $meters = $magnitude * %factor{$unit.lc};
say "$magnitude $unit to:\n", '_' x 40;
printf "%10s: %s\n", $_, $meters / %factor{$_} unless $_ eq $unit.lc
for %factor.keys.sort:{ +%factor{$_} }
}
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #REXX | REXX | /*REXX program converts a metric or old Russian length to various other lengths. */
numeric digits 200 /*lots of digits. */
/*──translation───*/
/*tip, top */ vershok = 22.492971 /*1.75 inch. */
/*palm, quarter */ piad = vershok / 4 /*(also) chetvert.*/
/*yard */ arshin = vershok / 16
/*fathom */ sazhen = arshin / 3
/*turn (of a plow)*/ verst = sazhen / 500 /*(also) a versta.*/
/*mile */ milia = verst / 1.5
/*inch */ diuym = arshin * 28
/*foot */ fut = diuym / 12 /*sounds like foot*/
/*line */ liniya = diuym * 10
/*point */ tochka = diuym * 100
KM= 1000; CM=100 /*define a couple of metric multipliers*/
sw= linesize() -1 /*get the linesize (screen width) - 1.*/
parse arg N what _ __ /*obtain the user's input from the C.L.*/
if N=='' then call err 'no arguments specified.'
if \datatype(N, 'N') then call err 'units not numeric: ' N
if _\=='' then call err 'too many arguments specified: ' _ __
n= n / 1 /*normalize it (004──►4 7.──►7, etc.*/
if what=='' then what= 'meters'; whatU= what /*None specified? Then assume meters. */
upper whatU /*an uppercase version for ABBREV bif. */
select /* [↓] convert the length ───► meters.*/
when abbrev('METRES' , whatU ) |,
abbrev('METERS' , whatU ) then m= N
when abbrev('KILOMETRES' , whatU, 2 ) |,
abbrev('KILOMETERS' , whatU, 2 ) |,
abbrev('KMS' , whatU, ) then m= N * KM
when abbrev('CENTIMETRES', whatU, 2 ) |,
abbrev('CENTIMETERS', whatU, 2 ) |,
abbrev('CMS' , whatU, 2 ) then m= N / CM
when abbrev('ARSHINS' , whatU ) then m= N / arshin
when abbrev('DIUYM' , whatU ) then m= N / diuym
when abbrev('FUT' , whatU ) then m= N / fut
when abbrev('LINIYA' , whatU ) then m= N / liniya
when abbrev('PIADS' , whatU ) |,
abbrev('CHETVERTS' , whatU, 2 ) then m= N / piad
when abbrev('SAZHENS' , whatU ) then m= N / sazhen
when abbrev('TOCHKA' , whatU ) then m= N / tochka
when abbrev('VERSHOKS' , whatU, 5 ) then m= N / vershok
when abbrev('VERSTAS' , whatU, 5 ) |,
abbrev('VERSTS' , whatU, 2 ) then m= N / verst
when abbrev('MILIA' , whatU, 2 ) then m= N / milia
otherwise call err 'invalid measure name: ' what
end /*select*/
say centre('metric', sw, "─")
call tell m / KM , 'kilometer'
call tell m , 'meter'
call tell m * CM , 'centimeter'
say centre('old Russian', sw, "─")
call tell m * milia , 'milia'
call tell m * verst , 'verst'
call tell m * sazhen , 'sazhen'
call tell m * arshin , 'arshin'
call tell m * fut , 'fut'
call tell m * piad , 'piad'
call tell m * vershok , 'vershok'
call tell m * diuym , 'diuym'
call tell m * liniya , 'liniya'
call tell m * tochka , 'tochka' /* ◄─── TELL shows eight decimal digits*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say center(' error ', sw % 2, "*"); do j=1 to arg(); say arg(j); end; exit 13
s: if arg(1)=1 then return arg(3); return word( arg(2) 's', 1) /*plurals.*/
tell: parse arg $; numeric digits 8; $= $ / 1; say right($, 40) arg(2)s($); return/*REXX program converts a metric or old Russian length to various other lengths. */
numeric digits 200 /*lots of digits. */
/*──translation───*/
/*tip, top */ vershok = 22.492971 /*1.75 inch. */
/*palm, quarter */ piad = vershok / 4 /*(also) chetvert.*/
/*yard */ arshin = vershok / 16
/*fathom */ sazhen = arshin / 3
/*turn (of a plow)*/ verst = sazhen / 500 /*(also) a versta.*/
/*mile */ milia = verst / 1.5
/*inch */ diuym = arshin * 28
/*foot */ fut = diuym / 12 /*sounds like foot*/
/*line */ liniya = diuym * 10
/*point */ tochka = diuym * 100
KM= 1000; CM=100 /*define a couple of metric multipliers*/
sw= linesize() -1 /*get the linesize (screen width) - 1.*/
parse arg N what _ __ /*obtain the user's input from the C.L.*/
if N=='' then call err 'no arguments specified.'
if \datatype(N, 'N') then call err 'units not numeric: ' N
if _\=='' then call err 'too many arguments specified: ' _ __
n= n / 1 /*normalize it (004──►4 7.──►7, etc.*/
if what=='' then what= 'meters'; whatU= what /*None specified? Then assume meters. */
upper whatU /*an uppercase version for ABBREV bif. */
select /* [↓] convert the length ───► meters.*/
when abbrev('METRES' , whatU ) |,
abbrev('METERS' , whatU ) then m= N
when abbrev('KILOMETRES' , whatU, 2 ) |,
abbrev('KILOMETERS' , whatU, 2 ) |,
abbrev('KMS' , whatU, ) then m= N * KM
when abbrev('CENTIMETRES', whatU, 2 ) |,
abbrev('CENTIMETERS', whatU, 2 ) |,
abbrev('CMS' , whatU, 2 ) then m= N / CM
when abbrev('ARSHINS' , whatU ) then m= N / arshin
when abbrev('DIUYM' , whatU ) then m= N / diuym
when abbrev('FUT' , whatU ) then m= N / fut
when abbrev('LINIYA' , whatU ) then m= N / liniya
when abbrev('PIADS' , whatU ) |,
abbrev('CHETVERTS' , whatU, 2 ) then m= N / piad
when abbrev('SAZHENS' , whatU ) then m= N / sazhen
when abbrev('TOCHKA' , whatU ) then m= N / tochka
when abbrev('VERSHOKS' , whatU, 5 ) then m= N / vershok
when abbrev('VERSTAS' , whatU, 5 ) |,
abbrev('VERSTS' , whatU, 2 ) then m= N / verst
when abbrev('MILIA' , whatU, 2 ) then m= N / milia
otherwise call err 'invalid measure name: ' what
end /*select*/
say centre('metric', sw, "─")
call tell m / KM , 'kilometer'
call tell m , 'meter'
call tell m * CM , 'centimeter'
say centre('old Russian', sw, "─")
call tell m * milia , 'milia'
call tell m * verst , 'verst'
call tell m * sazhen , 'sazhen'
call tell m * arshin , 'arshin'
call tell m * fut , 'fut'
call tell m * piad , 'piad'
call tell m * vershok , 'vershok'
call tell m * diuym , 'diuym'
call tell m * liniya , 'liniya'
call tell m * tochka , 'tochka' /* ◄─── TELL shows eight decimal digits*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say center(' error ', sw % 2, "*"); do j=1 to arg(); say arg(j); end; exit 13
s: if arg(1)=1 then return arg(3); return word( arg(2) 's', 1) /*plurals.*/
tell: parse arg $; numeric digits 8; $= $ / 1; say right($, 40) arg(2)s($); return |
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.
| #Ol | Ol |
(import (lib gl))
(gl:set-window-title "Rosettacode OpenGL example")
(import (OpenGL version-1-0))
(glShadeModel GL_SMOOTH)
(glClearColor 0.3 0.3 0.3 1)
(glMatrixMode GL_PROJECTION)
(glLoadIdentity)
(glOrtho -30.0 30.0 -30.0 30.0 -30.0 30.0)
(gl:set-renderer (lambda (mouse)
(glClear GL_COLOR_BUFFER_BIT)
(glMatrixMode GL_MODELVIEW)
(glLoadIdentity)
(glTranslatef -15.0 -15.0 0.0)
(glBegin GL_TRIANGLES)
(glColor3f 1.0 0.0 0.0)
(glVertex2f 0.0 0.0)
(glColor3f 0.0 1.0 0.0)
(glVertex2f 30.0 0.0)
(glColor3f 0.0 0.0 1.0)
(glVertex2f 0.0 30.0)
(glEnd)
))
|
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
| #J | J | randLineBig=:3 :0
file=. boxopen y
r=. ''
n=. 1
size=. fsize file
blocksize=. 1e7
buffer=. ''
for_block. |: blocksize -~/\@(] <. [ * 0 1 +/i.@>.@%~) size do.
buffer=. buffer, fread file,<block
linends=. LF = buffer
lines=. linends <;.2 buffer
buffer=. buffer }.~ {: 1+I.linends
pick=. (0 ?@$~ #lines) < % n+i.#lines
if. 1 e. pick do.
r=. ({:I.pick) {:: lines
end.
n=. n+#lines
end.
r
) |
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
| #Java | Java | import java.util.Arrays;
import java.util.Random;
public class OneOfNLines {
static Random rand;
public static int oneOfN(int n) {
int choice = 0;
for(int i = 1; i < n; i++) {
if(rand.nextInt(i+1) == 0)
choice = i;
}
return choice;
}
public static void main(String[] args) {
int n = 10;
int trials = 1000000;
int[] bins = new int[n];
rand = new Random();
for(int i = 0; i < trials; i++)
bins[oneOfN(n)]++;
System.out.println(Arrays.toString(bins));
}
}
|
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
| #Phix | Phix | function increment(integer i, inc=1)
return i+inc
end function
?increment(5) -- shows 6
?increment(5,2) -- shows 7
|
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
| #Phixmonti | Phixmonti | def mypower
1 tolist flatten len
1 == if
1 get 2
else
2 get swap 1 get rot
endif
power
nip
enddef
"2 ^2 = " print 2 mypower print nl
"2 ^3 = " print 2 3 2 tolist mypower print |
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.
| #Lhogho | Lhogho | print [1 2] = [1 2]
print [1 2] = [1 2 3]
print [1 3] = [1 2]
print [1 2 3] = [1 2]
make "list1 [1 2 3 4 5 6]
make "list2 [1 2 3 4 5 7]
print :list1 = :list2 |
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.
| #Lua | Lua | function arraycompare(a, b)
for i = 1, #a do
if b[i] == nil then
return true
end
if a[i] ~= b[i] then
return a[i] < b[1]
end
end
return true
end |
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
| #Lambdatalk | Lambdatalk |
{def maxOrderedWords
{def isOrdered
{lambda {:w}
{W.equal? :w {W.sort before :w}}}}
{def getOrdered
{lambda {:w}
{if {isOrdered :w} then :w else}}}
{def pushOrdered
{lambda {:m :w}
{if {= {W.length :w} :m} then {br}:w else}}}
{def maxOrderedWords.i
{lambda {:sortedWords}
{let { {:orderedWords {S.map getOrdered :sortedWords}} }
{S.map {{lambda {:m :w} {pushOrdered :m :w}}
{max {S.map {lambda {:w} {W.length :w}}
:orderedWords}}}
:orderedWords}}}}
{lambda {:s}
{maxOrderedWords.i {S.replace else by el_se in :s}}}}
-> maxOrderedWords
{maxOrderedWords UNIX.DICT}
->
abbott
accent
accept
access
accost
almost
bellow
billow
biopsy
chilly
choosy
choppy
effort
floppy
glossy
knotty
|
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
| #PowerBASIC | PowerBASIC | FUNCTION isPalindrome (what AS STRING) AS LONG
DIM whatcopy AS STRING, chk AS STRING, tmp AS STRING * 1, L0 AS LONG
FOR L0 = 1 TO LEN(what)
tmp = UCASE$(MID$(what, L0, 1))
SELECT CASE tmp
CASE "A" TO "Z"
whatcopy = whatcopy & tmp
chk = tmp & chk
CASE "0" TO "9"
MSGBOX "Numbers are cheating! (""" & what & """)"
FUNCTION = 0
EXIT FUNCTION
END SELECT
NEXT
FUNCTION = ISTRUE((whatcopy) = chk)
END FUNCTION
FUNCTION PBMAIN () AS LONG
DATA "My dog has fleas", "Madam, I'm Adam.", "1 on 1", "In girum imus nocte et consumimur igni"
DIM L1 AS LONG, w AS STRING
FOR L1 = 1 TO DATACOUNT
w = READ$(L1)
IF ISTRUE(isPalindrome(w)) THEN
MSGBOX $DQ & w & """ is a palindrome"
ELSE
MSGBOX $DQ & w & """ is not a palindrome"
END IF
NEXT
END FUNCTION |
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
| #Icon_and_Unicon | Icon and Unicon | record num(val,err)
procedure main(a)
x1 := num(100.0, 1.1)
y1 := num(50.0, 1.2)
x2 := num(200.0, 2.2)
y2 := num(100.0, 2.3)
d := pow(add(pow(sub(x1,x2),2),pow(sub(y1,y2),2)),0.5)
write("d = [",d.val,", ",d.err,"]")
end
procedure add(a,b)
return (numeric(a)+numeric(b)) |
num(numeric(a)+b.val, b.err) |
num(a.val+numeric(b), a.err) |
num(a.val+b.val, (a.err^2 + b.err^2) ^ 0.5)
end
procedure sub(a,b)
return (numeric(a)-numeric(b)) |
num(numeric(a)-b.val, b.err) |
num(a.val-numeric(b), a.err) |
num(a.val-b.val, (a.err^2 + b.err^2) ^ 0.5)
end
procedure mul(a,b)
return (numeric(a)*numeric(b)) |
num(numeric(a)*b.val, abs(a*b.err)) |
num(a.val*numeric(b), abs(b*a.err)) |
num(f := a.val*b.val, ((f^2*((a.err/a.val)^2+(b.err/b.val)^2))^0.5))
end
procedure div(a,b)
return (numeric(a)/numeric(b)) |
num(numeric(a)/b.val, abs(a*b.err)) |
num(a.val/numeric(b), abs(b*a.err)) |
num(f := a.val/b.val, ((f^2*((a.err/a.val)^2+(b.err/b.val)^2))^0.5))
end
procedure pow(a,b)
return (numeric(a)^numeric(b)) |
num(f := a.val^numeric(b), abs(f*b*(a.err/a.val)))
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.
| #Haskell | Haskell | import System.IO
(BufferMode(..), getContents, hSetBuffering, stdin, stdout)
import Data.Char (isAlpha)
split :: String -> (String, String)
split = span isAlpha
parse :: String -> String
parse [] = []
parse l =
let (a, w) = split l
(b, x) = splitAt 1 w
(c, y) = split x
(d, z) = splitAt 1 y
in a <> b <> reverse c <> d <> parse z
main :: IO ()
main =
hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> getContents >>=
putStr . takeWhile (/= '.') . parse >>
putStrLn "." |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Integers_In_English is
type Spellable is range -999_999_999_999_999_999..999_999_999_999_999_999;
function Spell (N : Spellable) return String is
function Twenty (N : Spellable) return String is
begin
case N mod 20 is
when 0 => return "zero";
when 1 => return "one";
when 2 => return "two";
when 3 => return "three";
when 4 => return "four";
when 5 => return "five";
when 6 => return "six";
when 7 => return "seven";
when 8 => return "eight";
when 9 => return "nine";
when 10 => return "ten";
when 11 => return "eleven";
when 12 => return "twelve";
when 13 => return "thirteen";
when 14 => return "fourteen";
when 15 => return "fifteen";
when 16 => return "sixteen";
when 17 => return "seventeen";
when 18 => return "eighteen";
when others => return "nineteen";
end case;
end Twenty;
function Decade (N : Spellable) return String is
begin
case N mod 10 is
when 2 => return "twenty";
when 3 => return "thirty";
when 4 => return "forty";
when 5 => return "fifty";
when 6 => return "sixty";
when 7 => return "seventy";
when 8 => return "eighty";
when others => return "ninety";
end case;
end Decade;
function Hundred (N : Spellable) return String is
begin
if N < 20 then
return Twenty (N);
elsif 0 = N mod 10 then
return Decade (N / 10 mod 10);
else
return Decade (N / 10) & '-' & Twenty (N mod 10);
end if;
end Hundred;
function Thousand (N : Spellable) return String is
begin
if N < 100 then
return Hundred (N);
elsif 0 = N mod 100 then
return Twenty (N / 100) & " hundred";
else
return Twenty (N / 100) & " hundred and " & Hundred (N mod 100);
end if;
end Thousand;
function Triplet
( N : Spellable;
Order : Spellable;
Name : String;
Rest : not null access function (N : Spellable) return String
) return String is
High : Spellable := N / Order;
Low : Spellable := N mod Order;
begin
if High = 0 then
return Rest (Low);
elsif Low = 0 then
return Thousand (High) & ' ' & Name;
else
return Thousand (High) & ' ' & Name & ", " & Rest (Low);
end if;
end Triplet;
function Million (N : Spellable) return String is
begin
return Triplet (N, 10**3, "thousand", Thousand'Access);
end Million;
function Milliard (N : Spellable) return String is
begin
return Triplet (N, 10**6, "million", Million'Access);
end Milliard;
function Billion (N : Spellable) return String is
begin
return Triplet (N, 10**9, "milliard", Milliard'Access);
end Billion;
function Billiard (N : Spellable) return String is
begin
return Triplet (N, 10**12, "billion", Billion'Access);
end Billiard;
begin
if N < 0 then
return "negative " & Spell(-N);
else
return Triplet (N, 10**15, "billiard", Billiard'Access);
end if;
end Spell;
procedure Spell_And_Print(N: Spellable) is
Number: constant String := Spellable'Image(N);
Spaces: constant String(1 .. 20) := (others => ' '); -- 20 * ' '
begin
Ada.Text_IO.Put_Line(Spaces(Spaces'First .. Spaces'Last-Number'Length)
& Number & ' ' & Spell(N));
end Spell_And_Print;
Samples: constant array (Natural range <>) of Spellable
:= (99, 300, 310, 1_501, 12_609, 512_609, 43_112_609, 77_000_112_609,
2_000_000_000_100, 999_999_999_999_999_999,
0, -99, -1501, -77_000_112_609, -123_456_789_987_654_321);
begin
for I in Samples'Range loop
Spell_And_Print(Samples(I));
end loop;
end Integers_In_English; |
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
| #Astro | Astro | print '# Number reversal game'
var data, trials = list(1..9), 0
while data == sort data:
random.shuffle data
while data != sort data:
trials += 1
flip = int input '#${trials}: LIST: ${join data} Flip how many?: '
data[:flip] = reverse data[:flip]
print '\nYou took ${trials} attempts to put digits in order!' |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program nullobj.s */
/* Constantes */
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szCarriageReturn: .asciz "\n"
szMessResult: .asciz "Value is null.\n" @ message result
iPtrObjet: .int 0 @ objet pointer
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main: @ entry of program
ldr r0,iAdriPtrObjet @ load pointer address
ldr r0,[r0] @ load pointer value
cmp r0,#0 @ is null ?
ldreq r0,iAdrszMessResult @ yes -> display message
bleq affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @ restaur 2 registers
mov r7, #EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdriPtrObjet: .int iPtrObjet
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
|
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.
| #C | C | #include <stdio.h>
#include <string.h>
char trans[] = "___#_##_";
#define v(i) (cell[i] != '_')
int evolve(char cell[], char backup[], int len)
{
int i, diff = 0;
for (i = 0; i < len; i++) {
/* use left, self, right as binary number bits for table index */
backup[i] = trans[ v(i-1) * 4 + v(i) * 2 + v(i + 1) ];
diff += (backup[i] != cell[i]);
}
strcpy(cell, backup);
return diff;
}
int main()
{
char c[] = "_###_##_#_#_#_#__#__\n",
b[] = "____________________\n";
do { printf(c + 1); } while (evolve(c + 1, b + 1, sizeof(c) - 3));
return 0;
} |
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.
| #C.2B.2B | C++ | // the integration routine
template<typename Method, typename F, typename Float>
double integrate(F f, Float a, Float b, int steps, Method m)
{
double s = 0;
double h = (b-a)/steps;
for (int i = 0; i < steps; ++i)
s += m(f, a + h*i, h);
return h*s;
}
// methods
class rectangular
{
public:
enum position_type { left, middle, right };
rectangular(position_type pos): position(pos) {}
template<typename F, typename Float>
double operator()(F f, Float x, Float h) const
{
switch(position)
{
case left:
return f(x);
case middle:
return f(x+h/2);
case right:
return f(x+h);
}
}
private:
const position_type position;
};
class trapezium
{
public:
template<typename F, typename Float>
double operator()(F f, Float x, Float h) const
{
return (f(x) + f(x+h))/2;
}
};
class simpson
{
public:
template<typename F, typename Float>
double operator()(F f, Float x, Float h) const
{
return (f(x) + 4*f(x+h/2) + f(x+h))/6;
}
};
// sample usage
double f(double x) { return x*x; }
// inside a function somewhere:
double rl = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::left));
double rm = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::middle));
double rr = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::right));
double t = integrate(f, 0.0, 1.0, 10, trapezium());
double s = integrate(f, 0.0, 1.0, 10, simpson()); |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #jq | jq | def risesEqualsFalls:
. as $n
| if . < 10 then true
else {rises: 0, falls: 0, prev: -1, n: $n}
| until (.n <= 0;
(.n % 10 ) as $d
| if .prev >= 0
then if $d < .prev then .rises += 1
elif $d > .prev then .falls += 1
else .
end
else .
end
| .prev = $d
| .n = ((.n/10)|floor) )
| .rises == .falls
end ;
def A296712: range(1; infinite) | select(risesEqualsFalls);
# Override jq's incorrect definition of nth/2
# Emit the $n-th value of the stream, counting from 0; or emit nothing
def nth($n; s):
if $n < 0 then error("nth/2 doesn't support negative indices")
else label $out
| foreach s as $x (-1; .+1; select(. >= $n) | $x, break $out)
end;
# The tasks
"First 200:",
[limit(200; A296712)],
"\nThe 10 millionth number in the sequence is \(
nth(1e7 - 1; A296712))" |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Julia | Julia | using Lazy
function rises_and_falls(n)
if n < 10
return 0, 0
end
lastr, rises, falls = n % 10, 0, 0
while n != 0
n, r = divrem(n, 10)
if r > lastr
falls += 1
elseif r < lastr
rises += 1
end
lastr = r
end
return rises, falls
end
isA296712(x) = ((a, b) = rises_and_falls(x); return a == b)
function genA296712(N, M)
A296712 = filter(isA296712, Lazy.range(1));
j = 0
for i in take(200, A296712)
j += 1
print(lpad(i, 4), j % 20 == 0 ? "\n" : "")
end
for i in take(M, A296712)
j = i
end
println("\nThe $M-th number in sequence A296712 is $j.")
end
genA296712(200, 10_000_000)
|
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #MAD | MAD | NORMAL MODE IS INTEGER
VECTOR VALUES FMT = $I8,1H:,I9*$
INTERNAL FUNCTION(NUM)
ENTRY TO RISFAL.
N=NUM
DEPTH = 0
DIGA = N-(N/10)*10
N = N/10
LOOP WHENEVER N.E.0, FUNCTION RETURN DEPTH.E.0
DIGB = DIGA
DIGA = N-(N/10)*10
N = N/10
WHENEVER DIGA.L.DIGB, DEPTH=DEPTH-1
WHENEVER DIGA.G.DIGB, DEPTH=DEPTH+1
TRANSFER TO LOOP
END OF FUNCTION
I=0
J=0
LOOP J=J+1
WHENEVER .NOT.RISFAL.(J), TRANSFER TO LOOP
I=I+1
WHENEVER I.LE.200, PRINT FORMAT FMT, I, J
WHENEVER I.L.10000000, TRANSFER TO LOOP
PRINT FORMAT FMT, I, J
END OF PROGRAM |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[EqualRisesAndFallsQ]
EqualRisesAndFallsQ[n_Integer] := Total[Sign[Differences[IntegerDigits[n]]]] == 0
Take[Select[Range[1000], EqualRisesAndFallsQ], 200]
valid = 0;
Dynamic[{i, valid}]
Do[
If[EqualRisesAndFallsQ[i],
valid += 1;
If[valid == 10^7, Print[i]; Break[]]
]
,
{i, 50 10^6}
] |
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}
| #JavaScript | JavaScript |
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
const M = n => (n - (n % 2 !== 0)) / 2;
const gaussLegendre = (fn, a, b, n) => {
// coefficients of the Legendre polynomial
const coef = [...Array(M(n) + 1)].map((v, m) => v = (-1) ** m * factorial(2 * n - 2 * m) / (2 ** n * factorial(m) * factorial(n - m) * factorial(n - 2 * m)));
// the polynomial function
const f = x => coef.map((v, i) => v * x ** (n - 2 * i)).reduce((sum, item) => sum + item, 0);
const terms = coef.length - (n % 2 === 0);
// coefficients of the derivative polybomial
const dcoef = [...Array(terms)].map((v, i) => v = n - 2 * i).map((val, i) => val * coef[i]);
// the derivative polynomial function
const df = x => dcoef.map((v, i) => v * x ** (n - 1 - 2 * i)).reduce((sum, item) => sum + item, 0);
const guess = [...Array(n)].map((v, i) => Math.cos(Math.PI * (i + 1 - 1 / 4) / (n + 1 / 2)));
// Newton Raphson
const roots = guess.map(xo => [...Array(100)].reduce(x => x - f(x) / df(x), xo));
const weights = roots.map(v => 2 / ((1 - v ** 2) * df(v) ** 2));
return (b - a) / 2 * weights.map((v, i) => v * fn((b - a) * roots[i] / 2 + (a + b) / 2)).reduce((sum, item) => sum + item, 0);
}
console.log(gaussLegendre(x => Math.exp(x), -3, 3, 5));
|
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Oz | Oz | {
package Greeting;
sub new {
my $v = "Hello world!\n";
bless \$v, shift;
};
sub stringify {
${shift()};
};
};
{
package Son::of::Greeting;
use base qw(Greeting); # inherit methods
sub new { # overwrite method of super class
my $v = "Hello world from Junior!\n";
bless \$v, shift;
};
};
{
use Storable qw(store retrieve);
package main;
my $g1 = Greeting->new;
my $s1 = Son::of::Greeting->new;
print $g1->stringify;
print $s1->stringify;
store $g1, 'objects.dat';
my $g2 = retrieve 'objects.dat';
store $s1, 'objects.dat';
my $s2 = retrieve 'objects.dat';
print $g2->stringify;
print $s2->stringify;
}; |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Perl | Perl | {
package Greeting;
sub new {
my $v = "Hello world!\n";
bless \$v, shift;
};
sub stringify {
${shift()};
};
};
{
package Son::of::Greeting;
use base qw(Greeting); # inherit methods
sub new { # overwrite method of super class
my $v = "Hello world from Junior!\n";
bless \$v, shift;
};
};
{
use Storable qw(store retrieve);
package main;
my $g1 = Greeting->new;
my $s1 = Son::of::Greeting->new;
print $g1->stringify;
print $s1->stringify;
store $g1, 'objects.dat';
my $g2 = retrieve 'objects.dat';
store $s1, 'objects.dat';
my $s2 = retrieve 'objects.dat';
print $g2->stringify;
print $s2->stringify;
}; |
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
| #Draco | Draco | proc nonrec animal(byte n) *char:
case n
incase 0: "fly"
incase 1: "spider"
incase 2: "bird"
incase 3: "cat"
incase 4: "dog"
incase 5: "goat"
incase 6: "cow"
incase 7: "horse"
esac
corp
proc nonrec line(byte n) *char:
case n
incase 0: "I don't know why she swallowed that fly,\r\n"
"Perhaps she'll die.\r\n"
incase 1: "That wiggled and jiggled and tickled inside her,"
incase 2: "How absurd to swallow a bird,"
incase 3: "Imagined that, she swallowed a cat,"
incase 4: "What a hog to swallow a dog,"
incase 5: "She just opened her throat and swallowed that goat,"
incase 6: "I don't know how she swallowed that cow,"
incase 7: "She's dead, of course."
esac
corp
proc nonrec verse(byte n) void:
byte a;
writeln("There was an old lady who swallowed a ", animal(n), ", ");
writeln(line(n));
if n/=7 then
for a from n downto 1 do
writeln("She swallowed the ", animal(a),
" to catch the ", animal(a-1), ", ");
if a <= 2 then writeln(line(a-1)) fi
od
fi
corp
proc nonrec main() void:
byte n;
for n from 0 upto 7 do verse(n) od
corp |
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
| #Elena | Elena | import extensions;
const Creatures = new string[]{"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"};
const Comments = new string[]
{
"I don't know why she swallowed that fly"$10"Perhaps she'll die",
"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"
};
public program()
{
for(int i := 0, i < Creatures.Length, i += 1)
{
console
.printLineFormatted("There was an old lady who swallowed a {0}",Creatures[i])
.printLine(Comments[i]);
if(i != 0 && i != Creatures.Length - 1)
{
for(int j := i, j > 0, j -= 1)
{
console.printLineFormatted("She swallowed the {0} to catch the {1}",Creatures[j],Creatures[j - 1])
};
console.writeLine(Comments[0])
};
console.writeLine()
}
} |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Ring | Ring |
# Project : Old Russian measure of length
decimals(7)
units = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer"]
convs = [0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676,
1, 100, 10000]
yn = "y"
unit = 1
p = 1
while yn != "n"
for i = 1 to 13
see "" + i + " " + units[i] + nl
next
see nl
see "please choose a unit 1 to 13 : "
give unit
see nl
see "now enter a value in that unit : "
give value
see nl
see "the equivalent in the remaining units is : "
see nl
for i = 1 to 13
if i = unit
loop
ok
see "" + units[i] + " : " + (value * convs[number(unit)] / convs[i]) + nl
next
see nl
while yn = "y" or yn = "n"
see "do another one y/n : "
give yn
yn = lower(yn)
end
end
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Ruby | Ruby | module Distances
RATIOS =
{arshin: 0.7112, centimeter: 0.01, diuym: 0.0254,
fut: 0.3048, kilometer: 1000.0, liniya: 0.00254,
meter: 1.0, milia: 7467.6, piad: 0.1778,
sazhen: 2.1336, tochka: 0.000254, vershok: 0.04445,
versta: 1066.8}
def self.method_missing(meth, arg)
from, to = meth.to_s.split("2").map(&:to_sym)
raise NoMethodError, meth if ([from,to]-RATIOS.keys).size > 0
RATIOS[from] * arg / RATIOS[to]
end
def self.print_others(name, num)
puts "#{num} #{name} ="
RATIOS.except(name.to_sym).each {|k,v| puts "#{ (1.0 / v*num)} #{k}" }
end
end
Distances.print_others("meter", 2)
puts
p Distances.meter2centimeter(3)
p Distances.arshin2meter(1)
p Distances.versta2kilometer(20) # en Hoeperdepoep zat op de stoep
# 13*13 = 169 methods supported, but not:
p Distances.mile2piad(1)
|
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.
| #OxygenBasic | OxygenBasic |
title="Rotating Triangle"
include "OpenglSceneFrame.inc"
sub Initialize(sys hWnd)
'=======================
SetTimer hWnd,1,10,NULL
end sub
'
sub Scene(sys hWnd)
'==================
'
static single ang1,angi1=1
'
glClearColor 0.3, 0.3, 0.5, 0
glClear GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT
'
glLoadIdentity
'
'
gltranslatef 0.0, 0.0, -4.0
glrotatef ang1, 0.0, 0.0, 1.0
'
glBegin GL_TRIANGLES
glColor3f 1.0, 0.0, 0.0 : glVertex3f 0.0, 1.0, 0.0
glColor3f 0.0, 1.0, 0.0 : glVertex3f -1.0, -1.0, 0.0
glColor3f 0.0, 0.0, 1.0 : glVertex3f 1.0, -1.0, 0.0
glEnd
'
'UPDATE ROTATION ANGLES
'
ang1+=angi1
if ang1>360 then ang1-=360
'
end sub
sub Release(sys hwnd)
'====================
killTimer hwnd, 1
end sub
|
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.
| #Pascal | Pascal | Program OpenGLDemo;
uses
SysUtils,
ctypes,
gl,
Glut;
procedure paint; cdecl;
begin
glClearColor(0.3,0.3,0.3,0.0);
glClear(GL_COLOR_BUFFER_BIT or 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(0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(30.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0.0, 30.0);
glEnd();
glFlush();
end;
procedure reshape(width, height: cint); cdecl;
begin
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0);
glMatrixMode(GL_MODELVIEW);
end;
begin
glutInit(@argc, @argv);
glutInitWindowSize(640, 480);
glutCreateWindow('Triangle');
glutDisplayFunc(@paint);
glutReshapeFunc(@reshape);
glutMainLoop();
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
| #jq | jq |
export LC_ALL=C
< /dev/random tr -cd '0-9' | fold -w 4 | jq -Mnr -f program.jq
|
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
| #Julia | Julia |
const N = 10
const GOAL = 10^6
function oneofn{T<:Integer}(n::T)
0 < n || error("n = ", n, ", but it should be positive.")
oon = 1
for i in 2:n
rand(1:i) == 1 || continue
oon = i
end
return oon
end
nhist = zeros(Int, N)
for i in 1:GOAL
nhist[oneofn(N)] += 1
end
println("Simulating oneofn(", N, ") ", GOAL, " times:")
for i in 1:N
println(@sprintf " %2d => %6d" i nhist[i])
end
|
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
| #PicoLisp | PicoLisp | (de sortTable (Tbl . @)
(let (Ordering prog Column 1 Reverse NIL) # Set defaults
(bind (rest) # Bind optional params
(setq Tbl
(by '((L) (Ordering (get L Column)))
sort
Tbl ) )
(if Reverse (flip Tbl) Tbl) ) ) ) |
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
| #Python | Python | >>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)
>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a" "b" "c"
"" "q" "z"
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
"" "q" "z"
"a" "b" "c"
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a" "b" "c"
"" "q" "z"
>>> printtable( sorttable(data, column=1) )
"a" "b" "c"
"" "q" "z"
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
"" "q" "z"
"a" "b" "c"
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a" "b" "c"
"" "q" "z"
>>> |
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.
| #Maple | Maple | orderLists := proc(num1,num2)
local len1, len2,i:
len1,len2 := numelems(num1),numelems(num2):
for i to min(len1,len2) do
if num1[i] <> num2[i] then
return evalb(num1[i]<num2[i]):
end if:
end do:
return evalb(len1 < len2):
end proc: |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | order[List1_, List2_] := With[{
L1 = List1[[1 ;; Min @@ Length /@ {List1, List2}]],
L2 = List2[[1 ;; Min @@ Length /@ {List1, List2}]]
},
If [Thread[Order[L1, L2]] == 0,
Length[List1] < Length[List2],
Thread[Order[L1, L2]] == 1
]] |
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
| #Lang5 | Lang5 | : >string-index
"" split
"&'0123456789abcdefghijklmnopqrstuvwxyz" "" split
swap index collapse ;
: chars "" split length swap drop ;
: cr "\n" . ;
: nip swap drop ;
: ordered?
dup grade subscript != '+ reduce if 0 else -1 then ;
: filtering
[] '_ set
0 do read
2dup chars
<=
if dup >string-index ordered?
if 2dup chars
<
if nip dup chars swap
[] '_ set
then
_ swap append '_ set
'. . # progress dot
else drop
then
else drop
then
eof if break then loop
cr _ . cr
;
: ordered-words
'< 'unixdict.txt open 'fh set
fh fin filtering fh close ;
ordered-words |
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
| #Lasso | Lasso | local(f = file('unixdict.txt'), words = array, ordered = array, maxleng = 0)
#f->dowithclose => {
#f->foreachLine => {
#words->insert(#1)
}
}
with w in #words
do => {
local(tosort = #w->asString->values)
#tosort->sort
if(#w->asString == #tosort->join('')) => {
#ordered->insert(#w->asString)
#w->asString->size > #maxleng ? #maxleng = #w->asString->size
}
}
with w in #ordered
where #w->size == #maxleng
do => {^ #w + '\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
| #PowerShell | PowerShell |
Function Test-Palindrome( [String] $Text ){
$CharArray = $Text.ToCharArray()
[Array]::Reverse($CharArray)
$Text -eq [string]::join('', $CharArray)
}
|
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
| #J | J | num=: {."1
unc=: {:@}."1 : ,.
dist=: +/&.:*: |
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
| #Java | Java | public class Approx {
private double value;
private double error;
public Approx(){this.value = this.error = 0;}
public Approx(Approx b){
this.value = b.value;
this.error = b.error;
}
public Approx(double value, double error){
this.value = value;
this.error = error;
}
public Approx add(Approx b){
value+= b.value;
error = Math.sqrt(error * error + b.error * b.error);
return this;
}
public Approx add(double b){
value+= b;
return this;
}
public Approx sub(Approx b){
value-= b.value;
error = Math.sqrt(error * error + b.error * b.error);
return this;
}
public Approx sub(double b){
value-= b;
return this;
}
public Approx mult(Approx b){
double oldVal = value;
value*= b.value;
error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
(b.error*b.error) / (b.value*b.value));
return this;
}
public Approx mult(double b){
value*= b;
error = Math.abs(b * error);
return this;
}
public Approx div(Approx b){
double oldVal = value;
value/= b.value;
error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
(b.error*b.error) / (b.value*b.value));
return this;
}
public Approx div(double b){
value/= b;
error = Math.abs(b * error);
return this;
}
public Approx pow(double b){
double oldVal = value;
value = Math.pow(value, b);
error = Math.abs(value * b * (error / oldVal));
return this;
}
@Override
public String toString(){return value+"±"+error;}
public static void main(String[] args){
Approx x1 = new Approx(100, 1.1);
Approx y1 = new Approx(50, 1.2);
Approx x2 = new Approx(200, 2.2);
Approx y2 = new Approx(100, 2.3);
x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);
System.out.println(x1);
}
} |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every OddWord(!["what,is,the;meaning,of:life.",
"we,are;not,in,kansas;any,more."])
end
procedure OddWord(stream) #: wrapper for demonstration
write("Input stream: ",stream)
writes("Output stream: ") & eWord(create !stream,'.,;:') & write()
end
procedure eWord(stream,marks) #: handle even words
repeat {
repeat
writes(@stream) ? if ="." then return else if any(marks) then break
if writes(oWord(stream,marks)) == '.' then return
}
end
procedure oWord(stream,marks) #: handle odd words (reverse)
if any(marks,s := @stream) then return s
return 1(oWord(stream,marks), writes(s))
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.
| #ALGOL_68 | ALGOL 68 | PROC number words = (INT n)STRING:(
# returns a string representation of n in words. Currently
deals with anything from 0 to 999 999 999. #
[]STRING digits = []STRING
("zero","one","two","three","four","five","six","seven","eight","nine")[@0];
[]STRING teens = []STRING
("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen")[@0];
[]STRING decades = []STRING
("twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety")[@2];
PROC three digits = (INT n)STRING: (
# does the conversion for n from 0 to 999. #
INT tens = n MOD 100 OVER 10;
INT units = n MOD 10;
(n >= 100|digits[n OVER 100] + " " + "hundred" + (n MOD 100 /= 0|" and "|"")|"") +
(tens /= 0|(tens = 1|teens[units]|decades[tens] + (units /= 0|"-"|""))|"") +
(units /= 0 AND tens /= 1 OR n = 0|digits[units]|"")
);
INT m = n OVER 1 000 000;
INT k = n MOD 1 000 000 OVER 1000;
INT u = n MOD 1000;
(m /= 0|three digits(m) + " million"|"") +
(m /= 0 AND (k /= 0 OR u >= 100)|", "|"") +
(k /= 0|three digits(k) + " thousand"|"") +
((m /= 0 OR k /= 0) AND u > 0 AND u < 100|" and " |: k /= 0 AND u /= 0|", "|"") +
(u /= 0 OR n = 0|three digits(u)|"")
);
on logical file end(stand in, (REF FILE f)BOOL: GOTO stop iteration);
on value error(stand in, (REF FILE f)BOOL: GOTO stop iteration);
DO # until user hits EOF #
INT n;
print("n? ");
read((n, new line));
print((number words(n), new line))
OD;
stop iteration:
SKIP |
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
| #AutoHotkey | AutoHotkey | ; Submitted by MasterFocus --- http://tiny.cc/iTunis
ScrambledList := CorrectList := "1 2 3 4 5 6 7 8 9" ; Declare two identical correct sequences
While ( ScrambledList = CorrectList )
Sort, ScrambledList, Random D%A_Space% ; Shuffle one of them inside a While-loop to ensure it's shuffled
Attempts := 0
While ( ScrambledList <> CorrectList ) ; Repeat until the sequence is correct
{
InputBox, EnteredNumber, Number Reversal Game, Attempts so far: %Attempts%`n`nCurrent sequence: %ScrambledList%`n`nHow many numbers (from the left) should be flipped?, , 400, 200
If ErrorLevel
ExitApp ; Exit if user presses ESC or Cancel
If EnteredNumber is not integer
Continue ; Discard attempt if entered number is not an integer
If ( EnteredNumber <= 1 )
Continue ; Discard attempt if entered number is <= 1
Attempts++ ; Increase the number of attempts
; Reverse the first part of the string and add the second part
; The entered number is multiplied by 2 to deal with the spaces
ScrambledList := Reverse(SubStr(ScrambledList,1,(EnteredNumber*2)-1)) SubStr(ScrambledList,EnteredNumber*2)
}
MsgBox, You took %Attempts% attempts to get the correct sequence. ; Final message
Return
;-------------------
Reverse(Str) ; Auxiliar function (flips a string)
{
Loop, Parse, Str
Out := A_LoopField Out
Return Out
} |
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.
| #Arturo | Arturo | v: null
if v=null -> print "got NULL!" |
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.
| #AutoHotkey | AutoHotkey | If (object == null)
MsgBox, object is null |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
const int n_iter = 10;
static int[] f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 };
public static void Main (string[] args)
{
for( int i=0; i<f.Length; i++ )
Console.Write( f[i]==0 ? "-" : "#" );
Console.WriteLine("");
int[] g = new int[f.Length];
for( int n=n_iter; n!=0; n-- )
{
for( int i=1; i<f.Length-1; i++ )
{
if ( (f[i-1] ^ f[i+1]) == 1 ) g[i] = f[i];
else if ( f[i] == 0 && (f[i-1] & f[i+1]) == 1 ) g[i] = 1;
else g[i] = 0;
}
g[0] = ( (f[0] & f[1]) == 1 ) ? 1 : 0;
g[g.Length-1] = ( (f[f.Length-1] & f[f.Length-2]) == 1 ) ? 1 : 0;
int[] tmp = f;
f = g;
g = tmp;
for( int i=0; i<f.Length; i++ )
Console.Write( f[i]==0 ? "-" : "#" );
Console.WriteLine("");
}
}
}
} |
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.
| #Chapel | Chapel |
proc f1(x:real):real {
return x**3;
}
proc f2(x:real):real {
return 1/x;
}
proc f3(x:real):real {
return x;
}
proc leftRectangleIntegration(a: real, b: real, N: int, f): real{
var h: real = (b - a)/N;
var sum: real = 0.0;
var x_n: real;
for n in 0..N-1 {
x_n = a + n * h;
sum = sum + f(x_n);
}
return h * sum;
}
proc rightRectangleIntegration(a: real, b: real, N: int, f): real{
var h: real = (b - a)/N;
var sum: real = 0.0;
var x_n: real;
for n in 0..N-1 {
x_n = a + (n + 1) * h;
sum = sum + f(x_n);
}
return h * sum;
}
proc midpointRectangleIntegration(a: real, b: real, N: int, f): real{
var h: real = (b - a)/N;
var sum: real = 0.0;
var x_n: real;
for n in 0..N-1 {
x_n = a + (n + 0.5) * h;
sum = sum + f(x_n);
}
return h * sum;
}
proc trapezoidIntegration(a: real(64), b: real(64), N: int(64), f): real{
var h: real(64) = (b - a)/N;
var sum: real(64) = f(a) + f(b);
var x_n: real(64);
for n in 1..N-1 {
x_n = a + n * h;
sum = sum + 2.0 * f(x_n);
}
return (h/2.0) * sum;
}
proc simpsonsIntegration(a: real(64), b: real(64), N: int(64), f): real{
var h: real(64) = (b - a)/N;
var sum: real(64) = f(a) + f(b);
var x_n: real(64);
for n in 1..N-1 by 2 {
x_n = a + n * h;
sum = sum + 4.0 * f(x_n);
}
for n in 2..N-2 by 2 {
x_n = a + n * h;
sum = sum + 2.0 * f(x_n);
}
return (h/3.0) * sum;
}
var exact:real;
var calculated:real;
writeln("f(x) = x**3 with 100 steps from 0 to 1");
exact = 0.25;
calculated = leftRectangleIntegration(a = 0.0, b = 1.0, N = 100, f = f1);
writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = rightRectangleIntegration(a = 0.0, b = 1.0, N = 100, f = f1);
writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = midpointRectangleIntegration(a = 0.0, b = 1.0, N = 100, f = f1);
writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = trapezoidIntegration(a = 0.0, b = 1.0, N = 100, f = f1);
writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = simpsonsIntegration(a = 0.0, b = 1.0, N = 100, f = f1);
writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
writeln();
writeln("f(x) = 1/x with 1000 steps from 1 to 100");
exact = 4.605170;
calculated = leftRectangleIntegration(a = 1.0, b = 100.0, N = 1000, f = f2);
writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = rightRectangleIntegration(a = 1.0, b = 100.0, N = 1000, f = f2);
writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = midpointRectangleIntegration(a = 1.0, b = 100.0, N = 1000, f = f2);
writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = trapezoidIntegration(a = 1.0, b = 100.0, N = 1000, f = f2);
writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = simpsonsIntegration(a = 1.0, b = 100.0, N = 1000, f = f2);
writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
writeln();
writeln("f(x) = x with 5000000 steps from 0 to 5000");
exact = 12500000;
calculated = leftRectangleIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3);
writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = rightRectangleIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3);
writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = midpointRectangleIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3);
writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = trapezoidIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3);
writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = simpsonsIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3);
writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
writeln();
writeln("f(x) = x with 6000000 steps from 0 to 6000");
exact = 18000000;
calculated = leftRectangleIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3);
writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = rightRectangleIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3);
writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = midpointRectangleIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3);
writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = trapezoidIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3);
writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
calculated = simpsonsIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3);
writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact));
writeln();
|
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Nim | Nim | import strutils
func insequence(n: Positive): bool =
## Return true if "n" is in the sequence.
if n < 10: return true
var diff = 0
var prev = n mod 10
var n = n div 10
while n != 0:
let digit = n mod 10
if digit < prev: inc diff
elif digit > prev: dec diff
prev = digit
n = n div 10
result = diff == 0
iterator a297712(): (int, int) =
## Yield the positions and the numbers of the sequence.
var n = 1
var pos = 0
while true:
if n.insequence:
inc pos
yield (pos, n)
inc n
echo "First 200 numbers in the sequence:"
for (pos, n) in a297712():
if pos <= 200:
stdout.write ($n).align(3), if pos mod 20 == 0: '\n' else: ' '
elif pos == 10_000_000:
echo "\nTen millionth number in the sequence: ", n
break |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
sub rf
{
local $_ = shift;
my $sum = 0;
$sum += $1 <=> $2 while /(.)(?=(.))/g;
$sum
}
my $count = 0;
my $n = 0;
my @numbers;
while( $count < 200 )
{
rf(++$n) or $count++, push @numbers, $n;
}
print "first 200: @numbers\n" =~ s/.{1,70}\K\s/\n/gr;
$count = 0;
$n = 0;
while( $count < 10e6 )
{
rf(++$n) or $count++;
}
print "\n10,000,000th number: $n\n"; |
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}
| #Julia | Julia | using LinearAlgebra
function gauss(a, b, N)
λ, Q = eigen(SymTridiagonal(zeros(N), [n / sqrt(4n^2 - 1) for n = 1:N-1]))
@. (λ + 1) * (b - a) / 2 + a, [2Q[1, i]^2 for i = 1:N] * (b - a) / 2
end |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Phix | Phix | include "builtins/serialize.e"
function randobj()
-- test function (generate some random garbage)
object res
if rand(10)<=3 then -- make sequence[1..3]
res = {}
for i=1 to rand(3) do
res = append(res,randobj())
end for
elsif rand(10)<=3 then -- make string
res = repeat('A'+rand(10),rand(10))
else
res = rand(10)/2 -- half int/half float
end if
return res
end function
object o1 = randobj(),
o2 = randobj(),
o3 = randobj()
pp({o1,o2,o3},{pp_Nest,1})
integer fh = open("objects.dat", "wb")
puts(fh, serialize(o1))
puts(fh, serialize(o2))
puts(fh, serialize(o3))
close(fh)
?"==="
fh = open("objects.dat", "rb")
?deserialize(fh)
?deserialize(fh)
?deserialize(fh)
close(fh)
{} = delete_file("objects.dat")
|
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
| #Elixir | Elixir | defmodule Old_lady do
@descriptions [
fly: "I don't know why S",
spider: "That wriggled and jiggled and tickled inside her.",
bird: "Quite absurd T",
cat: "Fancy that, S",
dog: "What a hog, S",
goat: "She opened her throat T",
cow: "I don't know how S",
horse: "She's dead, of course.",
]
def swallowed do
{descriptions, animals} = setup(@descriptions)
Enum.each(Enum.with_index(animals), fn {animal, idx} ->
IO.puts "There was an old lady who swallowed a #{animal}."
IO.puts descriptions[animal]
if animal == :horse, do: exit(:normal)
if idx > 0 do
Enum.each(idx..1, fn i ->
IO.puts "She swallowed the #{Enum.at(animals,i)} to catch the #{Enum.at(animals,i-1)}."
case Enum.at(animals,i-1) do
:spider -> IO.puts descriptions[:spider]
:fly -> IO.puts descriptions[:fly]
_ -> :ok
end
end)
end
IO.puts "Perhaps she'll die.\n"
end)
end
def setup(descriptions) do
animals = Keyword.keys(descriptions)
descs = Enum.reduce(animals, descriptions, fn animal, acc ->
Keyword.update!(acc, animal, fn d ->
case String.last(d) do
"S" -> String.replace(d, ~r/S$/, "she swallowed a #{animal}.")
"T" -> String.replace(d, ~r/T$/, "to swallow a #{animal}.")
_ -> d
end
end)
end)
{descs, animals}
end
end
Old_lady.swallowed |
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
| #Factor | Factor | USING: base85 compression.zlib ;
"c%1E4%WlIU5WMphn^P`UexSD=s^-?Jk$NVE7-Gs=fQ9_`T}Y~ggi4hvMSb{SX}vpQXJ;^Yqok7%xd(0
mjR3>N1W_UQ$c@1$1#sAzsbTkHfHerT%K*K_NT><Cl4r<3ZyEa}o#KN}<)twov|KQ@`BE=GXdzugXdWO
s-E}7At$_Vm9CX{KSX)nUpq1~~%N3WyS`ZLg9$IzcccWRh+KGlek2*-;TR+lUB6EZs0X5<&U()_dvQXE
CJ#gDjv>e5yCRDAFrgX{pAnt$DPGHxt*E9$RMRBPeRcoXvT{6xN%o=~9@t{fLM`G}XV^A6Hk!HSBn{YM
ylrFhv&t_M?=}Lzm^6W<+00(I)uM#EY@ah;z@Y)zDUk;J&o^8C<;g7LlMIS{^*(al_mjFQv=BG_DyZn
<}rUt#FCDtKB9S`Y4jg+0PuB?Qt-&(11p?caq^S=1C`$D1fa<y6|YD*77a{4949T_-MVet;6abaEn"
base85> 3215 <compressed> uncompress >string print |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Rust | Rust | use std::env;
use std::process;
use std::collections::HashMap;
fn main() {
let units: HashMap<&str, f32> = [("arshin",0.7112),("centimeter",0.01),("diuym",0.0254),("fut",0.3048),("kilometer",1000.0),("liniya",0.00254),("meter",1.0),("milia",7467.6),("piad",0.1778),("sazhen",2.1336),("tochka",0.000254),("vershok",0.04445),("versta",1066.8)].iter().cloned().collect();
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
eprintln!("A correct use is oldrus [amount] [unit].");
process::exit(1);
};
let length_float;
length_float = match args[1].parse::<f32>() {
Ok(length_float) => length_float,
Err(..) => 1 as f32,
};
let unit: &str = &args[2];
if ! units.contains_key(unit) {
let mut keys: Vec<&str> = Vec::new();
for i in units.keys() {
keys.push(i)
};
eprintln!("The correct units are: {}.", keys.join(", "));
process::exit(1);
};
println!("{} {} to:", length_float, unit);
for (lunit, length) in &units {
println!(" {}: {:?}", lunit, length_float * units.get(unit).unwrap() / length);
};
}
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Scala | Scala | import scala.collection.immutable.HashMap
object OldRussianLengths extends App {
private def measures = HashMap("tochka" -> 0.000254,
"liniya"-> 0.000254, "centimeter"-> 0.01, "diuym"-> 0.0254, "vershok"-> 0.04445,
"piad" -> 0.1778, "fut" -> 0.3048, "arshin"-> 0.7112, "meter" -> 1.0,
"sazhen"-> 2.1336, "kilometer" -> 1000.0, "versta"-> 1066.8, "milia" -> 7467.6
).withDefaultValue(Double.NaN)
if (args.length == 2 && args(0).matches("[+-]?\\d*(\\.\\d+)?")) {
val inputVal = measures(args(1))
def meters = args(0).toDouble * inputVal
if (!java.lang.Double.isNaN(inputVal)) {
printf("%s %s to: %n%n", args(0), args(1))
for (k <- measures) println(f"${k._1}%10s: ${meters / k._2}%g")
}
} else println("Please provide a number and unit on the command line.")
} |
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.
| #Perl | Perl | use OpenGL;
sub triangle {
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;
};
glpOpenWindow;
glMatrixMode GL_PROJECTION;
glLoadIdentity;
gluOrtho2D 0.0, 30.0, 0.0, 30.0;
glMatrixMode GL_MODELVIEW;
glClear GL_COLOR_BUFFER_BIT;
triangle;
glpFlush;
glpMainLoop; |
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
| #Kotlin | Kotlin | // version 1.1.51
import java.util.Random
val r = Random()
fun oneOfN(n: Int): Int {
var choice = 1
for (i in 2..n) {
if (r.nextDouble() < 1.0 / i) choice = i
}
return choice
}
fun main(args: Array<String>) {
val n = 10
val freqs = IntArray(n)
val reps = 1_000_000
repeat(reps) {
val num = oneOfN(n)
freqs[num - 1]++
}
for (i in 1..n) println("Line ${"%-2d".format(i)} = ${freqs[i - 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
| #Liberty_BASIC | Liberty BASIC |
DIM chosen(10)
FOR i = 1 TO 10000'00
c = oneofN(10)
chosen(c) = chosen(c) + 1
NEXT
FOR i = 1 TO 10
PRINT i, chosen(i)
NEXT
end
FUNCTION oneofN(n)
FOR i = 1 TO n
IF RND(1) < 1/i THEN oneofN = i
NEXT
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
| #R | R | tablesort <- function(x, ordering="lexicographic", column=1, reverse=false)
{
# Implementation
}
# Usage is e.g.
tablesort(mytable, column=3) |
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
| #Racket | Racket |
#lang racket
(define (sort-table table
[ordering string<=?]
[column 0]
[reverse? #f])
(sort table (if reverse?
(negate ordering)
ordering)
#:key (λ (row) (list-ref row column))))
|
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.
| #Maxima | Maxima | "<<"(a,b):=block([n:min(length(a),length(b))],
catch(for i thru n do (if a[i]#b[i] then throw(is(a[i]<b[i]))),
throw(is(length(a)<length(b)))))$
infix("<<")$
[1,2,3] << [1,2,4];
true
[1,2,3] << [1,2];
false
[1,2] << [1,2];
false |
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.
| #Mercury | Mercury | :- pred lt(list(int)::in, list(int)::in) is semidet.
lt([], [_|_]).
lt([H1|T1], [H2|T2]) :- H1 =< H2, T1 `lt` T2. |
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
| #Liberty_BASIC | Liberty BASIC |
'Ordered wordsFrom Rosetta Code
open "unixdict.txt" for input as #1
'this is not normal DOS/Windows file.
'It LF delimited, not CR LF
'So Line input would not work.
lf$=chr$(10)
curLen=0
wordList$=""
while not(eof(#1))
a$=inputto$(#1, lf$)
'now, check word
flag = 1
c$ = left$(a$,1)
for i = 2 to len(a$)
d$ = mid$(a$,i,1)
if c$>d$ then flag=0: exit for
c$=d$
next
'ckecked, proceed if ordered word
if flag then
if curLen=len(a$) then
wordList$=wordList$+" "+a$
else
if curLen<len(a$) then
curLen=len(a$)
wordList$=a$
end if
end if
end if
wend
close #1
print wordList$
|
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
| #Processing | Processing |
void setup(){
println(isPalindrome(InsertPalindromeHere));
}
boolean isPalindrome(string check){
char[] letters = new char[check.length];
string invert = " ";
string modCheck = " " + check;
for(int i = 0; i < letters.length; i++){
letters[i] = check.charAt(i);
}
for(int i = letters.length-1; i >= 0; i--){
invert = invert + letters[i];
}
if(invert == modCheck){
return true;
} else {
return false;
}
}
|
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
| #Julia | Julia |
using Measurements
x1 = measurement(100, 1.1)
x2 = measurement(200, 2.2)
y1 = measurement(50, 1.2)
y2 = measurement(100, 2.3)
d = sqrt((x1 - x2)^2 + (y1 - y2)^2)
@show d
@show d.val, d.err
|
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
| #Kotlin | Kotlin | import java.lang.Math.*
data class Approx(val ν: Double, val σ: Double = 0.0) {
constructor(a: Approx) : this(a.ν, a.σ)
constructor(n: Number) : this(n.toDouble(), 0.0)
override fun toString() = "$ν ±$σ"
operator infix fun plus(a: Approx) = Approx(ν + a.ν, sqrt(σ * σ + a.σ * a.σ))
operator infix fun plus(d: Double) = Approx(ν + d, σ)
operator infix fun minus(a: Approx) = Approx(ν - a.ν, sqrt(σ * σ + a.σ * a.σ))
operator infix fun minus(d: Double) = Approx(ν - d, σ)
operator infix fun times(a: Approx): Approx {
val v = ν * a.ν
return Approx(v, sqrt(v * v * σ * σ / (ν * ν) + a.σ * a.σ / (a.ν * a.ν)))
}
operator infix fun times(d: Double) = Approx(ν * d, abs(d * σ))
operator infix fun div(a: Approx): Approx {
val v = ν / a.ν
return Approx(v, sqrt(v * v * σ * σ / (ν * ν) + a.σ * a.σ / (a.ν * a.ν)))
}
operator infix fun div(d: Double) = Approx(ν / d, abs(d * σ))
fun pow(d: Double): Approx {
val v = pow(ν, d)
return Approx(v, abs(v * d * σ / ν))
}
}
fun main(args: Array<String>) {
val x1 = Approx(100.0, 1.1)
val y1 = Approx(50.0, 1.2)
val x2 = Approx(200.0, 2.2)
val y2 = Approx(100.0, 2.3)
println(((x1 - x2).pow(2.0) + (y1 - y2).pow(2.0)).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.
| #J | J | putch=: 4 :0 NB. coroutine verb
outch y
return x
)
isletter=: toupper ~: tolower
do_char=: 3 :0 NB. coroutine verb
ch=. getch''
if. isletter ch do.
if. odd do.
putch&ch yield do_char '' return.
end.
else.
odd=: -. odd
end.
return ch
)
evenodd=: 3 :0
clear_outstream begin_instream y
odd=: 0
whilst. '.'~:char do.
outch char=. do_char coroutine ''
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.
| #APL | APL | spell←{⎕IO←0
small←'' 'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight'
small,←'nine' 'ten' 'eleven' 'twelve' 'thirteen' 'fourteen'
small,←'fifteen' 'sixteen' 'seventeen' 'eighteen' 'nineteen'
teens←'twenty' 'thirty' 'forty' 'fifty' 'sixty' 'seventy'
teens,←'eighty' 'ninety'
orders←'m' 'b' 'tr' 'quadr',¨⊂'illion'
orders←(⊂¨,¨10*6+3×⍳∘≢)orders
orders←('hundred' 100)('thousand' 1000),orders
⍵=0:'zero'
{ ⍵<0:'minus ',∇-⍵
⍵<20:⍵⊃small
⍵<100:{
ty←((⌊⍵÷10)-2)⊃teens
0=n←10|⍵:ty
ty,'-',n⊃small
}⍵
(⊃⊃∇{
name size←⍺
cur n←⍵
rest←size|n
n≥size:(⊂cur,(⍺⍺⌊n÷size),' ',name,((0≠rest)↑'')),rest
(⊂cur),rest
}/orders,⊂(''⍵)),∇100|⍵
}⍵
} |
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
| #AWK | AWK | BEGIN {
print "\nWelcome to the number reversal game!\n"
print "You must put the numbers in order from 1 to 9."
print "Your only moves are to reverse groups of numbers"
print "on the left side of the list."
newgame()
prompt()
}
# start a new game
function newgame( i, j, t) {
# score = number of moves
score = 0
# list = list of numbers
split("123456789", list, "")
do {
# Knuth shuffle
for (i = 9; i > 1; i--) {
j = int(i * rand()) + 1
t = list[i]
list[i] = list[j]
list[j] = t
}
} while (win())
}
# numbers in order?
function win( i) {
# check if list[1] == 1, list[2] == 2, ...
for (i = 1; i <= 9; i++) if (list[i] != i) return 0
return 1
}
# user prompt
function prompt( i) {
printf "\nYour list: "
for (i = 1; i < 9; i++) printf "%d, ", list[i]
printf "%d\n", list[9]
if (win()) {
print "YOU WIN!"
printf "Your score is %d moves.\n", score
printf "Would you like to play again (y/n)? "
again = 1
} else {
printf "How many numbers to reverse? "
}
}
# user input in $1
{
if (again) {
again = 0
if (tolower(substr($1, 1, 1)) == "y")
newgame()
else
exit
} else {
score += 1
reverse($1)
}
prompt()
}
function reverse(right, left, t) {
left = 1
while (right > left) {
t = list[left]
list[left] = list[right]
list[right] = t
left++
right--
}
}
END { print "\n\nBye!" } |
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.
| #AutoIt | AutoIt | Local $object = Null
If $object = Null Then MsgBox(0, "NULL", "Object is null") |
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.
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
b=0;
print "<"b,length(b)">"
print "<"u,length(u)">"
print "<"u+0,length(u+0)">";
} |
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.
| #C.2B.2B | C++ | #include <iostream>
#include <bitset>
#include <string>
const int ArraySize = 20;
const int NumGenerations = 10;
const std::string Initial = "0011101101010101001000";
int main()
{
// + 2 for the fixed ends of the array
std::bitset<ArraySize + 2> array(Initial);
for(int j = 0; j < NumGenerations; ++j)
{
std::bitset<ArraySize + 2> tmpArray(array);
for(int i = ArraySize; i >= 1 ; --i)
{
if(array[i])
std::cout << "#";
else
std::cout << "_";
int val = (int)array[i-1] << 2 | (int)array[i] << 1 | (int)array[i+1];
tmpArray[i] = (val == 3 || val == 5 || val == 6);
}
array = tmpArray;
std::cout << std::endl;
}
} |
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.
| #CoffeeScript | CoffeeScript |
rules =
left_rect: (f, x, h) -> f(x)
mid_rect: (f, x, h) -> f(x+h/2)
right_rect: (f, x, h) -> f(x+h)
trapezium: (f, x, h) -> (f(x) + f(x+h)) / 2
simpson: (f, x, h) -> (f(x) + 4 * f(x + h/2) + f(x+h)) / 6
functions =
cube: (x) -> x*x*x
reciprocal: (x) -> 1/x
identity: (x) -> x
sum = (list) -> list.reduce ((a, b) -> a+b), 0
integrate = (f, a, b, steps, meth) ->
h = (b-a) / steps
h * sum(meth(f, a+i*h, h) for i in [0...steps])
# Tests
tests = [
[0, 1, 100, 'cube']
[1, 100, 1000, 'reciprocal']
[0, 5000, 5000000, 'identity']
[0, 6000, 6000000, 'identity']
]
for test in tests
[a, b, steps, func_name] = test
func = functions[func_name]
console.log "-- tests for #{func_name} with #{steps} steps from #{a} to #{b}"
for rule_name, rule of rules
result = integrate func, a, b, steps, rule
console.log rule_name, result
|
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Phix | Phix | with javascript_semantics
atom t1 = time()+1
integer count = 0, n = 0
printf(1,"The first 200 numbers are:\n")
while true do
n += 1
integer rmf = 0,
l = remainder(n,10),
r = floor(n/10)
while r do
integer p = remainder(r,10)
rmf += compare(l,p)
l = p
r = floor(r/10)
end while
if rmf=0 then
count += 1
if count<=200 then
printf(1,"%3d ",n)
if remainder(count,20)=0 then
printf(1,"\n")
end if
end if
if count == 1e7 then
if platform()!=JS then progress("") end if
printf(1,"\nThe %,dth number is %,d\n",{count,n})
exit
end if
if time()>t1 and platform()!=JS then
progress("%,d:%,d\r",{count,n})
t1 = time()+1
end if
end if
end while
|
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Python | Python | import itertools
def riseEqFall(num):
"""Check whether a number belongs to sequence A296712."""
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
"""Generate a sequence defined by a function"""
num=start-1
while True:
num += 1
while not fn(num): num += 1
yield num
a296712 = sequence(1, riseEqFall)
# Generate the first 200 numbers
print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))
# Generate the 10,000,000th number
print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
# It is necessary to subtract 200 from the index, because 200 numbers
# have already been consumed.
|
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}
| #Kotlin | Kotlin | import java.lang.Math.*
class Legendre(val N: Int) {
fun evaluate(n: Int, x: Double) = (n downTo 1).fold(c[n][n]) { s, i -> s * x + c[n][i - 1] }
fun diff(n: Int, x: Double) = n * (x * evaluate(n, x) - evaluate(n - 1, x)) / (x * x - 1)
fun integrate(f: (Double) -> Double, a: Double, b: Double): Double {
val c1 = (b - a) / 2
val c2 = (b + a) / 2
return c1 * (0 until N).fold(0.0) { s, i -> s + weights[i] * f(c1 * roots[i] + c2) }
}
private val roots = DoubleArray(N)
private val weights = DoubleArray(N)
private val c = Array(N + 1) { DoubleArray(N + 1) } // coefficients
init {
// coefficients:
c[0][0] = 1.0
c[1][1] = 1.0
for (n in 2..N) {
c[n][0] = (1 - n) * c[n - 2][0] / n
for (i in 1..n)
c[n][i] = ((2 * n - 1) * c[n - 1][i - 1] - (n - 1) * c[n - 2][i]) / n
}
// roots:
var x: Double
var x1: Double
for (i in 1..N) {
x = cos(PI * (i - 0.25) / (N + 0.5))
do {
x1 = x
x -= evaluate(N, x) / diff(N, x)
} while (x != x1)
x1 = diff(N, x)
roots[i - 1] = x
weights[i - 1] = 2 / ((1 - x * x) * x1 * x1)
}
print("Roots:")
roots.forEach { print(" %f".format(it)) }
println()
print("Weights:")
weights.forEach { print(" %f".format(it)) }
println()
}
}
fun main(args: Array<String>) {
val legendre = Legendre(5)
println("integrating Exp(x) over [-3, 3]:")
println("\t%10.8f".format(legendre.integrate(Math::exp, -3.0, 3.0)))
println("compared to actual:")
println("\t%10.8f".format(exp(3.0) - exp(-3.0)))
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #PHP | PHP | $myObj = new Object();
$serializedObj = serialize($myObj); |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #PicoLisp | PicoLisp | (class +Point)
# x y
(dm T (X Y)
(=: x (or X 0))
(=: y (or Y 0)) )
(dm print> ()
(prinl "Point " (: x) "," (: y)) )
(class +Circle +Point)
# r
(dm T (X Y R)
(super X Y)
(=: r (or R 0)) )
(dm print> ()
(prinl "Circle " (: x) "," (: y) "," (: r)) )
(setq
P (new '(+Point) 3 4)
C (new '(+Circle) 10 10 5) )
(print> P)
(print> C)
(out "objects.dat"
(pr (val P) (getl P))
(pr (val C) (getl C)) ) |
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
| #Forth | Forth | : string, ( c-addr u -- ) \ store string at HERE , with a count
dup c, here swap dup allot move ;
\ doubly linked list: (0|prev, 0|next, aside?, cstr animal; cstr aside)
\ aside? is true if the aside is always displayed.
variable swallowed
variable first
: >next ( swallow-addr -- swallow-addr' )
cell+ @ ;
: >aside? ( swallow-addr -- f )
2 cells + @ ;
: >animal ( swallow-addr -- c-addr u )
3 cells + count ;
: >aside ( swallow-addr -- c-addr u )
>animal + count ;
: swallow ( "animal" -- )
align swallowed @ if here swallowed @ cell+ ! else here first ! then
here swallowed @ , swallowed !
0 , 0 , parse-word string, ; \ data structure still needs the aside
: always ( -- ) \ set aside? of last-defined swallow to true
swallowed @ 2 cells + on ;
: aside ( "aside" -- )
0 parse string, ;
swallow fly always aside But I don't know why she swallowed the fly,
swallow spider always aside That wriggled and jiggled and tickled inside her;
swallow bird aside Quite absurd, she swallowed the bird;
swallow cat aside Fancy that, she swallowed the cat;
swallow dog aside What a hog, she swallowed the dog;
swallow pig aside Her mouth was so big, she swallowed the pig;
swallow goat aside She just opened her throat, she swallowed the goat;
swallow cow aside I don't know how, she swallowed the cow;
swallow donkey aside It was rather wonky, she swallowed the donkey;
: ?aside ( swallow-addr -- ) \ print aside if aside? is true
dup >aside? if >aside cr type else drop then ;
: reasons ( swallow-addr -- ) \ print reasons she swallowed something
begin dup @ while
dup cr ." She swallowed the " >animal type ." to catch the "
@ dup >animal type ." ," dup ?aside
repeat drop ;
: verse ( swallow-addr -- )
cr ." There was an old lady who swallowed a " dup >animal type ." ,"
dup >aside cr type
reasons
cr ." Perhaps she'll die!" ;
: song ( -- )
first @ begin dup verse cr >next dup 0= until drop
cr ." There was an old lady who swallowed a horse..."
cr ." She's dead, of course!" ; |
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
| #Fortran | Fortran |
program fly
!A program to print the "Old lady swallowed a fly" poem
implicit none
character(len=52), dimension(0:8,2) :: line
integer :: i,j
!Define Lines of Poem
line(1,1) = 'fly'
line(2,1) = 'spider'
line(3,1) = 'bird'
line(4,1) = 'cat'
line(5,1) = 'dog'
line(6,1) = 'goat'
line(7,1) = 'cow'
line(8,1) = 'horse'
line(0,2) = "Perhaps she'll die."
line(1,2) = "I don't know why she swallowed that fly."
line(2,2) = "That wiggled and jiggled and tickled inside her."
line(3,2) = "How absurd to swallow a bird."
line(4,2) = "Imagine that. She swallowed a cat."
line(5,2) = "What a hog to swallow a dog."
line(6,2) = "She just opened her throat and swallowed that goat."
line(7,2) = "I don't know how she swallowed that cow."
line(8,2) = "She's dead of course."
!List each verse
verses:do i = 1,8
write(*,*) 'There was an old lady who swallowed a '//trim(line(i,1))//"."
write(*,*) trim(line(i,2))
!List things swallowed
swallowed:do j = i,2,-1
write(*,*) "She swallowed the "//trim(line(j,1))//" to catch the "//trim(line(j-1,1))//","
end do swallowed
write(*,*) trim(line(0,2))
write(*,*)
end do verses
end program fly
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Sidef | Sidef | func convert (magnitude, unit) {
var factor = Hash(
tochka => 0.000254,
liniya => 0.00254,
diuym => 0.0254,
vershok => 0.04445,
piad => 0.1778,
fut => 0.3048,
arshin => 0.7112,
sazhen => 2.1336,
versta => 1066.8,
milia => 7467.6,
centimeter => 0.01,
meter => 1,
kilometer => 1000,
)
var meters = (magnitude * factor{unit.lc})
say("#{magnitude} #{unit} to:\n", '-' * 40)
for u,f in (factor.sort_by { |_,v| v }) {
printf("%10s: %s\n", u, meters / f) if (u != unit.lc)
}
}
convert(1, 'meter')
say('')
convert(1, 'milia') |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Tcl | Tcl |
package require units
set russian_units {
arshin 1.40607
centimeter 100
diuym 39.3701
fut 3.28084
kilometer 0.001
liniya 393.701
meter 1
milia 0.000133912
piad 5.6243
sazhen 0.468691
tochka 3937.01
vershok 22.4972
versta 0.000937383
}
proc add_russian_units {} {
foreach {name factor} $::russian_units {
if {$name eq "meter"} continue
set factor [expr {1/$factor}]
units::new $name "$factor meters" ;# teach units about the new unit
}
}
proc demo {} { ;# show some examples
foreach base {"1 meter" "1 milia"} {
puts "$base to:"
foreach {unit _} $::russian_units {
puts [format " %-12s: %s" $unit [units::convert $base $unit]]
}
puts ""
}
}
add_russian_units
demo
|
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.
| #Phix | Phix | --
-- demo\rosetta\OpenGL.exw
-- =======================
--
with javascript_semantics
requires("1.0.1")
include pGUI.e
include opengl.e
Ihandln dlg
Ihandle canvas
constant fragment_shader = """
precision highp float;
varying vec4 v_color;
void main(void) {
// "Varying" variables are implicitly interpolated across triangles.
gl_FragColor = v_color;
}""",
vertex_shader = """
attribute vec3 a_position;
attribute vec4 a_color;
varying vec4 v_color;
void main(void) {
gl_Position = vec4(a_position, 1.0);
v_color = a_color;
}"""
function get_shader(string src, integer stype)
integer shader = glCreateShader(stype)
glShaderSource(shader, src)
glCompileShader(shader)
if not glGetShaderParameter(shader, GL_COMPILE_STATUS) then
crash(glGetShaderInfoLog(shader))
end if
return shader
end function
constant vertices = { -0.5, -0.5, 0, -- (bl)
+0.5, -0.5, 0, -- (br)
-0.5, +0.5, 0 }, -- (tl)
-- +0.5, +0.5, 0 }, -- (tr)
colours = { 1, 0, 0, 1, -- red (bl)
0, 1, 0, 1, -- green (br)
0, 0, 1, 1 } -- blue (tl)
procedure set_shader()
IupGLMakeCurrent(canvas)
integer shaderProgram = glCreateProgram()
glAttachShader(shaderProgram, get_shader(vertex_shader,GL_VERTEX_SHADER))
glAttachShader(shaderProgram, get_shader(fragment_shader,GL_FRAGMENT_SHADER))
glLinkProgram(shaderProgram)
if not glGetProgramParameter(shaderProgram, GL_LINK_STATUS) then
crash(glGetProgramInfoLog(shaderProgram))
end if
glUseProgram(shaderProgram)
// Get the indexes to communicate vertex attributes to the program.
integer positionAttr = glGetAttribLocation(shaderProgram, "a_position"),
colorAttr = glGetAttribLocation(shaderProgram, "a_color")
// And specify that we will be actually delivering data to those attributes.
glEnableVertexAttribArray(positionAttr)
glEnableVertexAttribArray(colorAttr)
// Store vertex positions and colors in array buffer objects.
integer positionBuffer = glCreateBuffer()
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer)
{integer size, atom pData} = glFloat32Array(vertices)
glBufferData(GL_ARRAY_BUFFER, size, pData, GL_STATIC_DRAW)
glEnableVertexAttribArray(positionBuffer)
integer colorBuffer = glCreateBuffer()
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer)
{size, pData} = glFloat32Array(colours)
glBufferData(GL_ARRAY_BUFFER, size, pData, GL_STATIC_DRAW)
glEnableVertexAttribArray(colorBuffer)
glEnable(GL_DEPTH_TEST)
// Specify the array data to render.
// 3 and 4 are the lengths of the vectors (3 for XYZ, 4 for RGBA).
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer)
glVertexAttribPointer(positionAttr, 3, GL_FLOAT, false, 0, 0)
glEnableVertexAttribArray(positionAttr)
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer)
glVertexAttribPointer(colorAttr, 4, GL_FLOAT, false, 0, 0)
glEnableVertexAttribArray(colorAttr)
end procedure
bool drawn = false
function action(Ihandle /*ih*/)
if not drawn or platform()!=JS then
glClearColor(0.3, 0.3, 0.3, 1.0)
integer {w,h} = IupGetIntInt(canvas,"DRAWSIZE")
glViewport(0, 0, w, h)
glClear(GL_COLOR_BUFFER_BIT || GL_DEPTH_BUFFER_BIT)
// Draw triangles using the specified arrays.
integer numVertices = length(vertices)/3 // 3 coordinates per vertex
glDrawArrays(GL_TRIANGLES, 0, numVertices)
// Check for errors.
while true do
integer e = glGetError()
if e=GL_NO_ERROR then exit end if
printf(1,"GL error %d\n", e)
end while
glFlush()
drawn = true
end if
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupGLCanvas(Icallback("action"), "RASTERSIZE=640x480")
dlg = IupDialog(canvas, "TITLE=OpenGLShader, SHRINK=YES")
IupMap(dlg)
set_shader()
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
dlg = IupDestroy(dlg)
IupClose()
end if
end procedure
main()
|
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
| #Lua | Lua |
math.randomseed(os.time())
local n = 10
local trials = 1000000
function one(n)
local chosen = 1
for i = 1, n do
if math.random() < 1/i then
chosen = i
end
end
return chosen
end
-- 0 filled table for storing results
local results = {}
for i = 1, n do results[i] = 0 end
-- run simulation
for i = 1, trials do
local result = one(n)
results[result] = results[result] + 1
end
print("Value","Occurrences")
print("-------------------")
for k, v in ipairs(results) do
print(k,v)
end
|
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
| #Raku | Raku | method sorttable(:$column = 0, :$reverse, :&ordering = &infix:<cmp>) {
my @result = self»[$column].sort: &ordering;
return $reverse ?? @result.reverse !! @result;
} |
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.
| #Nim | Nim | proc `<`[T](a, b: openarray[T]): bool =
for i in 0 .. min(a.len, b.len):
if a[i] < b[i]: return true
if a[i] > b[i]: return false
return a.len < b.len
echo([1,2,1,3,2] < [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.
| #OCaml | OCaml | # [1;2;1;3;2] < [1;2;0;4;4;0;0;0];;
- : bool = 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
| #Lingo | Lingo | -- Contents of unixdict.txt passed as string
on printLongestOrderedWords (words)
res = []
maxlen = 0
_player.itemDelimiter = numtochar(10)
cnt = words.item.count
repeat with i = 1 to cnt
w = words.item[i]
len = w.length
ordered = TRUE
repeat with j = 2 to len
if chartonum(w.char[j-1])>chartonum(w.char[j]) then
ordered = FALSE
exit repeat
end if
end repeat
if ordered then
if len > maxlen then
res = [w]
maxlen = len
else if len = maxlen then
res.add(w)
end if
end if
end repeat
put res
end |
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
| #Lua | Lua | fp = io.open( "dictionary.txt" )
maxlen = 0
list = {}
for w in fp:lines() do
ordered = true
for l = 2, string.len(w) do
if string.byte( w, l-1 ) > string.byte( w, l ) then
ordered = false
break
end
end
if ordered then
if string.len(w) > maxlen then
list = {}
list[1] = w
maxlen = string.len(w)
elseif string.len(w) == maxlen then
list[#list+1] = w
end
end
end
for _, w in pairs(list) do
print( w )
end
fp:close() |
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
| #Prolog | Prolog | palindrome(Word) :- name(Word,List), reverse(List,List). |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | PlusMinus /: a_ ± σa_ + c_?NumericQ := N[(a + c) ± σa];
PlusMinus /: a_ ± σa_ + b_ ± σb_ := N[(a + b) ± Norm@{σa, σb}];
PlusMinus /: c_?NumericQ (a_ ± σa_) := N[c a ± Abs[c σa]];
PlusMinus /: (a_ ± σa_) (b_ ± σb_) := N[a b ± (a b Norm@{σa/a, σb/b})^2];
PlusMinus /: (a_ ± σa_)^c_?NumericQ := N[a^c ± Abs[a^c σa/a]]; |
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
| #Nim | Nim | import strformat
import math
type
Imprecise = object
x: float
σ: float
template `^`(a, b: float): float =
pow(a, b)
template `-`(a: Imprecise): Imprecise =
Imprecise(x: -a.x, σ: a.σ)
template `+`(a, b: Imprecise): Imprecise =
Imprecise(x: a.x + b.x, σ: sqrt(a.σ ^ 2 + b.σ ^ 2))
template `-`(a, b: Imprecise): Imprecise =
Imprecise(x: a.x - b.x, σ: sqrt(a.σ ^ 2 + b.σ ^ 2))
template `*`(a, b: Imprecise): Imprecise =
let x = a.x * b.x
let σ = sqrt(x ^ 2 * ((a.σ / a.x) ^ 2 + (b.σ / b.x) ^ 2))
Imprecise(x: x, σ: σ)
template `/`(a, b: Imprecise): Imprecise =
let x = a.x / b.x
let σ = sqrt(x ^ 2 * ((a.σ / a.x) ^ 2 + (b.σ / b.x) ^ 2))
Imprecise(x: x, σ: σ)
template `^`(a: Imprecise, b: float): Imprecise =
if b < 0:
raise newException(IOError, "Cannot raise to negative power.")
let x = a.x ^ b
let σ = abs(x * b * a.σ / a.x)
Imprecise(x: x, σ: σ)
template sqrt(a: Imprecise): Imprecise =
a ^ 0.5
proc `$`(a: Imprecise): string =
fmt"{a.x:.2f} ± {a.σ:.2f}"
var x1 = Imprecise(x: 100, σ: 1.1)
var y1 = Imprecise(x: 50, σ: 1.2)
var x2 = Imprecise(x: 200, σ: 2.2)
var y2 = Imprecise(x: 100, σ: 2.3)
echo sqrt((x1 - x2) ^ 2 + (y1 - y2) ^ 2) |
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.
| #Java | Java | public class OddWord {
interface CharHandler {
CharHandler handle(char c) throws Exception;
}
final CharHandler fwd = new CharHandler() {
public CharHandler handle(char c) {
System.out.print(c);
return (Character.isLetter(c) ? fwd : rev);
}
};
class Reverser extends Thread implements CharHandler {
Reverser() {
setDaemon(true);
start();
}
private Character ch; // For inter-thread comms
private char recur() throws Exception {
notify();
while (ch == null) wait();
char c = ch, ret = c;
ch = null;
if (Character.isLetter(c)) {
ret = recur();
System.out.print(c);
}
return ret;
}
public synchronized void run() {
try {
while (true) {
System.out.print(recur());
notify();
}
} catch (Exception e) {}
}
public synchronized CharHandler handle(char c) throws Exception {
while (ch != null) wait();
ch = c;
notify();
while (ch != null) wait();
return (Character.isLetter(c) ? rev : fwd);
}
}
final CharHandler rev = new Reverser();
public void loop() throws Exception {
CharHandler handler = fwd;
int c;
while ((c = System.in.read()) >= 0) {
handler = handler.handle((char) c);
}
}
public static void main(String[] args) throws Exception {
new OddWord().loop();
}
} |
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.
| #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on numberToWords(n)
return (current application's class "NSNumberFormatter"'s localizedStringFromNumber:(n) numberStyle:(current application's NSNumberFormatterSpellOutStyle)) as text
end numberToWords
numberToWords(-3.6028797018963E+10)
--> "minus thirty-six billion twenty-eight million seven hundred ninety-seven thousand eighteen point nine six three" |
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
| #BASIC | BASIC | PRINT "Given a jumbled list of the numbers 1 to 9,"
PRINT "you must select how many digits from the left to reverse."
PRINT "Your goal is to get the digits in order with 1 on the left and 9 on the right."
RANDOMIZE TIMER
DIM nums(1 TO 9) AS INTEGER
DIM L0 AS INTEGER, n AS INTEGER, flp AS INTEGER, tries AS INTEGER, again AS INTEGER
'initial values
FOR L0 = 1 TO 9
nums(L0) = L0
NEXT
DO 'shuffle
FOR L0 = 9 TO 2 STEP -1
n = INT(RND * (L0)) + 1
IF n <> L0 THEN SWAP nums(n), nums(L0)
NEXT
FOR L0 = 1 TO 8 'make sure it's not in order
IF nums(L0) > nums(L0 + 1) THEN EXIT DO
NEXT
LOOP
again = -1
DO
IF tries < 10 THEN PRINT " ";
PRINT tries; ":";
FOR L0 = 1 TO 9
PRINT nums(L0);
NEXT
IF NOT again THEN EXIT DO
INPUT " -- How many numbers should be flipped"; flp
IF flp < 0 THEN flp = 0
IF flp > 9 THEN flp = 0
FOR L0 = 1 TO (flp \ 2)
SWAP nums(L0), nums(flp - L0 + 1)
NEXT
again = 0
'check for order
FOR L0 = 1 TO 8
IF nums(L0) > nums(L0 + 1) THEN
again = -1
EXIT FOR
END IF
NEXT
IF flp > 0 THEN tries = tries + 1
LOOP
PRINT : PRINT "You took "; LTRIM$(RTRIM$(STR$(tries))); " tries to put the digits in order." |
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.
| #Axe | Axe | If P=0
Disp "NULL PTR",i
End |
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.