task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Create_a_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.
| #Dc | Dc | ! for d in . / ;do > "$d/output.txt" ; mkdir "$d/docs" ;done |
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.
| #DCL | DCL | open/write output_file output.txt
open/write output_file [000000]output.txt
create/directory [.docs]
create/directory [000000.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).
| #EchoLisp | EchoLisp |
;; CSV -> LISTS
(define (csv->row line) (string-split line ","))
(define (csv->table csv) (map csv->row (string-split csv "\n")))
;; LISTS->HTML
(define html 'html)
(define (emit-tag tag html-proc content )
(if (style tag)
(push html (format "<%s style='%a'>" tag (style tag)))
(push html (format "<%s>" tag )))
(html-proc content)
(push html (format "</%s> " tag )))
;; html procs : 1 tag, 1 proc
(define (h-raw content)
(push html (format "%s" content)))
(define (h-header headers)
(for ((h headers)) (emit-tag 'th h-raw h)))
(define (h-row row)
(for ((item row)) (emit-tag 'td h-raw item)))
(define (h-table table )
(emit-tag 'tr h-header (first table))
(for ((row (rest table))) (emit-tag 'tr h-row row)))
(define (html-dump) (string-join (stack->list html) " "))
;; STYLES
(style 'td "text-align:left")
(style 'table "border-spacing: 10px;border:28px ridge orange") ;; special biblical border
(style 'th "color:blue;")
|
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.
| #Kotlin | Kotlin | // version 1.1.3
import java.io.File
fun main(args: Array<String>) {
val lines = File("example.csv").readLines().toMutableList()
lines[0] += ",SUM"
for (i in 1 until lines.size) {
lines[i] += "," + lines[i].split(',').sumBy { it.toInt() }
}
val text = lines.joinToString("\n")
File("example2.csv").writeText(text) // write to new file
println(text) // print to console
} |
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.
| #uBasic.2F4tH | uBasic/4tH | Push 0, 3, 1, 7, 5, 9, 8, 6, 4, 2: i = FUNC(_Data(0))
Push 7, 0, 9, 2, 1, 5, 4, 8, 6, 3: i = FUNC(_Data(i))
Push 4, 2, 0, 6, 8, 7, 1, 3, 5, 9: i = FUNC(_Data(i))
Push 1, 7, 5, 0, 9, 8, 3, 4, 2, 6: i = FUNC(_Data(i))
Push 6, 1, 2, 3, 0, 4, 5, 9, 7, 8: i = FUNC(_Data(i))
Push 3, 6, 7, 4, 2, 0, 9, 5, 8, 1: i = FUNC(_Data(i))
Push 5, 8, 6, 9, 7, 2, 0, 1, 3, 4: i = FUNC(_Data(i))
Push 8, 9, 4, 5, 3, 6, 2, 0, 1, 7: i = FUNC(_Data(i))
Push 9, 4, 3, 8, 6, 1, 7, 2, 0, 5: i = FUNC(_Data(i))
Push 2, 5, 8, 1, 4, 3, 6, 7, 9, 0: i = FUNC(_Data(i))
' Read the table
Push 112949, 112946, 5727, 5724 ' Put numbers on the stack
For i = 1 To Used() ' Read up to the number of stack items
Print Using "______"; Tos();" is "; ' Print the header
If FUNC(_Damm (Str(Pop()))) Then Print "in";
Print "valid" ' invalid only if Damm() returns TRUE
Next ' Next stack item
End
_Data Param (1) ' Reads data in reverse order,
Local (2) ' starting with A@
c@ = a@ + Used() ' Calculate next offset
For b@ = c@-1 To a@ Step -1 ' Now place the elements
@(b@) = Pop() ' that are retrieved from the stack
Next b@ ' Next item
Return (c@) ' Return new offset
_Damm Param (1) ' Perform the Damm algorithm
Local (2)
c@ = 0 ' Reset the flag
For b@ = 0 To Len(a@) - 1 ' Check all characters in the string
c@ = @(c@*10 + peek(a@, b@) - ord("0"))
Next ' Next character
Return (c@) ' Return Flag |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
ReadOnly 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}
}
Function Damm(s As String) As Boolean
Dim interim = 0
For Each c In s
interim = table(interim, AscW(c) - AscW("0"))
Next
Return interim = 0
End Function
Sub Main()
Dim numbers = {5724, 5727, 112946, 112949}
For Each number In numbers
Dim isvalid = Damm(number.ToString())
If isvalid Then
Console.WriteLine("{0,6} is valid", number)
Else
Console.WriteLine("{0,6} is invalid", number)
End If
Next
End Sub
End Module |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Dim primes As List(Of Long) = {3L, 5L}.ToList()
Sub Main(args As String())
Const cutOff As Integer = 200, bigUn As Integer = 100000,
tn As String = " cuban prime"
Console.WriteLine("The first {0:n0}{1}s:", cutOff, tn)
Dim c As Integer = 0, showEach As Boolean = True, skip As Boolean = True,
v As Long = 0, st As DateTime = DateTime.Now
For i As Long = 1 To Long.MaxValue
v = 3 * i : v = v * i + v + 1
Dim found As Boolean = False, mx As Integer = Math.Ceiling(Math.Sqrt(v))
For Each item In primes
If item > mx Then Exit For
If v Mod item = 0 Then found = True : Exit For
Next : If Not found Then
c += 1 : If showEach Then
For z = primes.Last + 2 To v - 2 Step 2
Dim fnd As Boolean = False
For Each item In primes
If item > mx Then Exit For
If z Mod item = 0 Then fnd = True : Exit For
Next : If Not fnd Then primes.Add(z)
Next : primes.Add(v) : Console.Write("{0,11:n0}", v)
If c Mod 10 = 0 Then Console.WriteLine()
If c = cutOff Then showEach = False
Else
If skip Then skip = False : i += 772279 : c = bigUn - 1
End If
If c = bigUn Then Exit For
End If
Next
Console.WriteLine("{1}The {2:n0}th{3} is {0,17:n0}", v, vbLf, c, tn)
Console.WriteLine("Computation time was {0} seconds", (DateTime.Now - st).TotalSeconds)
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module |
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.
| #Pascal | Pascal | <@ SAI>
<@ ITEFORLI3>2121|2008|
<@ LETVARCAP>Christmas Day|25-Dec-<@ SAYVALFOR>...</@></@>
<@ TSTDOWVARLIT>Christmas Day|1</@>
<@ IFF>
<@ SAYCAP>Christmas Day <@ SAYVALFOR>...</@> is a Sunday</@><@ SAYKEY>__Newline</@>
</@>
</@>
</@> |
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.
| #Peloton | Peloton | <@ SAI>
<@ ITEFORLI3>2121|2008|
<@ LETVARCAP>Christmas Day|25-Dec-<@ SAYVALFOR>...</@></@>
<@ TSTDOWVARLIT>Christmas Day|1</@>
<@ IFF>
<@ SAYCAP>Christmas Day <@ SAYVALFOR>...</@> is a Sunday</@><@ SAYKEY>__Newline</@>
</@>
</@>
</@> |
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.
| #ERRE | ERRE |
PROGRAM DYNAMIC
!$DYNAMIC
DIM A%[0,0]
BEGIN
PRINT(CHR$(12);) !CLS
INPUT("Subscripts",R%,C%)
!$DIM A%[R%,C%]
A%[2,3]=6
PRINT("Value in row";2;"and col";3;"is";A%[2,3])
END PROGRAM
|
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.
| #Euphoria | Euphoria | include get.e
sequence array
integer height,width,i,j
height = floor(prompt_number("Enter height: ",{}))
width = floor(prompt_number("Enter width: ",{}))
array = repeat(repeat(0,width),height)
i = floor(height/2+0.5)
j = floor(width/2+0.5)
array[i][j] = height + width
printf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]}) |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
stddev() # reset state / empty
every s := stddev(![2,4,4,4,5,5,7,9]) do
write("stddev (so far) := ",s)
end
procedure stddev(x) # running standard deviation
static X,sumX,sum2X
if /x then { # reset state
X := []
sumX := sum2X := 0.
}
else { # accumulate
put(X,x)
sumX +:= x
sum2X +:= x^2
return sqrt( (sum2X / *X) - (sumX / *X)^2 )
}
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
| #Lua | Lua | local compute=require"zlib".crc32()
local sum=compute("The quick brown fox jumps over the lazy dog")
print(string.format("0x%x", sum))
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Function PrepareTable {
Dim Base 0, table(256)
For i = 0 To 255 {
k = i
For j = 0 To 7 {
If binary.and(k,1)=1 Then {
k =binary.Xor(binary.shift(k, -1) , 0xEDB88320)
} Else k=binary.shift(k, -1)
}
table(i) = k
}
=table()
}
crctable=PrepareTable()
crc32= lambda crctable (buf$) -> {
crc =0xFFFFFFFF
For i = 0 To Len(buf$) -1
crc = binary.xor(binary.shift(crc, -8), array(crctable, binary.xor(binary.and(crc, 0xff), asc(mid$(buf$, i+1, 1)))))
Next i
=0xFFFFFFFF-crc
}
Print crc32("The quick brown fox jumps over the lazy dog")=0x414fa339
}
CheckIt
|
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.
| #Common_Lisp | Common Lisp | (defun count-change (amount coins
&optional
(length (1- (length coins)))
(cache (make-array (list (1+ amount) (length coins))
:initial-element nil)))
(cond ((< length 0) 0)
((< amount 0) 0)
((= amount 0) 1)
(t (or (aref cache amount length)
(setf (aref cache amount length)
(+ (count-change (- amount (first coins)) coins length cache)
(count-change amount (rest coins) (1- length) cache)))))))
; (compile 'count-change) ; for CLISP
(print (count-change 100 '(25 10 5 1))) ; = 242
(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501
(terpri) |
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
| #BCPL | BCPL | get "libhdr"
let countsubstr(str, match) = valof
$( let i, count = 1, 0
while i <= str%0 do
test valof
$( for j = 1 to match%0
unless match%j = str%(i+j-1)
resultis false
resultis true
$)
then
$( count := count + 1
i := i + match%0
$)
else
i := i + 1
resultis count
$)
let show(str, match) be
writef("*"%S*" in *"%S*": %N*N",
match, str, countsubstr(str, match))
let start() be
$( show("the three truths", "th")
show("ababababab", "abab")
show("cat", "dog")
$) |
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
| #Bracmat | Bracmat | ( count-substring
= n S s p
. 0:?n:?p
& !arg:(?S.?s)
& @( !S
: ?
( [!p ? !s [?p ?
& !n+1:?n
& ~
)
)
| !n
)
& out$(count-substring$("the three truths".th))
& out$(count-substring$(ababababab.abab))
& ; |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #bc | bc | obase = 8 /* Output base is octal. */
for (num = 0; 1; num++) num /* Loop forever, printing counter. */ |
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.
| #BCPL | BCPL | get "libhdr"
let start() be
$( let x = 0
$( writeo(x)
wrch('*N')
x := x + 1
$) repeatuntil x = 0
$) |
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
| #Befunge | Befunge | 1>>>>:.48*"=",,::1-#v_.v
$<<<^_@#-"e":+1,+55$2<<<
v4_^#-1:/.:g00_00g1+>>0v
>8*"x",,:00g%!^!%g00:p0< |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16; /* be conservative */
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
} |
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.2B.2B | C++ | #include <fstream>
#include <boost/array.hpp>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sstream>
void makeGap( int gap , std::string & text ) {
for ( int i = 0 ; i < gap ; i++ )
text.append( " " ) ;
}
int main( ) {
boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ;
int headgap = 3 ;
int bodygap = 3 ;
int tablegap = 6 ;
int rowgap = 9 ;
std::string tabletext( "<html>\n" ) ;
makeGap( headgap , tabletext ) ;
tabletext += "<head></head>\n" ;
makeGap( bodygap , tabletext ) ;
tabletext += "<body>\n" ;
makeGap( tablegap , tabletext ) ;
tabletext += "<table>\n" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "<thead align=\"right\">\n" ;
makeGap( tablegap, tabletext ) ;
tabletext += "<tr><th></th>" ;
for ( int i = 0 ; i < 3 ; i++ ) {
tabletext += "<td>" ;
tabletext += *(chars.begin( ) + i ) ;
tabletext += "</td>" ;
}
tabletext += "</tr>\n" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "</thead>" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "<tbody align=\"right\">\n" ;
srand( time( 0 ) ) ;
for ( int row = 0 ; row < 5 ; row++ ) {
makeGap( rowgap , tabletext ) ;
std::ostringstream oss ;
tabletext += "<tr><td>" ;
oss << row ;
tabletext += oss.str( ) ;
for ( int col = 0 ; col < 3 ; col++ ) {
oss.str( "" ) ;
int randnumber = rand( ) % 10000 ;
oss << randnumber ;
tabletext += "<td>" ;
tabletext.append( oss.str( ) ) ;
tabletext += "</td>" ;
}
tabletext += "</tr>\n" ;
}
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "</tbody>\n" ;
makeGap( tablegap , tabletext ) ;
tabletext += "</table>\n" ;
makeGap( bodygap , tabletext ) ;
tabletext += "</body>\n" ;
tabletext += "</html>\n" ;
std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ;
htmltable << tabletext ;
htmltable.close( ) ;
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
| #ooRexx | ooRexx | /* REXX */
dats='20071123'
Say date('I',dats,'S')
Say date('W',dats,'S')',' date('M',dats,'S') substr(dats,7,2)',' left(dats,4)
Say date('W',dats,'S')',' date('M',dats,'S') translate('gh, abcd',dats,'abcdefgh')
dati=date('I')
Say dati
Say date('W',dati,'I')',' date('M',dati,'I') translate('ij, abcd',dati,'abcdefghij') |
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
| #OxygenBasic | OxygenBasic |
extern lib "kernel32.dll"
'http://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
void GetSystemTime(SYSTEMTIME*t);
void GetLocalTime(SYSTEMTIME*t);
end extern
SYSTEMTIME t
'GetSystemTime t 'GMT (Greenwich Mean Time)
GetLocalTime t
String WeekDay[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
String MonthName[12]={"January","February","March","April","May","June","July","August","September","October","November","December"}
String month=str t.wMonth : if len(month)<2 then month="0"+month
String day=str t.wDay : if len(day)<2 then day="0"+day
'
print "" t.wYear "-" month "-" day
print WeekDay[t.wDayOfWeek+1 and 7 ] " " MonthName[t.wMonth and 31] " " t.wDay " " t.wYear
|
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.
| #JavaScript | JavaScript |
var matrix = [
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3]
];
var freeTerms = [-3, -32, -47, 49];
var result = cramersRule(matrix,freeTerms);
console.log(result);
/**
* Compute Cramer's Rule
* @param {array} matrix x,y,z, etc. terms
* @param {array} freeTerms
* @return {array} solution for x,y,z, etc.
*/
function cramersRule(matrix,freeTerms) {
var det = detr(matrix),
returnArray = [],
i,
tmpMatrix;
for(i=0; i < matrix[0].length; i++) {
var tmpMatrix = insertInTerms(matrix, freeTerms,i)
returnArray.push(detr(tmpMatrix)/det)
}
return returnArray;
}
/**
* Inserts single dimensional array into
* @param {array} matrix multidimensional array to have ins inserted into
* @param {array} ins single dimensional array to be inserted vertically into matrix
* @param {array} at zero based offset for ins to be inserted into matrix
* @return {array} New multidimensional array with ins replacing the at column in matrix
*/
function insertInTerms(matrix, ins, at) {
var tmpMatrix = clone(matrix),
i;
for(i=0; i < matrix.length; i++) {
tmpMatrix[i][at] = ins[i];
}
return tmpMatrix;
}
/**
* Compute the determinate of a matrix. No protection, assumes square matrix
* function borrowed, and adapted from MIT Licensed numericjs library (www.numericjs.com)
* @param {array} m Input Matrix (multidimensional array)
* @return {number} result rounded to 2 decimal
*/
function detr(m) {
var ret = 1,
k,
A=clone(m),
n=m[0].length,
alpha;
for(var j =0; j < n-1; j++) {
k=j;
for(i=j+1;i<n;i++) { if(Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } }
if(k !== j) {
temp = A[k]; A[k] = A[j]; A[j] = temp;
ret *= -1;
}
Aj = A[j];
for(i=j+1;i<n;i++) {
Ai = A[i];
alpha = Ai[j]/Aj[j];
for(k=j+1;k<n-1;k+=2) {
k1 = k+1;
Ai[k] -= Aj[k]*alpha;
Ai[k1] -= Aj[k1]*alpha;
}
if(k!==n) { Ai[k] -= Aj[k]*alpha; }
}
if(Aj[j] === 0) { return 0; }
ret *= Aj[j];
}
return Math.round(ret*A[j][j]*100)/100;
}
/**
* Clone two dimensional Array using ECMAScript 5 map function and EcmaScript 3 slice
* @param {array} m Input matrix (multidimensional array) to clone
* @return {array} New matrix copy
*/
function clone(m) {
return m.map(function(a){return a.slice();});
}
|
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.
| #Delphi | Delphi |
program createFile;
{$APPTYPE CONSOLE}
uses
Classes,
SysUtils;
const
filename = 'output.txt';
var
cwdPath,
fsPath: string;
// Create empty file in current working directory
function CreateEmptyFile1: Boolean;
var
f: textfile;
begin
// Make path to the file to be created
cwdPath := ExtractFilePath(ParamStr(0)) + '1_'+filename;
// Create file
AssignFile(f,cwdPath);
{$I-}
Rewrite(f);
{$I+}
Result := IOResult = 0;
CloseFile(f);
end;
// Create empty file in filesystem root
function CreateEmptyFile2: Boolean;
var
f: textfile;
begin
// Make path to the file to be created
fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '2_'+filename;
// Create file
AssignFile(f,fsPath);
{$I-}
Rewrite(f);
{$I+}
Result := IOResult = 0;
CloseFile(f);
end;
function CreateEmptyFile3: Boolean;
var
fs: TFileStream;
begin
// Make path to the file to be created
cwdPath := ExtractFilePath(ParamStr(0)) + '3_'+filename;
// Create file
fs := TFileStream.Create(cwdPath,fmCreate);
fs.Free;
Result := FileExists(cwdPath);
end;
function CreateEmptyFile4: Boolean;
var
fs: TFileStream;
begin
// Make path to the file to be created
fsPath := ExtractFileDrive(ParamStr(0)) + '\' + '4_'+filename;
// Create file
fs := TFileStream.Create(fsPath,fmCreate);
fs.Free;
Result := FileExists(fsPath);
end;
begin
if CreateEmptyFile1 then
Writeln('File created at '+cwdPath)
else
Writeln('Error creating file at '+cwdPath);
if CreateEmptyFile2 then
Writeln('File created at '+fsPath)
else
Writeln('Error creating file at '+fsPath);
if CreateEmptyFile3 then
Writeln('File created at '+cwdPath)
else
Writeln('Error creating file at '+cwdPath);
if CreateEmptyFile4 then
Writeln('File created at '+fsPath)
else
Writeln('Error creating file at '+fsPath);
// Keep console window open
Readln;
end.
|
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).
| #Erlang | Erlang |
-module( csv_to_html ).
-export( [table_translation/1, task/0] ).
table_translation( CSV ) ->
[Headers | Contents] = [string:tokens(X, ",") || X <- string:tokens( CSV, "\n")],
Table = create_html_table:html_table( [{border, "1"}, {cellpadding, "10"}], Headers, Contents ),
create_html_table:external_format( Table ).
task() -> table_translation( csv() ).
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!".
|
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.
| #Lingo | Lingo | ----------------------------------------
-- Simplified CSV parser (without escape character support etc.).
-- First line is interrepted as header with column names.
-- @param {string} csvStr
-- @param {string} [sep=","] - single char as string
-- @param {string} [eol=RETURN]
-- @return {propList}
----------------------------------------
on parseSimpleCSVString (csvStr, sep, eol)
if voidP(sep) then sep=","
if voidP(eol) then eol = RETURN
lines = explode(eol, csvStr)
if lines.getLast()="" then lines.deleteAt(lines.count)
res = [:]
res[#header] = explode(sep, lines[1])
res[#data] = []
cnt = lines.count
repeat with i = 2 to cnt
res[#data].append(explodeBySingleChar(sep, lines[i]))
end repeat
return res
end
----------------------------------------
-- Simplified CSV creater (without escape character support etc.).
-- @param {propList} csvData
-- @param {string} [sep=","]
-- @param {string} [eol=RETURN]
-- @return {string}
----------------------------------------
on createSimpleCSVString (csvData, sep, eol)
if voidP(sep) then sep=","
if voidP(eol) then eol = RETURN
res = ""
put implode(sep, csvData[#header])&eol after res
cnt = csvData[#data].count
repeat with i = 1 to cnt
put implode(sep, csvData[#data][i])&eol after res
end repeat
return res
end
----------------------------------------
-- Explodes string into list
-- @param {string} delim
-- @param {string} str
-- @return {list}
----------------------------------------
on explode (delim, str)
if delim.length=1 then return explodeBySingleChar(delim, str)
l = []
if voidP(str) then return l
dl = delim.length
repeat while true
pos = offset(delim, str)
if pos=0 then exit repeat
l.add(str.char[1..pos-1])
delete char 1 to pos+dl-1 of str
end repeat
if pos=0 then pos = 1-dl
l.add(str.char[pos+dl..str.length])
return l
end
----------------------------------------
-- Explode string into list based on single char delimiter
-- (uses Lingo's build-in 'item' support, therefor faster)
-- @param {string} delim
-- @param {string} str
-- @return {list}
----------------------------------------
on explodeBySingleChar (delim, str)
l = []
if voidP(str) then return l
od = _player.itemDelimiter
_player.itemDelimiter = delim
cnt = str.item.count
repeat with i = 1 to cnt
l.add(str.item[i])
end repeat
_player.itemDelimiter = od
return l
end
----------------------------------------
-- Implodes list into string
-- @param {string} delim
-- @param {list} l
-- @return {string}
----------------------------------------
on implode (delim, l)
str = ""
cnt = l.count
repeat with i = 1 to cnt
put l[i]&delim after str
end repeat
delete char (str.length-delim.length+1) to str.length of str
return str
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.
| #Lua | Lua | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
|
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.
| #Vlang | Vlang | const table = [
[u8(0), 3, 1, 7, 5, 9, 8, 6, 4, 2],
[u8(7), 0, 9, 2, 1, 5, 4, 8, 6, 3],
[u8(4), 2, 0, 6, 8, 7, 1, 3, 5, 9],
[u8(1), 7, 5, 0, 9, 8, 3, 4, 2, 6],
[u8(6), 1, 2, 3, 0, 4, 5, 9, 7, 8],
[u8(3), 6, 7, 4, 2, 0, 9, 5, 8, 1],
[u8(5), 8, 6, 9, 7, 2, 0, 1, 3, 4],
[u8(8), 9, 4, 5, 3, 6, 2, 0, 1, 7],
[u8(9), 4, 3, 8, 6, 1, 7, 2, 0, 5],
[u8(2), 5, 8, 1, 4, 3, 6, 7, 9, 0],
]
fn damm(input string) bool {
mut interim := u8(0)
for c in input.bytes() {
interim = table[interim][c-'0'[0]]
}
return interim == 0
}
fn main() {
for s in ["5724", "5727", "112946", "112949"] {
println("${s:6} ${damm(s)}")
}
} |
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.
| #Wren | Wren | import "/fmt" for Fmt
var 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]
]
var damm = Fn.new { |input|
var interim = 0
for (c in input.bytes) interim = table[interim][c-48]
return interim == 0
}
for (s in ["5724", "5727", "112946", "112949"]) {
System.print("%(Fmt.s(6, s)) %(damm.call(s))")
} |
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.
| #Wren | Wren | import "/fmt" for Fmt
var start = System.clock
var primes = [3, 5]
var cutOff = 200
var bigOne = 100000
var cubans = []
var bigCuban = ""
var c = 0
var showEach = true
var u = 0
var v = 1
for (i in 1...(1<<20)) {
var found = false
u = u + 6
v = v + u
var mx = v.sqrt.floor
for (item in primes) {
if (item > mx) break
if (v%item == 0) {
found = true
break
}
}
if (!found) {
c = c + 1
if (showEach) {
var z = primes[-1]
while (z <= v -2) {
z = z + 2
var fnd = false
for (item in primes) {
if (item > mx) break
if (z%item == 0) {
fnd = true
break
}
}
if (!fnd) {
primes.add(z)
}
}
primes.add(v)
cubans.add(Fmt.commatize(v))
if (c == cutOff) showEach = false
}
if (c == bigOne) {
bigCuban = Fmt.commatize(v)
break
}
}
}
System.print("The first 200 cuban primes are:-")
for (i in 0...20) {
var j = i * 10
for (k in j...j+10) System.write(Fmt.s(10, cubans[k])) // 10 per line say
System.print()
}
System.print("\nThe 100,000th cuban prime is %(bigCuban)")
System.print("\nTook %(System.clock - start) secs") |
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.
| #Perl | Perl | #! /usr/bin/perl -w
use Time::Local;
use strict;
foreach my $i (2008 .. 2121)
{
my $time = timelocal(0,0,0,25,11,$i);
my ($s,$m,$h,$md,$mon,$y,$wd,$yd,$is) = localtime($time);
if ( $wd == 0 )
{
print "25 Dec $i is Sunday\n";
}
}
exit 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.
| #F.23 | F# | open System
let width = int( Console.ReadLine() )
let height = int( Console.ReadLine() )
let arr = Array2D.create width height 0
arr.[0,0] <- 42
printfn "%d" arr.[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
| #IS-BASIC | IS-BASIC | 100 PROGRAM "StDev.bas"
110 LET N=8
120 NUMERIC ARR(1 TO N)
130 FOR I=1 TO N
140 READ ARR(I)
150 NEXT
160 DEF STDEV(N)
170 LET S1,S2=0
180 FOR I=1 TO N
190 LET S1=S1+ARR(I)^2:LET S2=S2+ARR(I)
200 NEXT
210 LET STDEV=SQR((N*S1-S2^2)/N^2)
220 END DEF
230 FOR J=1 TO N
240 PRINT J;"item =";ARR(J),"standard dev =";STDEV(J)
250 NEXT
260 DATA 2,4,4,4,5,5,7,9 |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | type="CRC32"; (*pick one out of 13 predefined hash types*)
StringForm[
"The "<>type<>" hash code of \"``\" is ``.",
s="The quick brown fox jumps over the lazy dog",
Hash[s,type,"HexString"]
]
|
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
| #Neko | Neko | /**
<doc>CRC32 in Neko</doc>
**/
var int32_new = $loader.loadprim("std@int32_new", 1)
var update_crc32 = $loader.loadprim("zlib@update_crc32", 4)
var crc = int32_new(0)
var txt = "The quick brown fox jumps over the lazy dog"
crc = update_crc32(crc, txt, 0, $ssize(txt))
$print(crc, "\n") |
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.
| #D | D | import std.stdio, std.bigint;
auto changes(int amount, int[] coins) {
auto ways = new BigInt[amount + 1];
ways[0] = 1;
foreach (coin; coins)
foreach (j; coin .. amount + 1)
ways[j] += ways[j - coin];
return ways[$ - 1];
}
void main() {
changes( 1_00, [25, 10, 5, 1]).writeln;
changes(1000_00, [100, 50, 25, 10, 5, 1]).writeln;
} |
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
| #C | C | #include <stdio.h>
#include <string.h>
int match(const char *s, const char *p, int overlap)
{
int c = 0, l = strlen(p);
while (*s != '\0') {
if (strncmp(s++, p, l)) continue;
if (!overlap) s += l - 1;
c++;
}
return c;
}
int main()
{
printf("%d\n", match("the three truths", "th", 0));
printf("overlap:%d\n", match("abababababa", "aba", 1));
printf("not: %d\n", match("abababababa", "aba", 0));
return 0;
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Befunge | Befunge | :0\55+\:8%68>*#<+#8\#68#%/#8:_$>:#,_$1+:0`!#@_ |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Bracmat | Bracmat |
( oct
=
. !arg:<8
& (!arg:~<0|ERROR)
| str$(oct$(div$(!arg.8)) mod$(!arg.8))
)
& -1:?n
& whl'(1+!n:?n&out$(!n oct$!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.
| #Brainf.2A.2A.2A | Brainf*** | +[ Start with n=1 to kick off the loop
[>>++++++++<< Set up {n 0 8} for divmod magic
[->+>- Then
[>+>>]> do
[+[-<+>]>+>>] the
<<<<<<] magic
>>>+ Increment n % 8 so that 0s don't break things
>] Move into n / 8 and divmod that unless it's 0
-< Set up sentinel ‑1 then move into the first octal digit
[++++++++ ++++++++ ++++++++ Add 47 to get it to ASCII
++++++++ ++++++++ +++++++. and print it
[<]<] Get to a 0; the cell to the left is the next octal digit
>>[<+>-] Tape is {0 n}; make it {n 0}
>[>+] Get to the ‑1
<[[-]<] Zero the tape for the next iteration
++++++++++. Print a newline
[-]<+] Zero it then increment n and go again |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
} |
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.
| #Clojure | Clojure | (ns rosettacode.html-table
(:use 'hiccup.core))
(defn <tr> [el sq]
[:tr (map vector (cycle [el]) sq)])
(html
[:table
(<tr> :th ["" \X \Y \Z])
(for [n (range 1 4)]
(->> #(rand-int 10000) (repeatedly 3) (cons n) (<tr> :td)))]) |
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
| #Oz | Oz | declare
WeekDays = unit(0:"Sunday" "Monday" "Tuesday" "Wednesday"
"Thursday" "Friday" "Saturday")
Months = unit(0:"January" "February" "March" "April"
"May" "June" "July" "August" "September"
"October" "November" "December")
fun {DateISO Time}
Year = 1900 + Time.year
Month = Time.mon + 1
in
Year#"-"#{Align Month}#"-"#{Align Time.mDay}
end
fun {DateLong Time}
Year = 1900 + Time.year
in
WeekDays.(Time.wDay)#", "#Months.(Time.mon)#" "#Time.mDay#", "#Year
end
fun {Align Num}
if Num < 10 then "0"#Num else Num end
end
in
{System.showInfo {DateISO {OS.localTime}}}
{System.showInfo {DateLong {OS.localTime}}} |
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.
| #jq | jq | # The minor of the input matrix after removing the specified row and column.
# Assumptions: the input is square and the indices are hunky dory.
def minor(rowNum; colNum):
. as $in
| (length - 1) as $len
| reduce range(0; $len) as $i (null;
reduce range(0; $len) as $j (.;
if $i < rowNum and $j < colNum
then .[$i][$j] = $in[$i][$j]
elif $i >= rowNum and $j < colNum
then .[$i][$j] = $in[$i+1][$j]
elif $i < rowNum and $j >= colNum
then .[$i][$j] = $in[$i][$j+1]
else .[$i][$j] = $in[$i+1][$j+1]
end) );
# The determinant using Laplace expansion.
# Assumption: the matrix is square
def det:
. as $a
| length as $nr
| if $nr == 1 then .[0][0]
elif $nr == 2 then .[1][1] * .[0][0] - .[0][1] * .[1][0]
else reduce range(0; $nr) as $i (
{ sign: 1, sum: 0 };
($a|minor(0; $i)) as $m
| .sum += .sign * $a[0][$i] * ($m|det)
| .sign *= -1 )
| .sum
end ;
# Solve A X = D using Cramer's method
# a is assumed to be a JSON array representing the 2-d square matrix A
# d is assumed to be a JSON array representing the 1-d vector D
def cramer(a; d):
(a | length) as $n
| (a | det) as $ad
| if $ad == 0 then "matrix determinant is 0" | error
| reduce range(0; $n) as $c (null;
(reduce range(0; $n) as $r (a; .[$r][$c] = d[$r])) as $aa
| .[$c] = ($aa|det) / $ad ) ;
def a: [
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1],
[5, -2, -3, 3]
];
def d:
[ -3, -32, -47, 49 ] ;
"Solution is \(cramer(a; d))" |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #Julia | Julia | function cramersolve(A::Matrix, b::Vector)
return collect(begin B = copy(A); B[:, i] = b; det(B) end for i in eachindex(b)) ./ det(A)
end
A = [2 -1 5 1
3 2 2 -6
1 3 3 -1
5 -2 -3 3]
b = [-3, -32, -47, 49]
@show cramersolve(A, b) |
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.
| #E | E | <file:output.txt>.setBytes([])
<file:docs>.mkdir(null)
<file:///output.txt>.setBytes([])
<file:///docs>.mkdir(null) |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #EchoLisp | EchoLisp |
;; The file system is the browser local storage
;; It is divided into named stores (directories)
;; "user" is the default (home) store
; before : list of stores
(local-stores) → ("system" "user" "words" "reader" "info" "root")
(local-put-value "output.txt" "") → "output.txt" ; into "user"
(local-make-store "user/docs") → "user/docs"
(local-put-value "output.txt" "" "root") → "output.txt" ; into "root"
(local-make-store 'root/docs) → "root/docs"
; after : list of stores
(local-stores 'root) → ("root" "root/docs")
(local-stores 'user) → ("user" "user/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).
| #Euphoria | Euphoria | constant 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!"
puts(1,"<table>\n<tr><td>")
for i = 1 to length(input) do
switch input[i] do
case '\n' then puts(1,"</td></tr>\n<tr><td>")
case ',' then puts(1,"</td><td>")
case '<' then puts(1,"<")
case '>' then puts(1,">")
case '&' then puts(1,"&")
case else puts(1,input[i])
end switch
end for
puts(1,"</td></tr>\n</table>") |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Function Sum {
Long c=0
while not empty {
c+=number
}
=c
}
Document CSV$ = {C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
}
\\ export encoded to UTF-16LE
Save.Doc CSV$, "data1.csv", 0
\\ Open Wide read UTF-16LE
\\ use standard colum sep. as ","
\\ use standard decimal point char
\\ use standard (non json style string)
\\ True = use bare strings (without "")
Input With "",,,true
Write With"",,,true
\\ for excel csv use Input With chr$(9),,true, true
Open "data1.csv" for Wide Input as #M
Open "data2.csv" for Wide Output as #M1
Input #M, h1$, h2$, h3$, h4$, h5$
Write #M1, h1$, h2$, h3$, h4$, h5$
Print h1$, h2$, h3$, h4$, h5$
While not Eof(#M) {
Input #M, A1, A2, A3, A4, A5
Write #M1, A1, A2, A3, A4, A5, Sum(A1, A2, A3, A4, A5)
Print A1, A2, A3, A4, A5
}
close #M1
Close #M
Open "data2.csv" for Wide Input as #M
Input #M, h1$, h2$, h3$, h4$, h5$
Print h1$, h2$, h3$, h4$, h5$
While not Eof(#M) {
Input #M, A1, A2, A3, A4, A5, Sum
Print A1, A2, A3, A4, A5, Sum
}
Close #M
}
Checkit
|
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.
| #Maple | Maple | M := ImportMatrix("data.csv",source=csv);
M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >;
ExportMatrix("data_out.csv",M,target=csv);
|
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.
| #zkl | zkl | fcn damm(digits){ // digits is something that supports an iterator of integers
var [const] tbl=Data(0,Int, // 10x10 byte bucket
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);
0 == digits.reduce(fcn(interim,digit){ tbl[interim*10 + digit] },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.
| #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
cubans:=(1).walker(*).tweak('wrap(n){ // lazy iterator
p:=3*n*(n + 1) + 1;
BI(p).probablyPrime() and p or Void.Skip
});
println("First 200 cuban primes:");
do(20){ (10).pump(String, cubans.next, "%10,d".fmt).println() }
cubans.drop(100_000 - cubans.n).value :
println("\nThe 100,000th cuban prime is: %,d".fmt(_)); |
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.
| #Phix | Phix | -- demo\rosetta\Day_of_the_week.exw
sequence res = {}
for y=2008 to 2121 do
if day_of_week(y,12,25,true)="Sunday" then
res = append(res,y)
end if
end for
?res
|
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.
| #PHP | PHP | <?php
for($i=2008; $i<2121; $i++)
{
$datetime = new DateTime("$i-12-25 00:00:00");
if ( $datetime->format("w") == 0 )
{
echo "25 Dec $i is Sunday\n";
}
}
?> |
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.
| #Factor | Factor | USING: io kernel math.matrices math.parser prettyprint
sequences ;
IN: rosettacode.runtime2darray
: set-Mi,j ( elt {i,j} matrix -- )
[ first2 swap ] dip nth set-nth ;
: Mi,j ( {i,j} matrix -- elt )
[ first2 swap ] dip nth nth ;
: example ( -- )
readln readln [ string>number ] bi@ zero-matrix ! create the array
[ [ 42 { 0 0 } ] dip set-Mi,j ] ! set the { 0 0 } element to 42
[ [ { 0 0 } ] dip Mi,j . ] ! read the { 0 0 } element
bi ; |
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.
| #Fermat | Fermat | ?m; {imput the dimensions of the array}
?n;
Array a[m,n]; {generate an array of m rows and n columns}
a[m\2, n\2] := m+n-1; {put some value in one of the cells}
!!a[m\2, n\2]; {display that entry}
@[a]; {delete the 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
| #J | J | mean=: +/ % #
dev=: - mean
stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP
stddevP=: [: mean&.:*: dev NB. B) uses Under (&.:) to apply inverse of *: after mean
stddevP=: %:@(mean@:*: - *:@mean) NB. C) sqrt of ((mean of squares) - (square of mean))
stddevP\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2 |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.util.zip.CRC32
toBeEncoded = String("The quick brown fox jumps over the lazy dog")
myCRC = CRC32()
myCRC.update(toBeEncoded.getBytes())
say "The CRC-32 value is :" Long.toHexString(myCRC.getValue()) "!"
return
|
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
| #Nim | Nim | import strutils
type TCrc32* = uint32
const InitCrc32* = TCrc32(0xffffffff)
proc createCrcTable(): array[0..255, TCrc32] =
for i in 0..255:
var rem = TCrc32(i)
for j in 0..7:
if (rem and 1) > 0: rem = (rem shr 1) xor TCrc32(0xedb88320)
else: rem = rem shr 1
result[i] = rem
# Table created at compile time
const crc32table = createCrcTable()
proc crc32(s: string): TCrc32 =
result = InitCrc32
for c in s:
result = (result shr 8) xor crc32table[(result and 0xff) xor byte(c)]
result = not result
echo crc32("The quick brown fox jumps over the lazy dog").int64.toHex(8) |
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.
| #Dart | Dart |
var cache = new Map();
main() {
var stopwatch = new Stopwatch()..start();
// use the brute-force recursion for the small problem
int amount = 100;
list coinTypes = [25,10,5,1];
print (coins(amount,coinTypes).toString() + " ways for $amount using $coinTypes coins.");
// use the cache version for the big problem
amount = 100000;
coinTypes = [100,50,25,10,5,1];
print (cachedCoins(amount,coinTypes).toString() + " ways for $amount using $coinTypes coins.");
stopwatch.stop();
print ("... completed in " + (stopwatch.elapsedMilliseconds/1000).toString() + " seconds");
}
coins(int amount, list coinTypes) {
int count = 0;
if(coinTypes.length == 1) return (1); // just pennies available, so only one way to make change
for(int i=0; i<=(amount/coinTypes[0]).toInt(); i++){ // brute force recursion
count += coins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)'
}
// uncomment if you want to see intermediate steps
//print("there are " + count.toString() +" ways to count change for ${amount.toString()} using ${coinTypes} coins.");
return(count);
}
cachedCoins(int amount, list coinTypes) {
int count = 0;
// this is more efficient, looks at last two coins. but not fast enough for the optional exercise.
if(coinTypes.length == 2) return ((amount/coinTypes[0]).toInt() + 1);
var key = "$amount.$coinTypes"; // lookes like "100.[25,10,5,1]"
var cacheValue = cache[key]; // check whether we have seen this before
if(cacheValue != null) return(cacheValue);
count = 0;
// same recursion as simple method, but caches all subqueries too
for(int i=0; i<=(amount/coinTypes[0]).toInt(); i++){
count += cachedCoins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)'
}
cache[key] = count; // add this to the cache
return(count);
}
|
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Delphi | Delphi |
program Count_the_coins;
{$APPTYPE CONSOLE}
function Count(c: array of Integer; m, n: Integer): Integer;
var
table: array of Integer;
i, j: Integer;
begin
SetLength(table, n + 1);
table[0] := 1;
for i := 0 to m - 1 do
for j := c[i] to n do
table[j] := table[j] + table[j - c[i]];
Exit(table[n]);
end;
var
c: array of Integer;
m, n: Integer;
begin
c := [1, 5, 10, 25];
m := Length(c);
n := 100;
Writeln(Count(c, m, n)); //242
Readln;
end.
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.23 | C# | using System;
class SubStringTestClass
{
public static int CountSubStrings(this string testString, string testSubstring)
{
int count = 0;
if (testString.Contains(testSubstring))
{
for (int i = 0; i < testString.Length; i++)
{
if (testString.Substring(i).Length >= testSubstring.Length)
{
bool equals = testString.Substring(i, testSubstring.Length).Equals(testSubstring);
if (equals)
{
count++;
i += testSubstring.Length - 1; // Fix: Don't count overlapping matches
}
}
}
}
return count;
}
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <iostream>
#include <string>
// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
if (sub.length() == 0) return 0;
int count = 0;
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset + sub.length()))
{
++count;
}
return count;
}
int main()
{
std::cout << countSubstring("the three truths", "th") << '\n';
std::cout << countSubstring("ababababab", "abab") << '\n';
std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';
return 0;
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #C | C | #include <stdio.h>
int main()
{
unsigned int i = 0;
do { printf("%o\n", i++); } while(i);
return 0;
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #C.23 | C# | using System;
class Program
{
static void Main()
{
var number = 0;
do
{
Console.WriteLine(Convert.ToString(number, 8));
} while (++number > 0);
}
} |
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
| #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
} |
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.
| #CoffeeScript | CoffeeScript |
# This is one of many ways to create a table. CoffeeScript plays nice
# with any templating solution built for JavaScript, and of course you
# can build tables in the browser using DOM APIs. This approach is just
# brute force string manipulation.
table = (header_row, rows) ->
"""
<table>
#{header_row}
#{rows.join '\n'}
</table>
"""
tr = (cells) -> "<tr>#{cells.join ''}</tr>"
th = (s) -> "<th align='right'>#{s}</th>"
td = (s) -> "<td align='right'>#{s}</td>"
rand_n = -> Math.floor Math.random() * 10000
header_cols = ['', 'X', 'Y', 'Z']
header_row = tr (th s for s in header_cols)
rows = []
for i in [1..5]
rows.push tr [
th(i)
td rand_n()
td rand_n()
td rand_n()
]
html = table header_row, rows
console.log html
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Pascal | Pascal | program dateform;
uses DOS;
{ Format digit with leading zero }
function lz(w: word): string;
var
s: string;
begin
str(w,s);
if length(s) = 1 then
s := '0' + s;
lz := s
end;
function m2s(mon: integer): string;
begin
case mon of
1: m2s := 'January';
2: m2s := 'February';
3: m2s := 'March';
4: m2s := 'April';
5: m2s := 'May';
6: m2s := 'June';
7: m2s := 'July';
8: m2s := 'August';
9: m2s := 'September';
10: m2s := 'October';
11: m2s := 'November';
12: m2s := 'December'
end
end;
function d2s(dow: integer): string;
begin
case dow of
0: d2s := 'Sunday';
1: d2s := 'Monday';
2: d2s := 'Tueday';
3: d2s := 'Wednesday';
4: d2s := 'Thursday';
5: d2s := 'Friday';
6: d2s := 'Saturday'
end
end;
var
yr,mo,dy,dow: word;
mname,dname: string;
begin
GetDate(yr,mo,dy,dow);
writeln(yr,'-',lz(mo),'-',lz(dy));
mname := m2s(mo); dname := d2s(dow);
writeln(dname,', ',mname,' ',dy,', ',yr)
end. |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
| #Kotlin | Kotlin | // version 1.1.3
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
val p = IntArray(n) { it } // permutation
val q = IntArray(n) { it } // inverse permutation
val d = IntArray(n) { -1 } // direction = 1 or -1
var sign = 1
val perms = mutableListOf<IntArray>()
val signs = mutableListOf<Int>()
fun permute(k: Int) {
if (k >= n) {
perms.add(p.copyOf())
signs.add(sign)
sign *= -1
return
}
permute(k + 1)
for (i in 0 until k) {
val z = p[q[k] + d[k]]
p[q[k]] = z
p[q[k] + d[k]] = k
q[z] = q[k]
q[k] += d[k]
permute(k + 1)
}
d[k] *= -1
}
permute(0)
return perms to signs
}
fun determinant(m: Matrix): Double {
val (sigmas, signs) = johnsonTrotter(m.size)
var sum = 0.0
for ((i, sigma) in sigmas.withIndex()) {
var prod = 1.0
for ((j, s) in sigma.withIndex()) prod *= m[j][s]
sum += signs[i] * prod
}
return sum
}
fun cramer(m: Matrix, d: Vector): Vector {
val divisor = determinant(m)
val numerators = Array(m.size) { Matrix(m.size) { m[it].copyOf() } }
val v = Vector(m.size)
for (i in 0 until m.size) {
for (j in 0 until m.size) numerators[i][j][i] = d[j]
}
for (i in 0 until m.size) v[i] = determinant(numerators[i]) / divisor
return v
}
fun main(args: Array<String>) {
val m = arrayOf(
doubleArrayOf(2.0, -1.0, 5.0, 1.0),
doubleArrayOf(3.0, 2.0, 2.0, -6.0),
doubleArrayOf(1.0, 3.0, 3.0, -1.0),
doubleArrayOf(5.0, -2.0, -3.0, 3.0)
)
val d = doubleArrayOf(-3.0, -32.0, -47.0, 49.0)
val (w, x, y, z) = cramer(m, d)
println("w = $w, x = $x, y = $y, z = $z")
} |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Elena | Elena | import system'io;
public program()
{
File.assign("output.txt").textwriter().close();
File.assign("\output.txt").textwriter().close();
Directory.assign("docs").create();
Directory.assign("\docs").create();
} |
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.
| #Elixir | Elixir | File.open("output.txt", [:write])
File.open("/output.txt", [:write])
File.mkdir!("docs")
File.mkdir!("/docs") |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #F.23 | F# | open System
open System.Text
open System.Xml
let data = """
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
"""
let csv =
Array.map
(fun (line : string) -> line.Split(','))
(data.Trim().Split([|'\n';'\r'|],StringSplitOptions.RemoveEmptyEntries))
[<EntryPoint>]
let main argv =
let style = argv.Length > 0 && argv.[0] = "-h"
Console.OutputEncoding <- UTF8Encoding()
let xs = XmlWriterSettings()
xs.Indent <- true // be friendly to humans
use x = XmlWriter.Create(Console.Out, xs)
x.WriteStartDocument()
x.WriteDocType("HTML", null, null, null) // HTML5
x.WriteStartElement("html")
x.WriteStartElement("head")
x.WriteElementString("title", "Rosettacode - CSV to HTML translation")
if style then
x.WriteStartElement("style"); x.WriteAttributeString("type", "text/css")
x.WriteString("""
table { border-collapse: collapse; }
td, th { border: 1px solid black; padding: .25em}
th { background-color: #EEE; }
tbody th { font-weight: normal; font-size: 85%; }
""")
x.WriteEndElement() // style
x.WriteEndElement() // head
x.WriteStartElement("body")
x.WriteStartElement("table")
x.WriteStartElement("thead"); x.WriteStartElement("tr")
for part in csv.[0] do x.WriteElementString("th", part)
x.WriteEndElement(); x.WriteEndElement() // tr thead
x.WriteStartElement("tbody")
for line in csv.[1..] do
x.WriteStartElement("tr")
x.WriteElementString("th", line.[0])
x.WriteElementString("td", line.[1])
x.WriteEndElement() // tr
x.Close()
0 |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | iCSV=Import["test.csv"]
->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}}
iCSV = Transpose@
Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]];
iCSV // MatrixForm
Export["test.csv",iCSV]; |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | filename='data.csv';
fid = fopen(filename);
header = fgetl(fid);
fclose(fid);
X = dlmread(filename,',',1,0);
fid = fopen('data.out.csv','w+');
fprintf(fid,'%s,sum\n',header);
for k=1:size(X,1),
fprintf(fid,"%i,",X(k,:));
fprintf(fid,"%i\n",sum(X(k,:)));
end;
fclose(fid); |
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.
| #Picat | Picat | go =>
L = [Year : Year in 2008..2121, dow(Year, 12, 25) == 0],
println(L),
println(len=L.length),
nl.
% Day of week, Sakamoto's method
dow(Y, M, D) = R =>
T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],
if M < 3 then
Y := Y - 1
end,
R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.
|
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.
| #PicoLisp | PicoLisp | (for (Y 2008 (>= 2121 Y) (inc Y))
(when (= "Sunday" (day (date Y 12 25)))
(printsp 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.
| #Forth | Forth | : cell-matrix
create ( width height "name" ) over , * cells allot
does> ( x y -- addr ) dup cell+ >r @ * + cells r> + ;
5 5 cell-matrix test
36 0 0 test !
0 0 test @ . \ 36 |
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.
| #Fortran | Fortran | PROGRAM Example
IMPLICIT NONE
INTEGER :: rows, columns, errcheck
INTEGER, ALLOCATABLE :: array(:,:)
WRITE(*,*) "Enter number of rows"
READ(*,*) rows
WRITE(*,*) "Enter number of columns"
READ(*,*) columns
ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checking
array(1,1) = 42
WRITE(*,*) array(1,1)
DEALLOCATE (array, STAT=errcheck)
END PROGRAM Example |
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
| #Java | Java | public class StdDev {
int n = 0;
double sum = 0;
double sum2 = 0;
public double sd(double x) {
n++;
sum += x;
sum2 += x*x;
return Math.sqrt(sum2/n - sum*sum/n/n);
}
public static void main(String[] args) {
double[] testData = {2,4,4,4,5,5,7,9};
StdDev sd = new StdDev();
for (double x : testData) {
System.out.println(sd.sd(x));
}
}
} |
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
| #NOWUT | NOWUT | ; link with PIOxxx.OBJ
sectionbss
crctable.d: resd 256
sectiondata
havetable.b: db 0
string: db "The quick brown fox jumps over the lazy dog"
stringend:
db 13,10,0 ; carriage return and null terminator
sectioncode
start!
gosub initplatform
beginfunc
localvar crc.d
callex ,printnt,"input = ".a
callex ,printnt,string
callex ,printnt,"The CRC-32 checksum = ".a
callex crc,crc32,string,stringend
callex ,printhexr,crc
endfunc
end
crc32:
beginfunc bufend.d,buf.d
localvar i.d,j.d,k.d,k2.d,crc.d
ifunequal havetable,0,tabledone
i=0
whileless i,256
k=i > j=8
countdown j
k2=k > k=_ shr 1
ifequal k2 and 1,0,noxor > k=_ xor $EDB88320
noxor:
nextcount
crctable(i shl 2)=k
i=_+1
wend
havetable=1
tabledone:
crc=-1
whileless buf,bufend
crc=_ shr 8 xor crctable(crc and $FF xor [buf].b shl 2)
buf=_+1
wend
crc=_ xor -1
endfunc crc
returnex 8 ; clean off 2 parameters from the stack
|
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
| #Oberon-2 | Oberon-2 |
MODULE CRC32;
IMPORT
NPCT:Zlib,
Strings,
Out;
VAR
s: ARRAY 128 OF CHAR;
BEGIN
COPY("The quick brown fox jumps over the lazy dog",s);
Out.Hex(Zlib.CRC32(0,s,0,Strings.Length(s)),0);Out.Ln
END CRC32.
|
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.
| #Dyalect | Dyalect | func countCoins(coins, n) {
var xs = Array.Empty(n + 1, 0)
xs[0] = 1
for c in coins {
var cj = c
while cj <= n {
xs[cj] += xs[cj - c]
cj += 1
}
}
return xs[n]
}
var coins = [1, 5, 10, 25]
print(countCoins(coins, 100)) |
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.
| #EchoLisp | EchoLisp |
(lib 'compile) ;; for (compile)
(lib 'bigint) ;; integer results > 32 bits
(lib 'hash) ;; hash table
;; h-table
(define Hcoins (make-hash))
;; the function to memoize
(define (sumways cents coins)
(+ (ways cents (cdr coins)) (ways (- cents (car coins)) coins)))
;; accelerator : ways (cents, coins) = ways ((cents - cents % 5) , coins)
(define (ways cents coins)
(cond ((null? coins) 0)
((negative? cents) 0)
((zero? cents) 1)
((eq? coins c-1) 1) ;; if coins = (1) --> 1
(else (hash-ref! Hcoins (list (- cents (modulo cents 5)) coins) sumways))))
(compile 'ways) ;; speed-up things
|
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
| #Clojure | Clojure |
(defn re-quote
"Produces a string that can be used to create a Pattern
that would match the string text as if it were a literal pattern.
Metacharacters or escape sequences in text will be given no special
meaning"
[text]
(java.util.regex.Pattern/quote text))
(defn count-substring [txt sub]
(count (re-seq (re-pattern (re-quote sub)) txt)))
|
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. testing.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 occurrences PIC 99.
PROCEDURE DIVISION.
INSPECT "the three truths" TALLYING occurrences FOR ALL "th"
DISPLAY occurrences
MOVE 0 TO occurrences
INSPECT "ababababab" TALLYING occurrences FOR ALL "abab"
DISPLAY occurrences
MOVE 0 TO occurrences
INSPECT "abaabba*bbaba*bbab" TALLYING occurrences
FOR ALL "a*b"
DISPLAY occurrences
GOBACK
. |
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.
| #C.2B.2B | C++ | #include <iostream>
int main()
{
unsigned i = 0;
do
{
std::cout << std::oct << i << std::endl;
++i;
} while(i != 0);
return 0;
} |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Clojure | Clojure | (doseq [i (range)] (println (format "%o" i))) |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Clojure | Clojure | (ns listfactors
(:gen-class))
(defn factors
"Return a list of factors of N."
([n]
(factors n 2 ()))
([n k acc]
(cond
(= n 1) (if (empty? acc)
[n]
(sort acc))
(>= k n) (if (empty? acc)
[n]
(sort (cons n acc)))
(= 0 (rem n k)) (recur (quot n k) k (cons k acc))
:else (recur n (inc k) acc))))
(doseq [q (range 1 26)]
(println q " = " (clojure.string/join " x "(factors q))))
|
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.
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. Table.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 1 January 2022.
************************************************************
** Program Abstract:
** Data values are hardcoded in this example but they
** could come from anywhere. Computed, read from a
** file, input from the keyboard.
************************************************************
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT Table-File ASSIGN TO "index.html"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD Table-File
DATA RECORD IS Table-Record.
01 Table-Record.
05 Field1 PIC X(80).
WORKING-STORAGE SECTION.
01 Table-Data.
05 Line3.
10 Line3-Value1 PIC S9(4) VALUE 1234.
10 Line3-Value2 PIC S9(4) VALUE 23.
10 Line3-Value3 PIC S9(4) VALUE -123.
05 Line4.
10 Line4-Value1 PIC S9(4) VALUE 123.
10 Line4-Value2 PIC S9(4) VALUE 12.
10 Line4-Value3 PIC S9(4) VALUE -1234.
05 Line5.
10 Line5-Value1 PIC S9(4) VALUE 567.
10 Line5-Value2 PIC S9(4) VALUE 6789.
10 Line5-Value3 PIC S9(4) VALUE 3.
01 Table-HTML.
05 Line1 PIC X(16) VALUE
"<table border=1>".
05 Line2 PIC X(40) VALUE
"<th></th><th>X</th><th>Y</th><th>Z</th>".
05 Line3.
10 Line3-Field1 PIC X(31) VALUE
"<tr align=center><th>1</th><td>".
10 Line3-Value1 PIC -ZZZ9.
10 Line3-Field3 PIC X(9) VALUE
"</td><td>".
10 Line3-Value2 PIC -ZZZ9.
10 Line3-Field5 PIC X(9) VALUE
"</td><td>".
10 Line3-Value3 PIC -ZZZ9.
10 Line3-Field5 PIC X(10) VALUE
"</td></tr>".
05 Line4.
10 Line4-Field1 PIC X(31) VALUE
"<tr align=center><th>2</th><td>".
10 Line4-Value1 PIC -ZZZ9.
10 Line4-Field3 PIC X(9) VALUE
"</td><td>".
10 Line4-Value2 PIC -ZZZ9.
10 Line4-Field5 PIC X(9) VALUE
"</td><td>".
10 Line4-Value3 PIC -ZZZ9.
10 Line4-Field5 PIC X(10) VALUE
"</td></tr>".
05 Line5.
10 Line5-Field1 PIC X(31) VALUE
"<tr align=center><th>3</th><td>".
10 Line5-Value1 PIC -ZZZ9.
10 Line5-Field3 PIC X(9) VALUE
"</td><td>".
10 Line5-Value2 PIC -ZZZ9.
10 Line5-Field5 PIC X(9) VALUE
"</td><td>".
10 Line5-Value3 PIC -ZZZ9.
10 Line5-Field5 PIC X(10) VALUE
"</td></tr>".
05 Line6 PIC X(8) VALUE
"</table>".
PROCEDURE DIVISION.
Main-Program.
OPEN OUTPUT Table-File.
MOVE CORRESPONDING Table-Data TO Table-HTML.
PERFORM Write-Table.
CLOSE Table-File.
STOP RUN.
Write-Table.
WRITE Table-Record FROM Line1 OF Table-HTML
AFTER ADVANCING 1 LINE.
WRITE Table-Record FROM Line2 OF Table-HTML
AFTER ADVANCING 1 LINE.
WRITE Table-Record FROM Line3 OF Table-HTML
AFTER ADVANCING 1 LINE.
WRITE Table-Record FROM Line4 OF Table-HTML
AFTER ADVANCING 1 LINE.
WRITE Table-Record FROM Line5 OF Table-HTML
AFTER ADVANCING 1 LINE.
WRITE Table-Record FROM Line6 OF Table-HTML
AFTER ADVANCING 1 LINE.
END-PROGRAM.
|
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
| #Perl | Perl | use POSIX;
print strftime('%Y-%m-%d', 0, 0, 0, 10, 10, 107), "\n";
print strftime('%A, %B %d, %Y', 0, 0, 0, 10, 10, 107), "\n"; |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Phix | Phix | with javascript_semantics
include builtins\timedate.e
?format_timedate(date(),"YYYY-MM-DD")
?format_timedate(date(),"Dddd, Mmmm d, YYYY")
|
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.
| #Lua | Lua | local matrix = require "matrix" -- https://github.com/davidm/lua-matrix
local function cramer(mat, vec)
-- Check if matrix is quadratic
assert(#mat == #mat[1], "Matrix is not square!")
-- Check if vector has the same size of the matrix
assert(#mat == #vec, "Vector has not the same size of the matrix!")
local size = #mat
local main_det = matrix.det(mat)
local aux_mats = {}
local dets = {}
local result = {}
for i = 1, size do
-- Construct the auxiliary matrixes
aux_mats[i] = matrix.copy(mat)
for j = 1, size do
aux_mats[i][j][i] = vec[j]
end
-- Calculate the auxiliary determinants
dets[i] = matrix.det(aux_mats[i])
-- Calculate results
result[i] = dets[i]/main_det
end
return result
end
-----------------------------------------------
local A = {{ 2, -1, 5, 1},
{ 3, 2, 2, -6},
{ 1, 3, 3, -1},
{ 5, -2, -3, 3}}
local b = {-3, -32, -47, 49}
local result = cramer(A, b)
print("Result: " .. table.concat(result, ", "))
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Emacs_Lisp | Emacs Lisp | (make-empty-file "output.txt")
(make-directory "docs")
(make-empty-file "/output.txt")
(make-directory "/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.
| #Erlang | Erlang |
-module(new_file).
-export([main/0]).
main() ->
ok = file:write_file( "output.txt", <<>> ),
ok = file:make_dir( "docs" ),
ok = file:write_file( filename:join(["/", "output.txt"]), <<>> ),
ok = file:make_dir( filename:join(["/", "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).
| #Factor | Factor | USING: csv html.streams prettyprint xml.writer ;
"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!"
string>csv [ simple-table. ] with-html-writer pprint-xml |
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.
| #Nanoquery | Nanoquery | def sum(record)
sum = 0
for i in range(1, len(record) - 1)
sum = sum + int(record ~ i)
end for
return sum
end def
open "file.csv"
add "SUM"
for i in range($dbsize, 1)
(i ~ @"SUM") = sum(#i)
end for
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols
import org.apache.commons.csv.
-- =============================================================================
class RCsv public final
properties private constant
NL = String System.getProperty("line.separator")
COL_NAME_SUM = String 'SUM, "integers"'
CSV_IFILE = 'data/csvtest_in.csv'
CSV_OFILE = 'data/csvtest_sumRexx.csv'
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
Arg = Rexx(args)
iCvs = Reader null
oCvs = Writer null
parse arg ifile ofile .
if ifile = '', ifile = '.' then ifile = CSV_IFILE
if ofile = '', ofile = '.' then ofile = CSV_OFILE
say textFileContentsToString(ifile)
do
iCvs = BufferedReader(FileReader(ifile))
oCvs = BufferedWriter(FileWriter(ofile))
processCsv(iCvs, oCvs);
catch ex = IOException
ex.printStackTrace();
finally
do
if iCvs \= null then iCvs.close()
if oCvs \= null then oCvs.close()
catch ex = IOException
ex.printStackTrace()
end
end
say textFileContentsToString(ofile)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException
printer = CSVPrinter null
do
printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL))
oCvsHeaders = java.util.List
oCvsRecord = java.util.List
records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs)
irHeader = records.getHeaderMap()
oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0])))
oCvsHeaders.add(COL_NAME_SUM)
printer.printRecord(oCvsHeaders)
recordIterator = records.iterator()
record = CSVRecord
loop while recordIterator.hasNext()
record = CSVRecord recordIterator.next()
oCvsRecord = record2list(record, oCvsHeaders)
printer.printRecord(oCvsRecord)
end
finally
if printer \= null then printer.close()
end
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List
cvsRecord = java.util.List
rMap = record.toMap()
recNo = record.getRecordNumber()
rMap = alterRecord(rMap, recNo)
sum = summation(record.iterator())
rMap.put(COL_NAME_SUM, sum)
cvsRecord = ArrayList()
loop ci = 0 to oCvsHeaders.size() - 1
key = oCvsHeaders.get(ci)
cvsRecord.add(rMap.get(key))
end ci
return cvsRecord
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method alterRecord(rMap = Map, recNo = long) private static binary returns Map
rv = int
rg = Random(recNo)
rv = rg.nextInt(50)
ks = rMap.keySet().toArray(String[0])
ix = rg.nextInt(ks.length)
yv = long 0
ky = ks[ix];
xv = String rMap.get(ky)
if xv \= null & xv.length() > 0 then do
yv = Long.valueOf(xv).longValue() + rv
rMap.put(ks[ix], String.valueOf(yv))
end
return rMap
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method summation(iColumn = Iterator) private static
sum = 0
loop while iColumn.hasNext()
nv = Rexx(String iColumn.next())
if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0
sum = sum + nv
end
return sum
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method textFileContentsToString(filename) private static
lineOut = ''
fs = Scanner null
do
fs = Scanner(File(filename))
lineOut = lineout || filename || NL
loop while fs.hasNextLine()
line = fs.nextLine()
lineOut = lineout || line || NL
end
catch ex = FileNotFoundException
ex.printStackTrace()
finally
if fs \= null then fs.close()
end
return lineOut
|
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.
| #Pike | Pike | filter(Calendar.Year(2008)->range(Calendar.Year(2121))->years()->month(12)->day(25), lambda(object day){ return day->week_day()==7; })->year()->format_nice(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.