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/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.
| #FreeBASIC | FreeBASIC |
Function determinant(matrix() As Double) As Double
Dim As long n=Ubound(matrix,1),sign=1
Dim As Double det=1,s=1
Dim As Double b(1 To n,1 To n)
For c As long=1 To n
For d As long=1 To n
b(c,d)=matrix(c,d)
Next d
Next c
#macro pivot(num)
For p1 As long = num To n - 1
For p2 As long = p1 + 1 To n
If Abs(b(p1,num))<Abs(b(p2,num)) Then
sign=-sign
For g As long=1 To n
Swap b(p1,g),b(p2,g)
Next g
End If
Next p2
Next p1
#endmacro
For k As long=1 To n-1
pivot(k)
For row As long =k To n-1
If b(row+1,k)=0 Then Exit For
Var f=b(k,k)/b(row+1,k)
s=s*f
For g As long=1 To n
b((row+1),g)=(b((row+1),g)*f-b(k,g))/f
Next g
Next row
Next k
For z As long=1 To n
det=det*b(z,z)
Next z
Return sign*det
End Function
'CRAMER COLUMN SWAPS
Sub swapcolumn(m() As Double,c() As Double,_new() As Double,column As long)
Redim _new(1 To Ubound(m,1),1 To Ubound(m,1))
For x As long=1 To Ubound(m,1)
For y As long=1 To Ubound(m,1)
_new(x,y)=m(x,y)
Next y
Next x
For z As long=1 To Ubound(m,1)
_new(z,column)=c(z)
Next z
End Sub
Sub solve(mat() As Double,rhs() As Double,_out() As Double)
redim _out(Lbound(mat,1) To Ubound(mat,1))
Redim As Double result(Lbound(mat,1) To Ubound(mat,1),Lbound(mat,1) To Ubound(mat,1))
Dim As Double maindeterminant=determinant(mat())
If Abs(maindeterminant) < 1e-12 Then Print "singular":Exit Sub
For column As Long=1 To Ubound(mat,1)
swapcolumn(mat(),rhs(),result(),column)
_out(column)= determinant(result())/maindeterminant
Next
End Sub
Dim As Double MainMat(1 To ...,1 To ...)={{2,-1,5,1}, _
{3,2,2,-6}, _
{1,3,3,-1}, _
{5,-2,-3,3}}
Dim As Double rhs(1 To ...)={-3,-32,-47,49}
Redim ans() As Double
solve(MainMat(),rhs(),ans())
For n As Long=1 To Ubound(ans)
Print Csng(ans(n))
Next
Sleep
|
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.
| #ChucK | ChucK |
FileIO text;
text.open("output.txt", FileIO.WRITE);
|
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.
| #Clojure | Clojure | (import '(java.io File))
(.createNewFile (new File "output.txt"))
(.mkdir (new File "docs"))
(.createNewFile (File. (str (File/separator) "output.txt")))
(.mkdir (File. (str (File/separator) "docs"))) |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #CoffeeScript | CoffeeScript | String::__defineGetter__ 'escaped', () ->
this.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"') // rosettacode doesn't like "
text = '''
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!
'''
lines = (line.split ',' for line in text.split /[\n\r]+/g)
header = lines.shift()
console.log """
<table cellspacing="0">
<thead>
<th scope="col">#{header[0]}</th>
<th scope="col">#{header[1]}</th>
</thead>
<tbody>
"""
for line in lines
[character, speech] = line
console.log """
<th scope="row">#{character}</th>
<td>#{speech.escaped}</td>
"""
console.log """
</tbody>
</table>
""" |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Icon_and_Unicon | Icon and Unicon | import Utils # To get CSV procedures
procedure main(A)
f := open(A[1]) | &input
i := 1
write(!f) # header line(?)
every csv := parseCSV(!f) do {
csv[i+:=1] *:= 100
write(encodeCSV(csv))
}
end |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #REXX | REXX | /* REXX */
Call init
Call test 5724
Call test 5727
Call test 112946
Call test 112940
Exit
test:
Parse Arg number
int_digit=0
Do p=1 To length(number)
d=substr(number,p,1)
int_digit=grid.int_digit.d
If p<length(number) Then cd=int_digit
End
If int_digit=0 Then
Say number 'is ok'
Else
Say number 'is not ok, check-digit should be' cd '(instead of' d')'
Return
init:
i=-2
Call setup '* 0 1 2 3 4 5 6 7 8 9'
Call setup '0 0 3 1 7 5 9 8 6 4 2'
Call setup '1 7 0 9 2 1 5 4 8 6 3'
Call setup '2 4 2 0 6 8 7 1 3 5 9'
Call setup '3 1 7 5 0 9 8 3 4 2 6'
Call setup '4 6 1 2 3 0 4 5 9 7 8'
Call setup '5 3 6 7 4 2 0 9 5 8 1'
Call setup '6 5 8 6 9 7 2 0 1 3 4'
Call setup '7 8 9 4 5 3 6 2 0 1 7'
Call setup '8 9 4 3 8 6 1 7 2 0 5'
Call setup '9 2 5 8 1 4 3 6 7 9 0'
Return
setup:
Parse Arg list
i=i+1
Do col=-1 To 9
grid.i.col=word(list,col+2)
End
Return |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #REXX | REXX | /*REXX program finds and displays a number of cuban primes or the Nth cuban prime. */
numeric digits 20 /*ensure enough decimal digits for #s. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/
Nth= N<0; N= abs(N) /*used for finding the Nth cuban prime.*/
@.=0; @.0=1; @.2=1; @.3=1; @.4=1; @.5=1; @.6=1; @.8=1 /*ending digs that aren't cubans.*/
sw= linesize() - 1; if sw<1 then sw= 79 /*obtain width of the terminal screen. */
w=12; #= 1; $= right(7, w) /*start with first cuban prime; count.*/
do j=1 until #=>N; x= (j+1)**3 - j**3 /*compute a possible cuban prime. */
parse var x '' -1 _; if @._ then iterate /*check last digit for non─cuban prime.*/
do k=1 until km*km>x; km= k*6 + 1 /*cuban primes can't be ÷ by 6k+1 */
if x//km==0 then iterate j /*Divisible? Then not a cuban prime. */
end /*k*/
#= #+1 /*bump the number of cuban primes found*/
if Nth then do; if #==N then do; say commas(x); leave j; end /*display 1 num.*/
else iterate /*j*/ /*keep searching*/
end /* [↑] try to fit as many #s per line.*/
cx= commas(x); L= length(cx) /*insert commas──►X; obtain the length.*/
cx= right(cx, max(w, L) ); new= $ cx /*right justify CX; concat to new list*/
if length(new)>sw then do; say $; $= cx /*line is too long, display #'s so far.*/
end /* [↑] initialize the (new) next line.*/
else $= new /*start with cuban # that wouldn't fit.*/
end /*j*/
if \Nth & $\=='' then say $ /*check for residual cuban primes in $.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #UNIX_Shell | UNIX Shell | epoch=$(date -d 'March 7 2009 7:30pm EST +12 hours' +%s)
date -d @$epoch
TZ=Asia/Shanghai date -d @$epoch |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Wren | Wren | import "/date" for Date
var fmt = "mmmm| |d| |yyyy| |H|:|MM|am| |zz|"
var d = Date.parse("March 7 2009 7:30pm EST", fmt)
Date.default = fmt
System.print("Original date/time : %(d)")
d = d.addHours(12)
System.print("12 hours later : %(d)")
// Adjust to MST say
d = d.adjustTime("MST")
System.print("Adjusted to MST : %(d)") |
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.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main()
{
@autoreleasepool {
for(NSUInteger i=2008; i<2121; i++)
{
NSCalendarDate *d = [[NSCalendarDate alloc]
initWithYear: i
month: 12
day: 25
hour: 0 minute: 0 second:0
timeZone: [NSTimeZone timeZoneWithAbbreviation:@"CET"] ];
if ( [d dayOfWeek] == 0 )
{
printf("25 Dec %u is Sunday\n", i);
}
}
}
return 0;
} |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #XPL0 | XPL0 | string 0; \use zero-terminated strings
func Valid(Cusip); \Return 'true' if valid CUSIP code
char Cusip;
int Sum, I, C, V;
[Sum:= 0;
for I:= 0 to 8-1 do
[C:= Cusip(I);
ChOut(0, C);
case of
C>=^0 & C<=^9: V:= C-^0;
C>=^A & C<=^Z: V:= C-^A+10;
C=^*: V:=36;
C=^@: V:=37;
C=^#: V:=38
other V:= -1;
if I&1 then V:= V*2;
Sum:= Sum + V/10 + rem(0);
];
C:= Cusip(I);
ChOut(0, C);
V:= rem( (10-rem(Sum/10)) / 10 );
return V = C-^0;
];
int Cusip, N;
[Cusip:= ["037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"];
for N:= 0 to 6-1 do
[Text(0, if Valid(Cusip(N))
then " is valid"
else " is invalid");
CrLf(0);
];
] |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Yabasic | Yabasic | sub cusip(inputStr$)
local i, v, sum, x$
Print inputStr$;
If Len(inputStr$) <> 9 Print " length is incorrect, invalid cusip" : return
For i = 1 To 8
x$ = mid$(inputStr$, i, 1)
switch x$
Case "*": v = 36 : break
Case "@": v = 37 : break
Case "#": v = 38 : break
default:
if x$ >= "A" and x$ <= "Z" then
v = asc(x$) - Asc("A") + 10
elsif x$ >= "0" and x$ <= "9" then
v = asc(x$) - asc("0")
else
Print " found a invalid character, invalid cusip"
return
end if
End switch
If and(i, 1) = 0 v = v * 2
sum = sum + int(v / 10) + mod(v, 10)
Next
sum = mod(10 - mod(sum, 10), 10)
If sum = asc(mid$(inputStr$, 9, 1)) - Asc("0") Then
Print " is valid"
Else
Print " is invalid"
End If
End Sub
// ------=< MAIN >=------
Data "037833100", "17275R102", "38259P508"
Data "594918104", "68389X106", "68389X105", ""
Print
do
Read inputStr$
if inputStr$ = "" break
cusip(inputStr$)
loop
|
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.
| #D | D | void main() {
import std.stdio, std.conv, std.string;
int nRow, nCol;
write("Give me the numer of rows: ");
try {
nRow = readln.strip.to!int;
} catch (StdioException) {
nRow = 3;
writeln;
}
write("Give me the numer of columns: ");
try {
nCol = readln.strip.to!int;
} catch (StdioException) {
nCol = 5;
writeln;
}
auto array = new float[][](nRow, nCol);
array[0][0] = 3.5;
writeln("The number at place [0, 0] is ", array[0][0]);
} |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Groovy | Groovy | List samples = []
def stdDev = { def sample ->
samples << sample
def sum = samples.sum()
def sumSq = samples.sum { it * it }
def count = samples.size()
(sumSq/count - (sum/count)**2)**0.5
}
[2,4,4,4,5,5,7,9].each {
println "${stdDev(it)}"
} |
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
| #J | J | ((i.32) e. 32 26 23 22 16 12 11 10 8 7 5 4 2 1 0) 128!:3 'The quick brown fox jumps over the lazy dog'
_3199229127 |
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
| #Java | Java | import java.util.zip.* ;
public class CRCMaker {
public static void main( String[ ] args ) {
String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
CRC32 myCRC = new CRC32( ) ;
myCRC.update( toBeEncoded.getBytes( ) ) ;
System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ;
}
} |
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.
| #C.2B.2B | C++ |
#include <iostream>
#include <stack>
#include <vector>
struct DataFrame {
int sum;
std::vector<int> coins;
std::vector<int> avail_coins;
};
int main() {
std::stack<DataFrame> s;
s.push({ 100, {}, { 25, 10, 5, 1 } });
int ways = 0;
while (!s.empty()) {
DataFrame top = s.top();
s.pop();
if (top.sum < 0) continue;
if (top.sum == 0) {
++ways;
continue;
}
if (top.avail_coins.empty()) continue;
DataFrame d = top;
d.sum -= top.avail_coins[0];
d.coins.push_back(top.avail_coins[0]);
s.push(d);
d = top;
d.avail_coins.erase(std::begin(d.avail_coins));
s.push(d);
}
std::cout << ways << std::endl;
return 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
| #Arturo | Arturo | countOccurrences: function [str, substr]-> size match str substr
loop [["the three truths" "th"] ["ababababab" "abab"]] 'pair ->
print [
~"occurrences of '|last pair|' in '|first pair|':"
countOccurrences first pair last pair
] |
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
| #AutoHotkey | AutoHotkey | MsgBox % countSubstring("the three truths","th") ; 3
MsgBox % countSubstring("ababababab","abab") ; 2
CountSubstring(fullstring, substring){
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
} |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program countoctal.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii "Count : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r4,#0 @ loop indice
1: @ begin loop
mov r0,r4
ldr r1,iAdrsMessValeur
bl conversion8 @ call conversion octal
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r4,#1
cmp r4,#64
ble 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to octal */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion8:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
mov r1,r0
lsr r0,#3 @ / by 8
sub r1,r0,lsl #3 @ compute remainder r1 - (r0 * 8)
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
|
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
| #Arturo | Arturo | loop 1..30 'x [
fs: [1]
if x<>1 -> fs: factors.prime x
print [pad to :string x 3 "=" join.with:" x " to [:string] fs]
] |
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.
| #BQN | BQN | Tag ← {∾"<"‿𝕨‿">"‿𝕩‿"</"‿𝕨‿">"}
•Show "table" Tag ∾∾⟜(@+10)¨("tr"Tag∾)¨⟨"th"⊸Tag¨ ""<⊸∾⥊¨"XYZ"⟩∾("td" Tag •Fmt)¨¨ 0‿0‿1‿2 + 1‿3‿3‿3 × 4/⟨↕4⟩ |
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
| #Nanoquery | Nanoquery | import Nanoquery.Util
d = new(Date)
println d.getYear() + "-" + d.getMonth() + "-" + d.getDay()
println d.getDayOfWeek() + ", " + d.getMonthName() + " " + d.getDay() + ", " + d.getYear() |
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
| #Neko | Neko | /**
<doc>
<h2>Date format</h2>
<p>Neko uses Int32 to store system date/time values.
And lib C strftime style formatting for converting to string form</p>
</doc>
*/
var date_now = $loader.loadprim("std@date_now", 0)
var date_format = $loader.loadprim("std@date_format", 2)
var now = date_now()
$print(date_format(now, "%F"), "\n")
$print(date_format(now, "%A, %B %d, %Y"), "\n") |
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.
| #Go | Go | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
var m = mat.NewDense(4, 4, []float64{
2, -1, 5, 1,
3, 2, 2, -6,
1, 3, 3, -1,
5, -2, -3, 3,
})
var v = []float64{-3, -32, -47, 49}
func main() {
x := make([]float64, len(v))
b := make([]float64, len(v))
d := mat.Det(m)
for c := range v {
mat.Col(b, c, m)
m.SetCol(c, v)
x[c] = mat.Det(m) / d
m.SetCol(c, b)
}
fmt.Println(x)
} |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #COBOL | COBOL | identification division.
program-id. create-a-file.
data division.
working-storage section.
01 skip pic 9 value 2.
01 file-name.
05 value "/output.txt".
01 dir-name.
05 value "/docs".
01 file-handle usage binary-long.
procedure division.
files-main.
*> create in current working directory
perform create-file-and-dir
*> create in root of file system, will fail without privilege
move 1 to skip
perform create-file-and-dir
goback.
create-file-and-dir.
*> create file in current working dir, for read/write
call "CBL_CREATE_FILE" using file-name(skip:) 3 0 0 file-handle
if return-code not equal 0 then
display "error: CBL_CREATE_FILE " file-name(skip:) ": "
file-handle ", " return-code upon syserr
end-if
*> create dir below current working dir, owner/group read/write
call "CBL_CREATE_DIR" using dir-name(skip:)
if return-code not equal 0 then
display "error: CBL_CREATE_DIR " dir-name(skip:) ": "
return-code upon syserr
end-if
.
end program create-a-file. |
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).
| #Common_Lisp | Common Lisp | (defvar *csv* "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!")
(defun split-string (string delim-char)
(let ((result '()))
(do* ((start 0 (1+ end))
(end (position delim-char string)
(position delim-char string :start start)))
((not end) (reverse (cons (subseq string start) result)))
(push (subseq string start end) result))))
;;; HTML escape code modified from:
;;; http://www.gigamonkeys.com/book/practical-an-html-generation-library-the-interpreter.html
(defun escape-char (char)
(case char
(#\& "&")
(#\< "<")
(#\> ">")
(t (format nil "&#~d;" (char-code char)))))
(defun escape (in)
(let ((to-escape "<>&"))
(flet ((needs-escape-p (char) (find char to-escape)))
(with-output-to-string (out)
(loop for start = 0 then (1+ pos)
for pos = (position-if #'needs-escape-p in :start start)
do (write-sequence in out :start start :end pos)
when pos do (write-sequence (escape-char (char in pos)) out)
while pos)))))
(defun html-row (values headerp)
(let ((tag (if headerp "th" "td")))
(with-output-to-string (out)
(write-string "<tr>" out)
(dolist (val values)
(format out "<~A>~A</~A>" tag (escape val) tag))
(write-string "</tr>" out))))
(defun csv->html (csv)
(let* ((lines (split-string csv #\Newline))
(cols (split-string (first lines) #\,))
(rows (mapcar (lambda (row) (split-string row #\,)) (rest lines))))
(with-output-to-string (html)
(format html "<table>~C" #\Newline)
(format html "~C~A~C" #\Tab (html-row cols t) #\Newline)
(dolist (row rows)
(format html "~C~A~C" #\Tab (html-row row nil) #\Newline))
(write-string "</table>" html)))) |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #J | J | data=: (','&splitstring);.2 freads 'rc_csv.csv' NB. read and parse data
data=: (<'"spam"') (<2 3)} data NB. amend cell in 3rd row, 4th column (0-indexing)
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data NB. format and write out amended data |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Java | Java | import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
} |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Ring | Ring | # Project : Damm algorithm
matrix = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]
see "5724" + encode(5724 ) + nl
see "5727" + encode(5727 ) + nl
see "112946" + encode(112946) + nl
func encode(n)
check = 0
for d in string(n)
check = matrix[check+1][d-'0'+1]
next
if check = 0
return " is valid"
else
return " is invalid"
ok |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Ruby | Ruby | TABLE = [
[0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3],
[4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6],
[6,1,2,3,0,4,5,9,7,8], [3,6,7,4,2,0,9,5,8,1],
[5,8,6,9,7,2,0,1,3,4], [8,9,4,5,3,6,2,0,1,7],
[9,4,3,8,6,1,7,2,0,5], [2,5,8,1,4,3,6,7,9,0]
]
def damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| TABLE[idx][a] } == 0
[5724, 5727, 112946].each{|n| puts "#{n}: #{damm_valid?(n) ? "" : "in"}valid"}
|
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Ring | Ring |
load "stdlib.ring"
sum = 0
limit = 1000
see "First 200 cuban primes:" + nl
for n = 1 to limit
pr = pow(n+1,3) - pow(n,3)
if isprime(pr)
sum = sum + 1
if sum < 201
see "" + pr + " "
else
exit
ok
ok
next
see "done..." + nl
|
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Ruby | Ruby | require "openssl"
RE = /(\d)(?=(\d\d\d)+(?!\d))/ # Activesupport uses this for commatizing
cuban_primes = Enumerator.new do |y|
(1..).each do |n|
cand = 3*n*(n+1) + 1
y << cand if OpenSSL::BN.new(cand).prime?
end
end
def commatize(num)
num.to_s.gsub(RE, "\\1,")
end
cbs = cuban_primes.take(200)
formatted = cbs.map{|cb| commatize(cb).rjust(10) }
puts formatted.each_slice(10).map(&:join)
t0 = Time.now
puts "
100_000th cuban prime is #{commatize( cuban_primes.take(100_000).last)}
which took #{(Time.now-t0).round} seconds to calculate." |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #zkl | zkl | var Date=Time.Date;
fcn add12h(dt){
re:=RegExp(0'|(\w+)\s+(\d+)\s+(\d+)\ +(.+)\s|);
re.search(dt);
_,M,D,Y,hms:=re.matched; //"March","7","2009","7:30pm"
M=Date.monthNames.index(M); //3
h,m,s:=Date.parseTime(hms); //19,30,0
dti:=T(Y,M,D, h,m,s).apply("toInt");
Y,M,D, h,m,s=Date.addHMS(dti,12);
"%s %d %d %s".fmt(Date.monthNames[M],D,Y,Date.toAMPMString(h,m));
} |
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.
| #OCaml | OCaml | #load "unix.cma"
open Unix
try
for i = 2008 to 2121 do
(* I'm lazy so we'll just borrow the current time
instead of having to set all the fields explicitly *)
let mytime = { (localtime (time ())) with
tm_year = i - 1900;
tm_mon = 11;
tm_mday = 25 } in
try
let _, mytime = mktime mytime in
if mytime.tm_wday = 0 then
Printf.printf "25 December %d is Sunday\n" i
with e ->
Printf.printf "%d is the last year we can specify\n" (i-1);
raise e
done
with _ -> () |
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.
| #Oforth | Oforth | import: date
seqFrom(2008, 2121) filter(#[ 12 25 Date newDate dayOfWeek Date.SUNDAY == ]) . |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Zig | Zig | const std = @import("std");
const print = std.debug.print;
pub fn CusipCheckDigit(cusip: *const [9:0]u8) bool {
var i: usize = 0;
var sum: i32 = 0;
while (i < 8) {
const c = cusip[i];
var v: i32 = undefined;
if (c <= '9' and c >= '0') {
v = c - 48;
}
else if (c <= 'Z' and c >= 'A') {
v = c - 55;
}
else if (c == '*') {
v = 36;
}
else if (c == '@') {
v = 37;
}
else if (c == '#') {
v = 38;
}
else {
return false;
}
if (i % 2 == 1) {
v *= 2;
}
sum = sum + @divFloor(v, 10) + @mod(v, 10);
i += 1;
}
return (cusip[8] - 48 == @mod((10 - @mod(sum, 10)), 10));
}
pub fn main() void {
const cusips = [_]*const [9:0]u8 {
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
};
for (cusips) |cusip| {
print("{s} -> {}\n", .{cusip, CusipCheckDigit(cusip)});
}
}
|
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #zkl | zkl | fcn cusipCheckDigit(cusip){
var [const] vs=[0..9].chain(["A".."Z"],T("*","@","#")).pump(String);
try{
sum:=Walker.cycle(1,2).zipWith(fcn(n,c){ v:=vs.index(c)*n; v/10 + v%10 },
cusip[0,8]).reduce('+);
((10 - sum%10)%10 == cusip[8].toInt()) and cusip.len()==9
}catch{ False }
} |
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.
| #Delphi | Delphi | program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
matrix:array of array of Byte;
i,j:Integer;
begin
Randomize;
//Finalization is not required in this case, but you have to do
//so when reusing the variable in scope
Finalize(matrix);
//Init first dimension with random size from 1..10
//Remember dynamic arrays are indexed from 0
SetLength(matrix,Random(10) + 1);
//Init 2nd dimension with random sizes too
for i := Low(matrix) to High(matrix) do
SetLength(matrix[i],Random(10) + 1);
//End of code, the following part is just output
Writeln(Format('Total amount of columns = %.2d',[Length(matrix)]));
for i := Low(matrix) to High(matrix) do
Writeln(Format('Column %.2d = %.2d rows',[i,Length(matrix[i])]));
Readln;
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
| #Haskell | Haskell | {-# LANGUAGE BangPatterns #-}
import Data.List (foldl') -- '
import Data.STRef
import Control.Monad.ST
data Pair a b = Pair !a !b
sumLen :: [Double] -> Pair Double Double
sumLen = fiof2 . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) --'
where fiof2 (Pair s l) = Pair s (fromIntegral l)
divl :: Pair Double Double -> Double
divl (Pair _ 0.0) = 0.0
divl (Pair s l) = s / l
sd :: [Double] -> Double
sd xs = sqrt $ foldl' (\a x -> a+(x-m)^2) 0 xs / l --'
where p@(Pair s l) = sumLen xs
m = divl p
mkSD :: ST s (Double -> ST s Double)
mkSD = go <$> newSTRef []
where go acc x =
modifySTRef acc (x:) >> (sd <$> readSTRef acc)
main = mapM_ print $ runST $
mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0] |
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
| #JavaScript | JavaScript | (() => {
'use strict';
// --------------------- CRC-32 ----------------------
// crc32 :: String -> Int
const crc32 = str => {
// table :: [Int]
const table = enumFromTo(0)(255).map(
n => take(9)(
iterate(
x => (
x & 1 ? (
z => 0xEDB88320 ^ z
) : identity
)(x >>> 1)
)(n)
)[8]
);
return chars(str).reduce(
(a, c) => (a >>> 8) ^ table[
(a ^ c.charCodeAt(0)) & 255
],
-1
) ^ -1;
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
showHex(
crc32('The quick brown fox jumps over the lazy dog')
);
// --------------------- GENERIC ---------------------
// chars :: String -> [Char]
const chars = s =>
s.split('');
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => !isNaN(m) ? (
Array.from({
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
// identity :: a -> a
const identity = x =>
// The identity function.
x;
// iterate :: (a -> a) -> a -> Gen [a]
const iterate = f =>
// An infinite list of repeated
// applications of f to x.
function* (x) {
let v = x;
while (true) {
yield(v);
v = f(v);
}
};
// showHex :: Int -> String
const showHex = n =>
// Hexadecimal string for a given integer.
'0x' + n.toString(16);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// MAIN -------------
const result = main();
return (
console.log(result),
result
);
})(); |
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.
| #Clojure | Clojure | (def denomination-kind [1 5 10 25])
(defn- cc [amount denominations]
(cond (= amount 0) 1
(or (< amount 0) (empty? denominations)) 0
:else (+ (cc amount (rest denominations))
(cc (- amount (first denominations)) denominations))))
(defn count-change
"Calculates the number of times you can give change with the given denominations."
[amount denominations]
(cc amount denominations))
(count-change 15 denomination-kind) ; = 6 |
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
| #AWK | AWK | #
# countsubstring(string, pattern)
# Returns number of occurrences of pattern in string
# Pattern treated as a literal string (regex characters not expanded)
#
function countsubstring(str, pat, len, i, c) {
c = 0
if( ! (len = length(pat) ) )
return 0
while(i = index(str, pat)) {
str = substr(str, i + len)
c++
}
return c
}
#
# countsubstring_regex(string, regex_pattern)
# Returns number of occurrences of pattern in string
# Pattern treated as regex
#
function countsubstring_regex(str, pat, c) {
c = 0
c += gsub(pat, "", str)
return c
}
BEGIN {
print countsubstring("[do&d~run?d!run&>run&]", "run&")
print countsubstring_regex("[do&d~run?d!run&>run&]", "run[&]")
print countsubstring("the three truths","th")
} |
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
| #BaCon | BaCon | FUNCTION Uniq_Tally(text$, part$)
LOCAL x
WHILE TALLY(text$, part$)
INCR x
text$ = MID$(text$, INSTR(text$, part$)+LEN(part$))
WEND
RETURN x
END FUNCTION
PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th")
PRINT "ababababab - abab: ", Uniq_Tally("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.
| #Arturo | Arturo | loop 1..40 'i ->
print ["number in base 10:" pad to :string i 2
"number in octal:" pad as.octal i 2] |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #AutoHotkey | AutoHotkey | DllCall("AllocConsole")
Octal(int){
While int
out := Mod(int, 8) . out, int := int//8
return out
}
Loop
{
FileAppend, % Octal(A_Index) "`n", CONOUT$
Sleep 200
} |
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
| #AutoHotkey | AutoHotkey | factorize(n){
if n = 1
return 1
if n < 1
return false
result := 0, m := n, k := 2
While n >= k{
while !Mod(m, k){
result .= " * " . k, m /= k
}
k++
}
return SubStr(result, 5)
}
Loop 22
out .= A_Index ": " factorize(A_index) "`n"
MsgBox % out |
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.
| #Bracmat | Bracmat | ( ( makeTable
= headTexts
minRowNr
maxRowNr
headCells
cells
rows
Generator
Table
. get$"xmlio.bra" { A library that converts from Bracmat format to XML or HTML }
& !arg:(?headTexts.?minRowNr.?maxRowNr.?Generator)
& ( headCells
= cellText
. !arg:%?cellText ?arg
& (th.,!cellText) headCells$!arg
|
)
& ( cells
= cellText cellTexts numberGenerator
. !arg
: (%?cellText ?cellTexts.(=?numberGenerator))
& (td.,numberGenerator$)
cells$(!cellTexts.'$numberGenerator)
|
)
& ( rows
= headTexts rowNr maxRowNr Generator
. !arg:(?headTexts.?rowNr.?maxRowNr.?Generator)
& !rowNr:~>!maxRowNr
& ( tr
.
, (td.,!rowNr)
cells$(!headTexts.!Generator)
)
\n
rows$(!headTexts.!rowNr+1.!maxRowNr.!Generator)
|
)
& ( table
.
, ( thead
. (align.right)
, \n (tr.,(th.," ") headCells$!headTexts)
)
\n
( tbody
. (align.right)
, \n
rows
$ (!headTexts.!minRowNr.!maxRowNr.!Generator)
)
)
: ?Table
& str$((XMLIO.convert)$!Table) { Call library function to create HTML }
)
& makeTable
$ ( X Y Z { Column headers }
. 1 { Lowest row number }
. 4 { Highest row number }
. { Function that generates numbers 9, 10, ...}
' ( cnt
. (cnt=$(new$(==8))) { This creates an object 'cnt' with scope as a local function variable that survives between calls. }
& !(cnt.)+1:?(cnt.)
)
)
) |
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
| #NetRexx | NetRexx |
import java.text.SimpleDateFormat
say SimpleDateFormat("yyyy-MM-dd").format(Date())
say SimpleDateFormat("EEEE, MMMM dd, yyyy").format(Date())
|
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
| #NewLISP | NewLISP | ; file: date-format.lsp
; url: http://rosettacode.org/wiki/Date_format
; author: oofoe 2012-02-01
; The "now" function returns the current time as a list. A time zone
; offset in minutes can be supplied. The example below is for Eastern
; Standard Time. NewLISP's implicit list indexing is used to extract
; the first three elements of the returned list (year, month and day).
(setq n (now (* -5 60)))
(println "short: " (format "%04d-%02d-%02d" (n 0) (n 1) (n 2)))
; The "date-value" function returns the time in seconds from the epoch
; when used without arguments. The "date" function converts the
; seconds into a time representation specified by the format string at
; the end. The offset argument ("0" in this example) specifies a
; time-zone offset in minutes.
(println "short: " (date (date-value) 0 "%Y-%m-%d"))
; The time formatting is supplied by the underlying C library, so
; there may be differences on certain platforms. Particularly, leading
; zeroes in day numbers can be suppressed with "%-d" on Linux and
; FreeBSD, "%e" on OpenBSD, SunOS/Solaris and Mac OS X. Use "%#d" for
; Windows.
(println "long: " (date (date-value) 0 "%A, %B %#d, %Y"))
; By setting the locale, the date will be displayed appropriately:
(set-locale "japanese")
(println "long: " (date (date-value) 0 "%A, %B %#d, %Y"))
(exit) |
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.
| #Groovy | Groovy | class CramersRule {
static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),
Arrays.asList(3d, 2d, 2d, -6d),
Arrays.asList(1d, 3d, 3d, -1d),
Arrays.asList(5d, -2d, -3d, 3d))
List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d)
println("Solution = " + cramersRule(mat, b))
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant()
List<Double> result = new ArrayList<>()
for (int i = 0; i < b.size(); i++) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator)
}
return result
}
private static class Matrix {
private List<List<Double>> matrix
@Override
String toString() {
return matrix.toString()
}
@SafeVarargs
Matrix(List<Double>... lists) {
matrix = new ArrayList<>()
for (List<Double> list : lists) {
matrix.add(list)
}
}
Matrix(List<List<Double>> mat) {
matrix = mat
}
double determinant() {
if (matrix.size() == 1) {
return get(0, 0)
}
if (matrix.size() == 2) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0)
}
double sum = 0
double sign = 1
for (int i = 0; i < matrix.size(); i++) {
sum += sign * get(0, i) * coFactor(0, i).determinant()
sign *= -1
}
return sum
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>()
for (int i = 0; i < matrix.size(); i++) {
if (i == row) {
continue
}
List<Double> list = new ArrayList<>()
for (int j = 0; j < matrix.size(); j++) {
if (j == col) {
continue
}
list.add(get(i, j))
}
mat.add(list)
}
return new Matrix(mat)
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>()
for (int row = 0; row < matrix.size(); row++) {
List<Double> list = new ArrayList<>()
for (int col = 0; col < matrix.size(); col++) {
double value = get(row, col)
if (col == column) {
value = b.get(row)
}
list.add(value)
}
mat.add(list)
}
return new Matrix(mat)
}
private double get(int row, int col) {
return matrix.get(row).get(col)
}
}
} |
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.
| #Common_Lisp | Common Lisp | (let ((stream (open "output.txt" :direction :output)))
(close stream)) |
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.
| #Component_Pascal | Component Pascal |
MODULE CreateFile;
IMPORT Files, StdLog;
PROCEDURE Do*;
VAR
f: Files.File;
res: INTEGER;
BEGIN
f := Files.dir.New(Files.dir.This("docs"),Files.dontAsk);
f.Register("output","txt",TRUE,res);
f.Close();
f := Files.dir.New(Files.dir.This("C:\AEAT\docs"),Files.dontAsk);
f.Register("output","txt",TRUE,res);
f.Close()
END Do;
END CreateFile.
|
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).
| #D | D | void main() {
import std.stdio;
immutable input =
"Character,Speech\n" ~
"The multitude,The messiah! Show us the messiah!\n" ~
"Brians mother,<angry>Now you listen here! He's not the messiah; " ~
"he's a very naughty boy! Now go away!</angry>\n" ~
"The multitude,Who are you?\n" ~
"Brians mother,I'm his mother; that's who!\n" ~
"The multitude,Behold his mother! Behold his mother!";
"<html>\n<head><meta charset=\"utf-8\"></head>\n<body>\n\n".write;
"<table border=\"1\" cellpadding=\"5\" cellspacing=\"0\">\n<thead>\n <tr><td>".write;
bool theadDone = false;
foreach (immutable c; input) {
switch(c) {
case '\n':
if (theadDone) {
"</td></tr>\n <tr><td>".write;
} else {
"</td></tr>\n</thead>\n<tbody>\n <tr><td>".write;
theadDone = true;
}
break;
case ',': "</td><td>".write; break;
case '<': "<".write; break;
case '>': ">".write; break;
case '&': "&".write; break;
default: c.write; break;
}
}
"</td></tr>\n</tbody>\n</table>\n\n</body></html>".write;
} |
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.
| #JavaScript | JavaScript | (function () {
'use strict';
// splitRegex :: Regex -> String -> [String]
function splitRegex(rgx, s) {
return s.split(rgx);
}
// lines :: String -> [String]
function lines(s) {
return s.split(/[\r\n]/);
}
// unlines :: [String] -> String
function unlines(xs) {
return xs.join('\n');
}
// macOS JavaScript for Automation version of readFile.
// Other JS contexts will need a different definition of this function,
// and some may have no access to the local file system at all.
// readFile :: FilePath -> maybe String
function readFile(strPath) {
var error = $(),
str = ObjC.unwrap(
$.NSString.stringWithContentsOfFileEncodingError(
$(strPath)
.stringByStandardizingPath,
$.NSUTF8StringEncoding,
error
)
);
return error.code ? error.localizedDescription : str;
}
// macOS JavaScript for Automation version of writeFile.
// Other JS contexts will need a different definition of this function,
// and some may have no access to the local file system at all.
// writeFile :: FilePath -> String -> IO ()
function writeFile(strPath, strText) {
$.NSString.alloc.initWithUTF8String(strText)
.writeToFileAtomicallyEncodingError(
$(strPath)
.stringByStandardizingPath, false,
$.NSUTF8StringEncoding, null
);
}
// EXAMPLE - appending a SUM column
var delimCSV = /,\s*/g;
var strSummed = unlines(
lines(readFile('~/csvSample.txt'))
.map(function (x, i) {
var xs = x ? splitRegex(delimCSV, x) : [];
return (xs.length ? xs.concat(
// 'SUM' appended to first line, others summed.
i > 0 ? xs.reduce(
function (a, b) {
return a + parseInt(b, 10);
}, 0
).toString() : 'SUM'
) : []).join(',');
})
);
return (
writeFile('~/csvSampleSummed.txt', strSummed),
strSummed
);
})(); |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Rust | Rust | fn damm(number: &str) -> u8 {
static TABLE: [[u8; 10]; 10] = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
];
number.chars().fold(0, |row, digit| {
let digit = digit.to_digit(10).unwrap();
TABLE[row as usize][digit as usize]
})
}
fn damm_validate(number: &str) -> bool {
damm(number) == 0
}
fn main() {
let numbers = &["5724", "5727", "112946"];
for number in numbers {
let is_valid = damm_validate(number);
if is_valid {
println!("{:>6} is valid", number);
} else {
println!("{:>6} is invalid", number);
}
}
} |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Scala | Scala | import scala.annotation.tailrec
object DammAlgorithm extends App {
private val numbers = Seq(5724, 5727, 112946, 112949)
@tailrec
private def damm(s: String, interim: Int): String = {
def table =
Vector(
Vector(0, 3, 1, 7, 5, 9, 8, 6, 4, 2),
Vector(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
Vector(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),
Vector(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),
Vector(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),
Vector(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),
Vector(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),
Vector(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),
Vector(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),
Vector(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
)
if (s.isEmpty) if (interim == 0) "✔" else "✘"
else damm(s.tail, table(interim)(s.head - '0'))
}
for (number <- numbers) println(f"$number%6d is ${damm(number.toString, 0)}.")
} |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Rust | Rust | use std::time::Instant;
use separator::Separatable;
const NUMBER_OF_CUBAN_PRIMES: usize = 200;
const COLUMNS: usize = 10;
const LAST_CUBAN_PRIME: usize = 100_000;
fn main() {
println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME);
let start = Instant::now();
let mut i: u64 = 0;
let mut j: u64 = 1;
let mut index: usize = 0;
let mut cuban_primes = Vec::new();
let mut cuban: u64 = 0;
while index < 100_000 {
cuban = {j += 1; j}.pow(3) - {i += 1; i}.pow(3);
if primal::is_prime(cuban) {
if index < NUMBER_OF_CUBAN_PRIMES {
cuban_primes.push(cuban);
}
index += 1;
}
}
let elapsed = start.elapsed();
println!("THE {} FIRST CUBAN PRIMES:", NUMBER_OF_CUBAN_PRIMES);
cuban_primes
.chunks(COLUMNS)
.map(|chunk| {
chunk.iter()
.map(|item| {
print!("{}\t", item)
})
.for_each(drop);
println!("");
})
.for_each(drop);
println!("The {}th cuban prime number is {}", LAST_CUBAN_PRIME, cuban.separated_string());
println!("Elapsed time: {:?}", elapsed);
} |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Scala | Scala | import spire.math.SafeLong
import spire.implicits._
import scala.annotation.tailrec
import scala.collection.parallel.immutable.ParVector
object CubanPrimes {
def main(args: Array[String]): Unit = {
println(formatTable(cubanPrimes.take(200).toVector, 10))
println(f"The 100,000th cuban prime is: ${getNthCubanPrime(100000).toBigInt}%,d")
}
def cubanPrimes: LazyList[SafeLong] = cubans.filter(isPrime)
def cubans: LazyList[SafeLong] = LazyList.iterate(SafeLong(0))(_ + 1).map(n => (n + 1).pow(3) - n.pow(3))
def isPrime(num: SafeLong): Boolean = (num > 1) && !(SafeLong(2) #:: LazyList.iterate(SafeLong(3)){n => n + 2}).takeWhile(n => n*n <= num).exists(num%_ == 0)
def getNthCubanPrime(num: Int): SafeLong = {
@tailrec
def nHelper(rem: Int, src: LazyList[SafeLong]): SafeLong = {
val cprimes = src.take(100000).to(ParVector).filter(isPrime)
if(cprimes.size < rem) nHelper(rem - cprimes.size, src.drop(100000))
else cprimes.toVector.sortWith(_<_)(rem - 1)
}
nHelper(num, cubans)
}
def formatTable(lst: Vector[SafeLong], rlen: Int): String = {
@tailrec
def fHelper(ac: Vector[String], src: Vector[String]): String = {
if(src.nonEmpty) fHelper(ac :+ src.take(rlen).mkString, src.drop(rlen))
else ac.mkString("\n")
}
val maxLen = lst.map(n => f"${n.toBigInt}%,d".length).max
val formatted = lst.map(n => s"%,${maxLen + 2}d".format(n.toInt))
fHelper(Vector[String](), formatted)
}
} |
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.
| #ooRexx | ooRexx | date = .datetime~new(2008, 12, 25)
lastdate = .datetime~new(2121, 12, 25)
resultList = .array~new -- our collector of years
-- date objects are directly comparable
loop while date <= lastdate
if date~weekday == 7 then resultList~append(date~year)
-- step to the next year
date = date~addYears(1)
end
say "Christmas falls on Sunday in the years" resultList~toString("Line", ", ") |
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.
| #Elena | Elena | import extensions;
public program()
{
var n := new Integer();
var m := new Integer();
console.write:"Enter two space delimited integers:";
console.loadLine(n,m);
var myArray := class Matrix<int>.allocate(n,m);
myArray.setAt(0,0,2);
console.printLine(myArray.at(0, 0))
} |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Elixir | Elixir |
defmodule TwoDimArray do
def create(w, h) do
List.duplicate(0, w)
|> List.duplicate(h)
end
def set(arr, x, y, value) do
List.replace_at(arr, x,
List.replace_at(Enum.at(arr, x), y, value)
)
end
def get(arr, x, y) do
arr |> Enum.at(x) |> Enum.at(y)
end
end
width = IO.gets "Enter Array Width: "
w = width |> String.trim() |> String.to_integer()
height = IO.gets "Enter Array Height: "
h = height |> String.trim() |> String.to_integer()
arr = TwoDimArray.create(w, h)
arr = TwoDimArray.set(arr,2,0,42)
IO.puts(TwoDimArray.get(arr,2,0))
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Haxe | Haxe | using Lambda;
class Main {
static function main():Void {
var nums = [2, 4, 4, 4, 5, 5, 7, 9];
for (i in 1...nums.length+1)
Sys.println(sdev(nums.slice(0, i)));
}
static function average<T:Float>(nums:Array<T>):Float {
return nums.fold(function(n, t) return n + t, 0) / nums.length;
}
static function sdev<T:Float>(nums:Array<T>):Float {
var store = [];
var avg = average(nums);
for (n in nums) {
store.push((n - avg) * (n - avg));
}
return Math.sqrt(average(store));
}
} |
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
| #Jsish | Jsish | # Util.crc32('The quick brown fox jumps over the lazy dog').toString(16); |
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
| #Julia | Julia | using Libz
println(string(Libz.crc32(UInt8.(b"The quick brown fox jumps over the lazy dog")), base=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.
| #COBOL | COBOL |
identification division.
program-id. CountCoins.
data division.
working-storage section.
77 i pic 9(3).
77 j pic 9(3).
77 m pic 9(3) value 4.
77 n pic 9(3) value 100.
77 edited-value pic z(18).
01 coins-table value "01051025".
05 coin pic 9(2) occurs 4.
01 ways-table.
05 way pic 9(18) occurs 100.
procedure division.
main.
perform calc-count
move way(n) to edited-value
display function trim(edited-value)
stop run
.
calc-count.
initialize ways-table
move 1 to way(1)
perform varying i from 1 by 1 until i > m
perform varying j from coin(i) by 1 until j > n
add way(j - coin(i)) to way(j)
end-perform
end-perform
.
|
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
| #BASIC | BASIC | DECLARE FUNCTION countSubstring& (where AS STRING, what AS STRING)
PRINT "the three truths, th:", countSubstring&("the three truths", "th")
PRINT "ababababab, abab:", countSubstring&("ababababab", "abab")
FUNCTION countSubstring& (where AS STRING, what AS STRING)
DIM c AS LONG, s AS LONG
s = 1 - LEN(what)
DO
s = INSTR(s + LEN(what), where, what)
IF 0 = s THEN EXIT DO
c = c + 1
LOOP
countSubstring = c
END FUNCTION |
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.
| #AWK | AWK | BEGIN {
for (l = 0; l <= 2147483647; l++) {
printf("%o\n", l);
}
} |
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.
| #BASIC | BASIC | DIM n AS LONG
FOR n = 0 TO &h7FFFFFFF
PRINT OCT$(n)
NEXT |
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
| #AWK | AWK |
# syntax: GAWK -f COUNT_IN_FACTORS.AWK
BEGIN {
fmt = "%d=%s\n"
for (i=1; i<=16; i++) {
printf(fmt,i,factors(i))
}
i = 2144; printf(fmt,i,factors(i))
i = 6358; printf(fmt,i,factors(i))
exit(0)
}
function factors(n, f,p) {
if (n == 1) {
return(1)
}
p = 2
while (p <= n) {
if (n % p == 0) {
f = sprintf("%s%s*",f,p)
n /= p
}
else {
p++
}
}
return(substr(f,1,length(f)-1))
}
|
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
printf("<table style=\"text-align:center; border: 1px solid\"><th></th>"
"<th>X</th><th>Y</th><th>Z</th>");
for (i = 0; i < 4; i++) {
printf("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>", i,
rand() % 10000, rand() % 10000, rand() % 10000);
}
printf("</table>");
return 0;
} |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Nim | Nim | import times
var t = now()
echo(t.format("yyyy-MM-dd"))
echo(t.format("dddd',' MMMM d',' yyyy")) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Objeck | Objeck |
use IO;
use Time;
bundle Default {
class CurrentDate {
function : Main(args : String[]) ~ Nil {
t := Date->New();
Console->Print(t->GetYear())->Print("-")->Print(t->GetMonth())->Print("-")
->PrintLine(t->GetDay());
Console->Print(t->GetDayName())->Print(", ")->Print(t->GetMonthName())
->Print(" ")->Print(t->GetDay())->Print(", ")
->PrintLine(t->GetYear());
}
}
}
|
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.
| #Haskell | Haskell | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = solveCramer a y
where a = fromLists [[2,-1, 5, 1]
,[3, 2, 2,-6]
,[1, 3, 3,-1]
,[5,-2,-3, 3]]
y = fromLists [[-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.
| #Crystal | Crystal | File.write "output.txt", ""
Dir.mkdir "docs"
File.write "/output.txt", ""
Dir.mkdir "/docs" |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #D | D | module fileio ;
import std.stdio ;
import std.path ;
import std.file ;
import std.stream ;
string[] genName(string name){
string cwd = curdir ~ sep ; // on current directory
string root = sep ; // on root
name = std.path.getBaseName(name) ;
return [cwd ~ name, root ~ name] ;
}
void Remove(string target){
if(exists(target)){
if (isfile(target))
std.file.remove(target);
else
std.file.rmdir(target) ;
}
}
void testCreate(string filename, string dirname){
// files:
foreach(fn ; genName(filename))
try{
writefln("file to be created : %s", fn) ;
std.file.write(fn, cast(void[])null) ;
writefln("\tsuccess by std.file.write") ; Remove(fn) ;
(new std.stream.File(fn, FileMode.OutNew)).close() ;
writefln("\tsuccess by std.stream") ; Remove(fn) ;
} catch(Exception e) {
writefln(e.msg) ;
}
// dirs:
foreach(dn ; genName(dirname))
try{
writefln("dir to be created : %s", dn) ;
std.file.mkdir(dn) ;
writefln("\tsuccess by std.file.mkdir") ; Remove(dn) ;
} catch(Exception e) {
writefln(e.msg) ;
}
}
void main(){
writefln("== test: File & Dir Creation ==") ;
testCreate("output.txt", "docs") ;
} |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Delphi | Delphi | program csv2html;
{$APPTYPE CONSOLE}
uses
SysUtils,
Classes;
const
// Carriage Return/Line Feed
CRLF = #13#10;
// The CSV data
csvData =
'Character,Speech'+CRLF+
'The multitude,The messiah! Show us the messiah!'+CRLF+
'Brians mother,<angry>Now you listen here! He''s not the messiah; he''s a very naughty boy! Now go away!</angry>'+CRLF+
'The multitude,Who are you?'+CRLF+
'Brians mother,I''m his mother; that''s who!'+CRLF+
'The multitude,Behold his mother! Behold his mother!';
// HTML header
htmlHead =
'<!DOCTYPE html'+CRLF+
'PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'+CRLF+
'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+CRLF+
'<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+CRLF+
'<head>'+CRLF+
'<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />'+CRLF+
'<title>CSV-to-HTML Conversion</title>'+CRLF+
'<style type="text/css">'+CRLF+
'body {font-family:verdana,helvetica,sans-serif;font-size:100%}'+CRLF+
'table {width:70%;border:0;font-size:80%;margin:auto}'+CRLF+
'th,td {padding:4px}'+CRLF+
'th {text-align:left;background-color:#eee}'+CRLF+
'th.c {width:15%}'+CRLF+
'td.c {width:15%}'+CRLF+
'</style>'+CRLF+
'</head>'+CRLF+
'<body>'+CRLF;
// HTML footer
htmlFoot =
'</body>'+CRLF+
'</html>';
{ Function to split a string into a list using a given delimiter }
procedure SplitString(S, Delim: string; Rslt: TStrings);
var
i: integer;
fld: string;
begin
fld := '';
for i := Length(S) downto 1 do
begin
if S[i] = Delim then
begin
Rslt.Insert(0,fld);
fld := '';
end
else
fld := S[i]+fld;
end;
if (fld <> '') then
Rslt.Insert(0,fld);
end;
{ Simple CSV parser with option to specify that the first row is a header row }
procedure ParseCSV(const csvIn: string; htmlOut: TStrings; FirstRowIsHeader: Boolean = True);
const
rowstart = '<tr><td class="c">';
rowend = '</td></tr>';
cellendstart = '</td><td class="s">';
hcellendstart = '</th><th class="s">';
hrowstart = '<tr><th class="c">';
hrowend = '</th></tr>';
var
tmp,pieces: TStrings;
i: Integer;
begin
// HTML header
htmlOut.Text := htmlHead + CRLF + CRLF;
// Start the HTML table
htmlOut.Text := htmlOut.Text + '<table summary="csv2table conversion">' + CRLF;
// Create stringlist
tmp := TStringList.Create;
try
// Assign CSV data to stringlist and fix occurences of '<' and '>'
tmp.Text := StringReplace(csvIn,'<','<',[rfReplaceAll]);
tmp.Text := StringReplace(tmp.Text,'>','>',[rfReplaceAll]);
// Create stringlist to hold the parts of the split data
pieces := TStringList.Create;
try
// Loop through the CSV rows
for i := 0 to Pred(tmp.Count) do
begin
// Split the current row
SplitString(tmp[i],',',pieces);
// Check if first row and FirstRowIsHeader flag set
if (i = 0) and FirstRowIsHeader then
// Render HTML
htmlOut.Text := htmlOut.Text + hrowstart + pieces[0] + hcellendstart + pieces[1] + hrowend + CRLF
else
htmlOut.Text := htmlOut.Text + rowstart + pieces[0] + cellendstart + pieces[1] + rowend + CRLF;
end;
// Finish the HTML table and end the HTML page
htmlOut.Text := htmlOut.Text + '</table>' + CRLF + htmlFoot;
finally
pieces.Free;
end;
finally
tmp.Free;
end;
end;
var
HTML: TStrings;
begin
// Create stringlist to hold HTML output
HTML := TStringList.Create;
try
Writeln('Basic:');
Writeln('');
// Load and parse the CSV data
ParseCSV(csvData,HTML,False);
// Output the HTML to the console
Writeln(HTML.Text);
// Save the HTML to a file (in application's folder)
HTML.SaveToFile('csv2html_basic.html');
Writeln('');
Writeln('=====================================');
Writeln('');
HTML.Clear;
Writeln('Extra Credit:');
Writeln('');
// Load and parse the CSV data
ParseCSV(csvData,HTML,True);
// Output the HTML to the console
Writeln(HTML.Text);
// Save the HTML to a file (in application's folder)
HTML.SaveToFile('csv2html_extra.html');
Writeln('');
Writeln('=====================================');
finally
HTML.Free;
end;
// Keep console window open
Readln;
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.
| #jq | jq | # Omit empty lines
def read_csv:
split("\n")
| map(if length>0 then split(",") else empty end) ;
# add_column(label) adds a summation column (with the given label) to
# the matrix representation of the CSV table, and assumes that all the
# entries in the body of the CSV file are, or can be converted to,
# numbers:
def add_column(label):
[.[0] + [label],
(reduce .[1:][] as $line
([]; ($line|map(tonumber)) as $line | . + [$line + [$line|add]]))[] ] ;
read_csv | add_column("SUM") | map(@csv)[] |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Julia | Julia | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
|
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Sidef | Sidef | func damm(digits) {
static tbl = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
]
!digits.flip.reduce({|row,col| tbl[row][col] }, 0)
}
for n in [5724, 5727, 112946] {
say "#{n}:\tChecksum digit #{ damm(n.digits) ? '' : 'in'}correct."
} |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Sidef | Sidef | func cuban_primes(n) {
1..Inf -> lazy.map {|k| 3*k*(k+1) + 1 }\
.grep{ .is_prime }\
.first(n)
}
cuban_primes(200).slices(10).each {
say .map { "%9s" % .commify }.join(' ')
}
say ("\n100,000th cuban prime is: ", cuban_primes(1e5).last.commify) |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Transd | Transd |
#lang transd
MainModule: {
primes: Vector<ULong>([3, 5]),
lim: 200,
bigUn: 100000,
chunks: 50,
little: 0,
c: 0,
showEach: true,
u: ULong(0),
v: ULong(1),
_start: (λ found Bool() fnd Bool() mx Int() z ULong()
(= little (/ bigUn chunks))
(for i in Range(1 (pow 2 20)) do
(= found false)
(+= u 6) (+= v u) (= mx (to-Int (sqrt v) 1))
(for item in primes do
(if (> item mx) break)
(if (not (mod v item)) (= found true)
break))
(if (not found)
(+= c 1)
(if showEach
(= z (get primes -1))
(while (< z (- v 2))
(+= z 2) (= fnd false)
(for item in primes do
(if (> item mx) break)
(if (not (mod z item)) (= fnd true)
break))
(if (not fnd) (append primes z)))
(append primes v)
(textout :width 11 :group v)
(if (not (mod c 10)) (textout :nl))
(if (== c lim) (= showEach false)
(textout "Progress to the " :group bigUn
"'th cuban prime:" ))
)
(if (not (mod c little)) (textout "."))
(if (== c bigUn) break)
)
)
(lout "The " :group c "'th cuban prime is " v )
)
}
|
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.
| #PARI.2FGP | PARI/GP |
njd(D) =
{
my (m, y);
if (D[2] > 2, y = D[1]; m = D[2]+1, y = D[1]-1; m = D[2]+13);
(1461*y)\4 + (306001*m)\10000 + D[3] - 694024 + if (100*(100*D[1]+D[2])+D[3] > 15821004, 2 - y\100 + y\400)
}
for (y = 2008, 2121, if (njd([y,12,25]) % 7 == 1, print(y)));
|
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.
| #Erlang | Erlang |
-module( two_dimensional_array ).
-export( [create/2, get/3, set/4, task/0] ).
create( X, Y ) -> array:new( [{size, X}, {default, array:new( [{size, Y}] )}] ).
get( X, Y, Array ) -> array:get( Y, array:get(X, Array) ).
set( X, Y, Value, Array ) ->
Y_array = array:get( X, Array ),
New_y_array = array:set( Y, Value, Y_array ),
array:set( X, New_y_array, Array ).
task() ->
{ok, [X, Y]} = io:fread( "Input two integers. Space delimited, please: ", "~d ~d" ),
Array = create( X, Y ),
New_array = set( X - 1, Y - 1, X * Y, Array ),
io:fwrite( "In position ~p ~p we have ~p~n", [X - 1, Y - 1, get( X - 1, Y - 1, New_array)] ).
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #HicEst | HicEst | REAL :: n=8, set(n), sum=0, sum2=0
set = (2,4,4,4,5,5,7,9)
DO k = 1, n
WRITE() 'Adding ' // set(k) // 'stdev = ' // stdev(set(k))
ENDDO
END ! end of "main"
FUNCTION stdev(x)
USE : sum, sum2, k
sum = sum + x
sum2 = sum2 + x*x
stdev = ( sum2/k - (sum/k)^2) ^ 0.5
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
| #Kotlin | Kotlin | // version 1.0.6
import java.util.zip.CRC32
fun main(args: Array<String>) {
val text = "The quick brown fox jumps over the lazy dog"
val crc = CRC32()
with (crc) {
update(text.toByteArray())
println("The CRC-32 checksum of '$text' = ${"%x".format(value)}")
}
} |
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
| #Lingo | Lingo | crcObj = script("CRC").new()
crc32 = crcObj.crc32("The quick brown fox jumps over the lazy dog")
put crc32
-- <ByteArrayObject length = 4 ByteArray = 0x41, 0x4f, 0xa3, 0x39 >
put crc32.toHexString(1, crc32.length)
-- "41 4f a3 39" |
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.
| #Coco | Coco | changes = (amount, coins) ->
ways = [1].concat [0] * amount
for coin of coins
for j from coin to amount
ways[j] += ways[j - coin]
ways[amount]
console.log changes 100, [1 5 10 25] |
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.
| #Commodore_BASIC | Commodore BASIC | 5 m=100:rem money = $1.00 or 100 pennies.
10 print chr$(147);chr$(14);"This program will calculate the number"
11 print "of combinations of 'change' that can be"
12 print "given for a $1 bill."
13 print:print "The coin values are:"
14 print "0.01 = Penny":print "0.05 = Nickle"
15 print "0.10 = Dime":print "0.25 = Quarter"
16 print
20 print "Would you like to see each combination?"
25 get k$:yn=(k$="y"):if k$="" then 25
100 p=m:ti$="000000"
130 q=int(m/25)
140 count=0:ps=1
147 if yn then print "Count P N D Q"
150 for qc=0 to q:d=int((m-qc*25)/10)
160 for dc=0 to d:n=int((m-dc*10)/5)
170 for nc=0 to n:p=m-nc*5
180 for pc=0 to p step 5
190 s=pc+nc*5+dc*10+qc*25
200 if s=m then count=count+1:if yn then gosub 1000
210 next:next:next:next
245 en$=ti$
250 print:print count;"different combinations found in"
260 print tab(len(str$(count))+1);
265 print left$(en$,2);":";mid$(en$,3,2);":";right$(en$,2);"."
270 end
1000 print count;tab(6);pc;tab(11);nc;tab(16);dc;tab(21);qc:return |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
::Main
call :countString "the three truths","th"
call :countString "ababababab","abab"
pause>nul
exit /b
::/Main
::Procedure
:countString
set input=%~1
set cnt=0
:count_loop
set trimmed=!input:*%~2=!
if "!trimmed!"=="!input!" (echo.!cnt!&goto :EOF)
set input=!trimmed!
set /a cnt+=1
goto count_loop |
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
| #BBC_BASIC | BBC BASIC | tst$ = "the three truths"
sub$ = "th"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
tst$ = "ababababab"
sub$ = "abab"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
END
DEF FNcountSubstring(A$, B$)
LOCAL I%, N%
I% = 1 : N% = 0
REPEAT
I% = INSTR(A$, B$, I%)
IF I% THEN N% += 1 : I% += LEN(B$)
UNTIL I% = 0
= N%
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Batch_File | Batch File |
@echo off
:: {CTRL + C} to exit the batch file
:: Send incrementing decimal values to the :to_Oct function
set loop=0
:loop1
call:to_Oct %loop%
set /a loop+=1
goto loop1
:: Convert the decimal values parsed [%1] to octal and output them on a new line
:to_Oct
set todivide=%1
set "fulloct="
:loop2
set tomod=%todivide%
set /a appendmod=%tomod% %% 8
set fulloct=%appendmod%%fulloct%
if %todivide% lss 8 (
echo %fulloct%
exit /b
)
set /a todivide/=8
goto loop2
|
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.
| #BBC_BASIC | BBC BASIC | N% = 0
REPEAT
PRINT FN_tobase(N%, 8, 0)
N% += 1
UNTIL FALSE
END
REM Convert N% to string in base B% with minimum M% digits:
DEF FN_tobase(N%, B%, M%)
LOCAL D%, A$
REPEAT
D% = N% MOD B%
N% DIV= B%
IF D%<0 D% += B% : N% -= 1
A$ = CHR$(48 + D% - 7*(D%>9)) + A$
M% -= 1
UNTIL (N%=FALSE OR N%=TRUE) AND M%<=0
=A$
|
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
| #BASIC | BASIC | 100 FOR I = 1 TO 20
110 GOSUB 200"FACTORIAL
120 PRINT I" = "FA$
130 NEXT I
140 END
200 FA$ = "1"
210 LET NUM = I
220 LET O = 5 - (I = 1) * 4
230 FOR F = 2 TO I
240 LET M = INT (NUM / F) * F
250 IF NUM - M GOTO 300
260 LET NUM = NUM / F
270 LET F$ = STR $(F)
280 FA$ = FA$ + " X " + F$
290 LET F = F - 1
300 NEXT F
310 FA$ = MID$ (FA$,O)
320 RETURN |
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
| #BBC_BASIC | BBC BASIC | FOR i% = 1 TO 20
PRINT i% " = " FNfactors(i%)
NEXT
END
DEF FNfactors(N%)
LOCAL P%, f$
IF N% = 1 THEN = "1"
P% = 2
WHILE P% <= N%
IF (N% MOD P%) = 0 THEN
f$ += STR$(P%) + " x "
N% DIV= P%
ELSE
P% += 1
ENDIF
ENDWHILE
= LEFT$(f$, LEN(f$) - 3)
|
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.
| #C.23 | C# | using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
StringBuilder s = new StringBuilder();
Random rnd = new Random();
s.AppendLine("<table>");
s.AppendLine("<thead align = \"right\">");
s.Append("<tr><th></th>");
for(int i=0; i<3; i++)
s.Append("<td>" + "XYZ"[i] + "</td>");
s.AppendLine("</tr>");
s.AppendLine("</thead>");
s.AppendLine("<tbody align = \"right\">");
for( int i=0; i<3; i++ )
{
s.Append("<tr><td>"+i+"</td>");
for( int j=0; j<3; j++ )
s.Append("<td>"+rnd.Next(10000)+"</td>");
s.AppendLine("</tr>");
}
s.AppendLine("</tbody>");
s.AppendLine("</table>");
Console.WriteLine( s );
}
}
} |
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
| #Objective-C | Objective-C | NSLog(@"%@", [NSDate date]);
NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil]);
NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%A, %B %d, %Y" timeZone:nil locale:nil]); |
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
| #OCaml | OCaml | # #load "unix.cma";;
# open Unix;;
# let t = time() ;;
val t : float = 1219997516.
# let gmt = gmtime t ;;
val gmt : Unix.tm =
{tm_sec = 56; tm_min = 11; tm_hour = 8; tm_mday = 29; tm_mon = 7;
tm_year = 108; tm_wday = 5; tm_yday = 241; tm_isdst = false}
# Printf.sprintf "%d-%02d-%02d" (1900 + gmt.tm_year) (1 + gmt.tm_mon) gmt.tm_mday ;;
- : string = "2008-08-29" |
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.
| #J | J | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
) |
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.
| #Java | Java |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CramersRule {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),
Arrays.asList(3d, 2d, 2d, -6d),
Arrays.asList(1d, 3d, 3d, -1d),
Arrays.asList(5d, -2d, -3d, 3d));
List<Double> b = Arrays.asList(-3d, -32d, -47d, 49d);
System.out.println("Solution = " + cramersRule(mat, b));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.