task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Count_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.
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Coins.bas"
110 LET MONEY=100
120 LET COUNT=0
125 PRINT "Count Pennies Nickles Dimes Quaters"
130 FOR QC=0 TO INT(MONEY/25)
150 FOR DC=0 TO INT((MONEY-QC*25)/10)
170 FOR NC=0 TO INT((MONEY-DC*10)/5)
190 FOR PC=0 TO MONEY-NC*5 STEP 5
200 LET S=PC+NC*5+DC*10+QC*25
210 IF S=MONEY THEN
220 LET COUNT=COUNT+1
230 PRINT COUNT,PC,NC,DC,QC
240 END IF
250 NEXT
260 NEXT
270 NEXT
280 NEXT
290 PRINT COUNT;"different combinations found." |
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.
| #J | J | merge=: ({:"1 (+/@:({."1),{:@{:)/. ])@;
count=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@]
init=: (1 ,. ,.)^:(0=#@$)
nsplits=: 0 { [: +/ [: (merge@:(count"1) init)/ }.@/:~@~.@, |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function countSubstring(s As String, search As String) As Integer
If s = "" OrElse search = "" Then Return 0
Dim As Integer count = 0, length = Len(search)
For i As Integer = 1 To Len(s)
If Mid(s, i, length) = Search Then
count += 1
i += length - 1
End If
Next
Return count
End Function
Print countSubstring("the three truths","th")
Print countSubstring("ababababab","abab")
Print countSubString("zzzzzzzzzzzzzzz", "z")
Print
Print "Press any key to quit"
Sleep |
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
| #FunL | FunL | import util.Regex
def countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()
println( countSubstring("the three truths", "th") )
println( countSubstring("ababababab", "abab") ) |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Fortran | Fortran | program Octal
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer(i64) :: n = 0
! Will stop when n overflows from
! 9223372036854775807 to -92233720368547758078 (1000000000000000000000 octal)
do while(n >= 0)
write(*, "(o0)") n
n = n + 1
end do
end program |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim ub As UByte = 0 ' only has a range of 0 to 255
Do
Print Oct(ub, 3)
ub += 1
Loop Until ub = 0 ' wraps around to 0 when reaches 256
Print
Print "Press any key to quit"
Sleep |
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
| #Factor | Factor | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each |
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
| #Forth | Forth | : .factors ( n -- )
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or \ next odd number
else -rot nip dup . ." x "
then
repeat
drop . ;
: main ( n -- )
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye |
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.
| #Forth | Forth | include random.hsf
\ parser routines
: totag
[char] < PARSE pad place \ parse input up to '<' char
-1 >in +! \ move the interpreter pointer back 1 char
pad count type ;
: '"' [char] " emit ;
: '"..' '"' space ; \ output a quote char with trailing space
: toquote \ parse input to " then print as quoted text
'"' [char] " PARSE pad place
pad count type '"..' ;
: > [char] > emit space ; \ output the '>' with trailing space
\ Create some HTML extensions to the Forth interpreter
: <table> ." <table>" cr ; : </table> ." </table>" cr ;
: <table ." <table " ;
: style=" ." style=" toquote ;
: align=" ." align=" toquote ;
: border=" ." border=" toquote ;
: width=" ." width=" toquote ;
: cellspacing=" ." cellspacing=" toquote ;
: colspacing=" ." colspacing=" toquote ;
: <tr> ." <tr>" cr ; : </tr> ." </tr>" cr ;
: <td> ." <td> " totag ; : </td> ." </td>" cr ;
: <td ." <td " ;
: <thead> ." <thead>" ; : </thead> ." </thead>" ;
: <th> ." <th>" ; : </th> ." </th>" cr ;
: <th ." <th " ;
: <tbody ." <tbody " ; : </tbody> ." </tbody> " ;
: <caption> cr ." <caption>" totag ; : </caption> ." </caption>" cr ;
\ Write the source code that generates HTML in our EXTENDED FORTH
cr
<table border=" 1" width=" 30%" >
<caption> This table was created with FORTH HTML tags</caption>
<tr>
<th align=" right" > </th>
<th align=" right" > ." A" </th>
<th align=" right" > ." B" </th>
<th align=" right" > ." C" </th>
</tr>
<tr>
<th align=" right" > 1 . </th>
<td align=" right" > 1000 RND . </td>
<td align=" right" > 1000 RND . </td>
<td align=" right" > 1000 RND . </td>
</tr>
<tr>
<th align=" right" > 2 . </th>
<td align=" right" > 1000 RND . </td>
<td align=" right" > 1000 RND . </td>
<td align=" right" > 1000 RND . </td>
</tr>
<tr>
<th align=" right" > 3 . </th>
<td align=" right" > 1000 RND . </td>
<td align=" right" > 1000 RND . </td>
<td align=" right" > 1000 RND . </td>
</tr>
</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
| #Run_BASIC | Run BASIC | 'Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007".
print date$("yyyy-mm-dd")
print date$("dddd");", "; 'return full day of the week (eg. Wednesday
print date$("mmmm");" "; 'return full month name (eg. March)
print date$("dd, yyyy") 'return day, year |
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
| #Rust | Rust | fn main() {
let now = chrono::Utc::now();
println!("{}", now.format("%Y-%m-%d"));
println!("{}", now.format("%A, %B %d, %Y"));
} |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #Sidef | Sidef | func cramers_rule(A, terms) {
gather {
for i in ^A {
var Ai = A.map{.map{_}}
for j in ^terms {
Ai[j][i] = terms[j]
}
take(Ai.det)
}
} »/» A.det
}
var matrix = [
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
]
var free_terms = [-3, -32, -47, 49]
var (w, x, y, z) = cramers_rule(matrix, free_terms)...
say "w = #{w}"
say "x = #{x}"
say "y = #{y}"
say "z = #{z}" |
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.
| #J | J | '' 1!:2 <'/output.txt' NB. write an empty file
1!:5 <'/docs' NB. create a directory |
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.
| #Java | Java | import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
} |
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).
| #JavaScript | JavaScript | var csv = "Character,Speech\n" +
"The multitude,The messiah! Show us the messiah!\n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" +
"The multitude,Who are you?\n" +
"Brians mother,I'm his mother; that's who!\n" +
"The multitude,Behold his mother! Behold his mother!";
var lines = csv.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.split(/[\n\r]/)
.map(function(line) { return line.split(',')})
.map(function(row) {return '\t\t<tr><td>' + row[0] + '</td><td>' + row[1] + '</td></tr>';});
console.log('<table>\n\t<thead>\n' + lines[0] +
'\n\t</thead>\n\t<tbody>\n' + lines.slice(1).join('\n') +
'\t</tbody>\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.
| #Prolog | Prolog | test :- augment('test.csv', 'test.out.csv').
% augment( +InFileName, +OutFileName)
augment(InFile, OutFile) :-
open(OutFile, write, OutStream),
( ( csv_read_file_row(InFile, Row, [line(Line)]),
% Row is of the form row( Item1, Item2, ....).
addrow(Row, Out),
csv_write_stream(OutStream, [Out], []),
fail
)
; close(OutStream)
).
% If the first item in a row is an integer, then append the sum;
% otherwise append 'SUM':
addrow( Term, NewTerm ) :-
Term =.. [F | List],
List = [X|_],
(integer(X) -> sum_list(List, Sum) ; Sum = 'SUM'),
append(List, [Sum], NewList),
NewTerm =.. [F | NewList].
|
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.
| #Scheme | Scheme | (define (day-of-week year month day)
(if (< month 3)
(begin (set! month (+ month 12)) (set! year (- year 1))))
(+ 1
(remainder (+ 5 day (quotient (* (+ 1 month) 13) 5)
year (quotient year 4) (* (quotient year 100) 6) (quotient year 400))
7)))
(define (task)
(let loop ((y 2121) (v '()))
(if (< y 2008)
v
(loop (- y 1)
(if (= 7 (day-of-week y 12 25))
(cons y v)
v)))))
(task)
; (2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118) |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckArray {
Do {
Input "A, B=", A% ,B%
} Until A%>0 and B%>0
\\ 1@ is 1 Decimal
addone=lambda N=1@ ->{=N : N++}
Dim Base 1, Arr(A%,B%)<<addone()
\\ pi also is decimal
Arr(1,1)=pi
Print Arr(1,1)
Print Arr()
\\ all variables/arrays/inner functions/modules erased now
}
CheckArray
|
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.
| #Maple | Maple | > a := Array( 1 .. 3, 1 .. 4 ): # initialised to 0s
> a[1,1] := 1: # assign an element
> a[2,3] := 4: # assign an element
> a; # display the array
[1 0 0 0]
[ ]
[0 0 4 0]
[ ]
[0 0 0 0]
> a := 'a': # unassign the name
> gc(); # force a garbage collection; may or may not actually collect the array, but it will be eventually |
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 0 П4 П5 П6 С/П П0 ИП5 + П5 ИП0
x^2 ИП6 + П6 КИП4 ИП6 ИП4 / ИП5 ИП4
/ x^2 - КвКор БП 04 |
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
| #REXX | REXX | /*REXX program computes the CRC─32 (32 bit Cyclic Redundancy Check) checksum for a */
/*─────────────────────────────────given string [as described in ISO 3309, ITU─T V.42].*/
call show 'The quick brown fox jumps over the lazy dog' /*the 1st string.*/
call show 'Generate CRC32 Checksum For Byte Array Example' /* " 2nd " */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
CRC_32: procedure; parse arg !,$; c= 'edb88320'x /*2nd arg used for repeated invocations*/
f= 'ffFFffFF'x /* [↓] build an 8─bit indexed table,*/
do i=0 for 256; z= d2c(i) /* one byte at a time.*/
r= right(z, 4, '0'x) /*insure the "R" is thirty─two bits.*/
/* [↓] handle each rightmost byte bit.*/
do j=0 for 8; rb= x2b(c2x(r)) /*handle each bit of rightmost 8 bits. */
r= x2c( b2x(0 || left(rb, 31) ) ) /*shift it right (an unsigned) 1 bit.*/
if right(rb,1) then r= bitxor(r, c) /*this is a bin bit for XOR grunt─work.*/
end /*j*/
!.z= r /*assign to an eight─bit index table. */
end /*i*/
$=bitxor( word($ '0000000'x, 1), f) /*utilize the user's CRC or a default. */
do k=1 for length(! ) /*start number crunching the input data*/
?= bitxor(right($,1), substr(!,k,1) )
$= bitxor('0'x || left($, 3), !.?)
end /*k*/
return $ /*return with cyclic redundancy check. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: procedure; parse arg Xstring; numeric digits 12; say; say
checksum= bitxor(CRC_32(Xstring), 'ffFFffFF'x) /*invoke CRC_32 to create a CRC. */
say center(' input string [length of' length(Xstring) "bytes] ", 79, '═')
say Xstring; say /*show the string on its own line*/
say "hex CRC─32 checksum =" c2x(checksum) left('', 15),
"dec CRC─32 checksum =" c2d(checksum) /*show the CRC─32 in hex and dec.*/
return |
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.
| #Java | Java | import java.util.Arrays;
import java.math.BigInteger;
class CountTheCoins {
private static BigInteger countChanges(int amount, int[] coins){
final int n = coins.length;
int cycle = 0;
for (int c : coins)
if (c <= amount && c >= cycle)
cycle = c + 1;
cycle *= n;
BigInteger[] table = new BigInteger[cycle];
Arrays.fill(table, 0, n, BigInteger.ONE);
Arrays.fill(table, n, cycle, BigInteger.ZERO);
int pos = n;
for (int s = 1; s <= amount; s++) {
for (int i = 0; i < n; i++) {
if (i == 0 && pos >= cycle)
pos = 0;
if (coins[i] <= s) {
final int q = pos - (coins[i] * n);
table[pos] = (q >= 0) ? table[q] : table[q + cycle];
}
if (i != 0)
table[pos] = table[pos].add(table[pos - 1]);
pos++;
}
}
return table[pos - 1];
}
public static void main(String[] args) {
final int[][] coinsUsEu = {{100, 50, 25, 10, 5, 1},
{200, 100, 50, 20, 10, 5, 2, 1}};
for (int[] coins : coinsUsEu) {
System.out.println(countChanges( 100,
Arrays.copyOfRange(coins, 2, coins.length)));
System.out.println(countChanges( 100000, coins));
System.out.println(countChanges( 1000000, coins));
System.out.println(countChanges(10000000, coins) + "\n");
}
}
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th")) // says: 3
fmt.Println(strings.Count("ababababab", "abab")) // says: 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
| #Go | Go | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th")) // says: 3
fmt.Println(strings.Count("ababababab", "abab")) // says: 2
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Frink | Frink | i = 0
while true
{
println[i -> octal]
i = i + 1
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Futhark | Futhark |
fun octal(x: int): int =
loop ((out,mult,x) = (0,1,x)) = while x > 0 do
let digit = x % 8
let out = out + digit * mult
in (out, mult * 10, x / 8)
in out
fun main(n: int): [n]int =
map octal (iota n)
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #FutureBasic | FutureBasic | window 1, @"Count in Octal"
defstr word
dim as short i
text ,,,,, 50
print @"dec",@"oct"
for i = 0 to 25
print i,oct(i)
next
HandleEvents |
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
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Thu Jun 6 23:29:06
!
!a=./f && make $a && echo -2 | OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
! assert 1 = */ 1
! assert 2 = */ 2
! assert 3 = */ 3
! assert 4 = */ 2 2
! assert 5 = */ 5
! assert 6 = */ 2 3
! assert 7 = */ 7
! assert 8 = */ 2 2 2
! assert 9 = */ 3 3
! assert 10 = */ 2 5
! assert 11 = */ 11
! assert 12 = */ 3 2 2
! assert 13 = */ 13
! assert 14 = */ 2 7
! assert 15 = */ 3 5
! assert 16 = */ 2 2 2 2
! assert 17 = */ 17
! assert 18 = */ 3 2 3
! assert 19 = */ 19
! assert 20 = */ 2 2 5
! assert 21 = */ 3 7
! assert 22 = */ 2 11
! assert 23 = */ 23
! assert 24 = */ 3 2 2 2
! assert 25 = */ 5 5
! assert 26 = */ 2 13
! assert 27 = */ 3 3 3
! assert 28 = */ 2 2 7
! assert 29 = */ 29
! assert 30 = */ 5 2 3
! assert 31 = */ 31
! assert 32 = */ 2 2 2 2 2
! assert 33 = */ 3 11
! assert 34 = */ 2 17
! assert 35 = */ 5 7
! assert 36 = */ 3 3 2 2
! assert 37 = */ 37
! assert 38 = */ 2 19
! assert 39 = */ 3 13
! assert 40 = */ 5 2 2 2
module prime_mod
! sieve_table stores 0 in prime numbers, and a prime factor in composites.
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
! setup routine must be called first!
subroutine sieve(n) ! populate sieve_table. If n is 0 it deallocates storage, invalidating sieve_table.
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p ! number to factor
integer, dimension(:), intent(out) :: rv ! the prime factors
integer, intent(out) :: n ! number of factors returned
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40) ! setup
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0) ! release memory
end program count_in_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.
| #Fortran | Fortran |
MODULE PARAMETERS !Assorted oddities that assorted routines pick and choose from.
CHARACTER*5 I AM !Assuage finicky compilers.
PARAMETER (IAM = "Gnash") !I AM!
INTEGER LUSERCODE !One day, I'll get around to devising some string protocol.
CHARACTER*28 USERCODE !I'm not too sure how long this can be.
DATA USERCODE,LUSERCODE/"",0/!Especially before I have a text.
END MODULE PARAMETERS
MODULE ASSISTANCE
CONTAINS !Assorted routines that seem to be of general use but don't seem worth isolating..
Subroutine Croak(Gasp) !A dying message, when horror is suddenly encountered.
Casts out some final words and STOP, relying on the SubInOut stuff to have been used.
Cut down from the full version of April MMI, that employed the SubIN and SubOUT protocol..
Character*(*) Gasp !The last gasp.
COMMON KBD,MSG
WRITE (MSG,1) GASP
1 FORMAT ("Oh dear! ",A)
STOP "I STOP now. Farewell..." !Whatever pit I was in, I'm gone.
End Subroutine Croak !That's it.
INTEGER FUNCTION LSTNB(TEXT) !Sigh. Last Not Blank.
Concocted yet again by R.N.McLean (whom God preserve) December MM.
Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness!
Can't DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ') !Control chars. regarded as spaces.
Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully.
Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable.
Comparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone.
Crappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only.
Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L!
Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB.
CHARACTER*(*),INTENT(IN):: TEXT !The bumf. If there must be copy-in, at least there need not be copy back.
INTEGER L !The length of the bumf.
L = LEN(TEXT) !So, what is it?
1 IF (L.LE.0) GO TO 2 !Are we there yet?
IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also.
L = L - 1 !Step back one.
GO TO 1 !And try again.
2 LSTNB = L !The last non-blank, possibly zero.
RETURN !Unsafe to use LSTNB as a variable.
END FUNCTION LSTNB !Compilers can bungle it.
CHARACTER*2 FUNCTION I2FMT(N) !These are all the same.
INTEGER*4 N !But, the compiler doesn't offer generalisations.
IF (N.LT.0) THEN !Negative numbers cop a sign.
IF (N.LT.-9) THEN !But there's not much room left.
I2FMT = "-!" !So this means 'overflow'.
ELSE !Otherwise, room for one negative digit.
I2FMT = "-"//CHAR(ICHAR("0") - N) !Thus. Presume adjacent character codes, etc.
END IF !So much for negative numbers.
ELSE IF (N.LT.10) THEN !Single digit positive?
I2FMT = " " //CHAR(ICHAR("0") + N) !Yes. This.
ELSE IF (N.LT.100) THEN !Two digit positive?
I2FMT = CHAR(N/10 + ICHAR("0")) !Yes.
1 //CHAR(MOD(N,10) + ICHAR("0")) !These.
ELSE !Otherwise,
I2FMT = "+!" !Positive overflow.
END IF !So much for that.
END FUNCTION I2FMT !No WRITE and FORMAT unlimbering.
CHARACTER*8 FUNCTION I8FMT(N) !Oh for proper strings.
INTEGER*4 N
CHARACTER*8 HIC
WRITE (HIC,1) N
1 FORMAT (I8)
I8FMT = HIC
END FUNCTION I8FMT
CHARACTER*42 FUNCTION ERRORWORDS(IT) !Look for an explanation. One day, the system may offer coherent messages.
Curious collection of encountered codes. Will they differ on other systems?
Compaq's compiler was taken over by unintel; http://software.intel.com/sites/products/documentation/hpc/compilerpro/en-us/fortran/lin/compiler_f/bldaps_for/common/bldaps_rterrs.htm
contains a schedule of error numbers that matched those I'd found for Compaq, and so some assumptions are added.
Copying all (hundreds!) is excessive; these seem possible for the usage so far made of error diversion.
Compaq's compiler interface ("visual" blah) has a help offering, which can provide error code information.
Compaq messages also appear in http://cens.ioc.ee/local/man/CompaqCompilers/cf/dfuum028.htm#tab_runtime_errors
Combines IOSTAT codes (file open, read etc) with STAT codes (allocate/deallocate) as their numbers are distinct.
Completeness and context remains a problem. Excess brevity means cause and effect can be confused.
INTEGER IT !The error code in question.
INTEGER LASTKNOWN !Some codes I know about.
PARAMETER (LASTKNOWN = 26) !But only a few, discovered by experiment and mishap.
TYPE HINT !For them, I can supply a table.
INTEGER CODE !The code number. (But, different systems..??)
CHARACTER*42 EXPLICATION !An explanation. Will it be the answer?
END TYPE HINT !Simple enough.
TYPE(HINT) ERROR(LASTKNOWN) !So, let's have a collection.
PARAMETER (ERROR = (/ !With these values.
1 HINT(-1,"End-of-file at the start of reading!"), !From examples supplied with the Compaq compiler involving IOSTAT.
2 HINT( 0,"No worries."), !Apparently the only standard value.
3 HINT( 9,"Permissions - read only?"),
4 HINT(10,"File already exists!"),
5 HINT(17,"Syntax error in NameList input."),
6 HINT(18,"Too many values for the recipient."),
7 HINT(19,"Invalid naming of a variable."),
8 HINT(24,"Surprise end-of-file during read!"), !From example source.
9 HINT(25,"Invalid record number!"),
o HINT(29,"File name not found."),
1 HINT(30,"Unavailable - exclusive use?"),
2 HINT(32,"Invalid fileunit number!"),
3 HINT(35,"'Binary' form usage is rejected."), !From example source.
4 HINT(36,"Record number for a non-existing record!"),
5 HINT(37,"No record length has been specified."),
6 HINT(38,"I/O error during a write!"),
7 HINT(39,"I/O error during a read!"),
8 HINT(41,"Insufficient memory available!"),
9 HINT(43,"Malformed file name."),
o HINT(47,"Attempting a write, but read-only is set."),
1 HINT(66,"Output overflows single record size."), !This one from experience.
2 HINT(67,"Input demand exceeds single record size."), !These two are for unformatted I/O.
3 HINT(151,"Can't allocate: already allocated!"), !These different numbers are for memory allocation failures.
4 HINT(153,"Can't deallocate: not allocated!"),
5 HINT(173,"The fingered item was not allocated!"), !Such as an ordinary array that was not allocated.
6 HINT(179,"Size exceeds addressable memory!")/))
INTEGER I !A stepper.
DO I = LASTKNOWN,1,-1 !So, step through the known codes.
IF (IT .EQ. ERROR(I).CODE) GO TO 1 !This one?
END DO !On to the next.
1 IF (I.LE.0) THEN !Fail with I = 0.
ERRORWORDS = I8FMT(IT)//" is a novel code!" !Reveal the mysterious number.
ELSE !But otherwise, it is found.
ERRORWORDS = ERROR(I).EXPLICATION !And these words might even apply.
END IF !But on all systems?
END FUNCTION ERRORWORDS !Hopefully, helpful.
END MODULE ASSISTANCE
MODULE LOGORRHOEA
CONTAINS
SUBROUTINE ECART(TEXT) !Produces trace output with many auxiliary details.
CHARACTER*(*) TEXT !The text to be annotated.
COMMON KBD,MSG !I/O units.
WRITE (MSG,1) TEXT !Just roll the text.
1 FORMAT ("Trace: ",A) !Lacks the names of the invoking routine, and that which invoked it.
END SUBROUTINE ECART
SUBROUTINE WRITE(OUT,TEXT,ON) !We get here in the end. Cast forth some pearls.
C Once upon a time, there was just confusion between ASCII and EBCDIC character codes and glyphs,
c after many variant collections caused annoyance. Now I see that modern computing has introduced
c many new variations, so that one text editor may display glyphs differing from those displayed
c by another editor and also different from those displayed when a programme writes to the screen
c in "teletype" mode, which is to say, employing the character/glyph combination of the moment.
c And in particular, decimal points and degree symbols differ and annoyance has grown.
c So, on re-arranging SAY to not send output to multiple distinations depending on the value of OUT,
c except for the special output to MSG that is echoed to TRAIL, it became less messy to make an assault
c on the text that goes to MSG, but after it was sent to TRAIL. I would have preferred to fiddle the
c "code page" for text output that determines what glyph to show for which code, but not only
c is it unclear how to do this, even if facilities were available, I suspect that the screen display
c software only loads the mysterious code page during startup.
c This fiddling means that any write to MSG should be done last, and writes of text literals
c should not include characters that will be fiddled, as text literals may be protected against change.
C Somewhere along the way, the cent character (¢) has disappeared. Perhaps it will return in "unicode".
USE ASSISTANCE !But might still have difficulty.
INTEGER OUT !The destination.
CHARACTER*(*) TEXT !The message. Possibly damaged. Any trailing spaces will be sent forth.
LOGICAL ON !Whether to terminate the line... TRUE sez that someone will be carrying on.
INTEGER IOSTAT !Furrytran gibberish.
c INCLUDE "cIOUnits.for" !I/O unit numbers.
COMMON KBD,MSG
c INTEGER*2,SAVE:: I Be !Self-identification.
c CALL SUBIN("Write",I Be) !Hullo!
IF (OUT.LE.0) GO TO 999 !Goodbye?
c IF (IOGOOD(OUT)) THEN !Is this one in good heart?
c IF (IOCOUNT(OUT).LE.0 .AND. OUT.NE.MSG) THEN !Is it attached to a file?
c IF (IONAME(OUT).EQ."") IONAME(OUT) = "Anome" !"No name".
c 1 //I2FMT(OUT)//".txt" !Clutch at straws.
c IF (.NOT.OPEN(OUT,IONAME(OUT),"REPLACE","WRITE")) THEN !Just in time?
c IOGOOD(OUT) = .FALSE. !No! Strangle further usage.
c GO TO 999 !Can't write, so give up!
c END IF !It might be better to hit the WRITE and fail.
c END IF !We should be ready now.
c IF (OUT.EQ.MSG .AND. SCRAGTEXTOUT) CALL SCRAG(TEXT) !Output to the screen is recoded for the screen.
IF (ON) THEN !Now for the actual output at last. This is annoying.
WRITE (OUT,1,ERR = 666,IOSTAT = IOSTAT) TEXT !Splurt.
1 FORMAT (A,$) !Don't move on to a new line. (The "$"! Is it not obvious?)
c IOPART(OUT) = IOPART(OUT) + 1 !Thus count a part-line in case someone fusses.
ELSE !But mostly, write and advance.
WRITE (OUT,2,ERR = 666,IOSTAT = IOSTAT) TEXT !Splurt.
2 FORMAT (A) !*-style "free" format chops at 80 or some such.
END IF !So much for last-moment dithering.
c IOCOUNT(OUT) = IOCOUNT(OUT) + 1 !Count another write (whole or part) so as to be not zero..
c END IF !So much for active passages.
c 999 CALL SUBOUT("Write") !I am closing.
999 RETURN !Done.
Confusions.
666 IF (OUT.NE.MSG) CALL CROAK("Can't write to unit "//I2FMT(OUT) !Why not?
c 1 //" (file "//IONAME(OUT)(1:LSTNB(IONAME(OUT))) !Possibly, no more disc space! In which case, this may fail also!
2 //") message "//ERRORWORDS(IOSTAT) !Hopefully, helpful.
3 //" length "//I8FMT(LEN(TEXT))//", this: "//TEXT) !The instigation.
STOP "Constipation!" !Just so.
END SUBROUTINE WRITE !The moving hand having writ, moves on.
SUBROUTINE SAY(OUT,TEXT) !And maybe a copy to the trail file as well.
USE PARAMETERS !Odds and ends.
USE ASSISTANCE !Just a little.
INTEGER OUT !The orifice.
CHARACTER*(*) TEXT !The blather. Can be modified if to MSG and certain characters are found.
CHARACTER*120 IS !For a snatched question.
INTEGER L !A finger.
c INCLUDE "cIOUnits.for" !I/O unit numbers.
COMMON KBD,MSG
c INTEGER*2,SAVE:: I Be !Self-identification.
c CALL SUBIN("Say",I Be) !Me do be Me, I say!
Chop off trailing spaces.
L = LEN(TEXT) !What I say may be rather brief.
1 IF (L.GT.0) THEN !So, is there a last character to look at?
IF (ICHAR(TEXT(L:L)).LE.ICHAR(" ")) THEN !Yes. Is it boring?
L = L - 1 !Yes! Trim it!
GO TO 1 !And check afresh.
END IF !A DO-loop has overhead with its iteration count as well.
END IF !Function LEN_TRIM copies the text first!!
Contemplate the disposition of TEXT(1:L)
c IF (OUT.NE.MSG) THEN !Normal stuff?
CALL WRITE(OUT,TEXT(1:L),.FALSE.) !Roll.
c ELSE !Echo what goes to MSG to the TRAIL file.
c CALL WRITE(TRAIL,TEXT(1:L),.FALSE.) !Thus.
c CALL WRITE( MSG,TEXT(1:L),.FALSE.) !Splot to the screen.
c IF (.NOT.BLABBERMOUTH) THEN !Do we know restraint?
c IF (IOCOUNT(MSG).GT.BURP) THEN !Yes. Consider it.
c WRITE (MSG,100) IOCOUNT(MSG) !Alas, triggered. So remark on quantity,
c 100 FORMAT (//I9," lines! Your spirit might flag." !Hint. (Not copied to the TRAIL file)
c 1 /," Type quit to set GIVEOVER to TRUE, with hope for "
c 2 ,"a speedy palliation,",
c 3 /," or QUIT to abandon everything, here, now",
c 4 /," or blabber to abandon further restraint,",
c 5 /," or anything else to carry on:")
c IS = REPLY("QUIT, quit, blabber or continue") !And ask.
c IF (IS.EQ."QUIT") CALL CROAK("Enough of this!") !No UPDATE, nothing.
c CALL UPCASE(IS) !Now we're past the nice distinction, simplify.
c IF (IS.EQ."QUIT") GIVEOVER = .TRUE. !Signal to those who listen.
c IF (IS.EQ."BLABBER") BLABBERMOUTH = .TRUE. !Well?
c IF (GIVEOVER) WRITE (MSG,101) !Announce hope.
c 101 FORMAT ("Let's hope that the babbler notices...") !Like, IF (GIVEOVER) GO TO ...
c IF (.NOT.GIVEOVER) WRITE (MSG,102) !Alternatively, firm resolve.
c 102 FORMAT("Onwards with renewed vigour!") !Fight the good fight.
c BURP = IOCOUNT(MSG) + ENOUGH !The next pause to come.
c END IF !So much for last-moment restraint.
c END IF !So much for restraint.
c END IF !So much for selection.
c CALL SUBOUT("Say") !I am merely the messenger.
END SUBROUTINE SAY !Enough said.
SUBROUTINE SAYON(OUT,TEXT) !Roll to the screen and to the trail file as well.
C This differs by not ending the line so that further output can be appended to it.
USE ASSISTANCE
INTEGER OUT !The orifice.
CHARACTER*(*) TEXT !The blather.
INTEGER L !A finger.
c INCLUDE "cIOUnits.for" !I/O unit numbers.
COMMON KBD,MSG
c INTEGER*2,SAVE:: I Be !Self-identification.
c CALL SUBIN("SayOn",I Be) !Me do be another. Me, I say on!
L = LEN(TEXT) !How much say I on?
1 IF (L.GT.0) THEN !I say on anything?
IF (ICHAR(TEXT(L:L)).LE.ICHAR(" ")) THEN !I end it spaceish?
L = L - 1 !Yes. Trim such.
GO TO 1 !And look afresh.
END IF !So much for trailing off.
END IF !Continue with L fingering the last non-blank.
c IF (OUT.EQ.MSG) CALL WRITE(TRAIL,TEXT(1:L),.TRUE.) !Writes to the screen go also to the TRAIL.
CALL WRITE( OUT,TEXT(1:L),.TRUE.) !It is said, and more is expected.
c CALL SUBOUT("SayOn") !I am merely the messenger.
END SUBROUTINE SAYON !And further messages impend.
END MODULE LOGORRHOEA
MODULE HTMLSTUFF !Assists with the production of decorated output.
Can't say I think much of the scheme. How about <+blah> ... <-blah> rather than the assymetric <blah> ... </blah>?
Cack-handed comment format as well...
USE PARAMETERS !To ascertain who I AM.
USE ASSISTANCE !To get at LSTNB.
USE LOGORRHOEA !To get at SAYON and SAY.
INTEGER INDEEP,HOLE !I keep track of some details.
PRIVATE INDEEP,HOLE !Amongst myselves.
DATA INDEEP,HOLE/0,0/ !Initially, I'm not doing anything.
Choose amongst output formats.
INTEGER LASTFILETYPENAME !Certain file types are recognised.
PARAMETER (LASTFILETYPENAME = 2) !Thus, three options.
INTEGER OUTTYPE,OUTTXT,OUTCSV,OUTHTML !The recognition.
CHARACTER*5 OUTSTYLE,FILETYPENAME(0:LASTFILETYPENAME) !Via the tail end of a file name.
PARAMETER (FILETYPENAME = (/".txt",".CSV",".HTML"/)) !Thusly. Note that WHATFILETYPE will not recognise ".txt" directly.
PARAMETER (OUTTXT = 0,OUTCSV = 1,OUTHTML = 2) !Mnemonics.
DATA OUTSTYLE/""/ !So OUTTYPE = OUTTXT. But if an output file is specified, its file type will be inspected.
TYPE HTMLMNEMONIC !I might as well get systematic, as these are global names.
CHARACTER* 9 COMMAH !This looks like a comma
CHARACTER* 9 COMMAD !And in another context, so does this.
CHARACTER* 6 SPACE !Some spaces are to be atomic.
CHARACTER*18 RED !Decoration and
CHARACTER* 7 DER !noitaroceD.
END TYPE HTMLMNEMONIC !That's enough for now.
TYPE(HTMLMNEMONIC) HTMLA !I'll have one set, please.
PARAMETER (HTMLA = HTMLMNEMONIC( !With these values.
1 "</th><th>", !But .html has its variants. For a heading.
2 "</td><td>", !For a table datum.
3 " ", !A space that is not to be split.
4 '<font color="red">', !Dabble in decoration.
5 '</font>')) !Grrrr. A font is for baptismal water.
CONTAINS !Mysterious assistants.
SUBROUTINE HTML(TEXT) !Rolls some text, with suitable indentation.
CHARACTER*(*) TEXT !The text.
c INCLUDE "cIOUnits.for" !I/O unit numbers.
IF (LEN(TEXT).LE.0) RETURN !Possibly boring.
IF (INDEEP.GT.0) THEN !Some indenting desired?
CALL WRITE(HOLE,REPEAT(" ",INDEEP),.TRUE.) !Yep. SAYON trims trailing spaces.
c IF (HOLE.EQ.MSG) CALL WRITE(TRAIL,REPEAT(" ",INDEEP),.TRUE.) !So I must copy.
END IF !Enough indenting.
CALL SAY(HOLE,TEXT) !Say the piece and end the line.
END SUBROUTINE HTML !Maintain stacks? Check entry/exit matching?
SUBROUTINE HTML3(HEAD,BUMF,TAIL) !Rolls some text, with suitable indentation.
Checks the BUMF for decimal points only. HTMLALINE handles text to HTML for troublesome characters, replacing them with special names for the desired glyph.
Confusion might arise, if & is in BUMF and is not to be converted. "&" vs "&so on"; similar worries with < and >.
CHARACTER*(*) HEAD !If not "", the start of the line, with indentation supplied.
CHARACTER*(*) BUMF !The main body of the text.
CHARACTER*(*) TAIL !If not "", this is for the end of the line.
INTEGER LB,L1,L2 !A length and some fingers for scanning.
CHARACTER*1 MUMBLE !These symbols may not be presented properly.
CHARACTER*8 MUTTER !But these encodements may be interpreted as desired.
PARAMETER (MUMBLE = "·") !I want certain glyphs, but encodement varies.
PARAMETER (MUTTER = "·") !As does recognition.
c INCLUDE "cIOUnits.for" !I/O unit numbers.
COMMON KBD,MSG
Commence with a new line?
IF (HEAD.NE."") THEN !Is a line to be started? (Spaces are equivalent to "" as well)
IF (INDEEP.GT.0) THEN !Some indentation is good.
CALL WRITE(HOLE,REPEAT(" ",INDEEP),.TRUE.) !Yep. SAYON trims trailing spaces.
c IF (HOLE.EQ.MSG) CALL WRITE(TRAIL, !So I must copy for the log.
c 1 REPEAT(" ",INDEEP),.TRUE.) !Hopefully, not generated a second time.
ELSE !The accountancy may be bungled.
CALL ECART("HTML huh? InDeep="//I8FMT(INDEEP)) !So, complain.
END IF !Also, REPEAT has misbehaved.
CALL SAYON(HOLE,HEAD) !Thus a suitable indentation.
END IF !So much for a starter.
Cast forth the bumf. Any trailing spaces will be dropped by SAYON.
LB = LEN(BUMF) !How much bumf? Trailing spaces will be rolled.
L1 = 1 !Waiting to be sent.
L2 = 0 !Syncopation.
1 L2 = L2 + 1 !Advance to the next character to be inspected..
IF (L2.GT.LB) GO TO 2 !Is there another?
IF (ICHAR(BUMF(L2:L2)).NE.ICHAR(MUMBLE)) GO TO 1 !Yes. Advance through the untroublesome.
IF (L1.LT.L2) THEN !A hit. Have any untroubled ones been passed?
CALL WRITE(HOLE,BUMF(L1:L2 - 1),.TRUE.) !Yes. Send them forth.
c IF (HOLE.EQ.MSG) CALL WRITE(TRAIL,BUMF(L1:L2 - 1),.TRUE.) !With any trailing spaces included.
END IF !Now to do something in place of BUMF(L2)
L1 = L2 + 1 !Moving the marker past it, like.
CALL SAYON(HOLE,MUTTER) !The replacement for BUMF(L2 as was).
GO TO 1 !Continue scanning.
2 IF (L2.GT.L1) THEN !Any tail end, but not ending the output line.
CALL WRITE(HOLE,BUMF(L1:L2 - 1),.TRUE.) !Yes. Away it goes.
c IF (HOLE.EQ.MSG) CALL WRITE(TRAIL,BUMF(L1:L2 - 1),.TRUE.) !And logged.
END IF !So much for the bumf.
Consider ending the line.
3 IF (TAIL.NE."") CALL SAY(HOLE,TAIL) !Enough!
END SUBROUTINE HTML3 !Maintain stacks? Check entry/exit matching?
SUBROUTINE HTMLSTART(OUT,TITLE,DESC) !Roll forth some gibberish.
INTEGER OUT !The mouthpiece, mentioned once only at the start, and remembered for future use.
CHARACTER*(*) TITLE !This should be brief.
CHARACTER*(*) DESC !This a little less brief.
CHARACTER*(*) METAH !Some repetition.
PARAMETER (METAH = '<Meta Name="') !The syntax is dubious.
CHARACTER*8 D !YYYYMMDD
CHARACTER*10 T !HHMMSS.FFF
HOLE = OUT !Keep a local copy to save on parameters.
INDEEP = 0 !We start.
CALL HTML('<!DOCTYPE HTML PUBLIC "' !Before we begin, we wave hands.
1 //'-//W3C//DTD HTML 4.01 Transitional//EN"' !Otherwise "nowrap" is objected to, as in http://validator.w3.org/check
2 //' "http://www.w3.org/TR/html4/loose.dtd">') !Endless blather.
CALL HTML('<HTML lang="en-NZ">') ! H E R E W E G O !
INDEEP = 1 !Its content.
CALL HTML("<Head>") !And the first decoration begins.
INDEEP = 2 !Its content.
CALL HTML("<Title>"//I AM//" " !This appears in the web page tag.
1 // TITLE(1:LSTNB(TITLE)) //"</Title>")!So it should be short.
CALL HTML('<Meta http-equiv="Content-Type"' !Crazed gibberish.
1 //' content="text/html; charset=utf-8">') !But said to be worthy.
CALL HTML(METAH//'Description" Content="'//DESC//'">') !Hopefully, helpful.
CALL HTML(METAH//'Generator" Content="'//I AM//'">') !I said.
CALL DATE_AND_TIME(DATE = D,TIME = T) !Not assignments, but attachments.
CALL HTML(METAH//'Created" Content="' !Convert the timestamp
1 //D(1:4)//"-"//D(5:6)//"-"//D(7:8) !Into an international standard.
2 //" "//T(1:2)//":"//T(3:4)//":"//T(5:10)//'">') !For date and time.
IF (LUSERCODE.GT.0) CALL HTML(METAH !Possibly, the user's code is known.
1 //'Author" Content="'//USERCODE(1:LUSERCODE) !If so, reveal.
2 //'"> <!-- User code as reported by GetLog.-->') !Disclaiming responsibility...
INDEEP = 1 !Finishing the content of the header.
CALL HTML("</Head>") !Enough of that.
CALL HTML("<BODY>") !A fresh line seems polite.
INDEEP = 2 !Its content follows..
END SUBROUTINE HTMLSTART !Others will follow on. Hopefully, correctly.
SUBROUTINE HTMLSTOP !And hopefully, this will be a good closure.
Could be more sophisticated and track the stack via INDEEP+- and names, to enable a desperate close-off if INDEEP is not 2.
IF (INDEEP.NE.2) CALL ECART("Misclosure! InDeep not 2 but" !But,
1 //I8FMT(INDEEP)) !It may not be.
INDEEP = 1 !Retreat to the first level.
CALL HTML("</BODY>") !End the "body".
INDEEP = 0 !Retreat to the start level.
CALL HTML("</HTML>") !End the whole thing.
END SUBROUTINE HTMLSTOP !Ah...
SUBROUTINE HTMLTSTART(B,SUMMARY) !Start a table.
INTEGER B !Border thickness.
CHARACTER*(*) SUMMARY !Some well-chosen words.
CALL HTML("<Table border="//I2FMT(B) !Just so. Text digits, or, digits in text?
1 //' summary="'//SUMMARY//'">') !Not displayed, but potentially used by non-display agencies...
INDEEP = INDEEP + 1 !Another level dug.
END SUBROUTINE HTMLTSTART!That part was easy.
SUBROUTINE HTMLTSTOP !And the ending is easy too.
INDEEP = INDEEP - 1 !Withdraw a level.
CALL HTML("</Table>") !Hopefully, aligning.
END SUBROUTINE HTMLTSTOP !The bounds are easy.
SUBROUTINE HTMLTHEADSTART !Start a table's heading.
CALL HTML("<tHead>") !Thus.
INDEEP = INDEEP + 1 !Dig deeper.
END SUBROUTINE HTMLTHEADSTART !Content should follow.
SUBROUTINE HTMLTHEADSTOP !And now, enough.
INDEEP = INDEEP - 1 !Retreat a level.
CALL HTML("</tHead>") !And end the head.
END SUBROUTINE HTMLTHEADSTOP !At the neck of the body?
SUBROUTINE HTMLTHEAD(N,TEXT) !Cast forth a whole-span table heading.
INTEGER N !The count of columns to be spanned.
CHARACTER*(*) TEXT !A brief description to place there.
CALL HTML3("<tr><th colspan=",I8FMT(N)//' align="center">',"") !Start the specification.
CALL HTML3("",TEXT(1:LSTNB(TEXT)),"</th></tr>") !This text, possibly verbose.
END SUBROUTINE HTMLTHEAD !Thus, all contained on one line.
SUBROUTINE HTMLTBODYSTART !Start on the table body.
CALL HTML('<tBody> <!--Profuse "align" usage ' !Simple, but I'm unhappy.
1 //'for all cells can be factored out to "row" ' !Alas, so far as I can make out.
2 //'but not to "body"-->') !And I don't think much of the "comment" formalism, either.
INDEEP = INDEEP + 1 !Anyway, we're ready with the alignment.
END SUBROUTINE HTMLTBODYSTART !Others will provide the body.
SUBROUTINE HTMLTBODYSTOP !And, they've had enough.
INDEEP = INDEEP - 1 !So, up out of the hole.
CALL HTML("</tBody>") !Take a breath.
END SUBROUTINE HTMLTBODYSTOP !And wander off.
SUBROUTINE HTMLTROWTEXT(TEXT,N) !Roll a row of column headings.
CHARACTER*(*) TEXT(:) !The headings.
INTEGER N !Their number.
INTEGER I,L !Assistants.
CALL HTML3("<tr>","","") !Start a row of headings-to-come, and don't end the line.
DO I = 1,N !Step through the headings.
L = LSTNB(TEXT(I)) !Trailing spaces are to be ignored.
IF (L.LE.0) THEN !Thus discovering blank texts.
CALL HTML3("","<th> </th>","") !This prevents the cell being collapsed.
ELSE !But for those with text,
CALL HTML3("","<th>"//TEXT(I)(1:L)//"</th>","") !Roll it.
END IF !So much for that text.
END DO !On to the next.
CALL HTML3("","","</tr>") !Finish the row, and thus the line.
END SUBROUTINE HTMLTROWTEXT !So much for texts.
SUBROUTINE HTMLTROWINTEGER(V,N) !Now for all integers.
INTEGER V(:) !The integers.
INTEGER N !Their number.
INTEGER I !A stepper.
CALL HTML3('<tr align="right">',"","") !Start a row of entries.
DO I = 1,N !Work through the row's values.
CALL HTML3("","<td>"//I8FMT(V(I))//"</td>","") !One by one.
END DO !On to the next.
CALL HTML3("","","</tr>") !Finish the row, and thus the line.
END SUBROUTINE HTMLTROWINTEGER !All the same type is not troublesome.
END MODULE HTMLSTUFF !Enough already.
PROGRAM MAKETABLE
USE PARAMETERS
USE ASSISTANCE
USE HTMLSTUFF
INTEGER KBD,MSG
INTEGER NCOLS !The usage of V must conform to this!
PARAMETER (NCOLS = 4) !Specified number of columns.
CHARACTER*3 COLNAME(NCOLS) !And they have names.
PARAMETER (COLNAME = (/"","X","Y","Z"/)) !As specified.
INTEGER V(NCOLS) !A scratchpad for a line's worth.
COMMON KBD,MSG !I/O units.
KBD = 5 !Keyboard.
MSG = 6 !Screen.
CALL GETLOG(USERCODE) !Who has poked me into life?
LUSERCODE = LSTNB(USERCODE) !Ah, text gnashing.
CALL HTMLSTART(MSG,"Powers","Table of integer powers") !Output to the screen will do.
CALL HTMLTSTART(1,"Successive powers of successive integers") !Start the table.
CALL HTMLTHEADSTART !The table heading.
CALL HTMLTHEAD(NCOLS,"Successive powers") !A full-width heading.
CALL HTMLTROWTEXT(COLNAME,NCOLS) !Headings for each column.
CALL HTMLTHEADSTOP !So much for the heading.
CALL HTMLTBODYSTART !Now for the content.
DO I = 1,10 !This should be enough.
V(1) = I !The unheaded row number.
V(2) = I**2 !Its square.
V(3) = I**3 !Cube.
V(4) = I**4 !Fourth power.
CALL HTMLTROWINTEGER(V,NCOLS) !Show a row's worth..
END DO !On to the next line.
CALL HTMLTBODYSTOP !No more content.
CALL HTMLTSTOP !End the table.
CALL HTMLSTOP
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
| #Scala | Scala | val now=new Date()
println("%tF".format(now))
println("%1$tA, %1$tB %1$td, %1$tY".format(now)) |
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
| #Scheme | Scheme | (define short-date
(lambda (lt)
(strftime "%Y-%m-%d" (localtime lt))))
(define long-date
(lambda (lt)
(strftime "%A, %B %d, %Y" (localtime lt))))
(define main
(lambda (args)
;; Current date
(let ((dt (car (gettimeofday))))
;; Short style
(display (short-date dt))(newline)
;; Long style
(display (long-date dt))(newline))))
|
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #Tcl | Tcl |
package require math::linearalgebra
namespace path ::math::linearalgebra
# Setting matrix to variable A and size to n
set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}]
set n [llength $A]
# Setting right side of equation
set right {-3 -32 -47 49}
# Calculating determinant of A
set detA [det $A]
# Apply Cramer's rule
for {set i 0} {$i < $n} {incr i} {
set tmp $A ;# copy A to tmp
setcol tmp $i $right ;# replace column i with right side vector
set detTmp [det $tmp] ;# calculate determinant of tmp
set v [expr $detTmp / $detA] ;# divide two determinants
puts [format "%0.4f" $v] ;# format and display result
}
|
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.
| #JavaScript | JavaScript | const fs = require('fs');
function fct(err) {
if (err) console.log(err);
}
fs.writeFile("output.txt", "", fct);
fs.writeFile("/output.txt", "", fct);
fs.mkdir("docs", fct);
fs.mkdir("/docs", fct); |
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.
| #JCL | JCL |
// EXEC PGM=IEFBR14
//* CREATE EMPTY FILE NAMED "OUTPUT.TXT" (file names upper case only)
//ANYNAME DD UNIT=SYSDA,SPACE=(0,0),DSN=OUTPUT.TXT,DISP=(,CATLG)
//* CREATE DIRECTORY (PARTITIONED DATA SET) NAMED "DOCS"
//ANYNAME DD UNIT=SYSDA,SPACE=(TRK,(1,1)),DSN=DOCS,DISP=(,CATLG)
|
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).
| #jq | jq | jq -R . csv2html.csv | jq -r -s -f csv2html.jq
|
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.
| #PureBasic | PureBasic |
EnableExplicit
#Separator$ = ","
Define fInput$ = "input.csv"; insert path to input file
Define fOutput$ = "output.csv"; insert path to output file
Define header$, row$, field$
Define nbColumns, sum, i
If OpenConsole()
If Not ReadFile(0, fInput$)
PrintN("Error opening input file")
Goto Finish
EndIf
If Not CreateFile(1, fOutput$)
PrintN("Error creating output file")
CloseFile(0)
Goto Finish
EndIf
; Read header row
header$ = ReadString(0)
; Determine number of columns
nbColumns = CountString(header$, ",") + 1
; Change header row
header$ + #Separator$ + "SUM"
; Write to output file
WriteStringN(1, header$)
; Read remaining rows, process and write to output file
While Not Eof(0)
row$ = ReadString(0)
sum = 0
For i = 1 To nbColumns
field$ = StringField(row$, i, #Separator$)
sum + Val(field$)
Next
row$ + #Separator$ + sum
WriteStringN(1, row$)
Wend
CloseFile(0)
CloseFile(1)
Finish:
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
local
var integer: year is 0;
begin
for year range 2008 to 2122 do
if dayOfWeek(date(year, 12, 25)) = 7 then
writeln("Christmas comes on a sunday in " <& year);
end if;
end for;
end func; |
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.
| #SenseTalk | SenseTalk | // In what years between 2008 and 2121 will the 25th of December be a Sunday?
repeat with year = 2008 to 2121
set Christmas to "12/25/" & year
if the WeekDayName of Christmas is Sunday then
put "Christmas in " & year & " falls on a Sunday"
end if
end repeat |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]},
array[[1,1]]=RandomReal[];
array[[1,1]]
] |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | width = input('Array Width: ');
height = input('Array Height: ');
array = zeros(width,height);
array(1,1) = 12;
disp(['Array element (1,1) = ' num2str(array(1,1))]);
clear array; % de-allocate (remove) array from workspace
|
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
| #Nanoquery | Nanoquery | class StdDev
declare n
declare sum
declare sum2
def StdDev()
n = 0
sum = 0
sum2 = 0
end
def sd(x)
this.n += 1
this.sum += x
this.sum2 += x*x
return sqrt(sum2/n - sum*sum/n/n)
end
end
testData = {2,4,4,4,5,5,7,9}
sd = new(StdDev)
for x in testData
println sd.sd(x)
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
| #Ruby | Ruby | require 'zlib'
printf "0x%08x\n", Zlib.crc32('The quick brown fox jumps over the lazy dog')
# => 0x414fa339 |
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
| #Rust | Rust |
fn crc32_compute_table() -> [u32; 256] {
let mut crc32_table = [0; 256];
for n in 0..256 {
crc32_table[n as usize] = (0..8).fold(n as u32, |acc, _| {
match acc & 1 {
1 => 0xedb88320 ^ (acc >> 1),
_ => acc >> 1,
}
});
}
crc32_table
}
fn crc32(buf: &str) -> u32 {
let crc_table = crc32_compute_table();
!buf.bytes().fold(!0, |acc, octet| {
(acc >> 8) ^ crc_table[((acc & 0xff) ^ octet as u32) as usize]
})
}
fn main() {
println!("{:x}", crc32("The quick brown fox jumps over the lazy dog"));
}
|
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.
| #JavaScript | JavaScript | function countcoins(t, o) {
'use strict';
var targetsLength = t + 1;
var operandsLength = o.length;
t = [1];
for (var a = 0; a < operandsLength; a++) {
for (var b = 1; b < targetsLength; b++) {
// initialise undefined target
t[b] = t[b] ? t[b] : 0;
// accumulate target + operand ways
t[b] += (b < o[a]) ? 0 : t[b - o[a]];
}
}
return t[targetsLength - 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
| #Groovy | Groovy | println (('the three truths' =~ /th/).count)
println (('ababababab' =~ /abab/).count)
println (('abaabba*bbaba*bbab' =~ /a*b/).count)
println (('abaabba*bbaba*bbab' =~ /a\*b/).count) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | import Data.Text hiding (length)
-- Return the number of non-overlapping occurrences of sub in str.
countSubStrs str sub = length $ breakOnAll (pack sub) (pack str)
main = do
print $ countSubStrs "the three truths" "th"
print $ countSubStrs "ababababab" "abab"
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
for i := int8(0); ; i++ {
fmt.Printf("%o\n", i)
if i == math.MaxInt8 {
break
}
}
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Groovy | Groovy | println 'decimal octal'
for (def i = 0; i <= Integer.MAX_VALUE; i++) {
printf ('%7d %#5o\n', i, i)
} |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub getPrimeFactors(factors() As UInteger, n As UInteger)
If n < 2 Then Return
Dim factor As UInteger = 2
Do
If n Mod factor = 0 Then
Redim Preserve factors(0 To UBound(factors) + 1)
factors(UBound(factors)) = factor
n \= factor
If n = 1 Then Return
Else
factor += 1
End If
Loop
End Sub
Dim factors() As UInteger
For i As UInteger = 1 To 20
Print Using "##"; i;
Print " = ";
If i > 1 Then
Erase factors
getPrimeFactors factors(), i
For j As Integer = LBound(factors) To UBound(factors)
Print factors(j);
If j < UBound(factors) Then Print " x ";
Next j
Print
Else
Print i
End If
Next i
Print
Print "Press any key to quit"
Sleep |
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.
| #FreeBASIC | FreeBASIC | Dim As Integer ncols = 3, nrows = 4
Dim As Integer col, row
Print "<!DOCTYPE html>" & Chr(10) & "<html>"
Print "<head></head>" & Chr(10) & "<body>"
Print "<table border = 1 cellpadding = 10 cellspacing =0>"
For row = 0 To nrows
If row = 0 Then
Print "<tr><th></th>" ;
Else
Print "<tr><th>" & row & "</th>" ;
End If
For col = 1 To ncols
If row = 0 Then
Print "<th>" & Chr(87 + col) & "</th>" ;
Else
Print "<td align=""right"">" & Rnd(9999) & "</td>" ;
End If
Next col
Print "</tr>"
Next row
Print "</table>"
Print "</body>" & Chr(10) & "</html>"
Sleep |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
local
const array string: months is [] ("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");
const array string: days is [] ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
var time: now is time.value;
begin
now := time(NOW);
writeln(strDate(now));
writeln(days[dayOfWeek(now)] <& ", " <& months[now.month] <& " " <& now.day <& ", " <& now.year);
end func; |
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
| #SenseTalk | SenseTalk |
put formattedTime( "[year]-[month]-[day]", the date)
put formattedTime( "[weekday], [month name] [day], [year]", the date)
|
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #VBA | VBA |
Sub CramersRule()
OrigM = [{2, -1, 5, 1; 3,2,2,-6;1,3,3,-1;5,-2,-3,3}]
OrigD = [{-3;-32;-47;49}]
MatrixSize = UBound(OrigM)
DetOrigM = WorksheetFunction.MDeterm(OrigM)
For i = 1 To MatrixSize
ChangeM = OrigM
For j = 1 To MatrixSize
ChangeM(j, i) = OrigD(j, 1)
Next j
DetChangeM = WorksheetFunction.MDeterm(ChangeM)
Debug.Print i & ": " & DetChangeM / DetOrigM
Next i
End Sub
|
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Runtime.CompilerServices
Imports System.Linq.Enumerable
Module Module1
<Extension()>
Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String
Return String.Join(seperator, source)
End Function
Private Class SubMatrix
Private ReadOnly source As Integer(,)
Private ReadOnly prev As SubMatrix
Private ReadOnly replaceColumn As Integer()
Public Sub New(source As Integer(,), replaceColumn As Integer())
Me.source = source
Me.replaceColumn = replaceColumn
prev = Nothing
ColumnIndex = -1
Size = replaceColumn.Length
End Sub
Public Sub New(prev As SubMatrix, Optional deletedColumnIndex As Integer = -1)
source = Nothing
replaceColumn = Nothing
Me.prev = prev
ColumnIndex = deletedColumnIndex
Size = prev.Size - 1
End Sub
Public Property ColumnIndex As Integer
Public ReadOnly Property Size As Integer
Default Public ReadOnly Property Index(row As Integer, column As Integer) As Integer
Get
If Not IsNothing(source) Then
Return If(column = ColumnIndex, replaceColumn(row), source(row, column))
Else
Return prev(row + 1, If(column < ColumnIndex, column, column + 1))
End If
End Get
End Property
Public Function Det() As Integer
If Size = 1 Then Return Me(0, 0)
If Size = 2 Then Return Me(0, 0) * Me(1, 1) - Me(0, 1) * Me(1, 0)
Dim m As New SubMatrix(Me)
Dim detVal = 0
Dim sign = 1
For c = 0 To Size - 1
m.ColumnIndex = c
Dim d = m.Det()
detVal += Me(0, c) * d * sign
sign = -sign
Next
Return detVal
End Function
Public Sub Print()
For r = 0 To Size - 1
Dim rl = r
Console.WriteLine(Range(0, Size).Select(Function(c) Me(rl, c)).DelimitWith(", "))
Next
Console.WriteLine()
End Sub
End Class
Private Function Solve(matrix As SubMatrix) As Integer()
Dim det = matrix.Det()
If det = 0 Then Throw New ArgumentException("The determinant is zero.")
Dim answer(matrix.Size - 1) As Integer
For i = 0 To matrix.Size - 1
matrix.ColumnIndex = i
answer(i) = matrix.Det() / det
Next
Return answer
End Function
Public Function SolveCramer(equations As Integer()()) As Integer()
Dim size = equations.Length
If equations.Any(Function(eq) eq.Length <> size + 1) Then Throw New ArgumentException($"Each equation must have {size + 1} terms.")
Dim matrix(size - 1, size - 1) As Integer
Dim column(size - 1) As Integer
For r = 0 To size - 1
column(r) = equations(r)(size)
For c = 0 To size - 1
matrix(r, c) = equations(r)(c)
Next
Next
Return Solve(New SubMatrix(matrix, column))
End Function
Sub Main()
Dim equations = {
({2, -1, 5, 1, -3}),
({3, 2, 2, -6, -32}),
({1, 3, 3, -1, -47}),
({5, -2, -3, 3, 49})
}
Dim solution = SolveCramer(equations)
Console.WriteLine(solution.DelimitWith(", "))
End Sub
End Module |
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.
| #Julia | Julia | # many I/O functions have UNIX names
touch("output.txt")
mkdir("docs")
# probably don't have permission
try
touch("/output.txt")
mkdir("/docs")
catch e
warn(e)
end |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #K | K | "output.txt" 1: ""
"/output.txt" 1: ""
\ mkdir docs
\ mkdir /docs |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Jsish | Jsish | /* CSV to HTML, in Jsish */
var csv = "Character,Speech\n" +
"The multitude,The messiah! Show us the messiah!\n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" +
"The multitude,Who are you?\n" +
"Brians mother,I'm his mother; that's who!\n" +
"The multitude,Behold his mother! Behold his mother!";
var lines = csv.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.split('\n')
.map(function(line) { return line.split(','); })
.map(function(row) { return '\t\t<tr><td>' + row[0] + '</td><td>' + row[1] + '</td></tr>'; });
if (Interp.conf('unitTest')) {
puts('<table>\n\t<thead>\n' + lines[0] + '\n\t</thead>\n\t<tbody>\n'
+ lines.slice(1).join('\n') + '\t</tbody>\n</table>');
}
/*
=!EXPECTSTART!=
<table>
<thead>
<tr><td>Character</td><td>Speech</td></tr>
</thead>
<tbody>
<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>
<tr><td>Brians mother</td><td><angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry></td></tr>
<tr><td>The multitude</td><td>Who are you?</td></tr>
<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>
<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr> </tbody>
</table>
=!EXPECTEND!=
*/ |
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.
| #Python | Python | import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, 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.
| #Sidef | Sidef | require('Time::Local')
for year in (2008 .. 2121) {
var time = %S<Time::Local>.timelocal(0,0,0,25,11,year)
var wd = Time(time).local.wday
if (wd == 0) {
say "25 Dec #{year} is Sunday"
}
} |
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.
| #Simula | Simula | BEGIN
INTEGER M,D,Y;
M := 12;
D := 25;
FOR Y := 2008 STEP 1 UNTIL 2121 DO BEGIN
INTEGER W,A,MM,YY;
A := (14 - M)//12;
MM := M + 12*A - 2;
YY := Y - A;
W := D + ((13*MM - 1)//5) + YY + (YY//4) - (YY//100) + (YY//400);
W := MOD(W,7);
IF W = 0 THEN
BEGIN OUTINT(Y,0);
OUTIMAGE;
END;
END;
END. |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Maxima | Maxima | printf(true, "in the following terminate every number with semicolon `;'")$
n: readonly("Input x-size: ")$
m: readonly("Input y-size: ")$
a: make_array(fixnum, n, m)$
fillarray(a, makelist(i, i, 1, m*n))$
/* indexing starts from 0 */
print(a[0,0]);
print(a[n-1,m-1]); |
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.
| #MAXScript | MAXScript | a = getKBValue prompt:"Enter first dimension:"
b = getKBValue prompt:"Enter second dimension:"
arr1 = #()
arr2 = #()
arr2[b] = undefined
for i in 1 to a do
(
append arr1 (deepCopy arr2)
)
arr1[a][b] = 1
print arr1[a][b] |
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
| #Nim | Nim | import math, strutils
var sdSum, sdSum2, sdN = 0.0
proc sd(x: float): float =
sdN += 1
sdSum += x
sdSum2 += x * x
sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))
for value in [float 2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value), precision = -1) |
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
| #Scala | Scala | import java.util.zip.CRC32
val crc=new CRC32
crc.update("The quick brown fox jumps over the lazy dog".getBytes)
println(crc.getValue.toHexString) //> 414fa339 |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "crc32.s7i";
const proc: main is func
begin
writeln(ord(crc32("The quick brown fox jumps over the lazy dog")) radix 16 lpad0 8);
end func; |
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.
| #jq | jq | # How many ways are there to make "target" cents, given a list of coin
# denominations as input.
# The strategy is to record at total[n] the number of ways to make n cents.
def countcoins(target):
. as $coin
| reduce range(0; length) as $a
( [1]; # there is 1 way to make 0 cents
reduce range(1; target + 1) as $b
(.; # total[]
if $b < $coin[$a] then .
else .[$b - $coin[$a]] as $count
| if $count == 0 then .
else .[$b] += $count
end
end ) )
| .[target] ; |
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.
| #Julia | Julia | function changes(amount::Int, coins::Array{Int})::Int128
ways = zeros(Int128, amount + 1)
ways[1] = 1
for coin in coins, j in coin+1:amount+1
ways[j] += ways[j - coin]
end
return ways[amount + 1]
end
@show changes(100, [1, 5, 10, 25])
@show 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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do
write("The string ",image(A[2])," occurs as a non-overlapping substring ",
countSubstring!A , " times in ",image(A[1]))
end
procedure countSubstring(s1,s2) #: return count of non-overlapping substrings
c := 0
s1 ? while tab(find(s2)) do {
move(*s2)
c +:= 1
}
return c
end |
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
| #J | J | require'strings'
countss=: #@] %~ #@[ - [ #@rplc '';~] |
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.
| #Haskell | Haskell | import Numeric (showOct)
main :: IO ()
main =
mapM_
(putStrLn . flip showOct "")
[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.
| #Icon_and_Unicon | Icon and Unicon | link convert # To get exbase10 method
procedure main()
limit := 8r37777777777
every write(exbase10(seq(0)\limit, 8))
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
| #Frink | Frink | i = 1
while true
{
println[join[" x ", factorFlat[i]]]
i = i + 1
} |
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
} |
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.
| #Go | Go | package main
import (
"fmt"
"html/template"
"os"
)
type row struct {
X, Y, Z int
}
var tmpl = `<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
{{range $ix, $row := .}} <tr><td>{{$ix}}</td>
<td>{{$row.X}}</td>
<td>{{$row.Y}}</td>
<td>{{$row.Z}}</td></tr>
{{end}}</table>
`
func main() {
// create template
ct := template.Must(template.New("").Parse(tmpl))
// make up data
data := make([]row, 4)
for r := range data {
data[r] = row{r*3, r*3+1, r*3+2}
}
// apply template to data
if err := ct.Execute(os.Stdout, data); err != nil {
fmt.Println(err)
}
} |
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
| #Shiny | Shiny | say time.format 'Y-m-d' time.now
say time.format 'l, F j, Y' time.now |
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
| #Sidef | Sidef | var time = Time.local;
say time.ctime;
say time.strftime("%Y-%m-%d");
say time.strftime("%A, %B %d, %Y"); |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #Wren | Wren | import "/matrix" for Matrix
var cramer = Fn.new { |a, d|
var n = a.numRows
var x = List.filled(n, 0)
var ad = a.det
for (c in 0...n) {
var aa = a.copy()
for (r in 0...n) aa[r, c] = d[r, 0]
x[c] = aa.det/ad
}
return x
}
var a = Matrix.new([
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3]
])
var d = Matrix.new([
[- 3],
[-32],
[-47],
[ 49]
])
var x = cramer.call(a, d)
System.print("Solution is %(x)") |
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.
| #Kotlin | Kotlin | /* testing on Windows 10 which needs administrative privileges
to create files in the root */
import java.io.File
fun main(args: Array<String>) {
val filePaths = arrayOf("output.txt", "c:\\output.txt")
val dirPaths = arrayOf("docs", "c:\\docs")
var f: File
for (path in filePaths) {
f = File(path)
if (f.createNewFile())
println("$path successfully created")
else
println("$path already exists")
}
for (path in dirPaths) {
f = File(path)
if (f.mkdir())
println("$path successfully created")
else
println("$path already exists")
}
} |
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.
| #LabVIEW | LabVIEW | // create file
local(f) = file
handle => { #f->close }
#f->openWriteOnly('output.txt')
// make directory, just like a file
local(d = dir('docs'))
#d->create
// create file in root file system (requires permissions at user OS level)
local(f) = file
handle => { #f->close }
#f->openWriteOnly('//output.txt')
// create directory in root file system (requires permissions at user OS level)
local(d = dir('//docs'))
#d->create |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Julia | Julia | using DataFrames, CSV
using CSV, DataFrames
function csv2html(fname; header::Bool=false)
csv = CSV.read(fname)
@assert(size(csv, 2) > 0)
str = """
<html>
<head>
<style type="text/css">
body {
margin: 2em;
}
h1 {
text-align: center;
}
table {
border-spacing: 0;
box-shadow: 0 0 0.25em #888;
margin: auto;
}
table,
tr,
th,
td {
border-collapse: collapse;
}
th {
color: white;
background-color: rgb(43, 53, 59);
}
th,
td {
padding: 0.5em;
}
table tr:nth-child(even) td {
background-color: rgba(218, 224, 229, 0.850);
}
</style>
</head>
<body>
<h1>csv2html Example</h1>
<table>
<tr>
"""
tags = header ? ("<th>", "</th>") : ("<td>", "</td>")
for i=1:size(csv, 2)
str *= " " * tags[1] * csv[1, i] * tags[2] * "\n"
end
str *= " "^8 * "</tr>\n"
for i=2:size(csv, 1)
str *= " <tr>\n"
for j=1:size(csv, 2)
str *= " " * "<td>" * csv[i, j] * "</td>\n"
end
str *= " </tr>\n"
end
str * " </table>\n</body>\n\n</html>\n"
end
print(csv2html("input.csv", header=true))
|
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.
| #Q | Q | t:("IIIII";enlist ",")0: `:input.csv / Read CSV file input.csv into table t
t:update SUM:sum value flip t from t / Add SUM column to t
`:output.csv 0: csv 0: t / Write updated table as CSV to output.csv |
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.
| #R | R |
df <- read.csv(textConnection(
"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"))
df$sum <- rowSums(df)
write.csv(df,row.names = FALSE)
|
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.
| #Smalltalk | Smalltalk | 2008 to: 2121 do: [ :year | |date|
date := Date newDay: 25 monthIndex: 12 year: year.
date dayName = #Sunday
ifTrue: [ date displayNl ]
] |
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.
| #SQL | SQL | SELECT EXTRACT(YEAR FROM dt) AS year_with_xmas_on_sunday
FROM (
SELECT add_months(DATE '2008-12-25', 12 * (level - 1)) AS dt
FROM dual
CONNECT BY level <= 2121 - 2008 + 1
)
WHERE to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'
ORDER BY 1
; |
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.
| #MUMPS | MUMPS |
ARA2D
NEW X,Y,A,I,J
REARA
WRITE !,"Please enter two positive integers"
READ:10 !,"First: ",X
READ:10 !,"Second: ",Y
GOTO:(X\1'=X)!(X<0)!(Y\1'=Y)!(Y<0) REARA
FOR I=1:1:X FOR J=1:1:Y SET A(I,J)=I+J
WRITE !,"The corner of X and Y is ",A(X,Y)
KILL X,Y,A,I,J
QUIT
|
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
say "give me the X and Y dimensions as two positive integers:"
parse ask xDim yDim
xPos = xDim % 2 -- integer divide to get close to the middle of the array
yPos = yDim % 2
arry = Rexx[xDim, yDim]
arry[xPos, yPos] = xDim / yDim -- make up a value...
say "arry["xPos","yPos"]:" arry[xPos, yPos]
return
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Objeck | Objeck |
use Structure;
bundle Default {
class StdDev {
nums : FloatVector;
New() {
nums := FloatVector->New();
}
function : Main(args : String[]) ~ Nil {
sd := StdDev->New();
test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
each(i : test_data) {
sd->AddNum(test_data[i]);
sd->GetSD()->PrintLine();
};
}
method : public : AddNum(num : Float) ~ Nil {
nums->AddBack(num);
}
method : public : native : GetSD() ~ Float {
sq_diffs := 0.0;
avg := nums->Average();
each(i : nums) {
num := nums->Get(i);
sq_diffs += (num - avg) * (num - avg);
};
return (sq_diffs / nums->Size())->SquareRoot();
}
}
}
|
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
| #Shell | Shell | #!/usr/bin/env bash
declare -i -a CRC32_LOOKUP_TABLE
__generate_crc_lookup_table() {
local -i -r LSB_CRC32_POLY=0xEDB88320 # The CRC32 polynomal LSB order
local -i index byte lsb
for index in {0..255}; do
((byte = 255 - index))
for _ in {0..7}; do # 8-bit lsb shift
((lsb = byte & 0x01, byte = ((byte >> 1) & 0x7FFFFFFF) ^ (lsb == 0 ? LSB_CRC32_POLY : 0)))
done
((CRC32_LOOKUP_TABLE[index] = byte))
done
}
__generate_crc_lookup_table
typeset -r CRC32_LOOKUP_TABLE
crc32_string() {
[[ ${#} -eq 1 ]] || return
local -i i byte crc=0xFFFFFFFF index
for ((i = 0; i < ${#1}; i++)); do
byte=$(printf '%d' "'${1:i:1}") # Get byte value of character at i
((index = (crc ^ byte) & 0xFF, crc = (CRC32_LOOKUP_TABLE[index] ^ (crc >> 8)) & 0xFFFFFFFF))
done
echo $((crc ^ 0xFFFFFFFF))
}
printf 'The CRC32 of: %s\nis: 0x%08x\n' "${1}" "$(crc32_string "${1}")"
# crc32_string "The quick brown fox jumps over the lazy dog"
# yields 414fa339
|
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.
| #Kotlin | Kotlin | // version 1.0.6
fun countCoins(c: IntArray, m: Int, n: Int): Long {
val table = LongArray(n + 1)
table[0] = 1
for (i in 0 until m)
for (j in c[i]..n) table[j] += table[j - c[i]]
return table[n]
}
fun main(args: Array<String>) {
val c = intArrayOf(1, 5, 10, 25, 50, 100)
println(countCoins(c, 4, 100))
println(countCoins(c, 6, 1000 * 100))
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("abab", "ababababab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
} |
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
| #JavaScript | JavaScript | function countSubstring(str, subStr) {
var matches = str.match(new RegExp(subStr, "g"));
return matches ? matches.length : 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.
| #J | J | disp=.([echo) ' '(-.~":)8&#.inv
(1+disp)^:_]0x |
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.
| #Java | Java | public class Count{
public static void main(String[] args){
for(int i = 0;i >= 0;i++){
System.out.println(Integer.toOctalString(i)); //optionally use "Integer.toString(i, 8)"
}
}
} |
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
| #Go | Go | package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
} |
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.
| #Groovy | Groovy | import groovy.xml.MarkupBuilder
def createTable(columns, rowCount) {
def writer = new StringWriter()
new MarkupBuilder(writer).table(style: 'border:1px solid;text-align:center;') {
tr {
th()
columns.each { title -> th(title)}
}
(1..rowCount).each { row ->
tr {
td(row)
columns.each { td((Math.random() * 9999) as int ) }
}
}
}
writer.toString()
}
println createTable(['X', 'Y', 'Z'], 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
| #Smalltalk | Smalltalk | | d |
d := Date today.
d printFormat: #(3 2 1 $- 1 1 2).
(d weekday asString), ', ', (d monthName), ' ', (d dayOfMonth asString), ', ', (d year asString) |
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
| #SQL | SQL |
SELECT to_char(sysdate,'YYYY-MM-DD') date_fmt_1 FROM dual;
SELECT to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 FROM dual;
|
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #XPL0 | XPL0 |
func Det(A, N); \Return value of determinate A, order N
int A, N;
int B, Sum, I, K, L, Term;
[if N = 1 then return A(0, 0);
B:= Reserve((N-1)*4\IntSize\);
Sum:= 0;
for I:= 0 to N-1 do
[L:= 0;
for K:= 0 to N-1 do
if K # I then
[B(L):= @A(K, 1); L:= L+1];
Term:= A(I, 0) * Det(B, N-1);
if I & 1 then Term:= -Term;
Sum:= Sum + Term;
];
return Sum;
];
real D;
[D:= float(Det([[2,-1,5,1], [3,2,2,-6], [1,3,3,-1], [5,-2,-3,3]], 4));
RlOut(0, float(Det([[-3,-1,5,1], [-32,2,2,-6], [-47,3,3,-1], [49,-2,-3,3]], 4)) / D);
RlOut(0, float(Det([[2,-3,5,1], [3,-32,2,-6], [1,-47,3,-1], [5,49,-3,3]], 4)) / D);
RlOut(0, float(Det([[2,-1,-3,1], [3,2,-32,-6], [1,3,-47,-1], [5,-2,49,3]], 4)) / D);
RlOut(0, float(Det([[2,-1,5,-3], [3,2,2,-32], [1,3,3,-47], [5,-2,-3,49]], 4)) / D);
] |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
A:=GSL.Matrix(4,4).set(2,-1, 5, 1,
3, 2, 2,-6,
1, 3, 3,-1,
5,-2,-3, 3);
b:=GSL.Vector(4).set(-3,-32,-47,49); |
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.
| #Lasso | Lasso | // create file
local(f) = file
handle => { #f->close }
#f->openWriteOnly('output.txt')
// make directory, just like a file
local(d = dir('docs'))
#d->create
// create file in root file system (requires permissions at user OS level)
local(f) = file
handle => { #f->close }
#f->openWriteOnly('//output.txt')
// create directory in root file system (requires permissions at user OS level)
local(d = dir('//docs'))
#d->create |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.