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_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.
| #Scala | Scala | Stream from 0 foreach (i => println(i.toOctalString)) |
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.
| #Scheme | Scheme | (do ((i 0 (+ i 1))) (#f) (display (number->string i 8)) (newline)) |
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.
| #Scratch | Scratch | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: i is 0;
begin
repeat
writeln(i radix 8);
incr(i);
until FALSE;
end func; |
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
| #REXX | REXX | /*REXX program lists the prime factors of a specified integer (or a range of integers).*/
@.=left('', 8); @.0="{unity} "; @.1='[prime] ' /*some tags and handy-dandy literals.*/
parse arg LO HI @ . /*get optional arguments from the C.L. */
if LO=='' | LO=="," then do; LO=1; HI=40; end /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= LO /* " " " " " " */
if @=='' then @= 'x' /* " " " " " " */
if length(@)\==1 then @= x2c(@) /*Not length 1? Then use hexadecimal. */
tell= (HI>0) /*if HIGH is positive, then show #'s.*/
HI= abs(HI) /*use the absolute value for HIGH. */
w= length(HI) /*get maximum width for pretty output. */
numeric digits max(9, w + 1) /*maybe bump the precision of numbers. */
#= 0 /*the number of primes found (so far). */
do n=abs(LO) to HI; f= factr(n) /*process a single number or a range.*/
p= words( translate(f, ,@) ) - (n==1) /*P: is the number of prime factors. */
if p==1 then #= # + 1 /*bump the primes counter (exclude N=1)*/
if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/
end /*n*/
say
say right(#, w) ' primes found.' /*display the number of primes found. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure expose @; parse arg z 1 n,$; if z<2 then return z /*is Z too small?*/
do while z//2==0; $= $||@||2; z= z%2; end /*maybe add factor of 2 */
do while z//3==0; $= $||@||3; z= z%3; end /* " " " " 3 */
do while z//5==0; $= $||@||5; z= z%5; end /* " " " " 5 */
do while z//7==0; $= $||@||7; z= z%7; end /* " " " " 7 */
do j=11 by 6 while j<=z /*insure that J isn't divisible by 3.*/
parse var j '' -1 _ /*get the last decimal digit of J. */
if _\==5 then do while z//j==0; $=$||@||j; z= z%j; end /*maybe reduce Z.*/
if _ ==3 then iterate /*Next # ÷ by 5? Skip. ___ */
if j*j>n then leave /*are we higher than the √ N ? */
y= j + 2 /*obtain the next odd divisor. */
do while z//y==0; $=$||@||y; z= z%y; end /*maybe reduce Z.*/
end /*j*/
if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/
return substr($||@||z, 1+length(@) ) /*elide superfluous header. */ |
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.
| #OCaml | OCaml | let () =
let buf = Buffer.create 1 in
let s = Buffer.add_string buf in
Random.self_init();
s "<table>";
s "<thead align='right'>";
s "<tr><th></th>";
List.iter (fun v ->
s ("<td>" ^ v ^ "</td>")
) ["X"; "Y"; "Z"];
s "</tr>";
s "</thead>";
s "<tbody align='right'>";
for i = 0 to pred 3 do
s ("<tr><td>" ^ string_of_int i ^ "</td>");
for j = 0 to pred 3 do
s ("<td>" ^ string_of_int (Random.int 1000) ^ "</td>");
done;
s "</tr>";
done;
s "</tbody>";
s "</table>";
print_endline (Buffer.contents buf) |
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.
| #Run_BASIC | Run BASIC | open "output.txt" for output as #f
close #f
dirOk = mkdir( "f:\doc")
if not(dirOk) then print "Directory not created!": end
open "f:\doc\output.txt" for output as #f
close #f |
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.
| #Rust | Rust | use std::io::{self, Write};
use std::fs::{DirBuilder, File};
use std::path::Path;
use std::{process,fmt};
const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";
fn main() {
create(".").and(create("/"))
.unwrap_or_else(|e| error_handler(e,1));
}
fn create<P>(root: P) -> io::Result<File>
where P: AsRef<Path>
{
let f_path = root.as_ref().join(FILE_NAME);
let d_path = root.as_ref().join(DIR_NAME);
DirBuilder::new().create(d_path).and(File::create(f_path))
}
fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
let _ = writeln!(&mut io::stderr(), "Error: {}", error);
process::exit(code)
} |
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).
| #R | R | File <- "~/test.csv"
Opened <- readLines(con = File)
Size <- length(Opened)
HTML <- "~/test.html"
Table <- list()
for(i in 1:Size)
{
#i=1
Split <- unlist(strsplit(Opened[i],split = ","))
Table[i] <- paste0("<td>",Split,"</td>",collapse = "")
Table[i] <- paste0("<tr>",Table[i],"</tr>")
}
Table[1] <- paste0("<table>",Table[1])
Table[length(Table)] <- paste0(Table[length(Table)],"</table>")
writeLines(as.character(Table), 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.
| #Vim_Script | Vim Script | " Create a two-dimensional array with r rows and c columns.
" The optional third argument specifies the initial value
" (default is 0).
function MakeArray(r, c, ...)
if a:0
let init = a:1
else
let init = 0
endif
let temp = []
for c in range(a:c)
call add(temp, init)
endfor
let array = []
for r in range(a:r)
call add(array, temp[:])
endfor
return array
endfunction
let rows = input("Enter number of rows: ")
let cols = input("Enter number of columns: ")
echo "\n"
let array = MakeArray(rows, cols)
let array[rows - 1][cols - 1] = rows * cols
echo array[rows - 1][cols - 1]
unlet 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
| #Scala | Scala | import scala.math.sqrt
object StddevCalc extends App {
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
def avg(ts: Iterable[T])(implicit num: Fractional[T]): T =
num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T
val mean: T = avg(ts) // Leave val type of T
// Root of mean diffs
val stdDev = sqrt(ts.map { x =>
val diff = num.toDouble(num.minus(x, mean))
diff * diff
}.sum / ts.size)
(mean, stdDev)
}
println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9)))
println(calcAvgAndStddev(Set(1.0, 2, 3, 4)))
println(calcAvgAndStddev(0.1 to 1.1 by 0.05))
println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200))))
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
} |
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.
| #Visual_Basic | Visual Basic | Option Explicit
'----------------------------------------------------------------------
Private Function coin_count(coins As Variant, amount As Long) As Variant
'return type will be Decimal
Dim s() As Variant
Dim n As Long, c As Long
ReDim s(amount + 1)
s(1) = CDec(1)
For c = LBound(coins) 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
'----------------------------------------------------------------------
Sub Main()
Dim us_common_coins As Variant
Dim us_coins As Variant
'The next line creates 0-based array
us_common_coins = Array(25, 10, 5, 1)
Debug.Print coin_count(us_common_coins, 100)
us_coins = Array(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.
| #Vlang | Vlang | fn main() {
amount := 100
println("amount, ways to make change: $amount ${count_change(amount)}"))
}
fn count_change(amount int) i64 {
return cc(amount, 4)
}
fn cc(amount int, kinds_of_coins int) i64 {
if amount == 0 {
return 1
} else if amount < 0 || kinds_of_coins == 0 {
return 0
}
return cc(amount, kinds_of_coins-1) +
cc(amount - first_denomination(kinds_of_coins), kinds_of_coins)
}
fn first_denomination(kinds_of_coins int) int {
match kinds_of_coins {
1 {
return 1
}
2 {
return 5
}
3 {
return 10
}
4 {
return 25
}
}
} |
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
| #Racket | Racket |
(define count-substring
(compose length regexp-match*))
|
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
| #Raku | Raku | sub count-substring($big, $little) { +$big.comb: / :r $little / }
say count-substring("the three truths", "th"); # 3
say count-substring("ababababab", "abab"); # 2
say count-substring(123123123, 12); # 3 |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: i is 0;
begin
repeat
writeln(i radix 8);
incr(i);
until FALSE;
end func; |
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.
| #Sidef | Sidef | var i = 0;
loop { say i++.as_oct } |
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.
| #Simula | Simula |
BEGIN
PROCEDURE OUTOCT(N); INTEGER N;
BEGIN
PROCEDURE OCT(N); INTEGER N;
BEGIN
IF N > 0 THEN BEGIN
OCT(N//8);
OUTCHAR(CHAR(RANK('0')+MOD(N,8)));
END;
END OCT;
IF N < 0 THEN BEGIN OUTCHAR('-'); OUTOCT(-N); END
ELSE IF N = 0 THEN OUTCHAR('0')
ELSE OCT(N);
END OUTOCT;
INTEGER I;
WHILE I < MAXINT DO BEGIN
OUTINT(I,0);
OUTTEXT(" => ");
OUTOCT(I);
OUTIMAGE;
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
| #Ring | Ring |
for i = 1 to 20
see "" + i + " = " + factors(i) + nl
next
func factors n
f = ""
if n = 1 return "1" ok
p = 2
while p <= n
if (n % p) = 0
f += string(p) + " x "
n = n/p
else p += 1 ok
end
return left(f, len(f) - 3)
|
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
| #Ruby | Ruby | require 'optparse'
require 'prime'
maximum = 10
OptionParser.new do |o|
o.banner = "Usage: #{File.basename $0} [-m MAXIMUM]"
o.on("-m MAXIMUM", Integer,
"Count up to MAXIMUM [#{maximum}]") { |m| maximum = m }
o.parse! rescue ($stderr.puts $!, o; exit 1)
($stderr.puts o; exit 1) unless ARGV.size == 0
end
# 1 has no prime factors
puts "1 is 1" unless maximum < 1
2.upto(maximum) do |i|
# i is 504 => i.prime_division is [[2, 3], [3, 2], [7, 1]]
f = i.prime_division.map! do |factor, exponent|
# convert [2, 3] to "2 x 2 x 2"
([factor] * exponent).join " x "
end.join " x "
puts "#{i} is #{f}"
end |
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.
| #Oz | Oz | declare
[Roads] = {Module.link ['x-ozlib://wmeyer/roads/Roads.ozf']}
fun {Table Session}
html(
head(title("Show a table with row and column headings")
style(type:"text/css"
css(td 'text-align':center)
))
body(
{TagFromList table
tr(th th("X") th("Y") th("Z"))
|
{CreateRows 3 5}
}))
end
fun {CreateRows NumCols NumRows}
{List.map {List.number 1 NumRows 1}
fun {$ Row}
{TagFromList tr
td( {Int.toString Row} )
|
{List.map {List.number 1 NumCols 1}
fun {$ Col}
SequentialNumber = (Row-1)*NumCols + Col
in
td( {Int.toString SequentialNumber} )
end
}}
end
}
end
TagFromList = List.toTuple
in
{Roads.registerFunction table Table}
{Roads.run} |
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.
| #Scala | Scala | import java.io.File
object CreateFile extends App {
try { new File("output.txt").createNewFile() }
catch { case e: Exception => println(s"Exception caught: $e with creating output.txt") }
try { new File(s"${File.separator}output.txt").createNewFile() }
catch { case e: Exception => println(s"Exception caught: $e with creating ${File.separator}output.txt") }
try { new File("docs").mkdir() }
catch { case e: Exception => println(s"Exception caught: $e with creating directory docs") }
try { new File(s"${File.separator}docs").mkdir() }
catch { case e: Exception => println(s"Exception caught: $e with creating directory ${File.separator}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).
| #Racket | Racket | #lang racket
(define e.g.-CSV
(string-join
'("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!")
"\n"))
(define (CSV-lines->HTML-table csv)
(define csv-rows
(regexp-split "\n" csv))
(define csv-row-cells
(map (lambda (row) (regexp-split "," row)) csv-rows))
(define (cell-data->HTML-data data)
`(td () ,data))
(define (row-data->HTML-row CSV-row)
`(tr () ,@(map cell-data->HTML-data CSV-row) "\n"))
`(table
(thead
,(row-data->HTML-row (car csv-row-cells)))
(tbody ,@(map row-data->HTML-row (cdr csv-row-cells)))))
(require xml)
(display (xexpr->string (CSV-lines->HTML-table e.g.-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.
| #Wren | Wren | import "io" for Stdin, Stdout
var x
var y
System.print("Enter the dimensions of the array:")
while (true) {
System.write(" First dimension : ")
Stdout.flush()
x = Num.fromString(Stdin.readLine())
if (x && (x is Num) && (x.isInteger) && (x > 0) ) {
System.write(" Second dimension : ")
Stdout.flush()
y = Num.fromString(Stdin.readLine())
if (y && (y is Num) && (y.isInteger) && (y > 0) ) break
System.print("Dimension must be a positive integer.")
} else {
System.print("Dimension must be a positive integer.")
}
}
// create the 2d array
var a = List.filled(x, null)
for (i in 0...x) a[i] = List.filled(y, 0)
// write an element
a[x - 1][y - 1] = 42
// print it
System.print("\na[%(x-1)][%(y-1)] = %(a[x-1][y-1])")
// make the array eligible for garbage collection
a = null |
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
| #Scheme | Scheme |
(define (standart-deviation-generator)
(let ((nums '()))
(lambda (x)
(set! nums (cons x nums))
(let* ((mean (/ (apply + nums) (length nums)))
(mean-sqr (lambda (y) (expt (- y mean) 2)))
(variance (/ (apply + (map mean-sqr nums)) (length nums))))
(sqrt variance)))))
(let loop ((f (standart-deviation-generator))
(input '(2 4 4 4 5 5 7 9)))
(if (not (null? input))
(begin
(display (f (car input)))
(newline)
(loop f (cdr input)))))
|
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.
| #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var countCoins = Fn.new { |c, m, n|
var table = List.filled(n + 1, null)
table[0] = BigInt.one
for (i in 1..n) table[i] = BigInt.zero
for (i in 0...m) {
for (j in c[i]..n) table[j] = table[j] + table[j-c[i]]
}
return table[n]
}
var c = [1, 5, 10, 25, 50, 100]
Fmt.print("Ways to make change for $$1 using 4 coins = $,i", countCoins.call(c, 4, 100))
Fmt.print("Ways to make change for $$1,000 using 6 coins = $,i", countCoins.call(c, 6, 1000 * 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
| #Red | Red | Red []
count-occurrences: function [string substring] [
length? parse string [collect [some [keep substring to substring]]]
]
test-case-1: "the three truths"
test-case-2: "ababababab"
print [test-case-1 "-" count-occurrences test-case-1 "th"]
print [test-case-2 "-" count-occurrences test-case-2 "abab"]
|
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
| #REXX | REXX | /*REXX program counts the occurrences of a (non─overlapping) substring in a string. */
w=. /*max. width so far.*/
bag= 'the three truths' ; x= "th" ; call showResult
bag= 'ababababab' ; x= "abab" ; call showResult
bag= 'aaaabacad' ; x= "aa" ; call showResult
bag= 'abaabba*bbaba*bbab' ; x= "a*b" ; call showResult
bag= 'abaabba*bbaba*bbab' ; x= " " ; call showResult
bag= ; x= "a" ; call showResult
bag= ; x= ; call showResult
bag= 'catapultcatalog' ; x= "cat" ; call showResult
bag= 'aaaaaaaaaaaaaa' ; x= "aa" ; call showResult
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
countstr: procedure; parse arg haystack,needle,start; if start=='' then start=1
width=length(needle)
do $=0 until p==0; p=pos(needle,haystack,start)
start=width + p /*prevent overlaps.*/
end /*$*/
return $ /*return the count.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
showResult: if w==. then do; w=30 /*W: largest haystack width.*/
say center('haystack',w) center('needle',w%2) center('count',5)
say left('', w, "═") left('', w%2, "═") left('', 5, "═")
end
if bag=='' then bag= " (null)" /*handle displaying of nulls.*/
if x=='' then x= " (null)" /* " " " " */
say left(bag, w) left(x, w%2) center(countstr(bag, x), 5)
return |
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.
| #Smalltalk | Smalltalk | 0 to:Integer infinity do:[:n |
n printOn:Stdout radix:8.
Stdout cr.
] |
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.
| #Sparkling | Sparkling | for (var i = 0; true; i++) {
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.
| #Standard_ML | Standard ML | local
fun count n = (print (Int.fmt StringCvt.OCT n ^ "\n"); count (n+1))
in
val _ = count 0
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
| #Run_BASIC | Run BASIC | for i = 1000 to 1016
print i;" = "; factorial$(i)
next
wait
function factorial$(num)
if num = 1 then factorial$ = "1"
fct = 2
while fct <= num
if (num mod fct) = 0 then
factorial$ = factorial$ ; x$ ; fct
x$ = " x "
num = num / fct
else
fct = fct + 1
end if
wend
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
| #Rust | Rust | use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
let n = if args.len() > 1 {
args[1].parse().expect("Not a valid number to count to")
}
else {
20
};
count_in_factors_to(n);
}
fn count_in_factors_to(n: u64) {
println!("1");
let mut primes = vec![];
for i in 2..=n {
let fs = factors(&primes, i);
if fs.len() <= 1 {
primes.push(i);
println!("{}", i);
}
else {
println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x "));
}
}
}
fn factors(primes: &[u64], mut n: u64) -> Vec<u64> {
let mut result = Vec::new();
for p in primes {
while n % p == 0 {
result.push(*p);
n /= p;
}
if n == 1 {
return result;
}
}
vec![n]
} |
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.
| #PARI.2FGP | PARI/GP | html(n=3)={
print("<table>\n<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>");
for(i=1,n,
print1("<tr><td>"i"</td>");
for(j=1,3,print1("<td>"random(9999)"</td>"));
print("</tr>")
);
print("</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.
| #Scheme | Scheme | (open-output-file "output.txt")
(open-output-file "/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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
local
var file: aFile is STD_NULL;
begin
aFile := open("output.txt", "w");
close(aFile);
mkdir("docs");
aFile := open("/output.txt", "w");
close(aFile);
mkdir("/docs");
end func; |
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).
| #Raku | Raku | my $str = "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!";
# comment the next line out, if you want to read from standard input instead of the hard-coded $str above
# my $str = $*IN.slurp;
my &escape = *.trans(« & < > » => « & < > »); # a function with one argument that escapes the entities
my &tag = {"<$^tag>"~$^what~"</$^tag>"};
printf
'<!DOCTYPE html>
<html>
<head><title>Some Text</title></head>
<body><table>
%s
</table></body></html>
', [~] # concatenation reduction ('a', 'b', 'c') → 'abc'
(escape($str).split(/\n/) # escape the string and split at newline
==> map -> $line {tag 'tr', # feed that into a map, that map function will tag as 'tr, and has an argument called $line
([~] $line.split(/','/)\ # split $line at ',',
# that / at the end is just an unspace, you can omit it, but then you have to delete
# all whitespace and comments between split(…) and .map
.map({tag 'td', $^cell}))})\ # map those cells as td
.join("\n"); # append a newline for nicer output |
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.
| #XPL0 | XPL0 | inc c:\cxpl\codes; \(command words can be abbreviated to first 3 letters)
def IntSize=4; \number of bytes in an integer (2 or 4 depending on version)
int X, Y, A, I;
[X:= IntIn(0); Y:= IntIn(0); \get 2 dimensions from user
A:= Reserve(X*IntSize);
for I:= 0 to X-1 do A(I):= Reserve(Y*IntSize);
A(X/2, Y/2):= X+Y;
IntOut(0, A(X/2, Y/2)); CrLf(0);
] |
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.
| #zkl | zkl | rows:=ask("Rows: ").toInt();
cols:=ask("columns: ").toInt();
array:=rows.pump(List.createLong(rows),List.createLong(cols,0).copy);
array[1][2]=123;
array.println();
array[1][2].println(); |
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
| #Scilab | Scilab | T=[2,4,4,4,5,5,7,9];
stdev(T)*sqrt((length(T)-1)/length(T)) |
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.
| #zkl | zkl | fcn ways_to_make_change(x, coins=T(25,10,5,1)){
if(not coins) return(0);
if(x<0) return(0);
if(x==0) return(1);
ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins)
}
ways_to_make_change(100).println(); |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET amount=100
20 GO SUB 1000
30 STOP
1000 LET nPennies=amount
1010 LET nNickles=INT (amount/5)
1020 LET nDimes=INT (amount/10)
1030 LET nQuarters=INT (amount/25)
1040 LET count=0
1050 FOR p=0 TO nPennies
1060 FOR n=0 TO nNickles
1070 FOR d=0 TO nDimes
1080 FOR q=0 TO nQuarters
1090 LET s=p+n*5+d*10+q*25
1100 IF s=100 THEN LET count=count+1
1110 NEXT q
1120 NEXT d
1130 NEXT n
1140 NEXT p
1150 PRINT count
1160 RETURN |
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
| #Ring | Ring |
aString = "Ring Welcome Ring to the Ring Ring Programming Ring Language Ring"
bString = "Ring"
see count(aString,bString)
func count cString,dString
sum = 0
while substr(cString,dString) > 0
sum++
cString = substr(cString,substr(cString,dString)+len(string(sum)))
end
return sum |
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
| #Ruby | Ruby | def countSubstrings str, subStr
str.scan(subStr).length
end
p countSubstrings "the three truths", "th" #=> 3
p countSubstrings "ababababab", "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.
| #Swift | Swift | import Foundation
func octalSuccessor(value: String) -> String {
if value.isEmpty {
return "1"
} else {
let i = value.startIndex, j = value.endIndex.predecessor()
switch (value[j]) {
case "0": return value[i..<j] + "1"
case "1": return value[i..<j] + "2"
case "2": return value[i..<j] + "3"
case "3": return value[i..<j] + "4"
case "4": return value[i..<j] + "5"
case "5": return value[i..<j] + "6"
case "6": return value[i..<j] + "7"
case "7": return octalSuccessor(value[i..<j]) + "0"
default:
NSException(name:"InvalidDigit", reason: "InvalidOctalDigit", userInfo: nil).raise();
return ""
}
}
}
var n = "0"
while strtoul(n, nil, 8) < UInt.max {
println(n)
n = octalSuccessor(n)
} |
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.
| #Tcl | Tcl | package require Tcl 8.5; # arbitrary precision integers; we can count until we run out of memory!
while 1 {
puts [format "%llo" [incr counter]]
} |
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.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
num=0
while true; do
echo $num
num=`echo "obase=8;ibase=8;$num+1"|bc`
done |
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
| #Sage | Sage | def count_in_factors(n):
if is_prime(n) or n == 1:
print(n,end="")
return
while n != 1:
p = next_prime(1)
while n % p != 0:
p = next_prime(p)
print(p,end="")
n = n / p
if n != 1: print(" x",end=" ")
for i in range(1, 101):
print(i,"=",end=" ")
count_in_factors(i)
print("") |
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
| #Scala | Scala |
object CountInFactors extends App {
def primeFactors(n: Int): List[Int] = {
def primeStream(s: LazyList[Int]): LazyList[Int] = {
s.head #:: primeStream(s.tail filter {
_ % s.head != 0
})
}
val primes = primeStream(LazyList.from(2))
def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match {
case None => Nil
case Some(p) => p :: factors(n / p)
}
if (n == 1) List(1) else factors(n)
}
// A little test...
{
val nums = (1 to 12).toList :+ 2144 :+ 6358
nums.foreach(n => println("%6d : %s".format(n, primeFactors(n).mkString(" * "))))
}
}
|
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.
| #Pascal | Pascal | <@ SDCLIT>
<@ DTBLIT>
<@ DTRLITLIT>
<@ DTDLITLIT>|[style]background-color:white</@>
<@ DTD>X</@>
<@ DTD>Y</@>
<@ DTD>Z</@>|[style]width:100%; background-color:brown;color:white; text-align:center</@>
<@ ITEFORLIT>10|
<@ DTRLITCAP>
<@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
|[style]background-color:white;color:black</@>
</@>
</@>
|Number 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.
| #SenseTalk | SenseTalk | set the folder to "~/Desktop"
put "" into file "docs/output.txt"
set the folder to "/"
put empty into file "/docs/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.
| #Sidef | Sidef | # Here
%f'output.txt' -> create;
%d'docs' -> create;
# Root dir
Dir.root + %f'output.txt' -> create;
Dir.root + %d'docs' -> create; |
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).
| #Red | Red | Red []
csv: {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!}
add2html: func [ bl ] [append html rejoin bl ] ;; helper function to add block data to html string
;;----------------------------------------------------------------------
csv2html: func ["function to generate string with html table from csv data file"
;;----------------------------------------------------------------------
s [string!] "input .csv data"
][
arr: split s newline ;; generate array (series) from string
html: copy "<table border=1>^/" ;; init html string
forall arr [ ;; i use forall here so that i can test for head? of series ...
either head? arr [ append html "<tr bgcolor=wheat>"]
[ append html "<tr>"]
replace/all first arr "<" "<" ;; escape "<" and ">" characters
replace/all first arr ">" ">"
foreach col split first arr "," [
either head? arr [
add2html ['<th> col '</th>]
][
add2html ['<td> col '</td>]
]
]
add2html ['</tr> newline]
]
return add2html ['</table>]
]
;;----------------------------------------------------------------------
print csv2html csv ;; call function
write %data.html csv2html csv ;; write to file
|
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.
| #zonnon | zonnon |
module Main;
type
Matrix = array *,* of integer;
var
m: Matrix;
i,j: integer;
begin
write("first dim? ");readln(i);
write("second dim? ");readln(j);
m := new Matrix(i,j);
m[0,0] := 10;
writeln("m[0,0]:> ",m[0,0]);
writeln("m[0,1].> ",m[0,1])
end Main.
|
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
| #Sidef | Sidef | class StdDevAccumulator(n=0, sum=0, sumofsquares=0) {
method <<(num) {
n += 1
sum += num
sumofsquares += num**2
self
}
method stddev {
sqrt(sumofsquares/n - pow(sum/n, 2))
}
method to_s {
self.stddev.to_s
}
}
var i = 0
var sd = StdDevAccumulator()
[2,4,4,4,5,5,7,9].each {|n|
say "adding #{n}: stddev of #{i+=1} samples is #{sd << 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
| #Run_BASIC | Run BASIC | print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")
FUNCTION countSubstring(s$,find$)
WHILE instr(s$,find$,i) <> 0
countSubstring = countSubstring + 1
i = instr(s$,find$,i) + len(find$)
WEND
END FUNCTION |
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
| #Rust | Rust |
fn main() {
println!("{}","the three truths".matches("th").count());
println!("{}","ababababab".matches("abab").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.
| #VBA | VBA |
Sub CountOctal()
Dim i As Integer
i = 0
On Error GoTo OctEnd
Do
Debug.Print Oct(i)
i = i + 1
Loop
OctEnd:
Debug.Print "Integer overflow - count terminated"
End Sub
|
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.
| #VBScript | VBScript |
For i = 0 To 20
WScript.StdOut.WriteLine Oct(i)
Next
|
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.
| #Vim_Script | Vim Script | let counter = 0
while counter >= 0
echon printf("%o\n", counter)
let counter += 1
endwhile |
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
| #Scheme | Scheme | (define (factors n)
(let facs ((l '()) (d 2) (x n))
(cond ((= x 1) (if (null? l) '(1) l))
((< x (* d d)) (cons x l))
(else (if (= 0 (modulo x d))
(facs (cons d l) d (/ x d))
(facs l (+ 1 d) x))))))
(define (show l)
(display (car l))
(if (not (null? (cdr l)))
(begin
(display " × ")
(show (cdr l)))
(display "\n")))
(do ((i 1 (+ i 1))) (#f)
(display i)
(display " = ")
(show (reverse (factors i)))) |
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.
| #Peloton | Peloton | <@ SDCLIT>
<@ DTBLIT>
<@ DTRLITLIT>
<@ DTDLITLIT>|[style]background-color:white</@>
<@ DTD>X</@>
<@ DTD>Y</@>
<@ DTD>Z</@>|[style]width:100%; background-color:brown;color:white; text-align:center</@>
<@ ITEFORLIT>10|
<@ DTRLITCAP>
<@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
|[style]background-color:white;color:black</@>
</@>
</@>
|Number 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.
| #Slate | Slate | (File newNamed: 'output.txt') touch.
(Directory current / 'output.txt') touch. |
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.
| #Smalltalk | Smalltalk | (FileDirectory on: 'c:\') newFileNamed: 'output.txt'; 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).
| #Retro | Retro | remapping off
"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!" remapping on
keepString constant CSV
: display ( c- )
[ ', = ] [ drop "</td><td>" puts ] when
[ 10 = ] [ drop "</td></tr>\n<tr><td>" puts ] when
[ '< = ] [ drop "<" puts ] when
[ '> = ] [ drop ">" puts ] when
[ '& = ] [ drop "&" puts ] when
putc ;
: displayHTML ( $- )
"<table>\n<tr><td>" puts
[ @ display ] ^types'STRING each@
"</td></tr>\n</table>" puts ;
CSV displayHTML |
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
| #Smalltalk | Smalltalk | Object subclass: SDAccum [
|sum sum2 num|
SDAccum class >> new [ |o|
o := super basicNew.
^ o init.
]
init [ sum := 0. sum2 := 0. num := 0 ]
value: aValue [
sum := sum + aValue.
sum2 := sum2 + ( aValue * aValue ).
num := num + 1.
^ self stddev
]
count [ ^ num ]
mean [ num>0 ifTrue: [^ sum / num] ifFalse: [ ^ 0.0 ] ]
variance [ |m| m := self mean.
num>0 ifTrue: [^ (sum2/num) - (m*m) ] ifFalse: [ ^ 0.0 ]
]
stddev [ ^ (self variance) sqrt ]
]. |
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
| #Scala | Scala | import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
@tailrec def count(pos:Int, c:Int):Int={
val idx=str1 indexOf(str2, pos)
if(idx == -1) c else count(idx+str2.size, c+1)
}
count(0,0)
} |
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
| #Scheme | Scheme | gosh> (use gauche.lazy)
#<undef>
gosh> (length (lrxmatch "th" "the three truths"))
3
gosh> (length (lrxmatch "abab" "ababababab"))
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.
| #Vlang | Vlang | import math
fn main() {
for i := i8(0); ; i++ {
println("${i:o}")
if i == math.max_i8 {
break
}
}
} |
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.
| #VTL-2 | VTL-2 | 1000 N=0
1010 #=2000
1020 ?=""
1030 #=N=65535*9999
1040 N=N+1
1050 #=1010
2000 R=!
2010 O=N
2020 D=1
2030 O=O/8
2040 :D)=%
2050 D=D+1
2060 #=O>1*2030
2070 E=D-1
2080 $=48+:E)
2090 E=E-1
2100 #=E>1*2080
2110 #=R |
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.
| #Whitespace | Whitespace | |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: writePrimeFactors (in var integer: number) is func
local
var boolean: laterElement is FALSE;
var integer: checker is 2;
begin
while checker * checker <= number do
if number rem checker = 0 then
if laterElement then
write(" * ");
end if;
laterElement := TRUE;
write(checker);
number := number div checker;
else
incr(checker);
end if;
end while;
if number <> 1 then
if laterElement then
write(" * ");
end if;
laterElement := TRUE;
write(number);
end if;
end func;
const proc: main is func
local
var integer: number is 0;
begin
writeln("1: 1");
for number range 2 to 2147483647 do
write(number <& ": ");
writePrimeFactors(number);
writeln;
end for;
end func; |
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
| #Sidef | Sidef | class Counter {
method factors(n, p=2) {
var a = gather {
while (n >= p*p) {
while (p `divides` n) {
take(p)
n //= p
}
p = self.next_prime(p)
}
}
(n > 1 || a.is_empty) ? (a << n) : a
}
method is_prime(n) {
self.factors(n).len == 1
}
method next_prime(p) {
do {
p == 2 ? (p = 3) : (p+=2)
} while (!self.is_prime(p))
return p
}
}
for i in (1..100) {
say "#{i} = #{Counter().factors(i).join(' × ')}"
} |
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.
| #Perl | Perl | my @heading = qw(X Y Z);
my $rows = 5;
print '<table><thead><td>',
(map { "<th>$_</th>" } @heading),
"</thead><tbody>";
for (1 .. $rows) {
print "<tr><th>$_</th>",
(map { "<td>".int(rand(10000))."</td>" } @heading),
"</tr>";
}
print "</tbody></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.
| #SNOBOL4 | SNOBOL4 | output(.file,1,'output.txt'); endfile(1) ;* Macro Spitbol
* output(.file,1,,'output.txt'); endfile(1) ;* CSnobol
host(1,'mkdir docs')
output(.file,1,'/output.txt'); endfile(1) ;* Macro Spitbol
* output(.file,1,,'/output.txt'); endfile(1) ;* CSnobol
host(1,'mkdir /docs')
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.
| #SQL_PL | SQL PL |
BEGIN
DECLARE UTL_FILE_HANDLER UTL_FILE.FILE_TYPE;
DECLARE DIR_ALIAS_CURRENT VARCHAR(128);
DECLARE DIR_ALIAS_ROOT VARCHAR(128);
DECLARE DIRECTORY VARCHAR(1024);
DECLARE FILENAME VARCHAR(255);
SET DIR_ALIAS_CURRENT = 'outputFileCurrent';
SET DIRECTORY = '/home/db2inst1/doc';
SET FILENAME = 'output.txt';
CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_CURRENT, DIRECTORY);
SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_CURRENT, FILENAME, 'a');
CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);
CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);
SET DIR_ALIAS_ROOT = 'outputFileRoot';
SET DIRECTORY = '/doc';
CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY(DIR_ALIAS_ROOT, DIRECTORY);
SET UTL_FILE_HANDLER = UTL_FILE.FOPEN(DIR_ALIAS_ROOT, FILENAME, 'a');
CALL UTL_FILE.FFLUSH(UTL_FILE_HANDLER);
CALL UTL_FILE.FCLOSE(UTL_FILE_HANDLER);
END @
|
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).
| #REXX | REXX | /*REXX program converts CSV ───► HTML table representing the CSV data. */
arg header_ . /*obtain an uppercase version of args. */
wantsHdr= (header_=='HEADER') /*is the arg (low/upp/mix case)=HEADER?*/
/* [↑] determine if user wants a hdr. */
iFID= 'CSV_HTML.TXT' /*the input fileID to be used. */
if wantsHdr then oFID= 'OUTPUTH.HTML' /*the output fileID with header.*/
else oFID= 'OUTPUT.HTML' /* " " " without " */
do rows=0 while lines(iFID)\==0 /*read the rows from a (text/txt) file.*/
row.rows= strip( linein(iFID) )
end /*rows*/
convFrom= '& < > "' /*special characters to be converted. */
convTo = '& < > "' /*display what they are converted into.*/
call write , '<html>'
call write , '<table border=4 cellpadding=9 cellspacing=1>'
do j=0 for rows; call write 5, '<tr>'
tx= 'td'
if wantsHdr & j==0 then tx= 'th' /*if user wants a header, then oblige. */
do while row.j\==''; parse var row.j yyy "," row.j
do k=1 for words(convFrom)
yyy=changestr( word( convFrom, k), yyy, word( convTo, k))
end /*k*/
call write 10, '<'tx">"yyy'</'tx">"
end /*forever*/
end /*j*/
call write 5, '<tr>'
call write , '</table>'
call write , '</html>'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
write: call lineout oFID, left('', 0 || arg(1) )arg(2); return |
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
| #SQL | SQL | -- the minimal table
CREATE TABLE IF NOT EXISTS teststd (n DOUBLE PRECISION NOT NULL);
-- code modularity with view, we could have used a common table expression instead
CREATE VIEW vteststd AS
SELECT COUNT(n) AS cnt,
SUM(n) AS tsum,
SUM(POWER(n,2)) AS tsqr
FROM teststd;
-- you can of course put this code into every query
CREATE OR REPLACE FUNCTION std_dev() RETURNS DOUBLE PRECISION AS $$
SELECT SQRT(tsqr/cnt - (tsum/cnt)^2) FROM vteststd;
$$ LANGUAGE SQL;
-- test data is: 2,4,4,4,5,5,7,9
INSERT INTO teststd VALUES (2);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (5);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (5);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (7);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (9);
SELECT std_dev() AS std_deviation;
-- cleanup test data
DELETE FROM teststd;
|
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: countSubstring (in string: stri, in string: searched) is func
result
var integer: count is 0;
local
var integer: offset is 0;
begin
offset := pos(stri, searched);
while offset <> 0 do
incr(count);
offset := pos(stri, searched, offset + length(searched));
end while;
end func;
const proc: main is func
begin
writeln(countSubstring("the three truths", "th"));
writeln(countSubstring("ababababab", "abab"));
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
| #SenseTalk | SenseTalk |
put the number of occurrences of "th" in "the three truths" --> 3
put the number of occurrences of "abab" in "ababababab" -- > 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.
| #Wren | Wren | import "/fmt" for Conv
var i = 0
while (true) {
System.print(Conv.oct(i))
i = i + 1
} |
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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic code declarations
proc OctOut(N); \Output N in octal
int N;
int R;
[R:= N&7;
N:= N>>3;
if N then OctOut(N);
ChOut(0, R+^0);
];
int I;
[I:= 0;
repeat OctOut(I); CrLf(0);
I:= I+1;
until KeyHit or I=0;
] |
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.
| #zig | zig | const std = @import("std");
const fmt = std.fmt;
const warn = std.debug.warn;
pub fn main() void {
var i: u8 = 0;
var buf: [3]u8 = undefined;
while (i < 255) : (i += 1) {
_ = fmt.formatIntBuf(buf[0..], i, 8, false, 0); // buffer, value, base, uppercase, width
warn("{}\n", buf);
}
} |
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
| #Swift | Swift | extension BinaryInteger {
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0 ? 2 : 3
while q <= maxQ && self % q != 0 {
q = step(d)
d += 1
}
return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]
}
}
for i in 1...20 {
if i == 1 {
print("1 = 1")
} else {
print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " x "))")
}
} |
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
| #Tcl | Tcl | package require Tcl 8.5
namespace eval prime {
variable primes [list 2 3 5 7 11]
proc restart {} {
variable index -1
variable primes
variable current [lindex $primes end]
}
proc get_next_prime {} {
variable primes
variable index
if {$index < [llength $primes]-1} {
return [lindex $primes [incr index]]
}
variable current
while 1 {
incr current 2
set p 1
foreach prime $primes {
if {$current % $prime} {} else {
set p 0
break
}
}
if {$p} {
return [lindex [lappend primes $current] [incr index]]
}
}
}
proc factors {num} {
restart
set factors [dict create]
for {set i [get_next_prime]} {$i <= $num} {} {
if {$num % $i == 0} {
dict incr factors $i
set num [expr {$num / $i}]
continue
} elseif {$i*$i > $num} {
dict incr factors $num
break
} else {
set i [get_next_prime]
}
}
return $factors
}
# Produce the factors in rendered form
proc factors.rendered {num} {
set factorDict [factors $num]
if {[dict size $factorDict] == 0} {
return 1
}
dict for {factor times} $factorDict {
lappend v {*}[lrepeat $times $factor]
}
return [join $v "*"]
}
} |
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.
| #Phix | Phix | puts(1,"<table border=2>\n")
puts(1," <tr><th></th>")
for j=1 to 3 do
printf(1,"<th>%s</th>",'W'+j)
end for
puts(1,"</tr>\n")
for i=1 to 3 do
printf(1," <tr><td>%d</td>",i)
for j=1 to 3 do
printf(1,"<td>%d</td>",rand(10000))
end for
puts(1,"</tr>\n")
end for
puts(1,"</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.
| #SQLite | SQLite |
/*
*Use '/' for *nix. Use whatever your root directory is on Windows.
*Must be run as admin.
*/
.shell mkdir "docs";
.shell mkdir "/docs";
.output output.txt
.output /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.
| #Standard_ML | Standard ML | let val out = TextIO.openOut "output.txt" in
TextIO.closeOut out
end;
OS.FileSys.mkDir "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).
| #Ruby | Ruby | ruby csv2html.rb header
|
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
| #Swift | Swift | import Darwin
class stdDev{
var n:Double = 0.0
var sum:Double = 0.0
var sum2:Double = 0.0
init(){
let testData:[Double] = [2,4,4,4,5,5,7,9];
for x in testData{
var a:Double = calcSd(x)
println("value \(Int(x)) SD = \(a)");
}
}
func calcSd(x:Double)->Double{
n += 1
sum += x
sum2 += x*x
return sqrt( sum2 / n - sum*sum / n / n)
}
}
var aa = stdDev() |
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
| #Sidef | Sidef | say "the three truths".count("th");
say "ababababab".count("abab"); |
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
| #Simula | Simula | BEGIN
INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;
BEGIN
INTEGER N,I;
I := 1;
WHILE I+TSUB.LENGTH-1 <= T.LENGTH DO
IF T.SUB(I,TSUB.LENGTH) = TSUB THEN
BEGIN
N := N+1;
I := I+MAX(TSUB.LENGTH,1);
END ELSE I := I+1;
COUNTSUBSTRING:= N;
END COUNTSUBSTRING;
OUTINT(COUNTSUBSTRING("THE THREE TRUTHS", "TH"),0);
OUTIMAGE;
OUTINT(COUNTSUBSTRING("ABABABABAB", "ABAB"),0);
OUTIMAGE;
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.
| #Z80_Assembly | Z80 Assembly | xor a ;LD A,0
ld b,&40 ;how many numbers to print.
loop_showOctal:
push af
push af
call ShowOctal
ld a,' '
call PrintChar ;put a blank space after the value
pop af
;;;;;;;;;;;;;;;;;;;;; this code starts a new line after every 8th output.
ld a,b
and &07
dec a
call z,NewLine
;;;;;;;;;;;;;;;;;;;;;;
pop af
inc a ;next number
djnz loop_showOctal
jp $ ;end program
ShowOctal:
push bc
ld c,a
add a
push af
ld a,7
and c
ld c,a
pop af
and &F0
or c
and &7F
pop bc
jp ShowHex
ShowHex: ;this isn't directly below ShowOctal, it's somewhere else entirely.
;thanks to Keith of Chibiakumas for this routine!
push af
and %11110000
ifdef gbz80
swap a ;game boy can use this, but Zilog Z80 cannot.
else
rrca
rrca
rrca
rrca
endif
call PrintHexChar
pop af
and %00001111
;execution flows into the subroutine below, effectively calling it for us without having to actually do so.
PrintHexChar:
or a ;Clear Carry Flag
daa
add a,&F0
adc a,&40 ;this sequence of instructions converts hexadecimal values to ASCII.
jp PrintChar ;hardware-specific routine, omitted. Thanks to Keith of Chibiakumas for this one! |
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.
| #zkl | zkl | foreach n in ([0..]){println("%.8B".fmt(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
| #VBScript | VBScript | Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
'The -1 is to account for the null element of arrP
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
'Testing the fucntions.
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine |
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.
| #PHP | PHP | <?php
/**
* @author Elad Yosifon
* @desc HTML Table - normal style
*/
$cols = array('', 'X', 'Y', 'Z');
$rows = 3;
$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';
foreach($cols as $col)
{
$html .= "<td>{$col}</td>";
}
unset($col);
$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
$html .= '<tr>';
foreach($cols as $key => $col)
{
$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
}
unset($col);
$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';
echo $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.
| #Stata | Stata | file open f using output.txt, write replace
file close f
mkdir docs
file open f using \output.txt, write replace
file close f
mkdir \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.
| #Tcl | Tcl | close [open output.txt w]
close [open [file nativename /output.txt] w]
file mkdir docs
file mkdir [file nativename /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).
| #Run_BASIC | Run BASIC | csv$ = "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!"
k = instr(csv$,",") ' 2 exra lines to get heading
csv$ = left$(csv$,k - 1) + "</th><th> + mid$(csv$,k + 1)
csv$ = strRep$(csv$,",","</td><td>")
html "<table border=1><TR bgcolor=wheat align=center><th>";strRep$(csv$,chr$(13),"</td></tr><tr><td>");"</td></tr></table"
wait
' --------------------------------
' string replace rep str with
' --------------------------------
FUNCTION strRep$(strRep$,rep$,with$)
ln = len(rep$)
k = instr(strRep$,rep$)
while k
strRep$ = left$(strRep$,k - 1) + with$ + mid$(strRep$,k + ln)
k = instr(strRep$,rep$)
WEND
END FUNCTION |
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
| #Tcl | Tcl | oo::class create SDAccum {
variable sum sum2 num
constructor {} {
set sum 0.0
set sum2 0.0
set num 0
}
method value {x} {
set sum2 [expr {$sum2 + $x**2}]
set sum [expr {$sum + $x}]
incr num
return [my stddev]
}
method count {} {
return $num
}
method mean {} {
expr {$sum / $num}
}
method variance {} {
expr {$sum2/$num - [my mean]**2}
}
method stddev {} {
expr {sqrt([my variance])}
}
}
# Demonstration
set sdacc [SDAccum new]
foreach val {2 4 4 4 5 5 7 9} {
set sd [$sdacc value $val]
}
puts "the standard deviation is: $sd" |
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
| #Smalltalk | Smalltalk | Transcript showCR:('the three truths' occurrencesOfString:'th').
Transcript showCR:('ababababab' occurrencesOfString:'abab') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.