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/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.
| #PL.2FI | PL/I |
declare i picture '9999';
do i = 2008 to 2121;
if weekday(days('25Dec' || i, 'DDMmmYYYY')) = 1 then
put skip list ('Christmas day ' || i || ' is a Sunday');
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]]
a = new array[dims, 0] // Create and initialize to 0
a@(rows-1)@(cols-1) = 10
println[a@(rows-1)@(cols-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.
| #Frink | Frink |
[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]]
a = new array[dims, 0] // Create and initialize to 0
a@(rows-1)@(cols-1) = 10
println[a@(rows-1)@(cols-1)]
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #JavaScript | JavaScript | function running_stddev() {
var n = 0;
var sum = 0.0;
var sum_sq = 0.0;
return function(num) {
n++;
sum += num;
sum_sq += num*num;
return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) );
}
}
var sd = running_stddev();
var nums = [2,4,4,4,5,5,7,9];
var stddev = [];
for (var i in nums)
stddev.push( sd(nums[i]) );
// using WSH
WScript.Echo(stddev.join(', '); |
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
| #Objeck | Objeck | class CRC32 {
function : Main(args : String[]) ~ Nil {
"The quick brown fox jumps over the lazy dog"->ToByteArray()->CRC32()->PrintLine();
}
}
|
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
| #OCaml | OCaml | let () =
let s = "The quick brown fox jumps over the lazy dog" in
let crc = Zlib.update_crc 0l s 0 (String.length s) in
Printf.printf "crc: %lX\n" crc |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #EDSAC_order_code | EDSAC order code |
["Count the coins" problem for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
T51K P56F [G parameter: print subroutine]
T54K P94F [C parameter: coins subroutine]
T47K P200F [M parameter: main routine]
[========================== M parameter ===============================]
E25K TM GK
[Parameter block for US coins. For convenience, all numbers
are in the address field, e.g. 25 cents is P25F not P12D.]
[0] UF SF [2-letter ID]
P100F [amount to be made with coins]
P4F [number of coin values]
P1F P5F P10F P25F [list of coin values]
[8] P@ [address of US parameter block]
[Parameter block for UK coins]
[9] UF KF
P100F
P7F
P1F P2F P5F P10F P20F P50F P100F
[20] P9@ [address of UK parameter block]
[Enter with acc = 0]
[21] A8@ [load address of parameter block for US coins]
T4F [pass to subroutine in 4F]
[23] A23@ [call subroutine to calculate and print result]
G13C
A20@ [same for UK coins]
T4F
[27] A27@
G13C
ZF [halt program]
[========================== C parameter ===============================]
[Subroutine to calculate and print the result for the given amount and
set of coins. Address of parameter block (see above) is passed in 4F.]
E25K TC GK
[0] SF [S order for start of coin list]
[1] A1023F [start table at top of memory and work downwarda]
[2] PF [S order for exclusive end of coin list]
[3] P2F [to increment address by 2]
[4] OF [(1) add to address to make O order
(2) add to A order to make T order with same address]
[5] SF [add to address to make S order]
[6] K4095F [add to S order to make A order, dec address]
[7] K2048F [set teleprinter to letters]
[8] #F [set teleprinter to figures]
[9] !F [space character]
[10] @F [carriage return]
[11] &F [line feed]
[12] K4096F [teleprinter null]
[Subroutine entry. In this EDSAC program, the table used
in the algorithm grows downward from the top of memory.]
[13] A3F [plant jump back to caller, as usual]
T89@
A4F [load address of parameter block]
A3@ [skip 2-letter ID]
A5@ [make S order for amount]
U27@ [plant in code]
A3@ [make S order for first coin value]
U@ [store it]
A6@ [make A order for number of coins]
T38@ [plant in code]
A2F [load 1 (in address field)]
[24] T1023F [store at start of table]
[Set all other table entries to 0]
A24@
T32@
[27] SF [acc := -amount]
[28] TF [set negative count in 0F]
A32@ [decrement address in manufactured order]
S2F
T32@
[32] TF [manufactured: set table entry to 0]
AF [update negative count]
A2F
G28@ [loop until count = 0]
[Here acc = 0. Manufactured order (4 lines up) is T order
for inclusive end of table; this is used again below.]
A@ [load S order for first coin value]
U43@ [plant in code]
[38] AF [make S order for exclusive end of coin list]
T2@ [store for comparison]
[Start of outer loop, round coin values]
[40] TF [clear acc]
A1@ [load A order for start of table]
U48@ [plant in code]
[43] SF [manufactured order: subtract coin value]
[Start of inner loop, round table entries]
[44] U47@ [plant A order in code]
A4@ [make T order for same address]
T49@ [plant in code]
[The next 3 orders are manufactured at run time]
[47] AF [load table entry]
[48] AF [add earlier table entry]
[49] TF [update table entry]
A32@ [load T order for inclusive end of table]
S49@ [reached end of table?]
E60@ [if yes, jump out of inner loop]
TF [clear acc]
A48@ [update the 3 manufactured instructions]
S2F
T48@
A47@
S2F
G44@ [always loops back, since A < 0]
[End of inner loop]
[60] TF [clear acc]
A43@ [update S order for coin value]
A2F
U43@
S2@ [reached exclusive end?]
G40@ [if no, loop back]
[End of outer loop]
[Here with acc = 0 and result at end of table]
[Value is in address field, so shift 1 right for printing]
A32@ [load T order for end of tab;e]
S4@ [make A order for same address]
T79@ [plant in code]
A4F [load address of parameter block]
A4@ [make O order for 1st char of ID]
U75@ [plant in code]
A2F [same for 2nd char]
T76@
O7@ [set teleprinter to letters]
[75] OF [print ID, followed by space]
[76] OF O9@
O8@ [set teleprinter to figures]
[79] AF [maunfactured order to load result]
RD [shift 1 right for printing]
TF [pass to print routine]
A9@ [replace leading 0's with space]
T1F
[84] A84@ [call print routine]
GG
O10@ O11@ [print CR, LF]
O12@ [print null to flush teleprinter buffer]
[89] ZF [replaced by jump back to caller]
[============================= G parameter ===============================]
E25K TG GK
[Subroutine to print non-negative 17-bit integer. Always prints 5 chars.
Caller specifies character for leading 0 (typically 0, space or null).
Parameters: 0F = integer to be printed (not preserved)
1F = character for leading zero (preserved)
Workspace: 4F..7F, 38 locations]
A3FT34@A1FT7FS35@T6FT4#FAFT4FH36@V4FRDA4#FR1024FH37@E23@O7FA2F
T6FT5FV4#FYFL8FT4#FA5FL1024FUFA6FG16@OFTFT7FA6FG17@ZFP4FZ219DTF
[========================== M parameter again ===============================]
E25K TM GK
E21Z [define entry point]
PF [enter with acc = 0]
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #CoffeeScript | CoffeeScript |
countSubstring = (str, substr) ->
n = 0
i = 0
while (pos = str.indexOf(substr, i)) != -1
n += 1
i = pos + substr.length
n
console.log countSubstring "the three truths", "th"
console.log countSubstring "ababababab", "abab"
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Common_Lisp | Common Lisp | (defun count-sub (str pat)
(loop with z = 0 with s = 0 while s do
(when (setf s (search pat str :start2 s))
(incf z) (incf s (length pat)))
finally (return z)))
(count-sub "ababa" "ab") ; 2
(count-sub "ababa" "aba") ; 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.
| #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. count-in-octal.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION dec-to-oct
.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 i PIC 9(18).
PROCEDURE DIVISION.
PERFORM VARYING i FROM 1 BY 1 UNTIL i = 0
DISPLAY FUNCTION dec-to-oct(i)
END-PERFORM
.
END PROGRAM count-in-octal.
IDENTIFICATION DIVISION.
FUNCTION-ID. dec-to-oct.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 rem PIC 9.
01 dec PIC 9(18).
LINKAGE SECTION.
01 dec-arg PIC 9(18).
01 oct PIC 9(18).
PROCEDURE DIVISION USING dec-arg RETURNING oct.
MOVE dec-arg TO dec *> Copy is made to avoid modifying reference arg.
PERFORM WITH TEST AFTER UNTIL dec = 0
MOVE FUNCTION REM(dec, 8) TO rem
STRING rem, oct DELIMITED BY SPACES INTO oct
DIVIDE 8 INTO dec
END-PERFORM
.
END FUNCTION dec-to-oct. |
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
| #CoffeeScript | CoffeeScript | count_primes = (max) ->
# Count through the natural numbers and give their prime
# factorization. This algorithm uses no division.
# Instead, each prime number starts a rolling odometer
# to help subsequent factorizations. The algorithm works similar
# to the Sieve of Eratosthenes, as we note when each prime number's
# odometer rolls a digit. (As it turns out, as long as your computer
# is not horribly slow at division, you're better off just doing simple
# prime factorizations on each new n vs. using this algorithm.)
console.log "1 = 1"
primes = []
n = 2
while n <= max
factors = []
for prime_odometer in primes
# digits are an array w/least significant digit in
# position 0; for example, [3, [0]] will roll as
# follows:
# [0] -> [1] -> [2] -> [0, 1]
[base, digits] = prime_odometer
i = 0
while true
digits[i] += 1
break if digits[i] < base
digits[i] = 0
factors.push base
i += 1
if i >= digits.length
digits.push 0
if factors.length == 0
primes.push [n, [0, 1]]
factors.push n
console.log "#{n} = #{factors.join('*')}"
n += 1
primes.length
num_primes = count_primes 10000
console.log num_primes |
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.
| #Common_Lisp | Common Lisp |
(ql:quickload :closure-html)
(use-package :closure-html)
(serialize-lhtml
`(table nil
(tr nil ,@(mapcar (lambda (x)
(list 'th nil x))
'("" "X" "Y" "Z")))
,@(loop for i from 1 to 4
collect `(tr nil
(th nil ,(format nil "~a" i))
,@(loop repeat 3 collect `(td nil ,(format nil "~a" (random 10000)))))))
(make-string-sink))
|
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
| #PHP | PHP | <?php
echo date('Y-m-d', time())."\n";
echo date('l, F j, Y', time())."\n";
?> |
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
| #PicoLisp | PicoLisp | (let (Date (date) Lst (date Date))
(prinl (dat$ Date "-")) # 2010-02-19
(prinl # Friday, February 19, 2010
(day Date)
", "
(get *MonFmt (cadr Lst))
" "
(caddr Lst)
", "
(car Lst) ) ) |
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.
| #Maple | Maple | with(LinearAlgebra):
cramer:=proc(A,B)
local n,d,X,V,i;
n:=upperbound(A,2);
d:=Determinant(A);
X:=Vector(n,0);
for i from 1 to n do
V:=A(1..-1,i);
A(1..-1,i):=B;
X[i]:=Determinant(A)/d;
A(1..-1,i):=V;
od;
X;
end:
A:=Matrix([[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]):
B:=Vector([-3,-32,-47,49]):
printf("%a",cramer(A,B)); |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | crule[m_, b_] := Module[{d = Det[m], a},
Table[a = m; a[[All, k]] = b; Det[a]/d, {k, Length[m]}]]
crule[{
{2, -1, 5, 1},
{3, 2, 2, -6},
{1, 3, 3, -1},
{5, -2, -3, 3}
} , {-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.
| #ERRE | ERRE |
PROGRAM FILE_TEST
!$INCLUDE="PC.LIB"
BEGIN
OPEN("O",#1,"output.txt")
CLOSE(1)
OS_MKDIR("C:\RC") ! with the appropriate access rights .......
OPEN("O",#1,"C:\RC\output.txt")
CLOSE(1)
END PROGRAM
|
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.
| #Euphoria | Euphoria | integer fn
-- In the current working directory
system("mkdir docs",2)
fn = open("output.txt","w")
close(fn)
-- In the filesystem root
system("mkdir \\docs",2)
fn = open("\\output.txt","w")
close(fn) |
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).
| #Forth | Forth | : BEGIN-COLUMN ." <td>" ;
: END-COLUMN ." </td>" ;
: BEGIN-ROW ." <tr>" BEGIN-COLUMN ;
: END-ROW END-COLUMN ." </tr>" CR ;
: CSV2HTML
." <table>" CR BEGIN-ROW
BEGIN KEY DUP #EOF <> WHILE
CASE
10 OF END-ROW BEGIN-ROW ENDOF
[CHAR] , OF END-COLUMN BEGIN-COLUMN ENDOF
[CHAR] < OF ." <" ENDOF
[CHAR] > OF ." >" ENDOF
[CHAR] & OF ." &" ENDOF
DUP EMIT
ENDCASE
REPEAT
END-ROW ." </table>" CR
;
CSV2HTML BYE |
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.
| #Nim | Nim | import strutils, streams
let
csv = newFileStream("data.csv", fmRead)
outf = newFileStream("data-out.csv", fmWrite)
var lineNumber = 1
while true:
if atEnd(csv):
break
var line = readLine(csv)
if lineNumber == 1:
line.add(",SUM")
else:
var sum = 0
for n in split(line, ","):
sum += parseInt(n)
line.add(",")
line.add($sum)
outf.writeLine(line)
inc lineNumber |
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.
| #Objeck | Objeck | use System.IO.File;
use Data.CSV;
class CsvData {
function : Main(args : String[]) ~ Nil {
file_out : FileWriter;
leaving {
if(file_out <> Nil) {
file_out->Close();
};
};
if(args->Size() > 0) {
file_name := args[0];
csv := CsvTable->New(FileReader->ReadFile(file_name));
if(csv->IsParsed()) {
csv->AppendColumn("SUM");
for(i := 1; i < csv->Size(); i += 1;) {
row := csv->Get(i);
sum := row->Sum(row->Size() - 1);
row->Set("SUM", sum->ToString());
};
};
output := csv->ToString();
output->PrintLine();
file_out := FileWriter->New("new-csv.csv");
file_out->WriteString(output);
};
}
}
|
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.
| #PowerShell | PowerShell | 2008..2121 | Where-Object { (Get-Date $_-12-25).DayOfWeek -eq "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.
| #Prolog | Prolog | main() :-
christmas_days_falling_on_sunday(2011, 2121, SundayList),
writeln(SundayList).
christmas_days_falling_on_sunday(StartYear, EndYear, SundayList) :-
numlist(StartYear, EndYear, YearRangeList),
include(is_christmas_day_a_sunday, YearRangeList, SundayList).
is_christmas_day_a_sunday(Year) :-
Date = date(Year, 12, 25),
day_of_the_week(Date, DayOfTheWeek),
DayOfTheWeek == 7.
|
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.
| #GAP | GAP | # Creating an array of 0
a := NullMat(2, 2);
# [ [ 0, 0 ], [ 0, 0 ] ]
# Some assignments
a[1][1] := 4;
a[1][2] := 5;
a[2][1] := 3;
a[2][2] := 4;
a
# [ [ 4, 5 ], [ 3, 4 ] ]
Determinant(a);
# 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.
| #Go | Go | package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
// allocate composed 2d array
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
// array elements initialized to 0
fmt.Println("a[0][0] =", a[0][0])
// assign
a[row-1][col-1] = 7
// retrieve
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
// remove only reference
a = nil
// memory allocated earlier with make can now be garbage collected.
} |
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
| #jq | jq | { "n": _, "ssd": _, "mean": _ }
|
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
| #Ol | Ol |
(define (crc32 str)
(bxor #xFFFFFFFF
(fold (lambda (crc char)
(let loop ((n 8) (crc crc) (bits char))
(if (eq? n 0)
crc
(let*((flag (band (bxor bits crc) 1))
(crc (>> crc 1))
(crc (if (eq? flag 0) crc (bxor crc #xEDB88320)))
(bits (>> bits 1)))
(loop (- n 1) crc bits)))))
#xFFFFFFFF
(string->list str))))
(print (number->string (crc32 "The quick brown fox jumps over the lazy dog") 16))
(print (number->string (crc32 (list->string (repeat #x00 32))) 16))
(print (number->string (crc32 (list->string (repeat #xFF 32))) 16))
(print (number->string (crc32 (list->string (iota 32))) 16))
|
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.
| #Elixir | Elixir | defmodule Coins do
def find(coins,lim) do
vals = Map.new(0..lim,&{&1,0}) |> Map.put(0,1)
count(coins,lim,vals)
|> Map.values
|> Enum.max
|> IO.inspect
end
defp count([],_,vals), do: vals
defp count([coin|coins],lim,vals) do
count(coins,lim,ways(coin,coin,lim,vals))
end
defp ways(num,_coin,lim,vals) when num > lim, do: vals
defp ways(num, coin,lim,vals) do
ways(num+1,coin,lim,ad(coin,num,vals))
end
defp ad(a,b,c), do: Map.put(c,b,c[b]+c[b-a])
end
Coins.find([1,5,10,25],100)
Coins.find([1,5,10,25,50,100],100_000) |
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.
| #Erlang | Erlang |
-module(coins).
-compile(export_all).
count(Amount, Coins) ->
{N,_C} = count(Amount, Coins, dict:new()),
N.
count(0,_,Cache) ->
{1,Cache};
count(N,_,Cache) when N < 0 ->
{0,Cache};
count(_N,[],Cache) ->
{0,Cache};
count(N,[C|Cs]=Coins,Cache) ->
case dict:is_key({N,length(Coins)},Cache) of
true ->
{dict:fetch({N,length(Coins)},Cache), Cache};
false ->
{N1,C1} = count(N-C,Coins,Cache),
{N2,C2} = count(N,Cs,C1),
{N1+N2,dict:store({N,length(Coins)},N1+N2,C2)}
end.
print(Amount, Coins) ->
io:format("~b ways to make change for ~b cents with ~p coins~n",[count(Amount,Coins),Amount,Coins]).
test() ->
A1 = 100, C1 = [25,10,5,1],
print(A1,C1),
A2 = 100000, C2 = [100, 50, 25, 10, 5, 1],
print(A2,C2).
|
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
| #Cowgol | Cowgol | include "cowgol.coh";
sub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is
count := 0;
while [str] != 0 loop
var find := match;
var loc := str;
while [loc] == [find] loop
find := @next find;
loc := @next loc;
end loop;
if [find] == 0 then
str := loc;
count := count + 1;
else
str := @next str;
end if;
end loop;
end sub;
print_i8(countSubstring("the three truths","th")); # should print 3
print_nl();
print_i8(countSubstring("ababababab","abab")); # should print 2
print_nl();
print_i8(countSubstring("cat","dog")); # should print 0
print_nl(); |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D | D | void main() {
import std.stdio, std.algorithm;
"the three truths".count("th").writeln;
"ababababab".count("abab").writeln;
} |
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.
| #CoffeeScript | CoffeeScript |
n = 0
while true
console.log n.toString(8)
n += 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.
| #Common_Lisp | Common Lisp | (loop for i from 0 do (format t "~o~%" 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
| #Common_Lisp | Common Lisp | (defparameter *primes*
(make-array 10 :adjustable t :fill-pointer 0 :element-type 'integer))
(mapc #'(lambda (x) (vector-push x *primes*)) '(2 3 5 7))
(defun extend-primes (n)
(let ((p (+ 2 (elt *primes* (1- (length *primes*))))))
(loop for i = p then (+ 2 i)
while (<= (* i i) n) do
(if (primep i t) (vector-push-extend i *primes*)))))
(defun primep (n &optional skip)
(if (not skip) (extend-primes n))
(if (= n 1) nil
(loop for p across *primes* while (<= (* p p) n)
never (zerop (mod n p)))))
(defun factors (n)
(extend-primes n)
(loop with res for x across *primes* while (> n (* x x)) do
(loop while (zerop (rem n x)) do
(setf n (/ n x))
(push x res))
finally (return (if (> n 1) (cons n res) res))))
(loop for n from 1 do
(format t "~a: ~{~a~^ × ~}~%" n (reverse (factors n)))) |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #D | D | void main() {
import std.stdio, std.random;
writeln(`<table style="text-align:center; border: 1px solid">`);
writeln("<th></th><th>X</th><th>Y</th><th>Z</th>");
foreach (immutable i; 0 .. 4)
writefln("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>",
i, uniform(0,1000), uniform(0,1000), uniform(0,1000));
writeln("</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
| #Pike | Pike |
object cal = Calendar.ISO.Day();
write( cal->format_ymd() +"\n" );
string special = sprintf("%s, %s %d, %d",
cal->week_day_name(),
cal->month_name(),
cal->month_day(),
cal->year_no());
write( special +"\n" );
|
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
| #PL.2FI | PL/I | df: proc Options(main);
declare day_of_week(7) character (9) varying initial(
'Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday');
declare today character (9);
today = datetime('YYYYMMDD');
put edit(substr(today,1,4),'-',substr(today,5,2),'-',substr(today,7))
(A);
today = datetime('MmmDDYYYY');
put skip edit(day_of_week(weekday(days())),', ') (A);
put edit(substr(today,1,3),' ',substr(today,4,2),', ',
substr(today,6,4))(A);
end; |
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.
| #Maxima | Maxima |
(%i1) eqns: [ 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];
(%o1) [z + 5 y - x + 2 w = - 3, (- 6 z) + 2 y + 2 x + 3 w = - 32,
(- z) + 3 y + 3 x + w = - 47, 3 z - 3 y - 2 x + 5 w = 49]
(%i2) A: augcoefmatrix (eqns, [w,x,y,z]);
[ 2 - 1 5 1 3 ]
[ ]
[ 3 2 2 - 6 32 ]
(%o2) [ ]
[ 1 3 3 - 1 47 ]
[ ]
[ 5 - 2 - 3 3 - 49 ]
(%i3) C: coefmatrix(eqns, [w,x,y,z]);
[ 2 - 1 5 1 ]
[ ]
[ 3 2 2 - 6 ]
(%o3) [ ]
[ 1 3 3 - 1 ]
[ ]
[ 5 - 2 - 3 3 ]
(%i4) c[n]:= (-1)^(n+1) * determinant (submatrix (A,n))/determinant (C);
n + 1
(- 1) determinant(submatrix(A, n))
(%o4) c := ---------------------------------------
n determinant(C)
(%i5) makelist (c[n],n,1,4);
(%o5) [2, - 12, - 4, 1]
(%i6) linsolve(eqns, [w,x,y,z]);
(%o6) [w = 2, x = - 12, y = - 4, z = 1]
|
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.
| #Nim | Nim | type
SquareMatrix[N: static Positive] = array[N, array[N, float]]
Vector[N: static Positive] = array[N, float]
####################################################################################################
# Templates.
template `[]`(m: SquareMatrix; i, j: Natural): float =
## Allow to get value of an element using m[i, j] syntax.
m[i][j]
template `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =
## Allow to set value of an element using m[i, j] syntax.
m[i][j] = val
#---------------------------------------------------------------------------------------------------
func det(m: SquareMatrix): float =
## Return the determinant of matrix "m".
var m = m
result = 1
for j in 0..m.high:
var imax = j
for i in (j + 1)..m.high:
if m[i, j] > m[imax, j]:
imax = i
if imax != j:
swap m[iMax], m[j]
result = -result
if abs(m[j, j]) < 1e-12:
return NaN
for i in (j + 1)..m.high:
let mult = -m[i, j] / m[j, j]
for k in 0..m.high:
m[i, k] += mult * m[j, k]
for i in 0..m.high:
result *= m[i, i]
#---------------------------------------------------------------------------------------------------
func cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =
## Apply Cramer rule on matrix "a", using vector "b" to replace column "col".
when a.N != b.N:
{.error: "incompatible matrix and vector sizes".}
else:
var a = a
for i in 0..a.high:
a[i, col] = b[i]
result = det(a) / detA
#———————————————————————————————————————————————————————————————————————————————————————————————————
import strformat
const
A: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
B: Vector[4] = [-3.0, -32.0, -47.0, 49.0]
let detA = det(A)
if detA == NaN:
echo "Singular matrix!"
quit(QuitFailure)
for i in 0..A.high:
echo &"{cramerSolve(A, detA, B, i):7.3f}" |
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.
| #F.23 | F# | open System.IO
[<EntryPoint>]
let main argv =
let fileName = "output.txt"
let dirName = "docs"
for path in ["."; "/"] do
ignore (File.Create(Path.Combine(path, fileName)))
ignore (Directory.CreateDirectory(Path.Combine(path, dirName)))
0 |
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.
| #Factor | Factor | USE: io.directories
"output.txt" "/output.txt" [ touch-file ] bi@
"docs" "/docs" [ make-directory ] bi@ |
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).
| #Fortran | Fortran |
SUBROUTINE CSVTEXT2HTML(FNAME,HEADED) !Does not recognise quoted strings.
Converts without checking field counts, or noting special characters.
CHARACTER*(*) FNAME !Names the input file.
LOGICAL HEADED !Perhaps its first line is to be a heading.
INTEGER MANY !How long is a piece of string?
PARAMETER (MANY=666) !This should suffice.
CHARACTER*(MANY) ALINE !A scratchpad for the input.
INTEGER MARK(0:MANY + 1) !Fingers the commas on a line.
INTEGER I,L,N !Assistants.
CHARACTER*2 WOT(2) !I don't see why a "table datum" could not be for either.
PARAMETER (WOT = (/"th","td"/)) !A table heding or a table datum
INTEGER IT !But, one must select appropriately.
INTEGER KBD,MSG,IN !A selection.
COMMON /IOUNITS/ KBD,MSG,IN !The caller thus avoids collisions.
OPEN(IN,FILE=FNAME,STATUS="OLD",ACTION="READ",ERR=661) !Go for the file.
WRITE (MSG,1) !Start the blather.
1 FORMAT ("<Table border=1>") !By stating that a table follows.
MARK(0) = 0 !Syncopation for the comma fingers.
N = 0 !No records read.
10 READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY)) !Carefully acquire some text.
11 FORMAT (Q,A) !Q = number of characters yet to read, A = characters.
N = N + 1 !So, a record has been read.
IF (L.GT.MANY) THEN !Perhaps it is rather long?
WRITE (MSG,12) N,L,MANY !Alas!
12 FORMAT ("Line ",I0," has length ",I0,"! My limit is ",I0) !Squawk/
L = MANY !The limit actually read.
END IF !So much for paranoia.
IF (N.EQ.1 .AND. HEADED) THEN !Is the first line to be treated specially?
WRITE (MSG,*) "<tHead>" !Yep. Nominate a heading.
IT = 1 !And select "th" rather than "td".
ELSE !But mostly,
IT = 2 !Just another row for the table.
END IF !So much for the first line.
NCOLS = 0 !No commas have been seen.
DO I = 1,L !So scan the text for them.
IF (ICHAR(ALINE(I:I)).EQ.ICHAR(",")) THEN !Here?
NCOLS = NCOLS + 1 !Yes!
MARK(NCOLS) = I !The texts are between commas.
END IF !So much for that character.
END DO !On to the next.
NCOLS = NCOLS + 1 !This is why the + 1 for the size of MARK.
MARK(NCOLS) = L + 1 !End-of-line is as if a comma was one further along.
WRITE (MSG,13) !Now roll all the texts.
1 (WOT(IT), !This starting a cell,
2 ALINE(MARK(I - 1) + 1:MARK(I) - 1), !This being the text between the commas,
3 WOT(IT), !And this ending each cell.
4 I = 1,NCOLS), !For this number of columns.
5 "/tr" !And this ends the row.
13 FORMAT (" <tr>",666("<",A,">",A,"</",A,">")) !How long is a piece of string?
IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) "</tHead>" !Finish the possible header.
GO TO 10 !And try for another record.
20 CLOSE (IN) !Finished with input.
WRITE (MSG,21) !And finished with output.
21 FORMAT ("</Table>") !This writes starting at column one.
RETURN !Done!
Confusions.
661 WRITE (MSG,*) "Can't open file ",FNAME !Alas.
END !So much for the conversion.
INTEGER KBD,MSG,IN
COMMON /IOUNITS/ KBD,MSG,IN
KBD = 5 !Standard input.
MSG = 6 !Standard output.
IN = 10 !Some unspecial number.
CALL CSVTEXT2HTML("Text.csv",.FALSE.) !The first line is not special.
WRITE (MSG,*)
CALL CSVTEXT2HTML("Text.csv",.TRUE.) !The first line is a heading.
END
|
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.
| #OCaml | OCaml | let list_add_last this lst =
List.rev (this :: (List.rev lst))
let () =
let csv = Csv.load "data.csv" in
let fields, data =
(List.hd csv,
List.tl csv)
in
let fields =
list_add_last "SUM" fields
in
let sums =
List.map (fun row ->
let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in
list_add_last (string_of_int tot) row
) data
in
Csv.output_all (Csv.to_channel stdout) (fields :: sums) |
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.
| #PureBasic | PureBasic | For i=2008 To 2037
If DayOfWeek(Date(i,12,25,0,0,0))=0
PrintN(Str(i))
EndIf
Next |
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.
| #Python | Python | from calendar import weekday, SUNDAY
[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY] |
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.
| #Groovy | Groovy | def make2d = { nrows, ncols ->
(0..<nrows).collect { [0]*ncols }
} |
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.
| #Haskell | Haskell | import Data.Array
doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)] |
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
| #Julia | Julia | function makerunningstd(::Type{T} = Float64) where T
∑x = ∑x² = zero(T)
n = 0
function runningstd(x)
∑x += x
∑x² += x ^ 2
n += 1
s = ∑x² / n - (∑x / n) ^ 2
return s
end
return runningstd
end
test = Float64[2, 4, 4, 4, 5, 5, 7, 9]
rstd = makerunningstd()
println("Perform a running standard deviation of ", test)
for i in test
println(" - add $i → ", rstd(i))
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
| #ooRexx | ooRexx | /* ooRexx */
clzCRC32=bsf.importClass("java.util.zip.CRC32")
myCRC32 =clzCRC32~new
toBeEncoded="The quick brown fox jumps over the lazy dog"
myCRC32~update(BsfRawBytes(toBeEncoded))
numeric digits 20
say 'The CRC-32 value of "'toBeEncoded'" is:' myCRC32~getValue~d2x
::requires "BSF.CLS" -- get Java bridge |
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
| #PARI.2FGP | PARI/GP |
install("crc32", "lLsL", "crc32", "libz.so");
s = "The quick brown fox jumps over the lazy dog";
printf("%0x\n", crc32(0, s, #s))
|
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.
| #F.23 | F# | let changes amount coins =
let ways = Array.zeroCreate (amount + 1)
ways.[0] <- 1L
List.iter (fun coin ->
for j = coin to amount do ways.[j] <- ways.[j] + ways.[j - coin]
) coins
ways.[amount]
[<EntryPoint>]
let main argv =
printfn "%d" (changes 100 [25; 10; 5; 1]);
printfn "%d" (changes 100000 [100; 50; 25; 10; 5; 1]);
0 |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Delphi | Delphi | program OccurrencesOfASubstring;
{$APPTYPE CONSOLE}
uses StrUtils;
function CountSubstring(const aString, aSubstring: string): Integer;
var
lPosition: Integer;
begin
Result := 0;
lPosition := PosEx(aSubstring, aString);
while lPosition <> 0 do
begin
Inc(Result);
lPosition := PosEx(aSubstring, aString, lPosition + Length(aSubstring));
end;
end;
begin
Writeln(CountSubstring('the three truths', 'th'));
Writeln(CountSubstring('ababababab', 'abab'));
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
| #Dyalect | Dyalect | func countSubstring(str, val) {
var idx = 0
var count = 0
while true {
idx = str.IndexOf(val, idx)
if idx == -1 {
break
}
idx += val.Length()
count += 1
}
return count
}
print(countSubstring("the three truths", "th"))
print(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.
| #Component_Pascal | Component Pascal |
MODULE CountOctal;
IMPORT StdLog,Strings;
PROCEDURE Do*;
VAR
i: INTEGER;
resp: ARRAY 32 OF CHAR;
BEGIN
FOR i := 0 TO 1000 DO
Strings.IntToStringForm(i,8,12,' ',TRUE,resp);
StdLog.String(resp);StdLog.Ln
END
END Do;
END CountOctal.
|
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.
| #Cowgol | Cowgol | include "cowgol.coh";
typedef N is uint16;
sub print_octal(n: N) is
var buf: uint8[12];
var p := &buf[11];
[p] := 0;
loop
p := @prev p;
[p] := '0' + (n as uint8 & 7);
n := n >> 3;
if n == 0 then break; end if;
end loop;
print(p);
end sub;
var n: N := 0;
loop
print_octal(n);
print_nl();
n := n + 1;
if n == 0 then break; end if;
end loop; |
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
| #D | D | int[] factorize(in int n) pure nothrow
in {
assert(n > 0);
} body {
if (n == 1) return [1];
int[] result;
int m = n, k = 2;
while (n >= k) {
while (m % k == 0) {
result ~= k;
m /= k;
}
k++;
}
return result;
}
void main() {
import std.stdio;
foreach (i; 1 .. 22)
writefln("%d: %(%d × %)", i, i.factorize());
} |
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.
| #Delphi | Delphi | program CreateHTMLTable;
{$APPTYPE CONSOLE}
uses SysUtils;
function AddTableRow(aRowNo: Integer): string;
begin
Result := Format(' <tr><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>',
[aRowNo, Random(10000), Random(10000), Random(10000)]);
end;
var
i: Integer;
begin
Randomize;
Writeln('<table>');
Writeln(' <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>');
for i := 1 to 4 do
Writeln(AddTableRow(i));
Writeln('</table>');
Readln;
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
| #PowerShell | PowerShell | "{0:yyyy-MM-dd}" -f (Get-Date)
"{0:dddd, MMMM d, yyyy}" -f (Get-Date)
# or
(Get-Date).ToString("yyyy-MM-dd")
(Get-Date).ToString("dddd, MMMM d, yyyy") |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Prolog | Prolog |
display_date :-
get_time(Time),
format_time(atom(Short), '%Y-%M-%d', Time),
format_time(atom(Long), '%A, %B %d, %Y', Time),
format('~w~n~w~n', [Short, Long]).
|
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.
| #PARI.2FGP | PARI/GP |
M = [2,-1,5,1;3,2,2,-6;1,3,3,-1;5,-2,-3,3];
V = Col([-3,-32,-47,49]);
matadjoint(M) * V / matdet(M)
|
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.
| #Perl | Perl | use Math::Matrix;
sub cramers_rule {
my ($A, $terms) = @_;
my @solutions;
my $det = $A->determinant;
foreach my $i (0 .. $#{$A}) {
my $Ai = $A->clone;
foreach my $j (0 .. $#{$terms}) {
$Ai->[$j][$i] = $terms->[$j];
}
push @solutions, $Ai->determinant / $det;
}
@solutions;
}
my $matrix = Math::Matrix->new(
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3],
);
my $free_terms = [-3, -32, -47, 49];
my ($w, $x, $y, $z) = cramers_rule($matrix, $free_terms);
print "w = $w\n";
print "x = $x\n";
print "y = $y\n";
print "z = $z\n"; |
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.
| #Fancy | Fancy | ["/", "./"] each: |dir| {
# create '/docs', then './docs'
Directory create: (dir ++ "docs")
# create files /output.txt, then ./output.txt
File open: (dir ++ "output.txt") modes: ['write] with: |f| {
f writeln: "hello, world!"
}
} |
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.
| #Forth | Forth | s" output.txt" w/o create-file throw ( fileid) drop
s" /output.txt" w/o create-file throw ( fileid) drop |
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).
| #FreeBASIC | FreeBASIC | Data "Character,Speech"
Data "The multitude,The messiah! Show us the messiah!"
Data "Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>"
Data "The multitude,Who are you?"
Data "Brian's mother,I'm his mother; that's who!"
Data "The multitude,Behold his mother! Behold his mother!"
Data "***"
Print "<!DOCTYPE html>" & Chr(10) & "<html>"
Print "<head>"
Print "</head>" & Chr(10)
Print "<body>"
Print "<h1 style=""text-align:center"">CSV to html translation </h1>"
Print: Print "<table border = 1 cellpadding = 10 cellspacing = 0>"
Dim As Boolean header = true
Dim As String cadenaCSV, txt
Do
Read cadenaCSV
If cadenaCSV = "***" then Exit Do
If header then
Print "<thead bgcolor=""green"">" & Chr(10) & "<tr><th>";
Else
Print "<tr><td>";
End If
For i As Integer = 1 To Len(cadenaCSV)
txt = Mid(cadenaCSV, i, 1)
Select Case txt
Case ",": If header then Print "</th><th>"; Else Print "</td><td>";
Case "<": Print "<";
Case ">": Print ">";
Case "&": Print "&";
Case Else: Print txt;
End Select
Next i
If header then
Print "</th></tr>" & Chr(10) & "</thead>" & Chr(10) & "<tbody bgcolor=""yellow"">"
Else
Print "</td></tr>"
End If
header = false
Loop Until false
Print "</tbody>" & Chr(10) & "</table>"
Print Chr(10) & "</body>"
Print "</html>"
Sleep |
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.
| #PARI.2FGP | PARI/GP |
\\ CSV data manipulation
\\ 10/24/16 aev
\\ processCsv(fn): Where fn is an input path and file name (but no actual extension).
processCsv(fn)=
{my(F, ifn=Str(fn,".csv"), ofn=Str(fn,"r.csv"), cn=",SUM",nf,nc,Vr,svr);
if(fn=="", return(-1));
F=readstr(ifn); nf=#F;
F[1] = Str(F[1],cn);
for(i=2, nf,
Vr=stok(F[i],","); if(i==2,nc=#Vr);
svr=sum(k=1,nc,eval(Vr[k]));
F[i] = Str(F[i],",",svr);
);\\fend i
for(j=1, nf, write(ofn,F[j]))
}
\\ Testing:
processCsv("c:\\pariData\\test");
|
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.
| #Quackery | Quackery | [ over 3 < if [ 1 - ]
dup 4 / over +
over 100 / -
swap 400 / +
swap 1 -
[ table
0 3 2 5 0 3
5 1 4 6 2 4 ]
+ + 7 mod ] is dayofweek ( day month year --> weekday )
say "The 25th of December is a Sunday in: " cr
2121 1+ 2008 - times
[ 25 12 i^ 2008 + dayofweek
0 = if [ i^ 2008 + echo sp ] ] |
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.
| #R | R | years <- 2008:2121
xmas <- as.POSIXlt(paste0(years, '/12/25'))
years[xmas$wday==0]
# 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118
# Also:
xmas=seq(as.Date("2008/12/25"), as.Date("2121/12/25"), by="year")
as.numeric(format(xmas[weekdays(xmas)== 'Sunday'], "%Y"))
# Still another solution, using ISOdate and weekdays
with(list(years=2008:2121), years[weekdays(ISOdate(years, 12, 25)) == "Sunday"])
# Or with "subset"
subset(data.frame(years=2008:2121), weekdays(ISOdate(years, 12, 25)) == "Sunday")$years
# Simply replace "Sunday" with whatever it's named in your country,
# or set locale first, with
Sys.setlocale(cat="LC_ALL", "en")
# Under MS Windows, write instead
Sys.setlocale("LC_ALL", "English") |
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.
| #HicEst | HicEst | REAL :: array(1)
DLG(NameEdit=rows, NameEdit=cols, Button='OK', TItle='Enter array dimensions')
ALLOCATE(array, cols, rows)
array(1,1) = 1.234
WRITE(Messagebox, Name) 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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(args)
nr := integer(args[1]) | 3 # Default to 3x3
nc := integer(args[2]) | 3
A := list(nr)
every !A := list(nc)
x := ?nr # Select a random element
y := ?nc
A[x][y] := &pi
write("A[",x,"][",y,"] -> ",A[x][y])
end |
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
| #Kotlin | Kotlin | // version 1.0.5-2
class CumStdDev {
private var n = 0
private var sum = 0.0
private var sum2 = 0.0
fun sd(x: Double): Double {
n++
sum += x
sum2 += x * x
return Math.sqrt(sum2 / n - sum * sum / n / n)
}
}
fun main(args: Array<String>) {
val testData = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)
val csd = CumStdDev()
for (d in testData) println("Add $d => ${csd.sd(d)}")
} |
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
| #Perl | Perl | #!/usr/bin/perl
use 5.010 ;
use strict ;
use warnings ;
use Digest::CRC qw( crc32 ) ;
my $crc = Digest::CRC->new( type => "crc32" ) ;
$crc->add ( "The quick brown fox jumps over the lazy dog" ) ;
say "The checksum is " . $crc->hexdigest( ) ;
|
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
| #Phix | Phix | with javascript_semantics
sequence table
bool have_table = false
function crc32(string s)
if not have_table then
have_table = true
table = repeat(0,256)
for i=0 to 255 do
atom rem = i
for j=1 to 8 do
if and_bits(rem,1) then
rem = xor_bits(floor(rem/2),#EDB88320)
else
rem = floor(rem/2)
end if
if rem<0 then
rem += #100000000
end if
end for
table[i+1] = rem
end for
end if
atom crc = #FFFFFFFF
for i=1 to length(s) do
crc = xor_bits(floor(crc/#100),table[xor_bits(and_bits(crc,0xff),s[i])+1])
if crc<0 then
crc += #100000000
end if
end for
return and_bits(not_bits(crc),#FFFFFFFF)
end function
string s = "The quick brown fox jumps over the lazy dog"
printf(1,"The CRC of %s is %08x\n",{s,crc32(s)})
|
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.
| #Factor | Factor | USING: combinators kernel locals math math.ranges sequences sets sorting ;
IN: rosetta.coins
<PRIVATE
! recursive-count uses memoization and local variables.
! coins must be a sequence.
MEMO:: recursive-count ( cents coins -- ways )
coins length :> types
{
! End condition: 1 way to make 0 cents.
{ [ cents zero? ] [ 1 ] }
! End condition: 0 ways to make money without any coins.
{ [ types zero? ] [ 0 ] }
! Optimization: At most 1 way to use 1 type of coin.
{ [ types 1 number= ] [
cents coins first mod zero? [ 1 ] [ 0 ] if
] }
! Find all ways to use the first type of coin.
[
! f = first type, r = other types of coins.
coins unclip-slice :> f :> r
! Loop for 0, f, 2*f, 3*f, ..., cents.
0 cents f <range> [
! Recursively count how many ways to make remaining cents
! with other types of coins.
cents swap - r recursive-count
] [ + ] map-reduce ! Sum the counts.
]
} cond ;
PRIVATE>
! How many ways can we make the given amount of cents
! with the given set of coins?
: make-change ( cents coins -- ways )
members [ ] inv-sort-with ! Sort coins in descending order.
recursive-count ; |
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.
| #Forth | Forth | \ counting change (SICP section 1.2.2)
: table create does> swap cells + @ ;
table coin-value 0 , 1 , 5 , 10 , 25 , 50 ,
: count-change ( total coin -- n )
over 0= if
2drop 1
else over 0< over 0= or if
2drop 0
else
2dup coin-value - over recurse
>r 1- recurse r> +
then then ;
100 5 count-change . |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | !. count "the three truths" "th"
!. count "ababababab" "abab" |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #EchoLisp | EchoLisp |
;; from Racket
(define count-substring
(compose length regexp-match*))
(count-substring "aab" "graabaabdfaabgh") ;; substring
→ 3
(count-substring "/ .e/" "Longtemps je me suis couché de bonne heure") ;; regexp
→ 4
|
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.
| #Crystal | Crystal | # version 0.21.1
# using unsigned 8 bit integer, range 0 to 255
(0_u8..255_u8).each { |i| puts i.to_s(8) } |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #D | D | void main() {
import std.stdio;
ubyte i;
do writefln("%o", i++);
while(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
| #DCL | DCL | $ close /nolog primes
$ on control_y then $ goto clean
$
$ n = 1
$ outer_loop:
$ x = n
$ open primes primes.txt
$
$ loop1:
$ read /end_of_file = prime primes prime
$ prime = f$integer( prime )
$ loop2:
$ t = x / prime
$ if t * prime .eq. x
$ then
$ if f$type( factorization ) .eqs. ""
$ then
$ factorization = f$string( prime )
$ else
$ factorization = factorization + "*" + f$string( prime )
$ endif
$ if t .eq. 1 then $ goto done
$ x = t
$ goto loop2
$ else
$ goto loop1
$ endif
$ prime:
$ if f$type( factorization ) .eqs. ""
$ then
$ factorization = f$string( x )
$ else
$ factorization = factorization + "*" + f$string( x )
$ endif
$ done:
$ write sys$output f$fao( "!4SL = ", n ), factorization
$ delete /symbol factorization
$ close primes
$ n = n + 1
$ if n .le. 2144 then $ goto outer_loop
$ exit
$
$ clean:
$ close /nolog primes |
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.
| #EchoLisp | EchoLisp |
;; styles -
(style 'td "text-align:right")
(style 'table "border-spacing: 10px;border:1px solid red")
(style 'th "color:blue;")
;; generic html5 builder
;; pushes <tag style=..> (proc content) </tag>
(define (emit-tag tag html-proc content )
(if (style tag)
(push html (format "<%s style='%a'>" tag (style tag)))
(push html (format "<%s>" tag )))
(html-proc content)
(push html (format "</%s> " tag )))
;; html procs : 1 tag, 1 proc
(define (h-raw content)
(push html (format "%s" content)))
(define (h-header headers)
(for ((h headers)) (emit-tag 'th h-raw h)))
(define (h-row row)
(for ((item row)) (emit-tag 'td h-raw item)))
(define (h-table table )
(emit-tag 'tr h-header (first table))
;; add row-num i at head of row
(for ((i 1000)(row (rest table))) (emit-tag 'tr h-row (cons i row))))
|
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
| #PureBasic | PureBasic | ;Declare Procedures
Declare.s MonthInText()
Declare.s DayInText()
;Output the requested strings
Debug FormatDate("%yyyy-%mm-%dd", Date())
Debug DayInText() + ", " + MonthInText() + FormatDate(" %dd, %yyyy", Date())
;Used procedures
Procedure.s DayInText()
Protected d$
Select DayOfWeek(Date())
Case 1: d$="Monday"
Case 2: d$="Tuesday"
Case 3: d$="Wednesday"
Case 4: d$="Thursday"
Case 5: d$="Friday"
Case 6: d$="Saturday"
Default: d$="Sunday"
EndSelect
ProcedureReturn d$
EndProcedure
Procedure.s MonthInText()
Protected m$
Select Month(Date())
Case 1: m$="January"
Case 2: m$="February"
Case 3: m$="March"
Case 4: m$="April"
Case 5: m$="May"
Case 6: m$="June"
Case 7: m$="July"
Case 8: m$="August"
Case 9: m$="September"
Case 10:m$="October"
Case 11:m$="November"
Default:m$="December"
EndSelect
ProcedureReturn m$
EndProcedure |
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.
| #Phix | Phix | requires("0.8.4")
with javascript_semantics
constant inf = 1e300*1e300,
nan = -(inf/inf)
function det(sequence a)
atom res = 1
a = deep_copy(a)
integer l = length(a)
for j=1 to l do
integer i_max = j
for i=j+1 to l do
if a[i][j] > a[i_max][j] then
i_max = i
end if
end for
if i_max != j then
sequence aim = a[i_max]
a[i_max] = a[j]
a[j] = aim
res *= -1
end if
if abs(a[j][j]) < 1e-12 then
puts(1,"Singular matrix!")
return nan
end if
for i=j+1 to l do
atom mult = -a[i][j] / a[j][j]
for k=1 to l do
a[i][k] += mult * a[j][k]
end for
end for
end for
for i=1 to l do
res *= a[i][i]
end for
return res
end function
function cramer_solve(sequence a, atom det_a, sequence b, integer v)
a = deep_copy(a)
for i=1 to length(a) do
a[i][v] = b[i]
end for
return det(a)/det_a
end function
sequence a = {{2,-1, 5, 1},
{3, 2, 2,-6},
{1, 3, 3,-1},
{5,-2,-3, 3}},
b = {-3,-32,-47,49}
integer det_a = det(a)
for i=1 to length(a) do
printf(1, "%7.3f\n", cramer_solve(a, det_a, b, i))
end for
|
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.
| #Fortran | Fortran |
PROGRAM CREATION
OPEN (UNIT=5, FILE="output.txt", STATUS="NEW") ! Current directory
CLOSE (UNIT=5)
OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") ! Root directory
CLOSE (UNIT=5)
!Directories (Use System from GNU Fortran Compiler)
! -- Added by Anant Dixit, November 2014
call system("mkdir docs/")
call system("mkdir ~/docs/")
END PROGRAM
|
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' create empty file and sub-directory in current directory
Open "output.txt" For Output As #1
Close #1
MkDir "docs"
' create empty file and sub-directory in root directory c:\
' creating file in root requires administrative privileges in Windows 10
Open "c:\output.txt" For Output As #1
Close #1
MkDir "c:\docs"
Print "Press any key to quit"
Sleep |
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).
| #Go | Go | package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"strings"
)
var c = `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!`
func main() {
if h, err := csvToHtml(c); err != nil {
fmt.Println(err)
} else {
fmt.Print(h)
}
}
func csvToHtml(c string) (string, error) {
data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
if err != nil {
return "", err
}
var b strings.Builder
err = template.Must(template.New("").Parse(`<table>
{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
return b.String(), err
} |
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.
| #Pascal | Pascal |
program CSV_Data_Manipulation;
uses Classes, SysUtils;
var s: string;
ts: tStringList;
inFile,
outFile: Text;
Sum: integer;
Number: string;
begin
Assign(inFile,'input.csv');
Reset(inFile);
Assign(outFile,'result.csv');
Rewrite(outFile);
ts:=tStringList.Create;
ts.StrictDelimiter:=True;
// Handle the header
ReadLn(inFile,s); // Read a line from input file
ts.CommaText:=s; // Split it to lines
ts.Add('SUM'); // Add a line
WriteLn(outFile,ts.CommaText); // Reassemble it with comma as delimiter
// Handle the data
while not eof(inFile) do
begin
ReadLn(inFile,s);
ts.CommaText:=s;
Sum:=0;
for Number in ts do
Sum+=StrToInt(Number);
ts.Add('%D',[Sum]);
writeln(outFile, ts.CommaText);
end;
Close(outFile);
Close(inFile);
ts.Free;
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.
| #Racket | Racket |
#lang racket
(require racket/date)
(define (xmas-on-sunday? year)
(zero? (date-week-day (seconds->date (find-seconds 0 0 12 25 12 year)))))
(for ([y (in-range 2008 2121)] #:when (xmas-on-sunday? y))
(displayln y))
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Raku | Raku | say join ' ', grep { Date.new($_, 12, 25).day-of-week == 7 }, 2008 .. 2121; |
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.
| #IDL | IDL | read, x, prompt='Enter x size:'
read, y, prompt='Enter y size:'
d = fltarr(x,y)
d[3,4] = 5.6
print,d[3,4]
;==> outputs 5.6
delvar, d |
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.
| #J | J | array1=:i. 3 4 NB. a 3 by 4 array with arbitrary values
array2=: 5 6 $ 2 NB. a 5 by 6 array where every value is the number 2 |
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
| #Liberty_BASIC | Liberty BASIC |
dim SD.storage$( 100) ' can call up to 100 versions, using ID to identify.. arrays are global.
' holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares
for i =1 to 8
read x
print "New data "; x; " so S.D. now = "; using( "###.######", standard.deviation( 1, x))
next i
end
function standard.deviation( ID, in)
if SD.storage$( ID) ="" then SD.storage$( ID) ="0 0 0"
num.so.far =val( word$( SD.storage$( ID), 1))
sum.vals =val( word$( SD.storage$( ID), 2))
sum.sqs =val( word$( SD.storage$( ID), 3))
num.so.far =num.so.far +1
sum.vals =sum.vals +in
sum.sqs =sum.sqs +in^2
' standard deviation = square root of (the average of the squares less the square of the average)
standard.deviation =( ( sum.sqs /num.so.far) - ( sum.vals /num.so.far)^2)^0.5
SD.storage$( ID) =str$( num.so.far) +" " +str$( sum.vals) +" " +str$( sum.sqs)
end function
Data 2, 4, 4, 4, 5, 5, 7, 9
|
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
| #PHP | PHP | printf("%x\n", crc32("The quick brown fox jumps over the lazy dog")); |
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
| #PicoLisp | PicoLisp | (setq *Table
(mapcar
'((N)
(do 8
(setq N
(if (bit? 1 N)
(x| (>> 1 N) `(hex "EDB88320"))
(>> 1 N) ) ) ) )
(range 0 255) ) )
(de crc32 (Lst)
(let Crc `(hex "FFFFFFFF")
(for I (chop Lst)
(setq Crc
(x|
(get
*Table
(inc (x| (& Crc 255) (char I))) )
(>> 8 Crc) ) ) )
(x| `(hex "FFFFFFFF") Crc) ) )
(let Str "The quick brown fox jumps over the lazy dog"
(println (hex (crc32 Str)))
(println
(hex (native "libz.so" "crc32" 'N 0 Str (length Str))) ) )
(bye) |
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.
| #FreeBASIC | FreeBASIC | ' version 09-10-2016
' compile with: fbc -s console
Function count(S() As UInteger, n As UInteger) As ULongInt
Dim As Integer i, j
' calculate m from array S()
Dim As UInteger m = UBound(S) - LBound(S) +1
Dim As ULongInt x, y
'' We need n+1 rows as the table is consturcted in bottom up manner using
'' the base case 0 value case (n = 0)
Dim As ULongInt table(n +1, m)
'' Fill the enteries for 0 value case (n = 0)
For i = 0 To m -1
table(0, i) = 1
Next
'' Fill rest of the table enteries in bottom up manner
For i = 1 To n
For j = 0 To m -1
'' Count of solutions including S[j]
x = IIf (i >= S(j), table(i - S(j), j), 0)
'' Count of solutions excluding S[j]
y = IIf (j >= 1, table(i, j -1), 0)
''total count
table(i, j) = x + y
Next
Next
Return table(n, m -1)
End Function
' ------=< MAIN >=------
Dim As UInteger n
Dim As UInteger value()
ReDim value(3)
value(0) = 1 : value(1) = 5 : value(2) = 10 : value(3) = 25
n = 100
print
Print " There are "; count(value(), n); " ways to make change for $";n/100;" with 4 coins"
Print
n = 100000
Print " There are "; count(value(), n); " ways to make change for $";n/100;" with 4 coins"
Print
ReDim value(5)
value(0) = 1 : value(1) = 5 : value(2) = 10
value(3) = 25 : value(4) = 50 : value(5) = 100
n = 100000
Print " There are "; count(value(), n); " ways to make change for $";n/100;" with 6 coins"
Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
| #EGL | EGL | program CountStrings
function main()
SysLib.writeStdout("Remove and Count:");
SysLib.writeStdout(countSubstring("th", "the three truths"));
SysLib.writeStdout(countSubstring("abab", "ababababab"));
SysLib.writeStdout(countSubstring("a*b", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstring("a", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstring(" ", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstring("", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstring("a", ""));
SysLib.writeStdout(countSubstring("", ""));
SysLib.writeStdout("Manual Loop:");
SysLib.writeStdout(countSubstringWithLoop("th", "the three truths"));
SysLib.writeStdout(countSubstringWithLoop("abab", "ababababab"));
SysLib.writeStdout(countSubstringWithLoop("a*b", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstringWithLoop("a", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstringWithLoop(" ", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstringWithLoop("", "abaabba*bbaba*bbab"));
SysLib.writeStdout(countSubstringWithLoop("a", ""));
SysLib.writeStdout(countSubstringWithLoop("", ""));
end
function countSubstring(substr string in, str string in) returns(int)
if(str.length() > 0 and substr.length() > 0)
return (str.length() - str.replaceStr(subStr, "").length()) / subStr.length();
else
return 0;
end
end
function countSubstringWithLoop(substr string in, str string in) returns(int)
count int = 0;
loc, index int = 1;
strlen int = str.length();
substrlen int = substr.length();
if(strlen > 0 and substrlen > 0)
while(loc != 0 and index <= strlen)
loc = str.indexOf(substr, index);
if(loc > 0)
count += 1;
index = loc + substrlen;
end
end
end
return count;
end
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
| #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
occurance := 0
from
index := 1
until
index > text.count
loop
temp := text.fuzzy_index(search_for, index, 0)
if
temp /= 0
then
index := temp + search_for.count
occurance := occurance + 1
else
index := text.count + 1
end
end
print(occurance)
end
index:INTEGER
temp:INTEGER
occurance:INTEGER
text:STRING = "ababababab"
search_for:STRING = "abab"
end
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Dc | Dc | 8o0[p1+lpx]dspx |
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.
| #DCL | DCL | $ i = 0
$ loop:
$ write sys$output f$fao( "!OL", i )
$ i = i + 1
$ goto loop |
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.
| #Delphi | Delphi | program CountingInOctal;
{$APPTYPE CONSOLE}
uses SysUtils;
function DecToOct(aValue: Integer): string;
var
lRemainder: Integer;
begin
Result := '';
repeat
lRemainder := aValue mod 8;
Result := IntToStr(lRemainder) + Result;
aValue := aValue div 8;
until aValue = 0;
end;
var
i: Integer;
begin
for i := 0 to 20 do
WriteLn(DecToOct(i));
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
| #Delphi | Delphi | function Factorize(n : Integer) : String;
begin
if n <= 1 then
Exit('1');
var k := 2;
while n >= k do begin
while (n mod k) = 0 do begin
Result += ' * '+IntToStr(k);
n := n div k;
end;
Inc(k);
end;
Result:=SubStr(Result, 4);
end;
var i : Integer;
for i := 1 to 22 do
PrintLn(IntToStr(i) + ': ' + Factorize(i)); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.