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/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.
| #Pop11 | Pop11 | vars itemrep;
incharitem(charin) -> itemrep;
;;; Read sizes
vars n1 = itemrep(), n2= itemrep();
;;; Create 0 based array
vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);
;;; Set element value
15 -> ar(0, 0);
;;; Print element value
ar(0,0) =>
;;; Make sure array is unreferenced
0 -> ar; |
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.
| #PowerShell | PowerShell |
function Read-ArrayIndex ([string]$Prompt = "Enter an integer greater than zero")
{
[int]$inputAsInteger = 0
while (-not [Int]::TryParse(([string]$inputString = Read-Host $Prompt), [ref]$inputAsInteger))
{
$inputString = Read-Host "Enter an integer greater than zero"
}
if ($inputAsInteger -gt 0) {return $inputAsInteger} else {return 1}
}
$x = $y = $null
do
{
if ($x -eq $null) {$x = Read-ArrayIndex -Prompt "Enter two dimensional array index X"}
if ($y -eq $null) {$y = Read-ArrayIndex -Prompt "Enter two dimensional array index Y"}
}
until (($x -ne $null) -and ($y -ne $null))
$array2d = New-Object -TypeName 'System.Object[,]' -ArgumentList $x, $y
|
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
| #PicoLisp | PicoLisp | (scl 2)
(de stdDev ()
(curry ((Data)) (N)
(push 'Data N)
(let (Len (length Data) M (*/ (apply + Data) Len))
(sqrt
(*/
(sum
'((N) (*/ (- N M) (- N M) 1.0))
Data )
1.0
Len )
T ) ) ) )
(let Fun (stdDev)
(for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0)
(prinl (format N *Scl) " -> " (format (Fun N) *Scl)) ) ) |
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.
| #Quackery | Quackery | [ stack ] is lim ( --> s )
[ swap dup 1+ lim put
1 0 rot of join
swap witheach
[ 0 over of
swap negate temp put
lim share times
[ over i^ peek
over temp share peek
+ join ]
temp take negate split
nip nip ]
-1 peek
lim release ] is makechange ( n [ --> n )
say "With US coins." cr
100 ' [ 1 5 10 25 ] makechange echo cr
100000 ' [ 1 5 10 25 50 100 ] makechange echo cr
cr
say "With EU coins." cr
100 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr
100000 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr |
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.
| #Racket | Racket | #lang racket
(define (ways-to-make-change cents coins)
(cond ((null? coins) 0)
((negative? cents) 0)
((zero? cents) 1)
(else
(+ (ways-to-make-change cents (cdr coins))
(ways-to-make-change (- cents (car coins)) coins)))))
(ways-to-make-change 100 '(25 10 5 1)) ; -> 242
|
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
| #Nemerle | Nemerle | using System.Console;
module CountSubStrings
{
CountSubStrings(this text : string, target : string) : int
{
match (target) {
|"" => 0
|_ => (text.Length - text.Replace(target, "").Length) / target.Length
}
}
Main() : void
{
def text1 = "the three truths";
def target1 = "th";
def text2 = "ababababab";
def target2 = "abab";
WriteLine($"$target1 occurs $(text1.CountSubStrings(target1)) times in $text1");
WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2");
}
} |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method countSubstring(inStr, findStr) public static
return inStr.countstr(findStr)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
strings = ''
find = 'FIND'
ix = 0
ix = ix + 1; strings[0] = ix; find[0] = ix; strings[ix] = 'the three truths'; strings[ix, find] = 'th'
ix = ix + 1; strings[0] = ix; find[0] = ix; strings[ix] = 'ababababab'; strings[ix, find] = 'abab'
loop ix = 1 to strings[0]
str = strings[ix]
fnd = strings[ix, find]
say 'there are' countSubstring(str, fnd) 'occurences of "'fnd'" in "'str'"'
end ix
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.
| #NewLISP | NewLISP | ; file: ocount.lsp
; url: http://rosettacode.org/wiki/Count_in_octal
; author: oofoe 2012-01-29
; Although NewLISP itself uses a 64-bit integer representation, the
; format function relies on underlying C library's printf function,
; which can only handle a 32-bit octal number on this implementation.
(for (i 0 (pow 2 32)) (println (format "%o" i)))
(exit) |
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.
| #Nim | Nim | import strutils
for i in 0 ..< int.high:
echo toOct(i, 16) |
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.
| #Oberon-2 | Oberon-2 |
MODULE CountInOctal;
IMPORT
NPCT:Tools,
Out := NPCT:Console;
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO MAX(INTEGER) DO;
Out.String(Tools.IntToOct(i));Out.Ln
END
END CountInOctal.
|
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
| #Maple | Maple | factorNum := proc(n)
local i, j, firstNum;
if n = 1 then
printf("%a", 1);
end if;
firstNum := true:
for i in ifactors(n)[2] do
for j to i[2] do
if firstNum then
printf ("%a", i[1]);
firstNum := false:
else
printf(" x %a", i[1]);
end if;
end do;
end do;
printf("\n");
return NULL;
end proc:
for i from 1 to 10 do
printf("%2a: ", i);
factorNum(i);
end do; |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
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.
| #Lasso | Lasso | define rand4dig => integer_random(9999, 1)
local(
output = '<table border=2 cellpadding=5 cellspace=0>\n<tr>'
)
with el in (' ,X,Y,Z') -> split(',') do {
#output -> append('<th>' + #el + '</th>')
}
#output -> append('</tr>\n')
loop(5) => {
#output -> append('<tr>\n<td style="font-weight: bold;">' + loop_count + '</td>')
loop(3) => {
#output -> append('<td>' + rand4dig + '</td>')
}
#output -> append('</tr>\n')
}
#output -> append('</table>\n')
#output |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #zkl | zkl | "%d-%02d-%02d".fmt(Time.Clock.localTime.xplode()).println()
//--> "2014-02-28" (ISO format) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #zonnon | zonnon |
module Main;
import System;
var
now: System.DateTime;
begin
now := System.DateTime.Now;
System.Console.WriteLine(now.ToString("yyyy-MM-dd");
System.Console.WriteLine("{0}, {1}",now.DayOfWeek,now.ToString("MMMM dd, yyyy"));
end Main.
|
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.
| #Nim | Nim | import os
open("output.txt", fmWrite).close()
createDir("docs")
open(DirSep & "output.txt", fmWrite).close()
createDir(DirSep & "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.
| #Objeck | Objeck |
use IO;
bundle Default {
class FileExample {
function : Main(args : String[]) ~ Nil {
file := FileWriter->New("output.txt");
file->Close();
file := FileWriter->New("/output.txt");
file->Close();
Directory->Create("docs");
Directory->Create("/docs");
}
}
}
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
parse arg inFileName .
if inFileName = '' | inFileName = '.' then inFileName = './data/Brian.csv'
csv = RREadFileLineByLine01.scanFile(inFileName)
header = htmlHeader()
pre = htmlCsvText(csv, inFileName)
table = htmlCsvTable(csv, inFileName)
footer = htmlFooter()
say header
say pre
say table
say footer
return
method htmlHeader() public static returns Rexx
html = '<?xml version="1.0" encoding="UTF-8"?>\n' -
|| '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n' -
|| '<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">\n' -
|| '<head>\n' -
|| '<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>\n' -
|| '<title>RCsv2Html</title>\n' -
|| '<style type="text/css">\n' -
|| '<!--\n' -
|| '/* <![DATA[ */\n' -
|| 'body {\n' -
|| ' font-family: "Verdana", "Geneva", "Helvetica Neue", "Helvetica", "DejaVu Sans", "Arial", sans-serif;\n' -
|| '}\n' -
|| 'table, th, td {\n' -
|| ' border: 1px solid black;\n' -
|| ' border-collapse: collapse;\n' -
|| ' padding: 0.25em;\n' -
|| ' font-size: 85%;\n' -
|| '}\n' -
|| 'th {\n' -
|| ' color: white;\n' -
|| ' background-color: green;\n' -
|| '}\n' -
|| 'p.classname {\n' -
|| ' font-size: inherit;\n' -
|| '}\n' -
|| '/* ]] */\n' -
|| '//-->\n' -
|| '</style>\n' -
|| '</head>\n' -
|| '<body>\n' -
|| '<h1>Rosetta Code – NetRexx Sample Output</h2>\n' -
|| '<h2><a href="http://rosettacode.org/wiki/CSV_to_HTML_translation">CSV to HTML translation</a></h2>\n' -
|| ''
return html
method htmlFooter() public static returns Rexx
html = '</body>\n' -
|| '</html>\n' -
|| ''
return html
method htmlCsvText(csv, fileName = '.') public static returns Rexx
html = '<h3>Contents of CSV <code>'fileName'</code></h3>\n' -
|| '<pre>\n' -
|| ''
loop row = 1 to csv[0]
html = html || csv[row]'\n'
end row
html = html -
|| '</pre>\n' -
|| ''
return html
method htmlCsvTable(csv, fileName = '.') public static returns Rexx
html = '<table>\n' -
|| '<caption>Translation of CSV <code>'fileName'</code></caption>\n' -
|| '<thead>\n' -
|| ''
html = html -
|| htmlCsvTableRow(csv[1], 'th')'\n' -
|| '</thead>\n' -
|| '<tbody>\n' -
|| ''
loop r_ = 2 to csv[0]
html = html -
|| htmlCsvTableRow(csv[r_])'\n' -
|| ''
end r_
html = html -
|| '</tbody>\n' -
|| '</table>\n' -
|| ''
return html
method htmlCsvTableRow(row, tag = 'td') public static returns Rexx
row = row.strip('t')
row = row.changestr('&', '&') -- need to do this one first to avoid double translation
row = row.changestr('"', '"')
row = row.changestr("'", ''')
row = row.changestr('<', '<')
row = row.changestr('>', '>')
elmts = ''
elmts[0] = 0
e_ = 0
loop while row.length() > 0
parse row elmt ',' row
e_ = e_ + 1; elmts[0] = e_; elmts[e_] = elmt
end
html = '<tr>\n' -
|| ''
loop e_ = 1 to elmts[0]
html = html -
|| '<'tag'>'elmts[e_]'</'tag'>\n' -
|| ''
end e_
html = html -
|| '</tr>\n' -
|| ''
return html
|
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Ursa | Ursa | #
# csv data manipulation
#
# declare a string stream to hold lines
decl string<> lines
# open the file specified on the command line, halting
# execution if they didn't enter one. it will be created if
# it doesn't exist yet
decl file f
if (< (size args) 2)
out "error: please specify a csv file" endl console
stop
end if
f.create args<1>
f.open args<1>
# read in all lines from the file
set lines (f.readlines)
# append sum column to header
set lines<0> (+ lines<0> ",SUM")
# determine sums and append them
decl int i sum
for (set i 1) (< i (size lines)) (inc i)
set sum 0
for (decl int j) (< j (size (split lines<i> ","))) (inc j)
set sum (int (+ sum (int (split lines<i> ",")<j>)))
end for
set lines<i> (+ lines<i> (+ "," sum))
end for
# delete the file, then create it again
f.delete args<1>
f.create args<1>
# output all lines to the file
for (set i 0) (< i (size lines)) (inc i)
out lines<i> endl f
end for |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #VBA | VBA | Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #zkl | zkl | var [const] D=Time.Date;
foreach y in ([2008..2121]){
if (D.Sunday==D.weekDay(y,12,25)) println(y)
} |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #zonnon | zonnon |
module Main;
(*Access to Mono System package *)
import System;
var
now: System.DateTime;
begin
now := System.DateTime.Now;
System.Console.Write(now.ToString("yyyy-MM-dd :"));
System.Console.WriteLine(now.DayOfWeek);
end Main.
|
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.
| #Python | Python | width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][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.
| #Quackery | Quackery | [ witheach peek ] is {peek} ( { p --> x )
[ dip dup
witheach [ peek dup ]
drop ] is depack ( { p --> * )
[ reverse
witheach
[ dip swap poke ] ] is repack ( * p --> { )
[ dup dip
[ rot dip
[ depack drop ] ]
repack ] is {poke} ( x { p --> { )
[ 0 swap of
nested swap of ] is 2array ( n n --> [ )
$ "Array width (at least 2): " input $->n drop
$ "Array length (at least 5): " input $->n drop
say "Creating " over echo say " by "
dup echo say " array." cr
2array
say "Writing 12345 to element {1,4} of array." cr
12345 swap ' [ 1 4 ] {poke}
say "Reading element {1,4} of array: "
' [ 1 4 ] {peek} echo |
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
| #PL.2FI | PL/I | *process source attributes xref;
stddev: proc options(main);
declare a(10) float init(1,2,3,4,5,6,7,8,9,10);
declare stdev float;
declare i fixed binary;
stdev=std_dev(a);
put skip list('Standard deviation', stdev);
std_dev: procedure(a) returns(float);
declare a(*) float, n fixed binary;
n=hbound(a,1);
begin;
declare b(n) float, average float;
declare i fixed binary;
do i=1 to n;
b(i)=a(i);
end;
average=sum(a)/n;
put skip data(average);
return( sqrt(sum(b**2)/n - average**2) );
end;
end std_dev;
end; |
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.
| #Raku | Raku | # Recursive (cached)
sub change-r($amount, @coins) {
my @cache = [1 xx @coins], |([] xx $amount);
multi ways($n where $n >= 0, @now [$coin,*@later]) {
@cache[$n;+@later] //= ways($n - $coin, @now) + ways($n, @later);
}
multi ways($,@) { 0 }
# more efficient to start with coins sorted in descending order
ways($amount, @coins.sort(-*).list);
}
# Iterative
sub change-i(\n, @coins) {
my @table = [1 xx @coins], [0 xx @coins] xx n;
(1..n).map: -> \i {
for ^@coins -> \j {
my \c = @coins[j];
@table[i;j] = [+]
@table[i - c;j] // 0,
@table[i;j - 1] // 0;
}
}
@table[*-1][*-1];
}
say "Iterative:";
say change-i 1_00, [1,5,10,25];
say change-i 1000_00, [1,5,10,25,50,100];
say "\nRecursive:";
say change-r 1_00, [1,5,10,25];
say change-r 1000_00, [1,5,10,25,50,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
| #NewLISP | NewLISP | ; file: stringcount.lsp
; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring
; author: oofoe 2012-01-29
; Obvious (and non-destructive...)
; Note that NewLISP performs an /implicit/ slice on a string or list
; with this form "(start# end# stringorlist)". If the end# is omitted,
; the slice will go to the end of the string. This is handy here to
; keep removing the front part of the string as it gets matched.
(define (scount needle haystack)
(let ((h (copy haystack)) ; Copy of haystack string.
(i 0) ; Cursor.
(c 0)) ; Count of occurences.
(while (setq i (find needle h))
(inc c)
(setq h ((+ i (length needle)) h)))
c)) ; Return count.
; Tricky -- Uses functionality from replace function to find all
; non-overlapping occurrences, replace them, and return the count of
; items replaced in system variable $0.
(define (rcount needle haystack)
(replace needle haystack "X") $0)
; Test
(define (test f needle haystack)
(println "Found " (f needle haystack)
" occurences of '" needle "' in '" haystack "'."))
(dolist (f (list scount rcount))
(test f "glart" "hinkerpop")
(test f "abab" "ababababab")
(test f "th" "the three truths")
(println)
)
(exit) |
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.
| #OCaml | OCaml | let () =
for i = 0 to max_int do
Printf.printf "%o\n" i
done |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #PARI.2FGP | PARI/GP | oct(n)=n=binary(n);if(#n%3,n=concat([[0,0],[0]][#n%3],n));forstep(i=1,#n,3,print1(4*n[i]+2*n[i+1]+n[i+2]));print;
n=0;while(1,oct(n);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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method factor(val) public static
rv = 1
if val > 1 then do
rv = ''
loop n_ = val until n_ = 1
parse checkFactor(2, n_, rv) n_ rv
if n_ = 1 then leave n_
parse checkFactor(3, n_, rv) n_ rv
if n_ = 1 then leave n_
loop m_ = 5 to n_ by 2 until n_ = 1
if m_ // 3 = 0 then iterate m_
parse checkFactor(m_, n_, rv) n_ rv
end m_
end n_
end
return rv
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method checkFactor(mult = long, n_ = long, fac) private static binary
msym = 'x'
loop while n_ // mult = 0
fac = fac msym mult
n_ = n_ % mult
end
fac = (fac.strip).strip('l', msym).space
return n_ fac
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
-- input is a list of pairs of numbers - no checking is done
if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010'
loop while arg \= ''
parse arg lv rv arg
say
say '-'.copies(60)
say lv.right(8) 'to' rv
say '-'.copies(60)
loop fv = lv to rv
fac = factor(fv)
pv = ''
if fac.words = 1 & fac \= 1 then pv = '<prime>'
say fv.right(8) '=' fac pv
end fv
end
return
|
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.
| #Liberty_BASIC | Liberty BASIC |
nomainwin
quote$ =chr$( 34)
html$ ="<html><head></head><body>"
html$ =html$ +"<table border =" +quote$ +"6"+ quote$ +" solid rules =none ; cellspacing =" +quote$ +"10" +quote$ +"> <th> </th> <th> X </th> <th> Y </th> <th> Z </th>"
for i =1 to 4
d1$ =str$( i)
d2$ =str$( int( 10000 *rnd( 1)))
d3$ =str$( int( 10000 *rnd( 1)))
d4$ =str$( int( 10000 *rnd( 1)))
html$ =html$ +"<tr align ="; quote$; "right"; quote$; "> <th>"; d1$; " </th> <td>" +d2$ +" </td> <td>" +d3$ +" </td> <td>" +d4$ +" </td> </tr>"
next i
html$ =html$ +"</table>"
html$ =html$ +"</body></html>"
open "table.html" for output as #o
#o html$;
close #o
address$ ="table.html"
run "explorer.exe "; address$
timer 5000, [on]
wait
[on]
timer 0
kill "table.html"
wait
sub quit w$
close #w$
end
end sub
|
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.
| #Objective-C | Objective-C | NSFileManager *fm = [NSFileManager defaultManager];
[fm createFileAtPath:@"output.txt" contents:[NSData data] attributes:nil];
// Pre-OS X 10.5
[fm createDirectoryAtPath:@"docs" attributes:nil];
// OS X 10.5+
[fm createDirectoryAtPath:@"docs" withIntermediateDirectories:NO attributes:nil error:NULL]; |
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.
| #OCaml | OCaml | # let oc = open_out "output.txt" in
close_out oc;;
- : unit = ()
# Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *)
- : unit = () |
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).
| #Nim | Nim | import cgi, strutils
const csvtext = """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!"""
proc row2tr(row: string): string =
result = "<tr>"
let cols = xmlEncode(row).split(",")
for col in cols:
result.add "<td>"&col&"</td>"
result.add "</tr>"
proc csv2html(txt: string): string =
result = "<table summary=\"csv2html program output\">\n"
for row in txt.splitLines():
result.add " <tbody>"&row2tr(row)&"</tbody>\n"
result.add "</table>"
echo csv2html(csvtext) |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #VBScript | VBScript | 'Instatiate FSO.
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv.
Set objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",1,False)
'Set header status to account for the first line as the column headers.
IsHeader = True
'Initialize the var for the output string.
OutTxt = ""
'Read each line of the file.
Do Until objInCSV.AtEndOfStream
line = objInCSV.ReadLine
If IsHeader Then
OutTxt = OutTxt & line & ",SUM" & vbCrLf
IsHeader = False
Else
OutTxt = OutTxt & line & "," & AddElements(line) & vbCrLf
End If
Loop
'Close the file.
objInCSV.Close
'Open the same file for writing.
Set objOutCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",2,True)
'Write the var OutTxt to the file overwriting existing contents.
objOutCSV.Write OutTxt
'Close the file.
objOutCSV.Close
Set objFSO = Nothing
'Routine to add each element in a row.
Function AddElements(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
AddElements = AddElements + CInt(arr(i))
Next
End Function |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Vedit_macro_language | Vedit macro language | File_Open("input.csv")
for (#1 = 0; #1 < 4; #1++) {
Goto_Line(#1+2) // line (starting from line 2)
if (#1) {
Search(",", ADVANCE+COUNT, #1) // column
}
#2 = Num_Eval() // #2 = old value
Del_Char(Chars_Matched) // delete old value
Num_Ins(#2+100, LEFT+NOCR) // write new value
}
File_Save_As("output.csv", OK+NOMSG) |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 CLS
20 FOR y=2008 TO 2121
30 LET year=y: LET m=12: LET d=25: GO SUB 1000
40 IF wd=0 THEN PRINT d;" ";m;" ";y
50 NEXT y
60 STOP
1000 REM week day
1010 IF m=1 OR m=2 THEN LET m=m+12: LET year=year-1
1020 LET wd=FN m(year+INT (year/4)-INT (year/100)+INT (year/400)+d+INT ((153*m+8)/5),7)
1030 RETURN
1100 DEF FN m(a,b)=a-INT (a/b)*b |
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.
| #R | R | input <- readline("Enter two integers. Space delimited, please: ")
dims <- as.numeric(strsplit(input, " ")[[1]])
arr <- array(dim=dims)
ii <- ceiling(dims[1]/2)
jj <- ceiling(dims[2]/2)
arr[ii, jj] <- sum(dims)
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="") |
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.
| #Racket | Racket |
#lang racket
(printf "Enter XY dimensions: ")
(define xy (cons (read) (read)))
(define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0)))
(printf "Enter a number for the top-left: ")
(vector-set! (vector-ref array 0) 0 (read))
(printf "Enter a number for the bottom-right: ")
(vector-set! (vector-ref array (sub1 (car xy))) (sub1 (cdr xy)) (read))
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
| #PowerShell | PowerShell | function Get-StandardDeviation {
begin {
$avg = 0
$nums = @()
}
process {
$nums += $_
$avg = ($nums | Measure-Object -Average).Average
$sum = 0;
$nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) }
[Math]::Sqrt($sum / $nums.Length)
}
} |
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.
| #REXX | REXX | /*REXX program counts the number of ways to make change with coins from an given amount.*/
numeric digits 20 /*be able to handle large amounts of $.*/
parse arg N $ /*obtain optional arguments from the CL*/
if N='' | N="," then N= 100 /*Not specified? Then Use $1 (≡100¢).*/
if $='' | $="," then $= 1 5 10 25 /*Use penny/nickel/dime/quarter default*/
if left(N, 1)=='$' then N= 100 * substr(N, 2) /*the count was specified in dollars. */
coins= words($) /*the number of coins specified. */
NN= N; do j=1 for coins /*create a fast way of accessing specie*/
_= word($, j) /*define an array element for the coin.*/
if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/
if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/
$.j= _ /*assign the value to a particular coin*/
end /*j*/
_= n//100; cnt=' cents' /* [↓] is the amount in whole dollars?*/
if _=0 then do; NN= '$' || (NN%100); cnt= /*show the amount in dollars, not cents*/
end /*show the amount in dollars, not cents*/
say 'with an amount of ' comma(NN)cnt", there are " comma( MKchg(N, coins) )
say 'ways to make change with coins of the following denominations: ' $
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
comma: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, "M")
e= verify(n, #'0', , verify(n, #"0.", 'M')) - 4
do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
MKchg: procedure expose $.; parse arg a,k /*this function is invoked recursively.*/
if a==0 then return 1 /*unroll for a special case of zero. */
if k==1 then return 1 /* " " " " " " unity. */
if k==2 then f= 1 /*handle this special case of two. */
else f= MKchg(a, k-1) /*count, and then recurse the amount. */
if a==$.k then return f+1 /*handle this special case of A=a coin.*/
if a <$.k then return f /* " " " " " A<a coin.*/
return f+MKchg(a-$.k,k) /*use diminished amount ($) for change.*/ |
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
| #Nim | Nim | import strutils
proc count(s, sub: string): int =
var i = 0
while true:
i = s.find(sub, i)
if i < 0:
break
i += sub.len # i += 1 for overlapping substrings
inc result
echo count("the three truths","th")
echo count("ababababab","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
| #Objective-C | Objective-C | @interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end
@implementation NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr {
return [[self componentsSeparatedByString:subStr] count] - 1;
}
@end
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]);
NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]);
NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]);
}
return 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.
| #Pascal | Pascal | program StrAdd;
{$Mode Delphi}
{$Optimization ON}
uses
sysutils;//IntToStr
const
maxCntOct = (SizeOf(NativeUint)*8+(3-1)) DIV 3;
procedure IntToOctString(i: NativeUint;var res:Ansistring);
var
p : array[0..maxCntOct] of byte;
c,cnt: LongInt;
begin
cnt := maxCntOct;
repeat
c := i AND 7;
p[cnt] := (c+Ord('0'));
dec(cnt);
i := i shr 3;
until (i = 0);
i := cnt+1;
cnt := maxCntOct-cnt;
//most time consuming with Ansistring
//call fpc_ansistr_unique
setlength(res,cnt);
move(p[i],res[1],cnt);
end;
procedure IncStr(var s:String;base:NativeInt);
var
le,c,dg:nativeInt;
begin
le := length(s);
IF le = 0 then
Begin
s := '1';
EXIT;
end;
repeat
dg := ord(s[le])-ord('0') +1;
c := ord(dg>=base);
dg := dg-(base AND (-c));
s[le] := chr(dg+ord('0'));
dec(le);
until (c = 0) or (le<=0);
if (c = 1) then
begin
le := length(s);
setlength(s,le+1);
move(s[1],s[2],le);
s[1] := '1';
end;
end;
const
MAX = 8*8*8*8*8*8*8*8*8;//8^9
var
sOct,
s : AnsiString;
i : nativeInt;
T1,T0: TDateTime;
Begin
sOct := '';
For i := 1 to 16 do
Begin
IncStr(sOct,8);
writeln(i:10,sOct:10);
end;
writeln;
For i := 1 to 16 do
Begin
IntToOctString(i,s);
writeln(i:10,s:10);
end;
sOct := '';
T0 := time;
For i := 1 to MAX do
IncStr(sOct,8);
T0 := (time-T0)*86400;
writeln(sOct);
T1 := time;
For i := 1 to MAX do
IntToOctString(i,s);
T1 := (time-T1)*86400;
writeln(s);
writeln;
writeln(MAX);
writeln('IncStr ',T0:8:3);
writeln('IntToOctString ',T1:8:3);
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
| #Nim | Nim | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo "" |
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
| #Objeck | Objeck |
class CountingInFactors {
function : Main(args : String[]) ~ Nil {
for(i := 1; i <= 10; i += 1;){
count := CountInFactors(i);
("{$i} = {$count}")->PrintLine();
};
for(i := 9991; i <= 10000; i += 1;){
count := CountInFactors(i);
("{$i} = {$count}")->PrintLine();
};
}
function : CountInFactors(n : Int) ~ String {
if(n = 1) {
return "1";
};
sb := "";
n := CheckFactor(2, n, sb);
if(n = 1) {
return sb;
};
n := CheckFactor(3, n, sb);
if(n = 1) {
return sb;
};
for(i := 5; i <= n; i += 2;) {
if(i % 3 <> 0) {
n := CheckFactor(i, n, sb);
if(n = 1) {
break;
};
};
};
return sb;
}
function : CheckFactor(mult : Int, n : Int, sb : String) ~ Int {
while(n % mult = 0 ) {
if(sb->Size() > 0) {
sb->Append(" x ");
};
sb->Append(mult);
n /= mult;
};
return 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.
| #Lingo | Lingo | on htmlTable (data)
str = "<table>"
-- table head
put "<thead><tr><th> </th>" after str
repeat with cell in data[1]
put "<th>"&cell&"</th>" after str
end repeat
put "</tr></thead>" after str
-- table body
put "<tbody>" after str
cnt = data.count
repeat with i = 2 to cnt
put "<tr><td>"&(i-1)&"</td>" after str
repeat with cell in data[i]
put "<td>"&cell&"</td>" after str
end repeat
put "</tr>" after str
end repeat
put "</tbody>" after str
put "</table>" after str
return str
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.
| #Oz | Oz | for Dir in ["/" "./"] do
File = {New Open.file init(name:Dir#"output.txt" flags:[create])}
in
{File close}
{OS.mkDir Dir#"docs" ['S_IRUSR' 'S_IWUSR' 'S_IXUSR' 'S_IXGRP']}
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.
| #PARI.2FGP | PARI/GP | write1("0.txt","")
write1("/0.txt","") |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Oberon-2 | Oberon-2 |
MODULE CSV2HTML;
IMPORT
Object,
IO,
IO:FileChannel,
IO:TextRider,
SB := ADT:StringBuffer,
NPCT:Tools,
NPCT:CGI:Utils,
Ex := Exception,
Out;
VAR
fileChannel: FileChannel.Channel;
rd: TextRider.Reader;
line: ARRAY 1024 OF CHAR;
table: SB.StringBuffer;
parts: ARRAY 2 OF STRING;
PROCEDURE DoTableHeader(sb: SB.StringBuffer;parts: ARRAY OF STRING);
BEGIN
sb.Append("<tr><th>"+Utils.EscapeHTML(parts[0])+"</th><th>"+Utils.EscapeHTML(parts[1])+"</th></tr>");
sb.AppendLn
END DoTableHeader;
PROCEDURE DoTableRow(sb: SB.StringBuffer;parts: ARRAY OF STRING);
BEGIN
sb.Append("<tr><td>"+Utils.EscapeHTML(parts[0])+"</td><td>"+Utils.EscapeHTML(parts[1])+"</td></tr>");
sb.AppendLn
END DoTableRow;
PROCEDURE DoTable(sb: SB.StringBuffer): STRING;
VAR
aux: SB.StringBuffer;
BEGIN
aux := SB.New("<table>");aux.AppendLn;
RETURN aux.ToString() + sb.ToString() + "</table>";
END DoTable;
BEGIN
TRY
fileChannel := FileChannel.OpenUnbuffered("script.csv",{FileChannel.read});
CATCH Ex.Exception(ex):
Out.Object(ex.GetMessage());Out.Ln;
HALT(1)
END;
rd := TextRider.ConnectReader(fileChannel);
(* Extract headers *)
TRY
rd.ReadLine(line);
table := NEW(SB.StringBuffer,2048);
Tools.Split(Object.NewLatin1(line),",",parts);
DoTableHeader(table,parts);
CATCH IO.Error(ex):
Out.Object(ex.Name() + ": " + ex.GetMessage());Out.Ln;
HALT(2)
END;
(* Extract data *)
LOOP
TRY
rd.ReadLine(line);
IF (line[0] # 0X)THEN (* skip empty lines *)
Tools.Split(Object.NewLatin1(line),",",parts);
DoTableRow(table,parts)
END
CATCH IO.Error(ex):
EXIT
END
END;
Out.Object(DoTable(table));Out.Ln;
fileChannel.Close()
END CSV2HTML.
|
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Visual_FoxPro | Visual FoxPro |
CLOSE DATABASES ALL
SET SAFETY OFF
MODIFY FILE file1.csv NOEDIT
*!* Create a cursor with integer columns
CREATE CURSOR tmp1 (C1 I, C2 I, C3 I, C4 I, C5 I)
APPEND FROM file1.csv TYPE CSV
SELECT C1, C2, C3, C4, C5, C1+C2+C3+C4+C5 As sum ;
FROM tmp1 INTO CURSOR tmp2
COPY TO file2.csv TYPE CSV
MODIFY FILE file2.csv NOEDIT IN SCREEN
SET SAFETY ON
|
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Wren | Wren | import "io" for File
var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList
var file = File.create("rc.csv") // overwrite existing file
file.writeBytes(lines[0] + ",SUM\n")
for (line in lines.skip(1)) {
if (line != "") {
var nums = line.split(",").map { |s| Num.fromString(s) }
var sum = nums.reduce { |acc, n| acc + n }
file.writeBytes(line + ",%(sum)\n")
}
}
file.close() |
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.
| #Raku | Raku | my ($major,$minor) = prompt("Dimensions? ").comb(/\d+/);
my @array = [ '@' xx $minor ] xx $major;
@array[ *.rand ][ *.rand ] = ' ';
.say for @array; |
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.
| #Red | Red | Red ["Create two-dimensional array at runtime"]
width: to-integer ask "What is the width of the array? "
height: to-integer ask "What is the height of the array? "
; 2D arrays are just nested blocks in Red.
matrix: copy [] ; Make an empty block to hold our rows.
loop height [ ; A loop for each row...
row: append/dup copy [] 0 width ; Create a block like [0 0 0 0] if width is 4.
append/only matrix row ; Append the row to our matrix as its own block.
]
a: 3
b: 2
matrix/2/4: 27 ; use path syntax to access or assign
matrix/1/1: 99 ; series are 1-indexed in Red; there is no matrix/0/0
matrix/(a)/(a): 10 ; accessing elements with words requires special care
matrix/:b/:b: 33 ; alternative
print mold matrix |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #PureBasic | PureBasic | ;Define our Standard deviation function
Declare.d Standard_deviation(x)
; Main program
If OpenConsole()
Define i, x
Restore MyList
For i=1 To 8
Read.i x
PrintN(StrD(Standard_deviation(x)))
Next i
Print(#CRLF$+"Press ENTER to exit"): Input()
EndIf
;Calculation procedure, with memory
Procedure.d Standard_deviation(In)
Static in_summa, antal
Static in_kvadrater.q
in_summa+in
in_kvadrater+in*in
antal+1
ProcedureReturn Pow((in_kvadrater/antal)-Pow(in_summa/antal,2),0.50)
EndProcedure
;data section
DataSection
MyList:
Data.i 2,4,4,4,5,5,7,9
EndDataSection |
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.
| #Ring | Ring |
penny = 1
nickel = 1
dime = 1
quarter = 1
count = 0
for penny = 0 to 100
for nickel = 0 to 20
for dime = 0 to 10
for quarter = 0 to 4
if (penny + nickel * 5 + dime * 10 + quarter * 25) = 100
see "" + penny + " pennies " + nickel + " nickels " + dime + " dimes " + quarter + " quarters" + nl
count = count + 1
ok
next
next
next
next
see count + " ways to make a dollar" + nl
|
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
| #OCaml | OCaml | let count_substring str sub =
let sub_len = String.length sub in
let len_diff = (String.length str) - sub_len
and reg = Str.regexp_string sub in
let rec aux i n =
if i > len_diff then n else
try
let pos = Str.search_forward reg str i in
aux (pos + sub_len) (succ n)
with Not_found -> n
in
aux 0 0
let () =
Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
;; |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Perl | Perl | use POSIX;
printf "%o\n", $_ for (0 .. POSIX::UINT_MAX); |
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.
| #Phix | Phix | without javascript_semantics
integer i = 0
constant ESC = #1B
while not find(get_key(),{ESC,'q','Q'}) do
printf(1,"%o\n",i)
i += 1
end while
|
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
| #OCaml | OCaml | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int |
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.
| #Lua | Lua | function htmlTable (data)
local html = "<table>\n<tr>\n<th></th>\n"
for _, heading in pairs(data[1]) do
html = html .. "<th>" .. heading .. "</th>" .. "\n"
end
html = html .. "</tr>\n"
for row = 2, #data do
html = html .. "<tr>\n<th>" .. row - 1 .. "</th>\n"
for _, field in pairs(data[row]) do
html = html .. "<td>" .. field .. "</td>\n"
end
html = html .. "</tr>\n"
end
return html .. "</table>"
end
local tableData = {
{"X", "Y", "Z"},
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
}
print(htmlTable(tableData)) |
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.
| #Pascal | Pascal |
program in out;
var
f : textfile;
begin
assignFile(f,'/output.txt');
rewrite(f);
close(f);
makedir('/docs');
assignFile(f,'/docs/output.txt');
rewrite(f);
close(f);
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.
| #Perl | Perl | use File::Spec::Functions qw(catfile rootdir);
{ # here
open my $fh, '>', 'output.txt';
mkdir 'docs';
};
{ # root dir
open my $fh, '>', catfile rootdir, 'output.txt';
mkdir catfile rootdir, '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).
| #Objeck | Objeck | use System.IO.File;
use Data.CSV;
class CsvToHtml {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
table := CsvTable->New(FileReader->ReadFile(args[0]));
if(table->IsParsed()) {
buffer := "<html><body><table>";
Header(table->GetHeaders(), buffer);
for(i := 1; i < table->Size(); i += 1;) {
Data(table->Get(i), buffer);
};
buffer += "</table></body></html>";
buffer->PrintLine();
};
};
}
function : Header(row : CsvRow, buffer : String) ~ Nil {
buffer += "<tr>";
each(i : row) {
buffer += "<th>";
buffer += Encode(row->Get(i));
buffer += "</th>";
};
buffer += "</tr>";
}
function : Data(row : CsvRow, buffer : String) ~ Nil {
buffer += "<tr>";
each(i : row) {
buffer += "<td>";
buffer += Encode(row->Get(i));
buffer += "</td>";
};
buffer += "</tr>";
}
function : Encode(in : String) ~ String {
out := "";
each(i : in) {
c := in->Get(i);
select(c) {
label '&': {
out->Append("&");
}
label '\'': {
out->Append("'");
}
label '<': {
out->Append("<");
}
label '>': {
out->Append(">");
}
other: {
out->Append(c);
}
};
};
return out;
}
}
|
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #XPL0 | XPL0 | string 0; \use zero-terminated strings
def LF=$0A, EOF=$1A;
int Val, Char;
char Str(80);
proc InField;
int I;
[I:= 0; Val:= 0;
loop [Char:= ChIn(1);
if Char=^, or Char=LF or Char=EOF then quit;
Str(I):= Char;
I:= I+1;
if Char>=^0 and Char<=^9 then
Val:= Val*10 + Char - ^0;
];
Str(I):= 0;
];
int Sum;
[loop [InField;
Text(0, Str);
if Char = LF then quit;
ChOut(0, ^,);
];
Text(0, ",SUM");
CrLf(0);
loop [Sum:= 0;
loop [InField;
if Char = EOF then return;
if rem(Val/5)=0 then Val:= Val*20;
IntOut(0, Val);
Sum:= Sum + Val;
if Char = LF then quit;
ChOut(0, ^,);
];
Text(0, ",");
IntOut(0, Sum);
CrLf(0);
];
] |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Yabasic | Yabasic | open #1, "manipy.csv", "r" //existing CSV file separated by spaces, not commas
open #2, "manip2.csv", "w" //new CSV file for writing changed data
line input #1 header$
header$ = header$ + ",SUM"
print #2 header$
while !eof(1)
input #1 c1, c2, c3, c4, c5
sum = c1 + c2 + c3 + c4 + c5
print #2 c1, c2, c3, c4, c5, sum
wend
close #1
close #2
end |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #REXX | REXX | /*REXX program allocates/populates/displays a two-dimensional array. */
call bloat /*the BLOAT procedure does all allocations.*/
/*no more array named @ at this point. */
exit /*stick a fork in it, we're all done honey.*/
/*─────────────────────────BLOAT subroutine─────────────────────────────*/
bloat: procedure; say /*"PROCEDURE" makes this a ··· procedure. */
say 'Enter two positive integers (a 2-dimensional array will be created).'
pull n m . /*elements are allocated as they're defined*/
/*N and M should be verified at this point.*/
@.=' · ' /*Initial value for all @ array elements,*/
/*this ensures every element has a value.*/
do j =1 for n /*traipse through the first dimension [N]*/
do k=1 for m /* " " " second " [M]*/
if random()//7==0 then @.j.k=j'~'k /*populate every 7th random*/
end /*k*/
end /*j*/
/* [↓] display array to console: row,col */
do r=1 for n; _= /*construct one row (or line) at a time. */
do c=1 for m /*construct row one column at a time. */
_=_ right(@.r.c,4) /*append a nice-aligned column to the line.*/
end /*kk*/ /* [↑] an nicely aligned line is built. */
say _ /*display one row at a time to the terminal*/
end /*jj*/
/*╔════════════════════════════════════════════════════════════════════╗
║ When the RETURN is executed (from a PROCEDURE in this case), and ║
║ array @ is "de─allocated", that is, it's no longer defined, and ║
║ the array's storage is now free for other REXX variables. If the ║
║ BLOAT subroutine didn't have a "PROCEDURE" on that statement,║
║ the array @ would've been left intact. The same effect is ║
║ performed by a DROP statement (an example is shown below). ║
╚════════════════════════════════════════════════════════════════════╝*/
drop @. /*because of the PROCEDURE statement, the*/
return /* [↑] DROP statement is superfluous. */ |
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
| #Python | Python | >>> from math import sqrt
>>> def sd(x):
sd.sum += x
sd.sum2 += x*x
sd.n += 1.0
sum, sum2, n = sd.sum, sd.sum2, sd.n
return sqrt(sum2/n - sum*sum/n/n)
>>> sd.sum = sd.sum2 = sd.n = 0
>>> for value in (2,4,4,4,5,5,7,9):
print (value, sd(value))
(2, 0.0)
(4, 1.0)
(4, 0.94280904158206258)
(4, 0.8660254037844386)
(5, 0.97979589711327075)
(5, 1.0)
(7, 1.3997084244475311)
(9, 2.0)
>>> |
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.
| #Ruby | Ruby | def make_change(amount, coins)
@cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)}
@coins = coins
do_count(amount, @coins.length - 1)
end
def do_count(n, m)
if n < 0 || m < 0
0
elsif @cache[n][m]
@cache[n][m]
else
@cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1)
end
end
p make_change( 1_00, [1,5,10,25])
p make_change(1000_00, [1,5,10,25,50,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
| #Oforth | Oforth |
: countSubString(s, sub)
0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ]
drop ; |
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
| #ooRexx | ooRexx |
bag="the three truths"
x="th"
say left(bag,30) left(x,15) 'found' bag~countstr(x)
bag="ababababab"
x="abab"
say left(bag,30) left(x,15) 'found' bag~countstr(x)
-- can be done caselessly too
bag="abABAbaBab"
x="abab"
say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)
|
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.
| #PHP | PHP | <?php
for ($n = 0; is_int($n); $n++) {
echo decoct($n), "\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.
| #Picat | Picat | go =>
gen(N),
println(to_oct_string(N)),
fail.
gen(I) :-
gen(0, I).
gen(I, I).
gen(I, J) :-
I2 is I + 1,
gen(I2, J). |
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.
| #PicoLisp | PicoLisp | (for (N 0 T (inc N))
(prinl (oct N)) ) |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Octave | Octave | for (n = 1:20)
printf ("%i: ", n)
printf ("%i ", factor (n))
printf ("\n")
endfor |
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
| #PARI.2FGP | PARI/GP | fnice(n)={
my(f,s="",s1);
if (n < 2, return(n));
f = factor(n);
s = Str(s, f[1,1]);
if (f[1, 2] != 1, s=Str(s, "^", f[1,2]));
for(i=2,#f[,1],
s1 = Str(" * ", f[i, 1]);
if (f[i, 2] != 1, s1 = Str(s1, "^", f[i, 2]));
s = Str(s, s1)
);
s
};
n=0;while(n++, print(fnice(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.
| #M2000_Interpreter | M2000 Interpreter |
MODULE HtmlTable {
tag$=LAMBDA$ (a$)-> {
=LAMBDA$ a$ -> {
IF ISNUM THEN w$=STR$(NUMBER,0) ELSE w$=LETTER$
READ ? part$
="<"+a$+IF$(LEN(part$)>0->" "+part$,"")+">"+w$+"</"+a$+">"+CHR$(13)+CHR$(10)
}
}
INVENTORY Fun
STACK NEW {
DATA "html", "head", "body", "table", "tr", "th", "td"
WHILE NOT EMPTY
OVER ' duplicate top of stack
APPEND Fun, LETTER$:=tag$(LETTER$)
END WHILE
}
DEF body0$="",body$=""
STACK NEW {
DATA "", "X", "Y", "Z"
FOR i=1 TO 4
body0$+=Fun$("th")(LETTER$)
z$=""
FOR j=1 TO 3 : z$+=Fun$("td")(RANDOM(0, 9999), {align="right"}) : NEXT j
body$+=Fun$("tr")(Fun$("th")(i)+z$)
NEXT i
}
table$=fun$("table")(fun$("tr")(body0$)+body$,"border=1 cellpadding=10 cellspacing=0")
DOCUMENT final$="<!DOCTYPE html>"+CHR$(13)+CHR$(10)
final$=fun$("html")(fun$("head")("")+fun$("body")(table$), {lang="en"})
file$="c:\doc.html"
REPORT final$
CLIPBOARD final$
SAVE.DOC final$, file$
WIN file$ ' execute, no wait
}
HtmlTable
|
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.
| #Phix | Phix | integer fn
-- In the current working directory
system("mkdir docs",2)
fn = open("output.txt","w")
close(fn)
-- In the filesystem root
system("mkdir \\docs",2)
fn = open("\\output.txt","w")
if fn=-1 then
puts(1,"unable to create \\output.txt\n")
else
close(fn)
end if |
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.
| #PHP | PHP | <?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
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).
| #OCaml | OCaml | open Printf
let csv_data = "\
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!"
(* General HTML escape *)
let escape =
let html_escapes = Str.regexp "\\([^A-Za-z0-9 ;!?'/]\\)" in
let esc s = sprintf "&#%04d;" (Char.code s.[Str.group_beginning 1]) in
Str.global_substitute html_escapes esc
let nl = Str.regexp "\n\r?"
let coma = Str.regexp ","
let list_of_csv csv =
List.map (fun l -> Str.split coma l) (Str.split nl csv)
let print_html_table segments =
printf "<table>\n";
List.iter (fun line ->
printf "<tr>";
List.iter (fun c -> printf "<td>%s</td>" (escape c)) line;
printf "</tr>\n";
) segments;
printf "</table>\n";
;;
let () =
print_html_table (list_of_csv csv_data) |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #zkl | zkl | csvFile:=File("test.csv");
header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space
listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") });
newFile:=File("test2.csv","w");
newFile.writeln(header + ",sum");
listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) });
newFile.close(); |
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.
| #Ring | Ring |
See 'Enter width : ' give width
See 'Enter height : ' give height
width=0+width height=0+height
aList = list(height) for x in aList x = list(width) next
aList[1][2] = 10 See aList[1][2] + nl
|
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.
| #Ruby | Ruby | puts 'Enter width and height: '
w=gets.to_i
arr = Array.new(gets.to_i){Array.new(w)}
arr[1][3] = 5
p arr[1][3] |
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
| #R | R | cumsd <- function(x) {
n <- seq_along(x)
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2)
}
set.seed(12345L)
x <- rnorm(10)
cumsd(x)
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
# Compare to the naive implementation, i.e. compute sd on each sublist:
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x))
# [1] NA 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
# Note that the first is NA because sd is unbiased formula, hence there is a division by n-1, which is 0 for n=1. |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Run_BASIC | Run BASIC | for penny = 0 to 100
for nickel = 0 to 20
for dime = 0 to 10
for quarter = 0 to 4
if penny + nickel * 5 + dime * 10 + quarter * 25 = 100 then
print penny;" pennies ";nickel;" nickels "; dime;" dimes ";quarter;" quarters"
count = count + 1
end if
next quarter
next dime
next nickel
next penny
print count;" ways to make a buck" |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Rust | Rust | fn make_change(coins: &[usize], cents: usize) -> usize {
let size = cents + 1;
let mut ways = vec![0; size];
ways[0] = 1;
for &coin in coins {
for amount in coin..size {
ways[amount] += ways[amount - coin];
}
}
ways[cents]
}
fn main() {
println!("{}", make_change(&[1,5,10,25], 100));
println!("{}", make_change(&[1,5,10,25,50,100], 100_000));
} |
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
| #PARI.2FGP | PARI/GP | subvec(v,u)={
my(i=1,s);
while(i+#u<=#v,
for(j=1,#u,
if(v[i+j-1]!=u[j], i++; next(2))
);
s++;
i+=#u
);
s
};
substr(s1,s2)=subvec(Vec(s1),Vec(s2));
substr("the three truths","th")
substr("ababababab","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
| #Pascal | Pascal | sub countSubstring {
my $str = shift;
my $sub = quotemeta(shift);
my $count = () = $str =~ /$sub/g;
return $count;
# or return scalar( () = $str =~ /$sub/g );
}
print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("ababababab","abab"), "\n"; # prints "2" |
http://rosettacode.org/wiki/Count_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.
| #Pike | Pike |
int i=1;
while(true)
write("0%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.
| #PL.2FI | PL/I | /* Do the actual counting in octal. */
count: procedure options (main);
declare v(5) fixed(1) static initial ((5)0);
declare (i, k) fixed;
do k = 1 to 999;
call inc;
put skip edit ( (v(i) do i = 1 to 5) ) (f(1));
end;
inc: proc;
declare (carry, i) fixed binary;
carry = 1;
do i = 5 to 1 by -1;
v(i) = v(i) + carry;
if v(i) > 7 then
do; v(i) = v(i) - 8; if i = 1 then stop; carry = 1; end;
else
carry = 0;
end;
end inc;
end count; |
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
| #Pascal | Pascal | program CountInFactors(output);
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
type
TdynArray = array of integer;
function factorize(number: integer): TdynArray;
var
k: integer;
begin
if number = 1 then
begin
setlength(Result, 1);
Result[0] := 1
end
else
begin
k := 2;
while number > 1 do
begin
while number mod k = 0 do
begin
setlength(Result, length(Result) + 1);
Result[high(Result)] := k;
number := number div k;
end;
inc(k);
end;
end
end;
var
i, j: integer;
fac: TdynArray;
begin
for i := 1 to 22 do
begin
write(i, ': ' );
fac := factorize(i);
write(fac[0]);
for j := 1 to high(fac) do
write(' * ', fac[j]);
writeln;
end;
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | x := RandomInteger[10];
Print["<table>", "\n","<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"]
Scan[Print["<tr><td>", #, "</td><td>", x, "</td><td>", x, "</td><td>","</td></tr>"] & , Range[3]]
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.
| #PicoLisp | PicoLisp | (out "output.txt") # Empty output
(call 'mkdir "docs") # Call external
(out "/output.txt")
(call '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.
| #Pike | Pike | import Stdio;
int main(){
write_file("input.txt","",0100);
write_file("/input.txt","",0100);
} |
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).
| #OpenEdge.2FProgress | OpenEdge/Progress |
FUNCTION csvToHtml RETURNS CHARACTER (
i_lhas_header AS LOGICAL,
i_cinput AS CHARACTER
):
DEFINE VARIABLE coutput AS CHARACTER NO-UNDO.
DEFINE VARIABLE irow AS INTEGER NO-UNDO.
DEFINE VARIABLE icolumn AS INTEGER NO-UNDO.
DEFINE VARIABLE crow AS CHARACTER NO-UNDO.
DEFINE VARIABLE ccell AS CHARACTER NO-UNDO.
coutput = "<html>~n~t<table>".
DO irow = 1 TO NUM-ENTRIES( i_cinput, "~n":U ):
coutput = coutput + "~n~t~t<tr>".
crow = ENTRY( irow, i_cinput, "~n":U ).
DO icolumn = 1 TO NUM-ENTRIES( crow ):
ccell = ENTRY( icolumn, crow ).
coutput = coutput + "~n~t~t~t" + IF i_lhas_header AND irow = 1 THEN "<th>" ELSE "<td>".
coutput = coutput + REPLACE( REPLACE( REPLACE( ccell, "&", "&" ), "<", "<" ), ">", ">" ).
coutput = coutput + IF i_lhas_header AND irow = 1 THEN "</th>" ELSE "</td>".
END.
coutput = coutput + "~n~t~t</tr>".
END.
coutput = coutput + "~n~t</table>~n</html>".
RETURN coutput.
END FUNCTION. /* csvToHtml */
MESSAGE
csvToHtml(
TRUE,
"Character,Speech" + "~n" +
"The multitude,The messiah! Show us the messiah!" + "~n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" + "~n" +
"The multitude,Who are you?" + "~n" +
"Brians mother,I'm his mother; that's who!" + "~n" +
"The multitude,Behold his mother! Behold his mother!"
)
VIEW-AS ALERT-BOX. |
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.
| #Rust | Rust | use std::env;
fn main() {
let mut args = env::args().skip(1).flat_map(|num| num.parse());
let rows = args.next().expect("Expected number of rows as first argument");
let cols = args.next().expect("Expected number of columns as second argument");
assert_ne!(rows, 0, "rows were zero");
assert_ne!(cols, 0, "cols were zero");
// Creates a vector of vectors with all elements initialized to 0.
let mut v = vec![vec![0; cols]; rows];
v[0][0] = 1;
println!("{}", v[0][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.
| #Scala | Scala | object Array2D{
def main(args: Array[String]): Unit = {
val x = Console.readInt
val y = Console.readInt
val a=Array.fill(x, y)(0)
a(0)(0)=42
println("The number at (0, 0) is "+a(0)(0))
}
} |
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
| #Racket | Racket |
#lang racket
(require math)
(define running-stddev
(let ([ns '()])
(λ(n) (set! ns (cons n ns)) (stddev ns))))
;; run it on each number, return the last result
(last (map running-stddev '(2 4 4 4 5 5 7 9)))
|
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #SAS | SAS | /* call OPTMODEL procedure in SAS/OR */
proc optmodel;
/* declare set and names of coins */
set COINS = {1,5,10,25};
str name {COINS} = ['penny','nickel','dime','quarter'];
/* declare variables and constraint */
var NumCoins {COINS} >= 0 integer;
con Dollar:
sum {i in COINS} i * NumCoins[i] = 100;
/* call CLP solver */
solve with CLP / findallsolns;
/* write solutions to SAS data set */
create data sols(drop=s) from [s]=(1.._NSOL_) {i in COINS} <col(name[i])=NumCoins[i].sol[s]>;
quit;
/* print all solutions */
proc print data=sols;
run; |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Scala | Scala | def countChange(amount: Int, coins:List[Int]) = {
val ways = Array.fill(amount + 1)(0)
ways(0) = 1
coins.foreach (coin =>
for (j<-coin to amount)
ways(j) = ways(j) + ways(j - coin)
)
ways(amount)
}
countChange (15, List(1, 5, 10, 25))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.