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/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #Wren | Wren | import "/fmt" for Conv
class CRC32 {
static init() {
__table = List.filled(256, 0)
for (i in 0..255) {
var word = i
for (j in 0..7) {
if (word&1 == 1) {
word = (word >> 1) ^ 0xedb88320
} else {
word = word >> 1
}
}
__table[i] = word
}
}
static compute(s) {
var crc = ~0
var le = s.bytes.count
for (i in 0...le) {
var crb = crc & 0xff
crc = __table[crb^s[i].bytes[0]] ^ (crc >> 8)
}
return ~crc
}
}
CRC32.init()
var crc = CRC32.compute("The quick brown fox jumps over the lazy dog")
System.print(Conv.hex(crc)) |
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.
| #OCaml | OCaml | let changes amount coins =
let ways = Array.make (amount + 1) 0L in
ways.(0) <- 1L;
List.iter (fun coin ->
for j = coin to amount do
ways.(j) <- Int64.add ways.(j) ways.(j - coin)
done
) coins;
ways.(amount)
let () =
Printf.printf "%Ld\n" (changes 1_00 [25; 10; 5; 1]);
Printf.printf "%Ld\n" (changes 1000_00 [100; 50; 25; 10; 5; 1]);
;; |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Liberty_BASIC | Liberty BASIC |
print countSubstring( "the three truths", "th")
print countSubstring( "ababababab", "abab")
end
function countSubstring( a$, s$)
c =0
la =len( a$)
ls =len( s$)
for i =1 to la -ls
if mid$( a$, i, ls) =s$ then c =c +1: i =i +ls -1
next i
countSubstring =c
end function
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Logtalk | Logtalk |
:- object(counting).
:- public(count/3).
count(String, SubString, Count) :-
count(String, SubString, 0, Count).
count(String, SubString, Count0, Count) :-
( sub_atom(String, Before, Length, After, SubString) ->
Count1 is Count0 + 1,
Start is Before + Length,
sub_atom(String, Start, After, 0, Rest),
count(Rest, SubString, Count1, Count)
; Count is Count0
).
:- end_object.
|
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.
| #LOLCODE | LOLCODE | HAI 1.3
HOW IZ I octal YR num
I HAS A digit, I HAS A oct ITZ ""
IM IN YR octalizer
digit R MOD OF num AN 8
oct R SMOOSH digit oct MKAY
num R QUOSHUNT OF num AN 8
NOT num, O RLY?
YA RLY, FOUND YR oct
OIC
IM OUTTA YR octalizer
IF U SAY SO
IM IN YR printer UPPIN YR num
VISIBLE I IZ octal YR num MKAY
IM OUTTA YR printer
KTHXBYE |
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.
| #Lua | Lua | for l=1,2147483647 do
print(string.format("%o",l))
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
| #JavaScript | JavaScript | for(i = 1; i <= 10; i++)
console.log(i + " : " + factor(i).join(" x "));
function factor(n) {
var factors = [];
if (n == 1) return [1];
for(p = 2; p <= n; ) {
if((n % p) == 0) {
factors[factors.length] = p;
n /= p;
}
else p++;
}
return factors;
} |
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.
| #JavaScript | JavaScript | <html><head><title>Table maker</title><script type="application/javascript">
// normally, don't do this: at least name it something other than "a"
Node.prototype.a = function (e) { this.appendChild(e); return this }
function ce(tag, txt) {
var x = document.createElement(tag);
x.textContent = (txt === undefined) ? '' : txt;
return x;
}
function make_table(cols, rows) {
var tbl = ce('table', ''), tr = ce('tr'), th;
tbl.a(tr.a(ce('th')));
var z = 'Z'.charCodeAt(0);
for (var l = z - cols + 1; l <= z; l++)
tr.a(ce('th', String.fromCharCode(l)));
for (var r = 1; r <= rows; r++) {
tbl.a(tr = ce('tr').a(ce('th', r)));
for (var c = 0; c < cols; c++)
tr.a(ce('td', Math.floor(Math.random() * 10000)));
}
document.body
.a(ce('style',
'td, th {border: 1px solid #696;' +
'padding:.4ex} td {text-align: right }' +
'table { border-collapse: collapse}'))
.a(tbl);
}
</script></head>
<body><script>make_table(5, 4)</script></body></html> |
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
| #Ursa | Ursa | cygnus/x ursa v0.78 (default, release 0)
[Oracle Corporation JVM 1.8.0_51 on Mac OS X 10.10.5 x86_64]
> import "java.util.Date"
> import "java.text.SimpleDateFormat"
> decl java.text.SimpleDateFormat sdf
> sdf.applyPattern "yyyy-MM-dd"
> decl java.util.Date d
> out (sdf.format d) endl console
2016-07-23
> sdf.applyPattern "EEEE, MMMM dd, yyyy"
> out (sdf.format d) endl console
Saturday, July 23, 2016
> _ |
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
| #Ursala | Ursala | #import std
#import cli
months = ~&p/block3'JanFebMarAprMayJunJulAugSepOctNovDec' block2'010203040506070809101112'
completion =
-:~& ~&pllrTXS/block3'SunMonTueWedThuFriSat'--(~&lS months) -- (
--','* sep`, 'day,day,sday,nesday,rsday,day,urday',
sep`, 'uary,ruary,ch,il,,e,y,ust,tember,ober,ember,ember')
text_form = sep` ; mat` + completion*+ <.~&hy,~&tth,--','@th,~&ttth>
numeric_form = sep` ; mat`-+ <.~&ttth,@tth -: months,~&th>
#show+
main = <.text_form,numeric_form> now0 |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | fid = fopen('output.txt','w'); fclose(fid);
fid = fopen('/output.txt','w'); fclose(fid);
mkdir('docs');
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.
| #Maxima | Maxima | f: openw("/output.txt");
close(f);
f: openw("output.txt");
close(f);
/* Maxima has no function to create directories, but one can use the underlying Lisp system */
:lisp (mapcar #'ensure-directories-exist '("docs/" "/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).
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a="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!";
(*Naive*)
StringJoin["<table>\n",Map[StringJoin["<tr><td>",#,"</td></tr>\n"]&,
StringSplit[StringReplace[a,{","->"</td><td>","<"->"<",">"->">"}],"\n"]]
,"</table>"]
(*Extra*)
StringJoin["<table>\n",StringJoin["<tr><th>",#,"</th></tr>\n"]&[
StringSplit[StringReplace[a,{","->"</td><td>","<"->"<",">"->">"}],"\n"]//First]
,Map[StringJoin["<tr><td>",#,"</td></tr>\n"]&,
StringSplit[StringReplace[a,{","->"</td><td>","<"->"<",">"->">"}],"\n"]//Rest]
,"</table>"]
|
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var file: input is STD_NULL;
var array array string: csvData is 0 times 0 times "";
var integer: line is 0;
begin
input := open(dir(PROGRAM) & "/csvDataManipulation.in", "r");
while hasNext(input) do
csvData &:= split(getln(input), ",");
end while;
csvData[3][3] := "X";
for key line range csvData do
writeln(join(csvData[line], ","));
end for;
end func; |
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.
| #SenseTalk | SenseTalk |
// For test purposes, start by creating (or re-creating) the data file
put {{
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
}} into file "myData.csv"
// Read the file as a list of lists (rather than as the default list of property lists)
put CSVValue(file "myData.csv", asLists:Yes) into csvData
insert "SUM" into item 1 of csvData -- add a new column heading
// Go through all of the data rows to add the sum
repeat with rowNum= 2 to the number of items in csvData
insert the sum of item rowNum of csvData into item rowNum of csvData
end repeat
put csvData -- see the modified data as a list of lists
put CSVFormat of csvData into file "myData.csv"
put file "myData.csv" -- display the updated file contents
|
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.
| #VBA | VBA | Option Explicit
Sub MainDayOfTheWeek()
Debug.Print "Xmas will be a Sunday in : " & XmasSunday(2008, 2121)
End Sub
Private Function XmasSunday(firstYear As Integer, lastYear As Integer) As String
Dim i As Integer, temp$
For i = firstYear To lastYear
If Weekday(CDate("25/12/" & i)) = vbSunday Then temp = temp & ", " & i
Next
XmasSunday = Mid(temp, 2)
End Function |
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.
| #VBScript | VBScript | For year = 2008 To 2121
If Weekday(DateSerial(year, 12, 25)) = 1 Then
WScript.Echo year
End If
Next |
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.
| #Perl | Perl | sub make_array($ $){
# get array sizes from provided params, but force numeric value
my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
# define array, then add multi-dimensional elements
my @array;
$array[0][0] = 'X '; # first by first element
$array[5][7] = 'X ' if (5 <= $y and 7 <= $x); # sixth by eighth element, if the max size is big enough
$array[12][15] = 'X ' if (12 <= $y and 15 <= $x); # thirteenth by sixteenth element, if the max size is big enough
# loop through the elements expected to exist base on input, and display the elements contents in a grid
foreach my $dy (0 .. $y){
foreach my $dx (0 .. $x){
(defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');
}
print "\n";
}
} |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Pascal | Pascal | program stddev;
uses math;
const
n=8;
var
arr: array[1..n] of real =(2,4,4,4,5,5,7,9);
function stddev(n: integer): real;
var
i: integer;
s1,s2,variance,x: real;
begin
for i:=1 to n do
begin
x:=arr[i];
s1:=s1+power(x,2);
s2:=s2+x
end;
variance:=((n*s1)-(power(s2,2)))/(power(n,2));
stddev:=sqrt(variance)
end;
var
i: integer;
begin
for i:=1 to n do
begin
writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15)
end
end. |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #XPL0 | XPL0 | code HexOut=27; \intrinsic routine
string 0; \use zero-terminated strings
func CRC32(Str, Len); \Return CRC-32 for given string
char Str; int Len; \byte array, number of bytes
int I, J, R, C;
[R:= -1; \initialize with all 1's
for J:= 0 to Len-1 do
[C:= Str(J);
for I:= 0 to 8-1 do \for each bit in byte...
[if (R xor C) and 1 then R:= R>>1 xor $EDB88320
else R:= R>>1;
C:= C>>1;
];
];
return not R;
];
HexOut(0, CRC32("The quick brown fox jumps over the lazy dog", 43)) |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #zkl | zkl | var [const] ZLib=Import("zeelib");
ZLib.calcCRC32(Data(Void,"The quick brown fox jumps over the lazy dog"));
//-->0x414fa339 |
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.
| #PARI.2FGP | PARI/GP | coins(v)=prod(i=1,#v,1/(1-'x^v[i]));
ways(v,n)=polcoeff(coins(v)+O('x^(n+1)),n);
ways([1,5,10,25],100)
ways([1,5,10,25,50,100],100000) |
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.
| #Perl | Perl | use 5.01;
use Memoize;
sub cc {
my $amount = shift;
return 0 if !@_ || $amount < 0;
return 1 if $amount == 0;
my $first = shift;
cc( $amount, @_ ) + cc( $amount - $first, $first, @_ );
}
memoize 'cc';
# Make recursive algorithm run faster by sorting coins descending by value:
sub cc_optimized {
my $amount = shift;
cc( $amount, sort { $b <=> $a } @_ );
}
say 'Ways to change $ 1 with common coins: ',
cc_optimized( 100, 1, 5, 10, 25 );
say 'Ways to change $ 1000 with addition of less common coins: ',
cc_optimized( 1000 * 100, 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
| #Lua | Lua | function countSubstring(s1, s2)
return select(2, s1:gsub(s2, ""))
end
print(countSubstring("the three truths", "th"))
print(countSubstring("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
| #Maple | Maple |
f:=proc(s::string,c::string,count::nonnegint) local n;
n:=StringTools:-Search(c,s);
if n>0 then 1+procname(s[n+length(c)..],c,count);
else 0; end if;
end proc:
f("the three truths","th",0);
f("ababababab","abab",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.
| #M4 | M4 | define(`forever',
`ifelse($#,0,``$0'',
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',eval($2+$3),$3,`$4')')')dnl
forever(`y',0,1, `eval(y,8)
') |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Maple | Maple |
octcount := proc (n)
seq(printf("%a \n", convert(i, octal)), i = 1 .. n);
end proc;
|
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.
| #MACRO-10 | MACRO-10 |
title OCTAL - Count in octal.
subttl PDP-10 assembly (MACRO-10 on TOPS-20). KJX 2022.
search monsym,macsym
comment \
If you want to see the overflow happening without waiting for
too long, change "movei b,1" to "move b,[377777,,777770]".
\
a=:1 ;Names for accumulators.
b=:2
c=:3
define crlf <tmsg <
>> ;Macro to print newline.
start:: reset% ;Initialize process.
movei b,1 ;B is the counter.
movei c,^d8 ;Octal output (nout%).
do.
movei a,.priou ;Use standard-output (nout%).
nout% ;Print number in B.
jrst [ tmsg <Output error.> ; NOUT can fail, print err-msg
jrst endprg ] ; and stop in that case.
crlf ;Print newline.
aos b ;Add one to B.
jfcl 10,[ tmsg <Arithmetic Overflow (AROV).> ;Handle overflow.
jrst endprg ]
loop. ;Do again.
enddo.
endprg: haltf% ;Halt program.
jrst start ;Allow continue-command.
end start
|
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
| #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
# Input: a non-negative integer determining when to stop
def count_in_factors:
"1: 1",
(range(2;.) | "\(.): \([factors] | join("x"))");
def count_in_factors($m;$n):
if . == 1 then "1: 1" else empty end,
(range($m;$n) | "\(.): \([factors] | join("x"))");
|
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Julia | Julia | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
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.
| #jq | jq | def html_row:
"<tr>",
" \(.[] | "<td>\(.)</td>")",
"</tr>";
def html_header:
"<thead align = 'right'>",
" \(html_row)",
"</thead>";
def html_table(header):
"<table>",
" \(header | html_header)",
" <tbody align = 'right'>",
" \(.[] | html_row)",
" </tbody",
"</table>";
# Prepend the sequence number
def html_table_with_sequence(header):
length as $length
| . as $in
| [range(0;length) | [.+1] + $in[.]] | html_table(header); |
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
| #VB-DOS | VB-DOS |
OPTION EXPLICIT
' Months
DATA "January", "February", "March", "April", "May", "June", "July"
DATA "August", "September", "October", "November", "December"
' Days of week
DATA "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
' Var
DIM dDate AS DOUBLE, sMonth(1 TO 12) AS STRING, sDay(1 TO 7) AS STRING
DIM i AS INTEGER
' Read Names of months
FOR i = 1 TO 12
READ sMonth(i)
NEXT i
' Read Names of days
FOR i = 1 TO 7
READ sDay(i)
NEXT i
' Assign current date to a variable
dDate = NOW
CLS
PRINT "Rosettacode: Display the current date formatted."
PRINT
PRINT "Today's date: "; FORMAT$(dDate, "ddddd")
PRINT
PRINT "Use of values in the lists."
PRINT "Today is "; sDay(WEEKDAY(dDate)); ", "; sMonth(MONTH(dDate)); " "; FORMAT$(DAY(dDate)); ", "; FORMAT$(YEAR(dDate)); "."
PRINT
PRINT "Use of just the FORMAT$() function."
PRINT "Today is "; FORMAT$(dDate, "dddd, mmmm d, yyyy"); "."
END
|
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
| #VBA | VBA | Function DateFormats()
Debug.Print Format(Date, "yyyy-mm-dd")
Debug.Print Format(Date, "dddd, mmmm dd yyyy")
End Function |
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.
| #MAXScript | MAXScript | -- Here
f = createFile "output.txt"
close f
makeDir (sysInfo.currentDir + "\docs")
-- System root
f = createFile "\output.txt"
close f
makeDir ("c:\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.
| #Mercury | Mercury | :- module create_file.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module dir.
main(!IO) :-
create_file("output.txt", !IO),
create_file("/output.txt", !IO),
create_dir("docs", !IO),
create_dir("/docs", !IO).
:- pred create_file(string::in, io::di, io::uo) is det.
create_file(FileName, !IO) :-
io.open_output(FileName, Result, !IO),
(
Result = ok(File),
io.close_output(File, !IO)
;
Result = error(Error),
print_io_error(Error, !IO)
).
:- pred create_dir(string::in, io::di, io::uo) is det.
create_dir(DirName, !IO) :-
dir.make_single_directory(DirName, Result, !IO),
(
Result = ok
;
Result = error(Error),
print_io_error(Error, !IO)
).
:- pred print_io_error(io.error::in, io::di, io::uo) is det.
print_io_error(Error, !IO) :-
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.nl(Stderr, !IO),
io.set_exit_status(1, !IO). |
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).
| #MATLAB | MATLAB |
inputString = fileread(csvFileName);
% using multiple regular expressions to clear up special chars
htmlFriendly = regexprep(regexprep(regexprep(regexprep(inputString,...
'&','&'),...
'"','"'),...
'<','<'),...
'>','>');
% split string into cell array
tableValues = regexp(regexp(htmlFriendly,'(\r\n|\r|\n)','split')',',','split');
%%% print in html format %%%
% <Extra Credit> first line gets treated as header
fprintf(1,['<table>\n\t<tr>' sprintf('\n\t\t<th>%s</th>',tableValues{1,:}{:})])
% print remaining lines of csv as html table (rows 2:end in cell array of csv values)
cellfun(@(x)fprintf(1,['\n\t<tr>' sprintf('\n\t\t<td>%s</td>',x{:}) '\n\t</tr>']),tableValues(2:end))
fprintf(1,'\n</table>')
|
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.
| #Sidef | Sidef | # Read
var csvfile = %f'data.csv';
var fh = csvfile.open_r;
var header = fh.line.trim_end.split(',');
var csv = fh.lines.map { .trim_end.split(',').map{.to_num} };
fh.close;
# Write
var out = csvfile.open_w;
out.say([header..., 'SUM'].join(','));
csv.each { |row| out.say([row..., row.sum].join(',')) };
out.close; |
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.
| #Stata | Stata | import delim input.csv, clear
replace c5=c3+c4
egen sum=rowtotal(c*)
drop if mod(c3,3)==0
export delim output.csv, replace |
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.
| #Vedit_macro_language | Vedit macro language | Buf_Switch(Buf_Free)
for (#3 = 2008; #3 < 2122; #3++) {
Reg_Set(10, "12/25/")
Num_Str(#3, 10, LEFT+APPEND)
if (JDate(@10) % 7 == 0) {
Num_Ins(#3, NOCR)
}
} |
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.
| #Visual_Objects | Visual Objects |
local i as dword
for i := 2008 upto 2121
if DOW(ConDate(i, 12, 25)) = 1
? AsString(i)
endif
next i
|
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.
| #Phix | Phix | -- demo\rosetta\Create2Darray.exw
with javascript_semantics -- (layout/spacing leaves a little to be desired...)
include pGUI.e
Ihandle lab, tab, res, dlg
function valuechanged_cb(Ihandle tab)
string s = IupGetAttribute(tab,"VALUE")
sequence r = scanf(s,"%d %d")
if length(r)=1 then
integer {height,width} = r[1],
i = floor(height/2+0.5),
j = floor(width/2+0.5)
if i>0 and j>0 then
sequence array = repeat(repeat(0,width),height)
array[i][j] = height + width
s = sprintf("array[%d][%d] is %d\n", {i,j,array[i][j]})
IupSetStrAttribute(res,"TITLE",s)
IupRefresh(res)
end if
end if
return IUP_DEFAULT
end function
procedure main()
IupOpen()
lab = IupLabel("Enter two numbers (>0) separated by a space")
tab = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),"EXPAND=HORIZONTAL")
res = IupLabel("")
dlg = IupDialog(IupVbox({IupHbox({lab,tab},"GAP=10,NORMALIZESIZE=VERTICAL"),
IupHbox({res})},"MARGIN=5x5"),`TITLE="Create 2D array"`)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Perl | Perl | {
package SDAccum;
sub new {
my $class = shift;
my $self = {};
$self->{sum} = 0.0;
$self->{sum2} = 0.0;
$self->{num} = 0;
bless $self, $class;
return $self;
}
sub count {
my $self = shift;
return $self->{num};
}
sub mean {
my $self = shift;
return ($self->{num}>0) ? $self->{sum}/$self->{num} : 0.0;
}
sub variance {
my $self = shift;
my $m = $self->mean;
return ($self->{num}>0) ? $self->{sum2}/$self->{num} - $m * $m : 0.0;
}
sub stddev {
my $self = shift;
return sqrt($self->variance);
}
sub value {
my $self = shift;
my $v = shift;
$self->{sum} += $v;
$self->{sum2} += $v * $v;
$self->{num}++;
return $self->stddev;
}
} |
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.
| #Phix | Phix | function coin_count(sequence coins, integer amount)
sequence s = repeat(0,amount+1)
s[1] = 1
for c=1 to length(coins) do
for n=coins[c] to amount do
s[n+1] += s[n-coins[c]+1]
end for
end for
return s[amount+1]
end function
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | StringPosition["the three truths","th",Overlaps->False]//Length
3
StringPosition["ababababab","abab",Overlaps->False]//Length
2 |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MATLAB_.2F_Octave | MATLAB / Octave | % Count occurrences of a substring without overlap
length(findstr("ababababab","abab",0))
length(findstr("the three truths","th",0))
% Count occurrences of a substring with overlap
length(findstr("ababababab","abab",1)) |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | x=0;
While[True,Print[BaseForm[x,8];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.
| #MATLAB_.2F_Octave | MATLAB / Octave | n = 0;
while (1)
dec2base(n,8)
n = n+1;
end; |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Mercury | Mercury |
:- module count_in_octal.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, string.
main(!IO) :-
count_in_octal(0, !IO).
:- pred count_in_octal(int::in, io::di, io::uo) is det.
count_in_octal(N, !IO) :-
io.format("%o\n", [i(N)], !IO),
count_in_octal(N + 1, !IO).
|
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
| #Kotlin | Kotlin | // version 1.1.2
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun getPrimeFactors(n: Int): List<Int> {
val factors = mutableListOf<Int>()
if (n < 1) return factors
if (n == 1 || isPrime(n)) {
factors.add(n)
return factors
}
var factor = 2
var nn = n
while (true) {
if (nn % factor == 0) {
factors.add(factor)
nn /= factor
if (nn == 1) return factors
if (isPrime(nn)) factor = nn
}
else if (factor >= 3) factor += 2
else factor = 3
}
}
fun main(args: Array<String>) {
val list = (MutableList(22) { it + 1 } + 2144) + 6358
for (i in list)
println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}")
} |
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.
| #Julia | Julia | function tag(x::Pair, attr::Pair...)
t, b = x
attrstr = join(" $n=\"$p\"" for (n, p) in attr)
return "<$t$attrstr>$b</$t>"
end
colnames = split(",X,Y,Z", ',')
header = join(tag(:th => txt) for txt in colnames) * "\n"
rows = collect(tag(:tr => join(tag(:td => i, :style => "font-weight: bold;") * join(tag(:td => rand(1000:9999)) for j in 1:3))) for i in 1:6)
body = "\n" * join(rows, '\n') * "\n"
table = tag(:table => string('\n', header, body, '\n'), :style => "width: 60%")
println(table) |
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
| #VBScript | VBScript |
'YYYY-MM-DD format
WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2)
'Weekday_Name, Month_Name DD, YYYY format
WScript.StdOut.WriteLine FormatDateTime(Now,1)
|
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
| #Vedit_macro_language | Vedit macro language | Date(REVERSE+NOMSG+VALUE, '-') |
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.
| #Mirah | Mirah | import java.io.File
File.new('output.txt').createNewFile()
File.new('docs').mkdir()
File.new("docs#{File.separator}output.txt").createNewFile()
|
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.
| #Modula-3 | Modula-3 | MODULE FileCreation EXPORTS Main;
IMPORT FS, File, OSError, IO, Stdio;
VAR file: File.T;
BEGIN
TRY
file := FS.OpenFile("output.txt");
file.close();
FS.CreateDirectory("docs");
file := FS.OpenFile("/output.txt");
file.close();
FS.CreateDirectory("/docs");
EXCEPT
| OSError.E => IO.Put("Error creating file or directory.\n", Stdio.stderr);
END;
END FileCreation. |
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).
| #Maxima | Maxima | infile: "input.csv";
outfile: "table.html";
instream: openr(infile);
outstream: openw(outfile);
printf(outstream, "<TABLE border=\"1\">~%");
nr: 0;
while (line: readline(instream))#false do (
nr: nr + 1,
line: ssubst("<", "<", line),
line: ssubst(">", ">", line),
value_list: map(lambda([f], strim(" ", f)), split(line, ",")),
if nr=1 then printf(outstream, " <THEAD bgcolor=\"yellow\">") else printf(outstream, " <TBODY bgcolor=\"orange\">"),
printf(outstream, "<TR>"),
for value in value_list do printf(outstream, "<TD>~a</TD>", value),
printf(outstream, "</TR>"),
if nr=1 then printf(outstream, "</THEAD>~%") else printf(outstream, "</TBODY>~%"));
printf(outstream, "</TABLE>~%");
close(instream);
close(outstream); |
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.
| #Tcl | Tcl | package require struct::matrix
package require csv
proc addSumColumn {filename {title "SUM"}} {
set m [struct::matrix]
# Load the CSV in
set f [open $filename]
csv::read2matrix $f $m "," auto
close $f
# Add the column with the sums
set sumcol [$m columns]
$m add column $title
for {set i 1} {$i < [$m rows]} {incr i} {
# Fill out a dummy value
$m set cell $sumcol $i 0
$m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]]
}
# Write the CSV out
set f [open $filename w]
csv::writematrix $m $f
close $f
$m destroy
}
addSumColumn "example.csv" |
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.
| #Vlang | Vlang | import time
fn main() {
for year := 2008; year <= 2121; year++ {
date := time.parse('${year}-12-25 00:00:00') or { continue }
if date.long_weekday_str() == 'Sunday' {
println('December 25 ${year} is a ${date.long_weekday_str()}')
}
}
} |
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.
| #VTL-2 | VTL-2 | 1000 #=2000
1010 R=!
1020 N=M
1030 X=Y
1040 #=N>3*1070
1050 N=N+12
1060 X=X-1
1070 J=X/100
1080 K=%
1090 W=N+1*26/10+D+K+(K/4)+(J/4)+(5*J)/7*0+%
1100 #=R
2000 ?="25th of December is a Sunday in";
2010 Y=2008
2020 M=12
2030 D=25
2040 #=1010
2050 #=W=1=0*2080
2060 $=32
2070 ?=Y
2080 Y=Y+1
2090 #=Y<2121*2040
2100 ?="" |
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.
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
"Enter height: " input tonum nl
"Enter width: " input tonum nl
0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/
-1 get 99 -1 set -1 set /# set the last element o last dimension #/
pstack /# show the content of the stack #/
-1 get -1 get "Value of the last element of the last dimension: " print print drop
drop /# remove array/list from the stack #/
|
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.
| #Picat | Picat | import util.
go =>
print("Input the number of rows and columns: "),
[Rows,Cols]=split(read_line()).map(to_int),
X=new_array(Rows,Cols),
X[1,1] = Rows*Cols+1,
println(X[1,1]). |
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
| #Phix | Phix | with javascript_semantics
atom sdn = 0, sdsum = 0, sdsumsq = 0
procedure sdadd(atom n)
sdn += 1
sdsum += n
sdsumsq += n*n
end procedure
function sdavg()
return sdsum/sdn
end function
function sddev()
return sqrt(sdsumsq/sdn - power(sdsum/sdn,2))
end function
--test code:
constant testset = {2, 4, 4, 4, 5, 5, 7, 9}
integer ti
for i=1 to length(testset) do
ti = testset[i]
sdadd(ti)
printf(1,"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n",{i,ti,sdavg(),sddev()})
end for
|
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.
| #Picat | Picat | go =>
Problems = [[ 1*100, [25,10,5,1]], % 1 dollar
[ 100*100, [100,50,25,10,5,1]], % 100 dollars
[ 1_000*100, [100,50,25,10,5,1]], % 1000 dollars
[ 10_000*100, [100,50,25,10,5,1]], % 10000 dollars
[100_000*100, [100,50,25,10,5,1]] % 100000 dollars
],
foreach([N,L] in Problems)
initialize_table, % clear the tabling from previous run
println([n=N,l=L]),
time(println(num_sols=coins(L,N,1)))
end.
table
coins(Coins, Money, M) = Sum =>
Sum1 = 0,
Len = Coins.length,
if M == Len then
Sum1 := 1,
else
foreach(I in M..Len)
if Money - Coins[I] == 0 then
Sum1 := Sum1 + 1
end,
if Money - Coins[I] > 0 then
Sum1 := Sum1 + coins(Coins, Money-Coins[I], I)
end,
end
end,
Sum = Sum1. |
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.
| #PicoLisp | PicoLisp | (de coins (Sum Coins)
(let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev)
(do Sum
(zero Prev)
(for L Buf
(inc (rot L) Prev)
(setq Prev (car L)) ) )
Prev ) ) |
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
| #Maxima | Maxima | scount(e, s) := block(
[n: 0, k: 1],
while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),
n
)$
scount("na", "banana");
2 |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MiniScript | MiniScript | string.count = function(s)
return self.split(s).len - 1
end function
print "the three truths".count("th")
print "ababababab".count("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.
| #min | min | (
(dup 0 ==) (pop () 0 shorten)
(((8 mod) (8 div)) cleave) 'cons linrec
reverse 'print! foreach newline
) :octal
0 (dup octal succ)
9.223e18 int times ; close to max int value |
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ИП0 П1 1 0 / [x] П1 Вx {x} 1
0 * 7 - x=0 21 ИП1 x#0 28 БП
02 ИП0 1 + П0 С/П БП 00 ИП0 lg
[x] 1 + 10^x П0 С/П БП 00 |
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.
| #Modula-2 | Modula-2 | MODULE octal;
IMPORT InOut;
VAR num : CARDINAL;
BEGIN
num := 0;
REPEAT
InOut.WriteOct (num, 12); InOut.WriteLn;
INC (num)
UNTIL num = 0
END octal. |
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
| #Liberty_BASIC | Liberty BASIC |
'see Run BASIC solution
for i = 1000 to 1016
print i;" = "; factorial$(i)
next
wait
function factorial$(num)
if num = 1 then factorial$ = "1"
fct = 2
while fct <= num
if (num mod fct) = 0 then
factorial$ = factorial$ ; x$ ; fct
x$ = " x "
num = num / fct
else
fct = fct + 1
end if
wend
end function |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Lua | Lua | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
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.
| #Kotlin | Kotlin | // version 1.1.3
import java.util.Random
fun main(args: Array<String>) {
val r = Random()
val sb = StringBuilder()
val i = " " // indent
with (sb) {
append("<html>\n<head>\n")
append("<style>\n")
append("table, th, td { border: 1px solid black; }\n")
append("th, td { text-align: right; }\n")
append("</style>\n</head>\n<body>\n")
append("<table style=\"width:60%\">\n")
append("$i<thead>\n")
append("$i$i<tr><th></th>")
for (c in 'X'..'Z') append("<th>$c</th>")
append("</tr>\n")
append("$i</thead>\n")
append("$i<tbody>\n")
val f = "$i$i<tr><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>\n"
for (j in 1..4) {
append(f.format(j, r.nextInt(10000), r.nextInt(10000), r.nextInt(10000)))
}
append("$i</tbody>\n")
append("</table>\n")
append("</body>\n</html>")
}
println(sb.toString())
} |
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
| #Vlang | Vlang | import time
fn main() {
println(time.now().custom_format("YYYY-MM-DD"))
println(time.now().custom_format("dddd, MMMM D, YYYY"))
} |
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
| #Wren | Wren | import "os" for Process
import "/date" for Date
var args = Process.arguments
if (args.count != 1) {
Fiber.abort("Please pass just the current date in yyyy-mm-dd format.")
}
var current = Date.parse(args[0])
System.print(current.format(Date.isoDate))
System.print(current.format("dddd|, |mmmm| |d|, |yyyy")) |
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.
| #Nanoquery | Nanoquery | import Nanoquery.IO
f = new(File)
f.create("output.txt")
f.createDir("docs")
// in the root directory
f.create("/output.txt")
f.createDir("/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.
| #Nemerle | Nemerle | using System;
using System.IO;
module CreateFile
{
Main() : void
{
unless (File.Exists("output.txt")) File.Create("output.txt"); // here
// returns a FileStream object which we're ignoring
try {
unless (File.Exists(@"\output.txt")) File.Create(@"\output.txt"); // root
}
catch {
|e is UnauthorizedAccessException => Console.WriteLine(
"Cannot create file in root directory without Administrator priveleges.")
}
unless (Directory.Exists("docs")) Directory.CreateDirectory("docs");
// returns a DirectoryInfo object which we're ignoring
unless (Directory.Exists(@"\docs")) Directory.CreateDirectory(@"\docs");
// no Exception for directory creation
}
} |
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).
| #ML.2FI | ML/I | MCSKIP "WITH" NL
"" CSV to HTML
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,[]
MCSKIP SL WITH ~
MCINS %.
"" C1=th before header output, td afterwards
MCCVAR 1,2
MCSET C1=[th]
"" HTML escapes
MCDEF < AS [[<]]
MCDEF > AS [[>]]
MCDEF & AS [[&]]
"" Main line processing
MCDEF SL N1 OPT , N1 OR NL ALL
AS [[ <tr>]
MCSET T2=1
%L1.MCGO L2 IF T2 GR T1
[<]%C1.[>]%AT2.[</]%C1.[>]
MCSET T2=T2+1
MCGO L1
%L2.[ </tr>]
MCSET C1=[td]
]
[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>HTML converted from CSV</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css"><!--
th {
font-weight:bold;
text-align:left
}
table,td,th {
border:1px solid;
border-collapse:collapse
}
td,th {
padding:10px
}
//-->
</style>
</head>
<body>
<table>]
MCSET S1=1
~MCSET S10=2
~MCSET S1=0
[</table>
</body>
</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.
| #TUSCRIPT | TUSCRIPT |
$$ MODE DATA
$$ csv=*
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
$$ MODE TUSCRIPT
LOOP/CLEAR n,line=csv
IF (n==1) THEN
line=CONCAT (line,",SUM")
ELSE
lineadd=EXCHANGE(line,":,:':")
sum=SUM(lineadd)
line=JOIN(line,",",sum)
ENDIF
csv=APPEND(csv,line)
ENDLOOP
|
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.
| #TXR | TXR | @(coll)@{name /[^,]+/}@(end)
@(collect :vars (value sum))
@ (bind sum 0)
@ (coll)@{value /[^,]+/}@(set sum @(+ sum (int-str value)))@(end)
@(end)
@(output)
@ (rep)@name,@(last)SUM@(end)
@ (repeat)
@ (rep)@value,@(last)@sum@(end)
@ (end)
@(end)
|
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.
| #Wortel | Wortel | !-&y = 0 `.getDay. @new Date[y 11 25] @range[2008 2121] |
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.
| #Wren | Wren | import "/date" for Date
System.print("Years between 2008 and 2121 when 25th December falls on Sunday:")
for (year in 2008..2121) {
if (Date.new(year, 12, 25).dayOfWeek == 7) System.print(year)
} |
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.
| #PicoLisp | PicoLisp | (de 2dimTest (DX DY)
(let A (make (do DX (link (need DY))))
(set (nth A 3 3) 999) # Set A[3][3] to 999
(mapc println A) # Print all
(get A 3 3) ) ) # Return A[3][3]
(2dimTest 5 5) |
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.
| #PL.2FI | PL/I |
/* First way using a controlled variable: */
declare A(*,*) float controlled;
get list (m, n);
allocate A(m,n);
get list (A);
put skip list (A);
/* The array remains allocated until the program terminates, */
/* or until explicitly destroyed using a FREE statement. */
free A;
|
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
| #PHP | PHP | <?php
class sdcalc {
private $cnt, $sumup, $square;
function __construct() {
$this->reset();
}
# callable on an instance
function reset() {
$this->cnt=0; $this->sumup=0; $this->square=0;
}
function add($f) {
$this->cnt++;
$this->sumup += $f;
$this->square += pow($f, 2);
return $this->calc();
}
function calc() {
if ($this->cnt==0 || $this->sumup==0) {
return 0;
} else {
return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2));
}
}
}
# start test, adding test data one by one
$c = new sdcalc();
foreach ([2,4,4,4,5,5,7,9] as $v) {
printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL);
} |
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.
| #Prolog | Prolog | :- use_module(library(clpfd)).
% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny
coins(Q, D, N, P, T) :-
[Q,D,N,P] ins 0..T,
T #= (Q * 25) + (D * 10) + (N * 5) + P.
coins_for(T) :-
coins(Q,D,N,P,T),
maplist(indomain, [Q,D,N,P]). |
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.
| #Python | Python | def changes(amount, coins):
ways = [0] * (amount + 1)
ways[0] = 1
for coin in coins:
for j in xrange(coin, amount + 1):
ways[j] += ways[j - coin]
return ways[amount]
print changes(100, [1, 5, 10, 25])
print changes(100000, [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
| #Mirah | Mirah | import java.util.regex.Pattern
import java.util.regex.Matcher
#The "remove and count the difference" method
def count_substring(pattern:string, source:string)
(source.length() - source.replace(pattern, "").length()) / pattern.length()
end
puts count_substring("th", "the three truths") # ==> 3
puts count_substring("abab", "ababababab") # ==> 2
puts count_substring("a*b", "abaabba*bbaba*bbab") # ==> 2
# The "split and count" method
def count_substring2(pattern:string, source:string)
# the result of split() will contain one more element than the delimiter
# the "-1" second argument makes it not discard trailing empty strings
source.split(Pattern.quote(pattern), -1).length - 1
end
puts count_substring2("th", "the three truths") # ==> 3
puts count_substring2("abab", "ababababab") # ==> 2
puts count_substring2("a*b", "abaabba*bbaba*bbab") # ==> 2
# This method does a match and counts how many times it matches
def count_substring3(pattern:string, source:string)
result = 0
Matcher m = Pattern.compile(Pattern.quote(pattern)).matcher(source);
while (m.find())
result = result + 1
end
result
end
puts count_substring3("th", "the three truths") # ==> 3
puts count_substring3("abab", "ababababab") # ==> 2
puts count_substring3("a*b", "abaabba*bbaba*bbab") # ==> 2
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nanoquery | Nanoquery | def countSubstring(str, subStr)
return int((len(str) - len(str.replace(subStr, ""))) / len(subStr))
end |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Nanoquery | Nanoquery | i = 0
while i < 2^64
println format("%o", i)
i += 1
end |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.math.BigInteger
-- allow an option to change the output radix.
parse arg radix .
if radix.length() == 0 then radix = 8
k_ = BigInteger
k_ = BigInteger.ZERO
loop forever
say k_.toString(int radix)
k_ = k_.add(BigInteger.ONE)
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
| #M2000_Interpreter | M2000 Interpreter |
Module Count_in_factors {
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
if exist(Known1, x) then =1=1 : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
Break}
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 4: if d<= x1 else Append Known1, x : =1=1: exit
loop
}
}
decompose=lambda IsPrime (n as decimal) -> {
Factors=(,)
{
k=2@
While frac(n/k)=0
n/=k
Append Factors, (k,)
End While
if n=1 then exit
k++
While frac(n/k)=0
n/=k
Append Factors, (k,)
End While
if n=1 then exit
{
k+=2
while not isprime(k) {k+=2}
While frac(n/k)=0
n/=k : Append Factors, (k,)
End While
if n=1 then exit
loop
}
}
=Factors
}
fold=lambda (a, f$)->{
Push if$(len(f$)=0->f$, f$+"x")+str$(a,"")
}
Print "1=1"
i=1@
do
i++
Print str$(i,"")+"="+Decompose(i)#fold$(fold,"")
always
}
Count_in_factors
|
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
| #M4 | M4 | define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl
define(`by',
`ifelse($1,$2,
$1,
`ifelse(eval($1%$2==0),1,
`$2 x by(eval($1/$2),$2)',
`by($1,eval($2+1))') ') ')dnl
define(`wby',
`$1 = ifelse($1,1,
$1,
`by($1,2)') ')dnl
for(`y',1,25,1, `wby(y)
') |
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.
| #Lambdatalk | Lambdatalk |
{table
{@ style="background:#ffe; width:50%;"}
{tr {@ style="text-align:right; font:bold 1.0em arial;"}
{td } {td X} {td Y} {td Z}}
{map {lambda {:i}
{tr {td {b :i}}
{map {lambda {_}
{td {@ style="text-align:right; font:italic 1.0em courier;"}
{floor {* {random} 10000}} }}
{serie 1 3}}}}
{serie 1 3}}}
|
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
| #XPL0 | XPL0 | include c:\cxpl\codes;
int CpuReg, Year, Month, Day, DName, MName, WDay;
[CpuReg:= GetReg; \access CPU registers
CpuReg(0):= $2A00; \DOS system call
SoftInt($21);
Year:= CpuReg(2);
Month:= CpuReg(3) >> 8;
Day:= CpuReg(3) & $FF;
WDay:= CpuReg(0) & $FF;
IntOut(0, Year); ChOut(0, ^-);
if Month<10 then ChOut(0, ^0); IntOut(0, Month); ChOut(0, ^-);
if Day<10 then ChOut(0, ^0); IntOut(0, Day); CrLf(0);
DName:= ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
MName:= [0, "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
Text(0, DName(WDay)); Text(0, ", "); Text(0, MName(Month)); Text(0, " ");
IntOut(0, Day); Text(0, ", "); IntOut(0, Year); CrLf(0);
] |
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
| #Yabasic | Yabasic | dim n$(1)
n = token(date$, n$(), "-")
print n$(4), "-", n$(2), "-", n$(3)
print nDay$(n$(5)), ", ", nMonth$(n$(6)), " ", n$(3), ", ", n$(4)
sub nDay$(n$)
switch n$
case "Mon": case "Fri": case "Sun": break
case "Tue": n$ = n$ + "s" : break
case "Wed": n$ = n$ + "nes" : break
case "Thu": n$ = n$ + "rs" : break
case "Sat": n$ = n$ + "ur" : break
default: n$ = "none" : break
end switch
return n$ + "day"
end sub
sub nMonth$(n$)
local month$(1), n
n = token("January, February, March, April, May, June, July, August, September, October, November, December", month$(), ", ")
n = instr("JanFebMarAprMayJunJulAugSepOctNovDec", n$)
return month$(int(n/3) + 1)
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
fName = ''; fName[0] = 2; fName[1] = '.' || File.separator || 'output.txt'; fName[2] = File.separator || 'output.txt'
dName = ''; dName[0] = 2; dName[1] = '.' || File.separator || 'docs'; dName[2] = File.separator || 'docs'
do
loop i_ = 1 to fName[0]
say fName[i_]
fc = File(fName[i_]).createNewFile()
if fc then say 'File' fName[i_] 'created successfully.'
else say 'File' fName[i_] 'aleady exists.'
end i_
loop i_ = 1 to dName[0]
say dName[i_]
dc = File(dName[i_]).mkdir()
if dc then say 'Directory' dName[i_] 'created successfully.'
else say 'Directory' dName[i_] 'aleady exists.'
end i_
catch iox = IOException
iox.printStackTrace
end
return
|
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).
| #Nanoquery | Nanoquery | // a method that converts a csv row into a html table row as a string
def toHtmlRow(record, tag)
htmlrow = "\t<tr>\n"
// loop through the values in the current csv row
for i in range(1, len(record))
htmlrow = htmlrow + "\t\t<" + tag + ">" + (record ~ i) + "</" + tag + ">\n"
end for
return htmlrow + "\t</tr>\n"
end def
// get the name of the csv file then open it
print "filename: "
input fname
open fname
// allocate a string to hold the table
htmltable = "<table>\n"
// add the column names to the table (#0 returns column names as a record object)
htmltable = (htmltable + toHtmlRow(#0, "th"))
// add all other rows to the table
for i in range(1, $dbsize)
htmltable = (htmltable + toHtmlRow(#i, "td"))
end for
// close the html table
htmltable = htmltable+"</table>"
println htmltable |
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.
| #UNIX_Shell | UNIX Shell | cat csv | while read S; do
[ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc`
done |
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.
| #uBasic.2F4tH | uBasic/4tH | if set (a, open ("yourcsv.csv", "r")) < 0 then
print "Cannot open \qyourcsv.csv\q" ' open file a for reading
end ' abort on file opening errors
endif
if set (b, open ("mycsv.csv", "w")) < 0 then
print "Cannot open \qmycsv.csv\q" ' open file a for writing
end ' abort on file opening errors
endif
if read (a) = 0 then ' read the header line
print "Unexpected end of file" ' if it fails, write the error
close a : close b : end ' close files and terminate
endif
' process the header line
for c = 0 step 1 ' don't know number of columns
p = here() ' get input buffer position
y = tok (ord (",")) ' parse the first field
until p = here() ' until buffer position doesn't change
write b, show (y);","; ' write it out
next
write b, "Sum" ' add a column
do while read (a) ' read a line
s = 0 ' reset the sum
for x = 0 to c-1 ' read all columns
y = iif (set (y, val (tok (ord (",")))) = info ("nil"), 0, y)
s = s + y ' add value to sum
write b, y;","; ' write the value
next ' next column
write b, s ' write the sum
loop
close a : close b : end ' close files and terminate
|
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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func WeekDay(Year, Month, Day); \Return day of week (0=Sat 1=Sun..6=Fri)
int Year, Month, Day;
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7);
]; \WeekDay
int Year;
[for Year:= 2008 to 2121 do
if WeekDay(Year, 12, 25) = 1 then \25th of December is a Sunday
[IntOut(0, Year); CrLf(0)];
] |
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.
| #Yabasic | Yabasic | sub wd(m, d, y)
If m < 3 Then // If m = 1 Or m = 2 Then
m = m + 12
y = y - 1
End If
Return mod((y + int(y / 4) - int(y / 100) + int(y / 400) + d + int((153 * m + 8) / 5)), 7)
End sub
// ------=< MAIN >=------
For yr = 2008 To 2121
If wd(12, 25, yr) = 0 Then
Print "Dec 25 ", yr
EndIf
Next |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.