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/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #Perl | Perl | sub countSubstring {
my $str = shift;
my $sub = quotemeta(shift);
my $count = () = $str =~ /$sub/g;
return $count;
# or return scalar( () = $str =~ /$sub/g );
}
print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("ababababab","abab"), "\n"; # prints "2" |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #Phix | Phix | sequence tests = {{"the three truths","th"},
{"ababababab","abab"},
{"ababababab","aba"},
{"ababababab","ab"},
{"ababababab","a"},
{"ababababab",""}}
integer start, count
string test, substring
for i=1 to length(tests) do
start = 1
count = 0
{test, substring} = tests[i]
while 1 do
start = match(substring,test,start)
if start=0 then exit end if
start += length(substring)
count += 1
end while
printf(1,"The string \"%s\" occurs as a non-overlapping substring %d times in \"%s\"\n",{substring,count,test})
end for
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #PL.2FM | PL/M | 100H: /* PRINT INTEGERS IN OCTAL */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$OCTAL: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, O$STR( 7 ) BYTE, W BYTE;
V = N;
O$STR( W := 0 ) = '0' + ( V AND 7 );
DO WHILE( ( V := SHR( V, 3 ) ) > 0 );
O$STR( W := W + 1 ) = '0' + ( V AND 7 );
END;
W = W + 1;
DO WHILE( W <> 0 );
CALL PR$CHAR( O$STR( W := W - 1 ) );
END;
END PR$OCTAL;
DECLARE N ADDRESS;
N = 0;
CALL PR$OCTAL( N );
CALL PR$NL;
DO WHILE( ( N := N + 1 ) > 0 ); /* AFTER 65535 N WILL WRAP 'ROUND TO 0 */
CALL PR$OCTAL( N );
CALL PR$NL;
END;
EOF |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Perl | Perl | use ntheory qw/factor/;
print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010; |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Phix | Phix | with javascript_semantics
procedure factorise(integer n)
sequence res = prime_factors(n,true)
res = join(apply(res,sprint)," x ")
printf(1,"%2d: %s\n",{n,res})
end procedure
papply(tagset(10)&{2144,1000000000},factorise)
|
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #MATLAB_.2F_Octave | MATLAB / Octave | function htmltable(fid,table,Label)
fprintf(fid,'<table>\n <thead align = "right">\n');
if nargin<3,
fprintf(fid,' <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = "right">\n');
else
fprintf(fid,' <tr><th></th>');
fprintf(fid,'<td>%s</td>',Label{:});
fprintf(fid,'</tr>\n </thead>\n <tbody align = "right">\n');
end;
fprintf(fid,' <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n', [1:size(table,1);table']);
fprintf(fid,' </tbody>\n</table>\n');
end |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #PL.2FI | PL/I |
open file (output) title ('/OUTPUT.TXT,type(text),recsize(100)' );
close file (output);
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #PowerShell | PowerShell | New-Item output.txt -ItemType File
New-Item \output.txt -ItemType File
New-Item docs -ItemType Directory
New-Item \docs -ItemType Directory |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Perl | Perl | use HTML::Entities;
sub row {
my $elem = shift;
my @cells = map {"<$elem>$_</$elem>"} split ',', shift;
print '<tr>', @cells, "</tr>\n";
}
my ($first, @rest) = map
{my $x = $_; chomp $x; encode_entities $x}
<STDIN>;
print "<table>\n";
row @ARGV ? 'th' : 'td', $first;
row 'td', $_ foreach @rest;
print "</table>\n"; |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Scheme | Scheme |
(import (scheme base)
(scheme read)
(scheme write))
;; Read x/y from user
(define x (begin (display "X: ") (flush-output-port) (read)))
(define y (begin (display "Y: ") (flush-output-port) (read)))
;; Create a vector, and fill it with a vector for each row
(define arr (make-vector x))
(do ((i 0 (+ 1 i)))
((= i x) )
(vector-set! arr i (make-vector y 0)))
;; set element (x/2, y/2) to 3
(vector-set! (vector-ref arr (floor (/ x 2)))
(floor (/ y 2))
3)
(display arr) (newline)
(display "Retrieved: ")
(display (vector-ref (vector-ref arr (floor (/ x 2)))
(floor (/ y 2))))
(newline)
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Raku | Raku | sub sd (@a) {
my $mean = @a R/ [+] @a;
sqrt @a R/ [+] map (* - $mean)**2, @a;
}
sub sdaccum {
my @a;
return { push @a, $^x; sd @a; };
}
my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9; |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Scheme | Scheme | (define ways-to-make-change
(lambda (x coins)
(cond
[(null? coins) 0]
[(< x 0) 0]
[(zero? x) 1]
[else (+ (ways-to-make-change x (cdr coins)) (ways-to-make-change (- x (car coins)) coins))])))
(ways-to-make-change 100) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #PHP | PHP | <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Picat | Picat | count_substrings_rec(S, SB) = C =>
count_rec(S,SB,0,C).
count_rec([],_SB,Count,Count).
count_rec(SBRest,SB,Count0,Count) :-
SBRest = SB ++ Rest, % "split" into substring and the rest of the string
count_rec(Rest,SB,Count0+1,Count).
count_rec([T|Rest],SB,Count0,Count) :-
T != SB, % this character is not a substring
count_rec(Rest,SB,Count0,Count). |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #PowerShell | PowerShell | [int64]$i = 0
While ( $True )
{
[Convert]::ToString( ++$i, 8 )
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Prolog | Prolog | o(O) :- member(O, [0,1,2,3,4,5,6,7]).
octal([O]) :- o(O).
octal([A|B]) :-
octal(O),
o(T),
append(O, [T], [A|B]),
dif(A, 0).
octalize :-
forall(
octal(X),
(maplist(write, X), nl)
). |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #PicoLisp | PicoLisp | (de factor (N)
(make
(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N))
(while (>= M D)
(if (=0 (% N D))
(setq M (sqrt (setq N (/ N (link D)))))
(inc 'D (pop 'L)) ) )
(link N) ) ) )
(for N 20
(prinl N ": " (glue " * " (factor N))) ) |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #PL.2FI | PL/I |
cnt: procedure options (main);
declare (i, k, n) fixed binary;
declare first bit (1) aligned;
do n = 1 to 40;
put skip list (n || ' =');
k = n; first = '1'b;
repeat:
do i = 2 to k-1;
if mod(k, i) = 0 then
do;
k = k/i;
if ^first then put edit (' x ')(A);
first = '0'b;
put edit (trim(i)) (A);
go to repeat;
end;
end;
if ^first then put edit (' x ')(A);
if n = 1 then i = 1;
put edit (trim(i)) (A);
end;
end cnt;
|
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Modula-2 | Modula-2 | MODULE testCGI;
FROM InOut IMPORT WriteCard, WriteLn, WriteString, WriteBf;
FROM Arguments IMPORT ArgTable, GetEnv;
FROM Strings IMPORT Assign, Length, String;
VAR EnvVars : ArgTable;
PROCEDURE ReadEnvVar;
VAR Value : String;
i : CARDINAL;
BEGIN
WriteString ('<table border="1" cellpadding="4" width="80%" align="center">');
WriteString ('<tr><th>Index</th><th>Length</th><th>Content</th></tr>');
i := 0;
LOOP
IF EnvVars^ [i] = NIL THEN EXIT END;
Assign (Value, EnvVars^ [i]^);
WriteString ('<tr><td align="center">');
WriteCard (i, 2);
WriteString ('</td><td align="center">');
WriteCard (Length (Value), 3);
WriteString ('</td><td>'); WriteString (Value);
WriteString ("</td></tr>");
WriteLn;
INC (i)
END;
WriteString("</table>");
END ReadEnvVar;
BEGIN
GetEnv (EnvVars);
WriteString ('Content-type:text/html');
WriteLn;
WriteLn;
WriteString ('<html><head>');
WriteString ('<title>CGI with the Mocka Modula-2 compiler</title>');
WriteString ('</head><body>');
WriteLn;
WriteString ('<center><h2>CGI environment passed along by your browser</h2></center><p>');
ReadEnvVar;
WriteString ('</body></html>');
WriteLn;
WriteBf
END testCGI. |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #ProDOS | ProDOS | makedirectory docs
changedirectory docs
makenewfile output.txt |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #PureBasic | PureBasic | CreateFile(0,"output.txt"):CloseFile(0)
CreateDirectory("docs")
CreateFile(0,"/output.txt"):CloseFile(0)
CreateDirectory("/docs") |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Phix | Phix | with javascript_semantics
constant input = """
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"""
puts(1,"<table>\n<tr><td>")
for i = 1 to length(input) do
switch input[i] do
case '\n' then puts(1,"</td></tr>\n<tr><td>")
case ',' then puts(1,"</td><td>")
case '<' then puts(1,"<")
case '>' then puts(1,">")
case '&' then puts(1,"&")
case else puts(1,input[i])
end switch
end for
puts(1,"</td></tr>\n</table>")
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: numRows is 0;
var integer: numCols is 0;
var array array integer: anArray is 0 times 0 times 0;
begin
write("Give me the numer of rows: ");
readln(numRows);
write("Give me the numer of columns: ");
readln(numCols);
anArray := numRows times numCols times 0;
anArray[1][1] := 3;
writeln("The number at place [1, 1] is " <& anArray[1][1]);
end func; |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Sidef | Sidef | func make_matrix(x, y) {
y.of { x.of(0) };
}
var y = Sys.scanln("rows: ").to_i;
var x = Sys.scanln("cols: ").to_i;
var matrix = make_matrix(x, y); # create the matrix
matrix[y/2][x/2] = 1; # write something inside it
say matrix; # display the matrix |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #REXX | REXX | /*REXX program calculates and displays the standard deviation of a given set of numbers.*/
parse arg # /*obtain optional arguments from the CL*/
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/
n= words(#); $= 0; $$= 0; L= length(n) /*N: # items; $,$$: sums to be zeroed*/
/* [↓] process each number in the list*/
do j=1 for n
_= word(#, j); $= $ + _
$$= $$ + _**2
say ' item' right(j, L)":" right(_, 4) ' average=' left($/j, 12),
' standard deviation=' sqrt($$/j - ($/j)**2)
end /*j*/ /* [↑] prettify output with whitespace*/
say 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate & display the std deviation*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9; numeric form
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1 |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Scilab | Scilab | amount=100;
coins=[25 10 5 1];
n_coins=zeros(coins);
ways=0;
for a=0:4
for b=0:10
for c=0:20
for d=0:100
n_coins=[a b c d];
change=sum(n_coins.*coins);
if change==amount then
ways=ways+1;
elseif change>amount
break
end
end
end
end
end
disp(ways); |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const func bigInteger: changeCount (in integer: amountCents, in array integer: coins) is func
result
var bigInteger: waysToChange is 0_;
local
var array bigInteger: t is 0 times 0_;
var integer: pos is 0;
var integer: s is 0;
var integer: i is 0;
begin
t := length(coins) times 1_ & (length(coins) * amountCents) times 0_;
pos := length(coins) + 1;
for s range 1 to amountCents do
if coins[1] <= s then
t[pos] := t[pos - (length(coins) * coins[1])];
end if;
incr(pos);
for i range 2 to length(coins) do
if coins[i] <= s then
t[pos] := t[pos - (length(coins) * coins[i])];
end if;
t[pos] +:= t[pos - 1];
incr(pos);
end for;
end for;
waysToChange := t[pos - 1];
end func;
const proc: main is func
local
const array integer: usCoins is [] (1, 5, 10, 25, 50, 100);
const array integer: euCoins is [] (1, 2, 5, 10, 20, 50, 100, 200);
begin
writeln(changeCount( 100, usCoins[.. 4]));
writeln(changeCount( 100000, usCoins));
writeln(changeCount(1000000, usCoins));
writeln(changeCount( 100000, euCoins));
writeln(changeCount(1000000, euCoins));
end func; |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PicoLisp | PicoLisp | (de countSubstring (Str Sub)
(let (Cnt 0 H (chop Sub))
(for (S (chop Str) S (cdr S))
(when (head H S)
(inc 'Cnt)
(setq S (map prog2 H S)) ) )
Cnt ) ) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #Pike | Pike |
write("%d %d\n",
String.count("the three truths", "th"),
String.count("ababababab", "abab"));
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #PureBasic | PureBasic | Procedure.s octal(n.q)
Static Dim digits(20)
Protected i, j, result.s
For i = 0 To 20
digits(i) = n % 8
n / 8
If n < 1
For j = i To 0 Step -1
result + Str(digits(j))
Next
Break
EndIf
Next
ProcedureReturn result
EndProcedure
Define n.q
If OpenConsole()
While n >= 0
PrintN(octal(n))
n + 1
Wend
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Python | Python | import sys
for n in xrange(sys.maxint):
print oct(n) |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #PowerShell | PowerShell |
function eratosthenes ($n) {
if($n -ge 1){
$prime = @(1..($n+1) | foreach{$true})
$prime[1] = $false
$m = [Math]::Floor([Math]::Sqrt($n))
for($i = 2; $i -le $m; $i++) {
if($prime[$i]) {
for($j = $i*$i; $j -le $n; $j += $i) {
$prime[$j] = $false
}
}
}
1..$n | where{$prime[$_]}
} else {
"$n must be equal or greater than 1"
}
}
function prime-decomposition ($n) {
$array = eratosthenes $n
$prime = @()
foreach($p in $array) {
while($n%$p -eq 0) {
$n /= $p
$prime += @($p)
}
}
$prime
}
$OFS = " x "
"$(prime-decomposition 2144)"
"$(prime-decomposition 100)"
"$(prime-decomposition 12)"
|
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Nanoquery | Nanoquery | import Nanoquery.Util
random = new(Random)
println "<table>"
// generate header
println "<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"
// generate five rows
for i in range(1, 5)
println "<tr><td style=\"font-weight: bold;\">" + i + "</td>"
println "<td>" + int($random.getInt(8999) + 1000) + "</td>"
println "<td>" + int($random.getInt(8999) + 1000) + "</td>"
println "<td>" + int($random.getInt(8999) + 1000) + "</td>"
println "</tr>"
end for
println "</table>" |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Python | Python | import os
for directory in ['/', './']:
open(directory + 'output.txt', 'w').close() # create /output.txt, then ./output.txt
os.mkdir(directory + 'docs') # create directory /docs, then ./docs |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #R | R | f <- file("output.txt", "w")
close(f)
# it may fails and the exact syntax to achieve the root
# changes according to the operating system
f <- file("/output.txt", "w")
close(f)
success <- dir.create("docs")
success <- dir.create("/docs") |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #PHP | PHP |
<?php
$csv = <<<EOT
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
EOT;
function convert($csv)
{
$out = [];
array_map(function($ln) use(&$out) {
$ln = htmlentities($ln);
$out[] = count($out) == 0
? '<thead><tr><th>'.implode('</th><th>',explode(',',$ln))."</th></tr></thead>\n"
: '<tr><td>'.implode('</td><td>',explode(',',$ln))."</td></tr>\n";
}, explode("\n",$csv));
return '<table>'.implode('',$out).'</table>';
}
echo convert($csv);
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Simula | Simula | BEGIN
INTEGER N,M;
M := ININT;
N := ININT;
BEGIN
INTEGER ARRAY A(1:M,1:N);
A(M,N) := 99;
OUTINT(A(M,N),0);
OUTIMAGE;
END;
! ARRAY A OUT OF SCOPE ;
END. |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Smalltalk | Smalltalk |
m := (FillInTheBlankMorph request: 'Number of rows?') asNumber.
n := (FillInTheBlankMorph request: 'Number of columns?') asNumber.
aMatrix := Matrix rows: m columns: n.
aMatrix
at: (aMatrix rowCount // 2)
at: (aMatrix columnCount // 2)
put: 3.4.
e := aMatrix
at: (aMatrix rowCount // 2)
at: (aMatrix columnCount // 2).
Transcript show: 'Entry is', e printString.
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ring | Ring |
# Project : Cumulative standard deviation
decimals(6)
sdsave = list(100)
sd = "2,4,4,4,5,5,7,9"
sumval = 0
sumsqs = 0
for num = 1 to 8
sd = substr(sd, ",", "")
stddata = number(sd[num])
sumval = sumval + stddata
sumsqs = sumsqs + pow(stddata,2)
standdev = pow(((sumsqs / num) - pow((sumval /num),2)),0.5)
sdsave[num] = string(num) + " " + string(sumval) +" " + string(sumsqs)
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next
|
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Sidef | Sidef | func cc(_) { 0 }
func cc({ .is_neg }, *_) { 0 }
func cc({ .is_zero }, *_) { 1 }
func cc(amount, first, *rest) is cached {
cc(amount, rest...) + cc(amount - first, first, rest...);
}
func cc_optimized(amount, *rest) {
cc(amount, rest.sort_by{|v| -v }...);
}
var x = cc_optimized(100, 1, 5, 10, 25);
say "Ways to change $1 with common coins: #{x}";
var y = cc_optimized(1000 * 100, 1, 5, 10, 25, 50, 100);
say "Ways to change $1000 with addition of less common coins: #{y}"; |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FI | PL/I | cnt: procedure options (main);
declare (i, tally) fixed binary;
declare (text, key) character (100) varying;
get edit (text) (L); put skip data (text);
get edit (key) (L); put skip data (key);
tally = 0; i = 1;
do until (i = 0);
i = index(text, key, i);
if i > 0 then do; tally = tally + 1; i = i + length(key); end;
end;
put skip list (tally);
end cnt; |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Quackery | Quackery | 8 base put
0 [ dup echo cr 1+ again ] |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Racket | Racket |
#lang racket
(for ([i (in-naturals)])
(displayln (number->string i 8)))
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Raku | Raku | say .base(8) for ^Inf; |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #PureBasic | PureBasic | Procedure Factorize(Number, List Factors())
Protected I = 3, Max
ClearList(Factors())
While Number % 2 = 0
AddElement(Factors())
Factors() = 2
Number / 2
Wend
Max = Number
While I <= Max And Number > 1
While Number % I = 0
AddElement(Factors())
Factors() = I
Number / I
Wend
I + 2
Wend
EndProcedure
If OpenConsole()
NewList n()
For a=1 To 20
text$=RSet(Str(a),2)+"= "
Factorize(a,n())
If ListSize(n())
ResetList(n())
While NextElement(n())
text$ + Str(n())
If ListSize(n())-ListIndex(n())>1
text$ + "*"
EndIf
Wend
Else
text$+Str(a) ; To handle the '1', which is not really a prime...
EndIf
PrintN(text$)
Next a
EndIf |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
-- create some test data. Put the data in a Rexx indexed string
maxI = 1000
rng = Random()
xyz = ''
xyz[0] = 1; xyz[1] = '. X Y Z' -- use a dot to indicate an empty cell
loop r_ = 1 for 5
ra = r_ rng.nextInt(maxI) rng.nextInt(maxI) rng.nextInt(maxI)
xyz[0] = r_ + 1; xyz[r_ + 1] = ra
end r_
-- build an HTML string
html = htmlHeader()
html = html || htmlTable(xyz)
html = html || htmlFooter()
-- display HTML at standard output device
say html
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- HTML boilerplate header
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlHeader() public static returns Rexx
html = '<?xml version="1.0" encoding="UTF-8"?>\n' -
|| '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n' -
|| '<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">\n' -
|| '<head>\n' -
|| '<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>\n' -
|| '<title>RCreateHTMLTable</title>\n' -
|| '<style type="text/css">\n' -
|| '<!--\n' -
|| '/* <![DATA[ */\n' -
|| 'body {font-family: "Lucida Grande", "Geneva", "Verdana", "Helvetica Neue", "Helvetica", "DejaVu Sans", "Arial", sans-serif;}\n' -
|| 'table, th, td {table-layout: fixed; border: 1px solid black; border-collapse: collapse; padding: 0.25em; font-size: 85%;}\n' -
|| 'th, td {width: 6em;}\n' -
|| 'th {color: white; background-color: green;}\n' -
|| 'td {text-align: right;}\n' -
|| 'p.classname {\n' -
|| ' font-size: inherit;\n' -
|| '}\n' -
|| '/* ]] */\n' -
|| '//-->\n' -
|| '</style>\n' -
|| '</head>\n' -
|| '<body>\n' -
|| '<h1>Rosetta Code – NetRexx Sample Output</h2>\n' -
|| '<h2><a href="http://rosettacode.org/wiki/Create_an_HTML_table">Create an HTML table</a></h2>\n' -
|| ''
return html
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- HTML footer
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlFooter() public static returns Rexx
html = '</body>\n' -
|| '</html>\n' -
|| ''
return html
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Create the table
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlTable(rows, caption = '') public static returns Rexx
html = '<table>\n'
if caption.length() > 0 then do
html = html -
|| '<caption>'caption'</caption>\n' -
|| '<thead>\n' -
|| ''
end
html = html -
|| htmlCsvTableRow(rows[1], 'th')'\n' -
|| '</thead>\n' -
|| '<tbody>\n' -
|| ''
loop r_ = 2 to rows[0]
html = html -
|| htmlCsvTableRow(rows[r_])
end r_
html = html -
|| '</tbody>\n' -
|| '</table>\n' -
|| ''
return html
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Add a row to the table
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlCsvTableRow(row, tag = 'td', sep = ' ', emptyCell = '.') public static returns Rexx
if tag = null then tag = 'td'
row = row.strip('t')
-- replace HTML special characters with symbol entities
row = row.changestr('&', '&') -- need to do this one first to avoid double translation
row = row.changestr('"', '"')
row = row.changestr("'", ''')
row = row.changestr('<', '<')
row = row.changestr('>', '>')
elmts = ''
elmts[0] = 0
e_ = 0
loop while row.length() > 0
parse row elmt (sep) row
if elmt == emptyCell then elmt = ' ' -- replace empy cells with non-breaking spaces
e_ = e_ + 1; elmts[0] = e_; elmts[e_] = elmt
end
html = '<tr>\n' -
|| ''
loop e_ = 1 to elmts[0]
html = html -
|| '<'tag'>'elmts[e_]'</'tag'>\n' -
|| ''
end e_
html = html -
|| '</tr>\n' -
|| ''
return html
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Racket | Racket | #lang racket
(display-to-file "" "output.txt")
(make-directory "docs")
(display-to-file "" "/output.txt")
(make-directory "/docs") |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Raku | Raku |
for '.', '' -> $prefix {
mkdir "$prefix/docs";
open "$prefix/output.txt", :w;
}
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #PicoLisp | PicoLisp | (load "@lib/http.l")
(in "text.csv"
(<table> 'myStyle NIL NIL
(prinl)
(while (split (line) ",")
(<row> NIL (ht:Prin (pack (car @))) (ht:Prin (pack (cadr @))))
(prinl) ) ) ) |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #SNOBOL4 | SNOBOL4 | * # Get user X,Y dimensions
output = 'Enter X,Y:'; xy = trim(input)
xy break(',') . x ',' rem . y
* # Define and create array, 1-based
arr = array(x ',' y) ;* Or arr = array(xy)
* # Display array prototype
output = 'Prototype: ' prototype(arr)
* # Assign elements, angle or square brackets
* # Same array can hold ints, strings, etc.
arr<x,y> = 99; arr[1,1] = 'dog'
* # Display elements
output = 'arr[' xy '] = ' arr[x,y]
output = 'arr[1,1] = ' arr[1,1]
* # Release array for garbage collection
arr =
end |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Standard_ML | Standard ML | val nbr1 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn);
val nbr2 = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn);
val array = Array2.array (nbr1, nbr2, 0.0);
Array2.update (array, 0, 0, 3.5);
print (Real.toString (Array2.sub (array, 0, 0)) ^ "\n"); |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ruby | Ruby | class StdDevAccumulator
def initialize
@n, @sum, @sumofsquares = 0, 0.0, 0.0
end
def <<(num)
# return self to make this possible: sd << 1 << 2 << 3 # => 0.816496580927726
@n += 1
@sum += num
@sumofsquares += num**2
self
end
def stddev
Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 )
end
def to_s
stddev.to_s
end
end
sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" } |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Swift | Swift | import BigInt
func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt {
let cycle = coins.filter({ $0 <= cents }).map({ $0 + 1 }).max()! * coins.count
var table = [BigInt](repeating: 0, count: cycle)
for x in 0..<coins.count {
table[x] = 1
}
var pos = coins.count
for s in 1..<cents+1 {
for i in 0..<coins.count {
if i == 0 && pos >= cycle {
pos = 0
}
if coins[i] <= s {
let q = pos - coins[i] * coins.count
table[pos] = q >= 0 ? table[q] : table[q + cycle]
}
if i != 0 {
table[pos] += table[pos - 1]
}
pos += 1
}
}
return table[pos - 1]
}
let usCoins = [100, 50, 25, 10, 5, 1]
let euCoins = [200, 100, 50, 20, 10, 5, 2, 1]
for set in [usCoins, euCoins] {
print(countCoins(amountCents: 100, coins: Array(set.dropFirst(2))))
print(countCoins(amountCents: 100000, coins: set))
print(countCoins(amountCents: 1000000, coins: set))
print(countCoins(amountCents: 10000000, coins: set))
print()
} |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Tailspin | Tailspin |
templates makeChange&{coins:}
def paid: $;
@: [1..$paid -> 0];
$coins... -> \(def coin: $;
@makeChange($coin): $@makeChange($coin) + 1;
$coin+1..$paid -> @makeChange($): $@makeChange($) + $@makeChange($-$coin);
\) -> !VOID
$@($paid)!
end makeChange
100 -> makeChange&{coins: [1,5,10,25]} -> '$; ways to change a dollar
' -> !OUT::write
100000 -> makeChange&{coins: [1,5,10,25,50,100]} -> '$; ways to change 1000 dollars with all coins
' -> !OUT::write
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FM | PL/M | 100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
DECLARE (P, N) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* COUNT OCCURRENCES OF SUBSTRING IN STRING */
COUNT$SUBSTRING: PROCEDURE (STR, MATCH) ADDRESS;
DECLARE (STR, MATCH) ADDRESS, C BASED STR BYTE;
DECLARE (SP, MP) ADDRESS, (SC BASED SP, MC BASED MP) BYTE;
DECLARE COUNT ADDRESS;
COUNT = 0;
DO WHILE C <> '$';
SP = STR;
MP = MATCH;
DO WHILE SC = MC;
SP = SP + 1;
MP = MP + 1;
END;
IF MC = '$' THEN DO;
STR = SP;
COUNT = COUNT + 1;
END;
ELSE DO;
STR = STR + 1;
END;
END;
RETURN COUNT;
END COUNT$SUBSTRING;
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'THE THREE TRUTHS$', .'TH$')); /* PRINTS 3 */
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'ABABABABAB$', .'ABAB$')); /* PRINTS 2 */
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'CAT$', .'DOG$')); /* PRINTS 0 */
CALL EXIT;
EOF |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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 PBMAIN () AS LONG
PRINT "the three truths, th:", TALLY("the three truths", "th")
PRINT "ababababab, abab:", TALLY("ababababab", "abab")
END FUNCTION |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #REXX | REXX | /*REXX program counts in octal until the number exceeds the number of program statements*/
/*┌────────────────────────────────────────────────────────────────────┐
│ Count all the protons (and electrons!) in the universe. │
│ │
│ According to Sir Arthur Eddington in 1938 at his Tamer Lecture at │
│ Trinity College (Cambridge), he postulated that there are exactly │
│ │
│ 136 ∙ 2^256 │
│ │
│ protons in the universe, and the same number of electrons, which │
│ is equal to around 1.57477e+79. │
│ │
│ [Although, a modern estimate is around 10^80.] │
└────────────────────────────────────────────────────────────────────┘*/
numeric digits 100000 /*handle almost any sized big numbers. */
numIn= right('number in', 20) /*used for indentation of the output. */
w= length( sourceline() ) /*used for formatting width of numbers.*/
do #=0 to 136 * (2**256) /*Sir Eddington, here we come ! */
!= x2b( d2x(#) )
_= right(!, 3 * (length(_) % 3 + 1), 0)
o=
do k=1 to length(_) by 3
o= o'0'substr(_, k, 3)
end /*k*/
say numIn 'base ten = ' right(#,w) numIn "octal = " right( b2x(o) + 0, w + w)
if #>sourceline() then leave /*stop if # of protons > pgm statements*/
end /*#*/
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Ring | Ring |
size = 30
for n = 1 to size
see octal(n) + nl
next
func octal m
output = ""
w = m
while fabs(w) > 0
oct = w & 7
w = floor(w / 8)
output = string(oct) + output
end
return output
|
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Python | Python | from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17] # Will be extended
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info()) |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #NewLISP | NewLISP | ; file: html-table.lsp
; url: http://rosettacode.org/wiki/Create_an_HTML_table
; author: oofoe 2012-01-29
(seed (time-of-day)) ; Initialize random number generator.
; The "tab" variable tracks the HTML indent. "pad" composes a line
; with the appropriate indent and a terminal newline.
(setq tab 0)
(define (pad text) (string (dup " " tab) text "\n"))
; NewLISP allows almost any character in an identifier, so I can name
; my functions after the HTML elements they invoke. This one formats a
; single table data cell.
(define (<td> text) (pad (string "<td>" text "</td>")))
; "<tr>" will accept either a number of arguments, each one to be
; formatted as a table cell, or a single list argument, which is
; broken into table cells. For convenience, I format each list item
; with the "<td>" function so I can feed it raw lists.
(define (<tr>)
(let ((data (args))
(s (pad "<tr>")))
(if (list? (data 0)) (setq data (data 0)))
(inc tab)
(dolist (el data) (extend s (<td> el)))
(dec tab)
(extend s (pad "</tr>"))
s))
; By defining "<table>" as a macro, I ensure that the rows won't be
; evaluated until I've got the table started, which preserves the
; formatting.
(define-macro (<table>)
(let ((s (pad "<table>")))
(inc tab) (doargs (row) (extend s (eval row))) (dec tab)
(extend s (pad "</table>"))
s
))
; Test
(print (<table> (<tr> "" "X" "Y" "Z")
(<tr> (cons 0 (rand 1000 3)))
(<tr> (cons 1 (rand 1000 3)))
(<tr> (cons 2 (rand 1000 3)))
))
(exit) |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Raven | Raven | "" as str
str 'output.txt' write
str '/output.txt' write
'docs' mkdir
'/docs' mkdir |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #REBOL | REBOL | ; Creating in current directory:
write %output.txt ""
make-dir %docs/
; Creating in root directory:
write %/output.txt ""
make-dir %/docs/
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #PowerShell | PowerShell |
Import-Csv -Path .\csv_html_test.csv | ConvertTo-Html -Fragment | Out-File .\csv_html_test.html
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Stata | Stata | display "Number of rows?" _request(nr)
display "Number of columns?" _request(nc)
matrix define a=J($nr,$nc,0)
matrix a[1,2]=1.5
matrix list a
matrix drop a |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Swift | Swift | import Foundation
print("Enter the dimensions of the array seperated by a space (width height): ")
let fileHandle = NSFileHandle.fileHandleWithStandardInput()
let dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ")
if let dims = dims where dims.count == 2{
let w = dims[0].integerValue
let h = dims[1].integerValue
if let w = w, h = h where w > 0 && h > 0 {
var array = Array<[Int!]>(count: h, repeatedValue: Array<Int!>(count: w, repeatedValue: nil))
array[0][0] = 2
println(array[0][0])
println(array)
}
} |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Run_BASIC | Run BASIC | dim sdSave$(100) 'can call up to 100 versions
'holds (space-separated) number of data , sum of values and sum of squares
sd$ = "2,4,4,4,5,5,7,9"
for num = 1 to 8
stdData = val(word$(sd$,num,","))
sumVal = sumVal + stdData
sumSqs = sumSqs + stdData^2
' standard deviation = square root of (the average of the squares less the square of the average)
standDev =((sumSqs / num) - (sumVal /num) ^ 2) ^ 0.5
sdSave$(num) = str$(num);" ";str$(sumVal);" ";str$(sumSqs)
print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev)
next num |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Tcl | Tcl | package require Tcl 8.5
proc makeChange {amount coins} {
set table [lrepeat [expr {$amount+1}] [lrepeat [llength $coins] {}]]
lset table 0 [lrepeat [llength $coins] 1]
for {set i 1} {$i <= $amount} {incr i} {
for {set j 0} {$j < [llength $coins]} {incr j} {
set k [expr {$i - [lindex $coins $j]}]
lset table $i $j [expr {
($k < 0 ? 0 : [lindex $table $k $j]) +
($j < 1 ? 0 : [lindex $table $i [expr {$j-1}]])
}]
}
}
return [lindex $table end end]
}
puts [makeChange 100 {1 5 10 25}]
puts [makeChange 100000 {1 5 10 25 50 100}]
# Making change with the EU coin set:
puts [makeChange 100 {1 2 5 10 20 50 100 200}]
puts [makeChange 100000 {1 2 5 10 20 50 100 200}] |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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 |
[regex]::Matches("the three truths", "th").count
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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 |
count_substring(String, Sub, Total) :-
count_substring(String, Sub, 0, Total).
count_substring(String, Sub, Count, Total) :-
( substring_rest(String, Sub, Rest)
->
succ(Count, NextCount),
count_substring(Rest, Sub, NextCount, Total)
;
Total = Count
).
substring_rest(String, Sub, Rest) :-
sub_string(String, Before, Length, Remain, Sub),
DropN is Before + Length,
sub_string(String, DropN, Remain, 0, Rest).
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Ruby | Ruby | n = 0
loop do
puts "%o" % n
n += 1
end
# or
for n in 0..Float::INFINITY
puts n.to_s(8)
end
# or
0.upto(1/0.0) do |n|
printf "%o\n", n
end
# version 2.1 later
0.step do |n|
puts format("%o", n)
end |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Run_BASIC | Run BASIC | input "Begin number:";b
input " End number:";e
for i = b to e
print i;" ";toBase$(8,i)
next i
end
function toBase$(base,base10)
for i = 10 to 1 step -1
toBase$ = str$(base10 mod base) +toBase$
base10 = int(base10 / base)
if base10 < 1 then exit for
next i
end function |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Quackery | Quackery | [ [] swap
dup times
[ [ dup i^ 2 + /mod
0 = while
nip dip
[ i^ 2 + join ]
again ]
drop
dup 1 = if conclude ]
drop ] is primefactors ( n --> [ )
[ 1 dup echo cr
[ 1+ dup primefactors
witheach
[ echo
i if [ say " x " ] ]
cr again ] ] is countinfactors ( --> )
countinfactors |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #R | R |
#initially I created a function which returns prime factors then I have created another function counts in the factors and #prints the values.
findfactors <- function(num) {
x <- c()
p1<- 2
p2 <- 3
everyprime <- num
while( everyprime != 1 ) {
while( everyprime%%p1 == 0 ) {
x <- c(x, p1)
everyprime <- floor(everyprime/ p1)
}
p1 <- p2
p2 <- p2 + 2
}
x
}
count_in_factors=function(x){
primes=findfactors(x)
x=c(1)
for (i in 1:length(primes)) {
x=paste(primes[i],"x",x)
}
return(x)
}
count_in_factors(72)
|
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Nim | Nim | import random, htmlgen
randomize()
template randTD(): string = td($rand(1000..9999))
proc randTR(x: int): string =
tr(td($x, style="font-weight: bold"), randTD, randTD, randTD)
echo table(
tr(th"", th"X", th"Y", th"Z"),
randTR 1,
randTR 2,
randTR 3,
randTR 4,
randTR 5) |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Retro | Retro |
'output.txt file:W file:open file:close
'/output.txt file:W file:open file:close |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #REXX | REXX | /*REXX pgm creates a new empty file and directory; in curr dir and root.*/
do 2 /*perform three statements twice.*/
'COPY NUL output.txt' /*copy a "null" (empty) file. */
'MKDIR DOCS' /*make a directory (aka: folder).*/
'CD \' /*change currect dir to the root.*/
end /*2*/ /*now, go and perform them again.*/
/*stick a fork in it, we're done.*/ |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Prolog | Prolog | csv_html :-
L = "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!",
csv_html(L, Out, []),
string_to_list(Str, Out),
writeln(Str).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% simple HTML
%
csv_html(L) -->
"<TABLE>\n",
csv_tr(L),
"</TABLE>".
csv_tr([]) --> [].
csv_tr(L) -->
"<TR>\n",
csv_td(L, S),
"\n</TR>\n",
csv_tr(S).
csv_td(L, S) -->
"<TD>",
csv_td_in(L, S),
"</TD>".
csv_td_in([], []) --> [].
csv_td_in([10|L], L) --> [].
csv_td_in([44|L], S) -->
"</TD><TD>",
csv_td_in(L,S).
csv_td_in([60|T], S) -->
"<",
csv_td_in(T, S).
csv_td_in([62|T], S) -->
">",
csv_td_in(T, S).
csv_td_in([H|T], S) -->
[H],
csv_td_in(T, S).
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Tcl | Tcl |
puts "Enter width:"
set width [gets stdin]
puts "Enter height:"
set height [gets stdin]
# Initialize array
for {set i 0} {$i < $width} {incr i} {
for {set j 0} {$j < $height} {incr j} {
set arr($i,$j) ""
}
}
# Store value
set arr(0,0) "abc"
# Print value
puts "Element (0/0): $arr(0,0)"
# Cleanup array
unset arr
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Toka | Toka | [ ( x y -- address )
cells malloc >r
dup cells >r
[ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterate
r> r> nip
] is 2D-array
[ ( a b address -- value )
array.get array.get
] is 2D-get-element
[ ( value a b address -- )
array.get array.put
] is 2D-put-element |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Rust | Rust | pub struct CumulativeStandardDeviation {
n: f64,
sum: f64,
sum_sq: f64
}
impl CumulativeStandardDeviation {
pub fn new() -> Self {
CumulativeStandardDeviation {
n: 0.,
sum: 0.,
sum_sq: 0.
}
}
fn push(&mut self, x: f64) -> f64 {
self.n += 1.;
self.sum += x;
self.sum_sq += x * x;
(self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()
}
}
fn main() {
let nums = [2, 4, 4, 4, 5, 5, 7, 9];
let mut cum_stdev = CumulativeStandardDeviation::new();
for num in nums.iter() {
println!("{}", cum_stdev.push(*num as f64));
}
} |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #uBasic.2F4tH | uBasic/4tH | c = 0
for p = 0 to 100
for n = 0 to 20
for d = 0 to 10
for q = 0 to 4
if p + n * 5 + d * 10 + q * 25 = 100 then
print p;" pennies ";n;" nickels "; d;" dimes ";q;" quarters"
c = c + 1
endif
next q
next d
next n
next p
print c;" ways to make a buck" |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #UNIX_Shell | UNIX Shell | function count_change {
local -i amount=$1 coin j
local ways=(1)
shift
for coin; do
for (( j=coin; j <= amount; j++ )); do
let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}
done
done
echo "${ways[amount]}"
}
count_change 100 25 10 5 1
count_change 100000 100 50 25 10 5 1 |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PureBasic | PureBasic | a = CountString("the three truths","th")
b = CountString("ababababab","abab")
; a = 3
; b = 2 |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #Python | Python | >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2 |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Rust | Rust | fn main() {
for i in 0..std::usize::MAX {
println!("{:o}", i);
}
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Salmon | Salmon | iterate (i; [0...+oo])
printf("%o%\n", i);; |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #S-BASIC | S-BASIC |
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return octal representation of n
function oct$(n = integer) = string
var s = string
s = ""
while n > 0 do
begin
s = chr(mod(n,8) + '0') + s
n = n / 8
end
end = s
rem - count in octal until overflow
var i = integer
i = 1
while i > 0 do
begin
print oct$(i)
i = i + 1
end
end
|
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Racket | Racket | #lang typed/racket
(require math/number-theory)
(define (factorise-as-primes [n : Natural])
(if
(= n 1)
'(1)
(let ((F (factorize n)))
(append*
(for/list : (Listof (Listof Natural))
((f (in-list F)))
(make-list (second f) (first f)))))))
(define (factor-count [start-inc : Natural] [end-inc : Natural])
(for ((i : Natural (in-range start-inc (add1 end-inc))))
(define f (string-join (map number->string (factorise-as-primes i)) " × "))
(printf "~a:\t~a~%" i f)))
(factor-count 1 22)
(factor-count 2140 2150)
; tb |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Raku | Raku | constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;
multi factors(1) { 1 }
multi factors(Int $remainder is copy) {
gather for @primes -> $factor {
# if remainder < factor², we're done
if $factor * $factor > $remainder {
take $remainder if $remainder > 1;
last;
}
# How many times can we divide by this prime?
while $remainder %% $factor {
take $factor;
last if ($remainder div= $factor) === 1;
}
}
}
say "$_: ", factors($_).join(" × ") for 1..*; |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Objeck | Objeck |
class CreateTable {
function : Main(args : String[]) ~ Nil {
s := String->New();
s->Append("<table>");
s->Append("<thead align = \"right\">");
s->Append("<tr><th></th>");
td := "XYZ";
for(i:=0; i<3; i+=1;) {
s->Append("<td>");
s->Append(td->Get(i));
s->Append("</td>");
};
s->Append("</tr>");
s->Append("</thead>");
s->Append("<tbody align = \"right\">");
for(i:=0; i<3; i+=1;) {
s->Append("<tr><td>");
s->Append(i);
s->Append("</td>");
for(j:=0; j<3; j+=1;) {
s->Append("<td>");
s->Append((Float->Random() * 10000)->As(Int));
s->Append("</td>");
};
s->Append("</tr>");
};
s->Append("</tbody>");
s->Append("</table>");
s->PrintLine();
}
}
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ring | Ring |
system("mkdir C:\Ring\docs")
fopen("C:\Ring\docs\output.txt", "w+")
system("mkdir docs")
fopen("output.txt", "w+")
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ruby | Ruby | ['/', './'].each{|dir|
Dir.mkdir(dir + 'docs') # create '/docs', then './docs'
File.open(dir + 'output.txt', 'w') {} # create empty file /output.txt, then ./output.txt
} |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Python | Python | csvtxt = '''\
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!\
'''
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>' % data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary="csv2html program output">\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt) |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Ursa | Ursa | decl int width height
out "width: " console
set width (in int console)
out "height: " console
set height (in int console)
decl int<><> twodstream
for (decl int i) (< i height) (inc i)
append (new int<>) twodstream
end for
for (set i 0) (< i height) (inc i)
decl int j
for (set j 0) (< j width) (inc j)
append 0 twodstream<i>
end for
end for
set twodstream<0><0> 5
out twodstream<0><0> endl console |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #VBA | VBA |
Option Explicit
Sub Main_Create_Array()
Dim NbColumns As Integer, NbRows As Integer
'Get two integers from the user,
Do
NbColumns = Application.InputBox("Enter number of columns : ", "Numeric only", 3, Type:=1)
NbRows = Application.InputBox("Enter number of rows : ", "Numeric only", 5, Type:=1)
Loop While NbColumns = 0 Or NbRows = 0
'Create a two-dimensional array at runtime
ReDim myArray(1 To NbRows, 1 To NbColumns)
'Write some element of that array,
myArray(LBound(myArray, 1), UBound(myArray, 2)) = "Toto"
'and then output that element.
MsgBox myArray(LBound(myArray, 1), UBound(myArray, 2))
'destroy the array
Erase myArray
End Sub
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #SAS | SAS |
*--Load the test data;
data test1;
input x @@;
obs=_n_;
datalines;
2 4 4 4 5 5 7 9
;
run;
*--Create a dataset with the cummulative data for each set of data for which the SD should be calculated;
data test2 (drop=i obs);
set test1;
y=x;
do i=1 to n;
set test1 (rename=(obs=setid)) nobs=n point=i;
if obs<=setid then output;
end;
proc sort;
by setid;
run;
*--Calulate the standards deviation (and mean) using PROC MEANS;
proc means data=test2 vardef=n noprint; *--use vardef=n option to calculate the population SD;
by setid;
var y;
output out=stat1 n=n mean=mean std=sd;
run;
*--Output the calculated standard deviations;
proc print data=stat1 noobs;
var n sd /*mean*/;
run;
|
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #VBA | VBA | Private Function coin_count(coins As Variant, amount As Long) As Variant 'return type will be Decimal
'sequence s = Repeat(0, amount + 1)
Dim s As Variant
ReDim s(amount + 1)
Dim c As Integer
s(1) = CDec(1)
For c = 1 To UBound(coins)
For n = coins(c) To amount
s(n + 1) = CDec(s(n + 1) + s(n - coins(c) + 1))
Next n
Next c
coin_count = s(amount + 1)
End Function
Public Sub main2()
Dim us_commons_coins As Variant
'The next line creates a base 1 array
us_common_coins = [{25, 10, 5, 1}]
Debug.Print coin_count(us_common_coins, 100)
Dim us_coins As Variant
us_coins = [{100,50,25, 10, 5, 1}]
Debug.Print coin_count(us_coins, 100000)
End Sub |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #VBScript | VBScript |
Function count(coins,m,n)
ReDim table(n+1)
table(0) = 1
i = 0
Do While i < m
j = coins(i)
Do While j <= n
table(j) = table(j) + table(j - coins(i))
j = j + 1
Loop
i = i + 1
Loop
count = table(n)
End Function
'testing
arr = Array(1,5,10,25)
m = UBound(arr) + 1
n = 100
WScript.StdOut.WriteLine count(arr,m,n)
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #Quackery | Quackery | [ [] 95 times
[ i^ space +
join ] ] constant is alphabet ( --> $ )
[ [ 2dup != while
-1 split drop
swap 1 split
unrot drop again ]
drop size ] is overlap ( [ [ --> n )
[ temp put [] swap
alphabet witheach
[ over -1 poke
over overlap
dup temp share
= if negate
swap dip join ]
drop temp release ] is eachend ( [ n --> [ )
[ [] swap
dup temp put
size times
[ temp share
i 1+ split drop
temp share size eachend
nested swap join ]
temp release ] is buildfsm ( $ --> [ )
[ dup [] = iff -1
else
[ behead
dup carriage = if
[ drop space ]
space - ]
swap ] is nextcharn ( $ --> n $ )
[ swap dup size
swap temp put
swap 0
[ over swap peek
temp take
nextcharn
temp put
dup 0 < iff
[ 2drop 0 ] done
peek
dup 0 < until ]
nip
temp take size - + ] is usefsm ( $ [ --> n )
[ over size 0 = iff
[ 2drop 0 ]
else
[ swap buildfsm
usefsm ] ] is find$ ( $ $ --> n ) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
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
| #R | R | count = function(haystack, needle)
{v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
if (identical(v, -1L)) 0 else length(v)}
print(count("hello", "l")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.