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.
| #LFE | LFE |
(: file write_file '"output.txt" '"Some data")
(: file make_dir '"docs")
(: file write_file '"/output.txt" '"Some data")
(: file make_dir '"/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).
| #Kotlin | Kotlin | // version 1.1.3
val csv =
"Character,Speech\n" +
"The multitude,The messiah! Show us the messiah!\n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; " +
"he's a very naughty boy! Now go away!</angry>\n" +
"The multitude,Who are you?\n" +
"Brians mother,I'm his mother; that's who!\n" +
"The multitude,Behold his mother! Behold his mother!"
fun main(args: Array<String>) {
val i = " " // indent
val sb = StringBuilder("<table>\n$i<tr>\n$i$i<td>")
for (c in csv) {
sb.append( when (c) {
'\n' -> "</td>\n$i</tr>\n$i<tr>\n$i$i<td>"
',' -> "</td>\n$i$i<td>"
'&' -> "&"
'\'' -> "'"
'<' -> "<"
'>' -> ">"
else -> c.toString()
})
}
sb.append("</td>\n$i</tr>\n</table>")
println(sb.toString())
println()
// now using first row as a table header
sb.setLength(0)
sb.append("<table>\n$i<thead>\n$i$i<tr>\n$i$i$i<td>")
val hLength = csv.indexOf('\n') + 1 // find length of first row including CR
for (c in csv.take(hLength)) {
sb.append( when (c) {
'\n' -> "</td>\n$i$i</tr>\n$i</thead>\n$i<tbody>\n$i$i<tr>\n$i$i$i<td>"
',' -> "</td>\n$i$i$i<td>"
else -> c.toString()
})
}
for (c in csv.drop(hLength)) {
sb.append( when (c) {
'\n' -> "</td>\n$i$i</tr>\n$i$i<tr>\n$i$i$i<td>"
',' -> "</td>\n$i$i$i<td>"
'&' -> "&"
'\'' -> "'"
'<' -> "<"
'>' -> ">"
else -> c.toString()
})
}
sb.append("</td>\n$i$i</tr>\n$i</tbody>\n</table>")
println(sb.toString())
} |
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.
| #Racket | Racket | #lang racket
(require (planet neil/csv:1:=7) net/url)
(define make-reader
(make-csv-reader-maker
'((separator-chars #\,)
(strip-leading-whitespace? . #t)
(strip-trailing-whitespace? . #t))))
(define (all-rows port)
(define read-row (make-reader port))
(define head (append (read-row) '("SUM")))
(define rows (for/list ([row (in-producer read-row '())])
(define xs (map string->number row))
(append row (list (~a (apply + xs))))))
(define (->string row) (string-join row "," #:after-last "\n"))
(string-append* (map ->string (cons head rows)))) |
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.
| #Raku | Raku | my $csvfile = './whatever.csv';
my $fh = open($csvfile, :r);
my @header = $fh.get.split(',');
my @csv = map {[.split(',')]>>.Num}, $fh.lines;
close $fh;
my $out = open($csvfile, :w);
$out.say((@header,'SUM').join(','));
$out.say((@$_, [+] @$_).join(',')) for @csv;
close $out; |
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.
| #Standard_ML | Standard ML | (* Call: yearsOfSundayXmas(2008, 2121) *)
fun yearsOfSundayXmas(fromYear, toYear) =
if fromYear>toYear then
()
else
let
val d = Date.date {year=fromYear, month=Date.Dec, day=25,
hour=0, minute=0, second=0,
offset=SOME Time.zeroTime}
val wd = Date.weekDay d
in
if wd=Date.Sun then
(
print(Int.toString fromYear ^ "\n");
yearsOfSundayXmas(fromYear+1, toYear)
)
else
yearsOfSundayXmas(fromYear+1, toYear)
end; |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Stata | Stata | clear
sca n=2121-2008+1
set obs `=n'
gen year=2007+_n
list if dow(mdy(12,25,year))==0, noobs sep(0)
+------+
| year |
|------|
| 2011 |
| 2016 |
| 2022 |
| 2033 |
| 2039 |
| 2044 |
| 2050 |
| 2061 |
| 2067 |
| 2072 |
| 2078 |
| 2089 |
| 2095 |
| 2101 |
| 2107 |
| 2112 |
| 2118 |
+------+ |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Nim | Nim | import strutils, rdstdin
let
w = readLineFromStdin("Width: ").parseInt()
h = readLineFromStdin("Height: ").parseInt()
# Create the rows.
var s = newSeq[seq[int]](h)
# Create the columns.
for i in 0 ..< h:
s[i].newSeq(w)
# Store a value in an element.
s[0][0] = 5
# Retrieve and print it.
echo s[0][0]
# The allocated memory is freed by the garbage collector. |
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.
| #Objeck | Objeck |
use IO;
bundle Default {
class TwoDee {
function : Main(args : System.String[]) ~ Nil {
DoIt();
}
function : native : DoIt() ~ Nil {
Console->GetInstance()->Print("Enter x: ");
x := Console->GetInstance()->ReadString()->ToInt();
Console->GetInstance()->Print("Enter y: ");
y := Console->GetInstance()->ReadString()->ToInt();
if(x > 0 & y > 0) {
array : Int[,] := Int->New[x, y];
array[0, 0] := 2;
array[0, 0]->PrintLine();
};
}
}
}
|
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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface SDAccum : NSObject
{
double sum, sum2;
unsigned int num;
}
-(double)value: (double)v;
-(unsigned int)count;
-(double)mean;
-(double)variance;
-(double)stddev;
@end
@implementation SDAccum
-(double)value: (double)v
{
sum += v;
sum2 += v*v;
num++;
return [self stddev];
}
-(unsigned int)count
{
return num;
}
-(double)mean
{
return (num>0) ? sum/(double)num : 0.0;
}
-(double)variance
{
double m = [self mean];
return (num>0) ? (sum2/(double)num - m*m) : 0.0;
}
-(double)stddev
{
return sqrt([self variance]);
}
@end
int main()
{
@autoreleasepool {
double v[] = { 2,4,4,4,5,5,7,9 };
SDAccum *sdacc = [[SDAccum alloc] init];
for(int i=0; i < sizeof(v)/sizeof(*v) ; i++)
printf("adding %f\tstddev = %f\n", v[i], [sdacc value: v[i]]);
}
return 0;
} |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #Smalltalk | Smalltalk | CRC32Stream hashValueOf:'The quick brown fox jumps over the lazy dog' |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #Swift | Swift | import Foundation
let strData = "The quick brown fox jumps over the lazy dog".dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)
let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length))
println(NSString(format:"%2X", crc)) |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Lasso | Lasso | define cointcoins(
target::integer,
operands::array
) => {
local(
targetlength = #target + 1,
operandlength = #operands -> size,
output = staticarray_join(#targetlength,0),
outerloopcount
)
#output -> get(1) = 1
loop(#operandlength) => {
#outerloopcount = loop_count
loop(#targetlength) => {
if(loop_count >= #operands -> get(#outerloopcount) and loop_count - #operands -> get(#outerloopcount) > 0) => {
#output -> get(loop_count) += #output -> get(loop_count - #operands -> get(#outerloopcount))
}
}
}
return #output -> get(#targetlength)
}
cointcoins(100, array(1,5,10,25,))
'<br />'
cointcoins(100000, array(1, 5, 10, 25, 50, 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.
| #Lua | Lua | function countSums (amount, values)
local t = {}
for i = 1, amount do t[i] = 0 end
t[0] = 1
for k, val in pairs(values) do
for i = val, amount do t[i] = t[i] + t[i - val] end
end
return t[amount]
end
print(countSums(100, {1, 5, 10, 25}))
print(countSums(100000, {1, 5, 10, 25, 50, 100})) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq |
def countSubstring(sub):
[match(sub; "g")] | length; |
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
| #Julia | Julia | matchall(r::Regex, s::String[, overlap::Bool=false]) -> Vector{String}
Return a vector of the matching substrings from eachmatch.
|
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.
| #JavaScript | JavaScript | for (var n = 0; n < 1e14; n++) { // arbitrary limit that's not too big
document.writeln(n.toString(8)); // not sure what's the best way to output it in JavaScript
} |
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.
| #jq | jq | # generate octals as strings, beginning with "0"
def octals:
# input and output: array of octal digits in reverse order
def octal_add1:
[foreach (.[], null) as $d ({carry: 1};
if $d then ($d + .carry ) as $r
| if $r > 7
then {carry: 1, emit: ($r - 8)}
else {carry: 0, emit: $r }
end
elif (.carry == 0) then .emit = null
else .emit = .carry
end;
select(.emit).emit)];
[0] | recurse(octal_add1) | reverse | join("");
octals |
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.
| #Julia | Julia |
for i in one(Int64):typemax(Int64)
print(oct(i), " ")
sleep(0.1)
end
|
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Groovy | Groovy | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
} |
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.
| #Haskell | Haskell | import Data.List (unfoldr)
import Control.Monad (forM_)
import qualified Text.Blaze.Html5 as B
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
import System.Random (RandomGen, getStdGen, randomRs, split)
makeTable
:: RandomGen g
=> [String] -> Int -> g -> B.Html
makeTable headings nRows gen =
B.table $
do B.thead $ B.tr $ forM_ (B.toHtml <$> headings) B.th
B.tbody $
forM_
(zip [1 .. nRows] $ unfoldr (Just . split) gen)
(\(x, g) ->
B.tr $
forM_
(take (length headings) (x : randomRs (1000, 9999) g))
(B.td . B.toHtml))
main :: IO ()
main = do
g <- getStdGen
putStrLn $ renderHtml $ makeTable ["", "X", "Y", "Z"] 3 g |
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
| #Standard_ML | Standard ML | print (Date.fmt "%Y-%m-%d" (Date.fromTimeLocal (Time.now ())) ^ "\n");
print (Date.fmt "%A, %B %d, %Y" (Date.fromTimeLocal (Time.now ())) ^ "\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
| #Stata | Stata | display %tdCCYY-NN-DD td($S_DATE)
display %tdDayname,_Month_dd,_CCYY td($S_DATE) |
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.
| #Liberty_BASIC | Liberty BASIC |
nomainwin
open "output.txt" for output as #f
close #f
result = mkdir( "F:\RC")
if result <>0 then notice "Directory not created!": end
open "F:\RC\output.txt" for output as #f
close #f
end
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Lingo | Lingo | -- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp.createFile("output.txt") |
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).
| #Lambdatalk | Lambdatalk |
{def CSV
Character,Speech\n
The multitude,The messiah! Show us the messiah!\n
Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\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!\n
}
-> CSV
{def csv2html
{lambda {:csv}
{table {@ style="background:#eee;"}
{S.replace ([^,]*),([^_]*)_
by {tr {td {@ style="width:120px;"}{b €1}} {td {i €2}}}
in {S.replace \\n by _ in :csv}}}}}
-> csv2html
{csv2html {CSV}} ->
|
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Red | Red | >>filein: read/lines %file.csv
>>data: copy []
>>foreach item filein [append/only data split item ","]
; [["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"]] |
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.
| #REXX | REXX | /* REXX ***************************************************************
* extend in.csv to add a column containing the sum of the lines' elems
* 21.06.2013 Walter Pachl
**********************************************************************/
csv='in.csv'
Do i=1 By 1 While lines(csv)>0
l=linein(csv)
If i=1 Then
l.i=l',SUM'
Else Do
ol=l
sum=0
Do While l<>''
Parse Var l e ',' l
sum=sum+e
End
l.i=ol','sum
End
End
Call lineout csv
'erase' csv
Do i=1 To i-1
Call lineout csv,l.i
End |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Suneido | Suneido | year = 2008
while (year <= 2121)
{
if Date('#' $ year $ '1225').WeekDay() is 0
Print(year)
++year
} |
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.
| #Swift | Swift | import Cocoa
var year=2008
let formatter=NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
while (year<2122){
var date:NSDate!=formatter.dateFromString(String(year)+"-12-25")
var components=gregorian.components(NSCalendarUnit.CalendarUnitWeekday, fromDate: date)
var dayOfWeek:NSInteger=components.weekday
if(dayOfWeek==1){
println(year)
}
year++
} |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main()
{
@autoreleasepool {
int num1, num2;
scanf("%d %d", &num1, &num2);
NSLog(@"%d %d", num1, num2);
NSMutableArray *arr = [NSMutableArray arrayWithCapacity: (num1*num2)];
// initialize it with 0s
for(int i=0; i < (num1*num2); i++) [arr addObject: @0];
// replace 0s with something more interesting
for(int i=0; i < num1; i++) {
for(int j=0; j < num2; j++) {
arr[i*num2+j] = @(i*j);
}
}
// access a value: i*num2+j, where i,j are the indexes for the bidimensional array
NSLog(@"%@", arr[1*num2+3]);
}
return 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
| #OCaml | OCaml | let sqr x = x *. x
let stddev l =
let n, sx, sx2 =
List.fold_left
(fun (n, sx, sx2) x -> succ n, sx +. x, sx2 +. sqr x)
(0, 0., 0.) l
in
sqrt ((sx2 -. sqr sx /. float n) /. float n)
let _ =
let l = [ 2.;4.;4.;4.;5.;5.;7.;9. ] in
Printf.printf "List: ";
List.iter (Printf.printf "%g ") l;
Printf.printf "\nStandard deviation: %g\n" (stddev l) |
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
| #Tcl | Tcl | package require Tcl 8.6
set data "The quick brown fox jumps over the lazy dog"
puts [format "%x" [zlib crc32 $data]] |
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
| #TXR | TXR | (crc32 "The quick brown fox jumps over the lazy dog") |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #M2000_Interpreter | M2000 Interpreter |
Module FindCoins {
Function count(c(), n) {
dim table(n+1)=0@ : table(0)=1@
for c=0 to len(c())-1 {
if c(c)>n then exit
}
if c else exit
for i=0 to c-1 {for j=c(i) to n {table(j)+=table(j-c(i))}}
=table(n)
}
Print "For 1$ ways to change:";count((1,5,10,25),100)
Print "For 100$ (optional task ways to change):";count((1,5,10,25,50,100),100000)
}
FindCoins
|
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.
| #Maple | Maple | assume(p::posint,abs(x)<1):
coin:=unapply(sum(x^(p*n),n=0..infinity),p):
ways:=(amount,purse)->coeff(series(mul(coin(k),k in purse),x,amount+1),x,amount):
ways(100,[1,5,10,25]);
# 242
ways(1000,[1,5,10,25,50,100]);
# 2103596
ways(10000,[1,5,10,25,50,100]);
# 139946140451
ways(100000,[1,5,10,25,50,100]);
# 13398445413854501 |
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
| #K | K | "the three truths" _ss "th"
0 4 13
#"the three truths" _ss "th"
3
"ababababab" _ss "abab"
0 4
#"ababababab" _ss "abab"
2
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
:count %s !s
0 >ps
[ps> 1 + >ps
$s len nip + snip nip] [$s find dup] while
drop drop ps>
;
"the three truths" "th" count ?
"ababababab" "abab" count ?
" " input |
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.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
:octal "" >ps [dup 7 band tostr ps> chain >ps 8 / int] [dup abs 0 >] while ps> tonum bor ;
( 0 10 ) sequence @octal map pstack
" " input |
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.
| #Kotlin | Kotlin | // version 1.1
// counts up to 177 octal i.e. 127 decimal
fun main(args: Array<String>) {
(0..Byte.MAX_VALUE).forEach { println("%03o".format(it)) }
} |
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.
| #LabVIEW | LabVIEW | '%4o '__number_format set
0 do dup 1 compress . "\n" . 1 + loop |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Haskell | Haskell | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
-- Pointfree form
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize) |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
printf("<table>\n <tr><th></th><th>X</th><th>Y</th><th>Z</th>")
every r := 1 to 4 do {
printf("</tr>\n <tr><td>%d</td>",r)
every 1 to 3 do printf("<td>%d</td>",?9999) # random 4 digit numbers per cell
}
printf("</tr>\n</table>\n")
end
link printf |
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
| #Suneido | Suneido | Date().Format('yyyy-MM-dd') --> "2010-03-16"
Date().LongDate() --> "Tuesday, March 16, 2010" |
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
| #Swift | Swift | import Foundation
extension String {
func toStandardDateWithDateFormat(format: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
dateFormatter.dateStyle = .LongStyle
return dateFormatter.stringFromDate(dateFormatter.dateFromString(self)!)
}
}
let date = "2015-08-28".toStandardDateWithDateFormat("yyyy-MM-dd") |
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.
| #Little | Little | void create_file(string path) {
FILE f;
unless (exists(path)) {
unless (f = fopen(path, "w")){
die(path);
} else {
puts("file ${path} created");
fclose(f);
}
} else {
puts("File ${path} already exists");
}
}
void create_dir(string path) {
unless (exists(path)) {
unless(mkdir(path)) { //mkdir returns 0 on success, -1 on error
puts("directory ${path} created");
} else {
puts(stderr, "Error: directory ${path} not created");
}
} else {
puts("directory ${path} already exists");
}
}
create_file("output.txt");
create_file("/tmp/output.txt");
create_dir("docs");
create_dir("/tmp/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).
| #Liberty_BASIC | Liberty BASIC |
newline$ ="|"
' No escape behaviour, so can't refer to '/n'.
' Generally imported csv would have separator CR LF; easily converted first if needed
csv$ ="Character,Speech" +newline$+_
"The multitude,The messiah! Show us the messiah!" +newline$+_
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" +newline$+_
"The multitude,Who are you?" +newline$+_
"Brians mother,I'm his mother; that's who!" +newline$+_
"The multitude,Behold his mother! Behold his mother!"
print "<HTML>"
print "<HEAD>"
print "</HEAD>"
print "<BODY>"
print "<center><H1>CSV to HTML translation </H1></center>"
print "<table border=1 cellpadding =10>"
print "<tr><td>"
for i =1 to len( csv$)
c$ =mid$( csv$, i, 1)
select case c$
case "|": print "</td></tr>": print "<tr><td>"
case ",": print "</td><td>";
case "<": print "&"+"lt;";
case ">": print "&"+"gt;";
case "&": print "&"+"amp;";
case else: print c$;
end select
next i
print "</td></tr>"
print "</table>"
print "</BODY>"
print "</HTML>"
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.
| #Ring | Ring |
# Project : CSV data manipulation
load "stdlib.ring"
fnin = "input.csv"
fnout = "output.csv"
fpin = fopen(fnin,"r")
fpout = fopen(fnout,"r")
csv = read(fnin)
nr = 0
csvstr = ""
while not feof(fpin)
sum = 0
nr = nr + 1
line = readline(fpin)
if nr = 1
line = substr(line,nl,"")
line = line + ",SUM"
csvstr = csvstr + line + windowsnl()
else
csvarr = split(line,",")
for n = 1 to len(csvarr)
sum = sum + csvarr[n]
next
line = substr(line,nl,"")
line = line + "," + string(sum)
csvstr = csvstr + line + windowsnl()
ok
end
write(fnout,csvstr)
csvend = read(fnout)
fclose(fpin)
fclose(fpout)
see csvend + nl
|
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.
| #Ruby | Ruby | require 'csv'
# read:
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
# manipulate:
ar.first << "SUM"
ar[1..-1].each{|row| row << row.sum}
# write:
CSV.open("out.csv", 'w') do |csv|
ar.each{|line| csv << line}
end |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Tcl | Tcl | package require Tcl 8.5
for {set y 2008} {$y <= 2121} {incr y} {
if {[clock format [clock scan "$y-12-25" -format {%Y-%m-%d}] -format %w] == 0} {
puts "xmas $y is a sunday"
}
} |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #TI-83_BASIC | TI-83 BASIC |
:For(A,2008,2121
:If dayofWk(A,12,25)=1
:Disp A
:End
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #OCaml | OCaml | let nbr1 = read_int ();;
let nbr2 = read_int ();;
let array = Array.make_matrix nbr1 nbr2 0.0;;
array.(0).(0) <- 3.5;;
print_float array.(0).(0); print_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.
| #ooRexx | ooRexx | Say "enter first dimension"
pull d1
say "enter the second dimension"
pull d2
a = .array~new(d1, d2)
a[1, 1] = "Abc"
say a[1, 1]
say d1 d2 a[d1,d2]
say a[10,10]
max=1000000000
b = .array~new(max,max) |
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
| #Oforth | Oforth | Channel new [ ] over send drop const: StdValues
: stddev(x)
| l |
StdValues receive x + dup ->l StdValues send drop
#qs l map sum l size asFloat / l avg sq - sqrt ; |
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
| #Vala | Vala | using ZLib.Utility;
void main() {
var str = (uint8[])"The quick brown fox jumps over the lazy dog".to_utf8();
stdout.printf("%lx\n", crc32(0, str));
} |
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
| #VAX_Assembly | VAX Assembly | EDB88320 0000 1 poly: .long ^xedb88320 ;crc32
00000044 0004 2 table: .blkl 16
0044 3
4C 58 21 0000004C'010E0000' 0044 4 fmt: .ascid "!XL" ;result format
36 35 34 33 32 31 00000057'010E0000' 004F 5 result: .ascid "12345678" ; and buffer
38 37 005D
0000 005F 6 .entry crc,0
A0 AF 7F 0061 7 pushaq table ;fill table
99 AF DF 0064 8 pushal poly ; for
00000000'GF 02 FB 0067 9 calls #2, g^lib$crc_table ; crc opcode
2B' FFFFFFFF 8F 93 AF 0B 006E 10 crc table, #-1, s^#len, b^msg ;table,init,len,string
98'AF 0077
50 50 D2 0079 11 mcoml r0, r0 ;invert result
007C 12 $fao_s ctrstr = fmt, outbuf = result, p1 = r0 ; format
BF AF 7F 008D 13 pushaq result ;and show
00000000'GF 01 FB 0090 14 calls #1, g^lib$put_output ; result 414fa339
04 0097 15 ret
0098 16
72 62 20 6B 63 69 75 71 20 65 68 54 0098 17 msg: .ascii "The quick brown fox jumps over the lazy dog"
70 6D 75 6A 20 78 6F 66 20 6E 77 6F 00A4
6C 20 65 68 74 20 72 65 76 6F 20 73 00B0
67 6F 64 20 79 7A 61 00BC
0000002B 00C3 18 len = .-msg
00C3 19 .end crc |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pennies
15 pennies
Task
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
Optional
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
References
an algorithm from the book Structure and Interpretation of Computer Programs.
an article in the algorithmist.
Change-making problem on Wikipedia.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CountCoins[amount_, coinlist_] := ( ways = ConstantArray[1, amount];
Do[For[j = coin, j <= amount, j++,
If[ j - coin == 0,
ways[[j]] ++,
ways[[j]] += ways[[j - coin]]
]]
, {coin, coinlist}];
ways[[amount]]) |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave |
%% Count_The_Coins
clear;close all;clc;
tic
for i = 1:2 % 1st loop is main challenge 2nd loop is optional challenge
if (i == 1)
amount = 100; % Matlab indexes from 1 not 0, so we need to add 1 to our target value
amount = amount + 1;
coins = [1 5 10 25]; % Value of coins we can use
else
amount = 100*1000; % Matlab indexes from 1 not 0, so we need to add 1 to our target value
amount = amount + 1;
coins = [1 5 10 25 50 100]; % Value of coins we can use
end % End if
ways = zeros(1,amount); % Preallocating for speed
ways(1) = 1; % First solution is 1
% Solves from smallest sub problem to largest (bottom up approach of dynamic programming).
for j = 1:length(coins)
for K = coins(j)+1:amount
ways(K) = ways(K) + ways(K-coins(j));
end % End for
end % End for
if (i == 1)
fprintf(‘Main Challenge: %d \n', ways(amount));
else
fprintf(‘Bonus Challenge: %d \n', ways(amount));
end % End if
end % End for
toc
|
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
| #Kotlin | Kotlin | // version 1.0.6
fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1
fun main(args: Array<String>) {
println(countSubstring("the three truths","th"))
println(countSubstring("ababababab","abab"))
println(countSubstring("",""))
} |
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
| #Lambdatalk | Lambdatalk |
{def countSubstring
{def countSubstring.r
{lambda {:n :i :acc :s}
{if {>= :i :n}
then :acc
else {countSubstring.r :n
{+ :i 1}
{if {W.equal? {W.get :i :s} ⫖}
then {+ :acc 1}
else :acc}
:s} }}}
{lambda {:w :s}
{countSubstring.r {W.length :s} 0 0
{S.replace \s by ⫕ in
{S.replace :w by ⫖ in :s}}}}}
-> countSubstring
{countSubstring th the three truths}
-> 3
{countSubstring ab ababa}
-> 2
{countSubstring aba ababa}
-> 1
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Lang5 | Lang5 | '%4o '__number_format set
0 do dup 1 compress . "\n" . 1 + loop |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #langur | langur | val .limit = 70000
for .i = 0; .i <= .limit; .i += 1 {
writeln $"10x\.i; == 8x\.i:8x;"
} |
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.
| #LFE | LFE | (: lists foreach
(lambda (x)
(: io format '"~p~n" (list (: erlang integer_to_list x 8))))
(: lists seq 0 2000))
|
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
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Factors.bas"
110 FOR I=1 TO 30
120 PRINT I;"= ";FACTORS$(I)
130 NEXT
140 DEF FACTORS$(N)
150 LET F$=""
160 IF N=1 THEN
170 LET FACTORS$="1"
180 ELSE
190 LET P=2
200 DO WHILE P<=N
210 IF MOD(N,P)=0 THEN
220 LET F$=F$&STR$(P)&"*"
230 LET N=INT(N/P)
240 ELSE
250 LET P=P+1
260 END IF
270 LOOP
280 LET FACTORS$=F$(1:LEN(F$)-1)
290 END IF
300 END DEF |
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
| #J | J | 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.
| #J | J | ele=:4 :0
nm=. x-.LF
lf=. x-.nm
;('<',nm,'>') ,L:0 y ,L:0 '</',nm,'>',lf
)
hTbl=:4 :0
rows=. 'td' <@ele"1 ":&.>y
'table' ele ('tr',LF) <@ele ('th' ele x); rows
) |
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
| #Tcl | Tcl | set now [clock seconds]
puts [clock format $now -format "%Y-%m-%d"]
puts [clock format $now -format "%A, %B %d, %Y"] |
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
| #Terraform | Terraform | locals {
today = timestamp()
}
output "iso" {
value = formatdate("YYYY-MM-DD", local.today)
}
output "us-long" {
value = formatdate("EEEE, MMMM D, YYYY", local.today)
} |
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.
| #Lua | Lua | io.open("output.txt", "w"):close()
io.open("\\output.txt", "w"):close() |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module MakeDirAndFile {
Def WorkingDir$, RootDir$
If Drive$(Dir$)="Drive Fixed" Then WorkingDir$=Dir$
If Drive$("C:\")="Drive Fixed" Then RootDir$="C:\"
if WorkingDir$<>"" Then task(WorkingDir$)
If RootDir$<>"" then task(RootDir$)
Dir User ' return to user directory
Sub task(WorkingDir$)
Dir WorkingDir$
If Not Exist.Dir("docs") then SubDir "docs" : Dir WorkingDir$
If Exist.Dir("docs") Then Print str$(File.Stamp("docs"), "YYYY|MM|DD|hh:nn:ss")
Open "output.txt" For Output as #F
Close #f
If Exist("output.txt") Then Print str$(File.Stamp("output.txt"), "YYYY|MM|DD|hh:nn:ss")
End Sub
}
MakeDirAndFile
|
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).
| #Lua | Lua | FS = "," -- field separator
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!
]]
csv = csv:gsub( "<", "<" )
csv = csv:gsub( ">", "&gr;" )
html = { "<table>" }
for line in string.gmatch( csv, "(.-\n)" ) do
str = "<tr>"
for field in string.gmatch( line, "(.-)["..FS.."?\n?]" ) do
str = str .. "<td>" .. field .. "</td>"
end
str = str .. "</tr>"
html[#html+1] = str;
end
html[#html+1] = "</table>"
for _, line in pairs(html) do
print(line)
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.
| #Run_BASIC | Run BASIC | 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
"
print csv$
dim csvData$(5,5)
for r = 1 to 5
a$ = word$(csv$,r,chr$(13))
for c = 1 to 5
csvData$(r,c) = word$(a$,c,",")
next c
next r
[loop]
input "Row to change:";r
input "Col to change;";c
if r > 5 or c > 5 then
print "Row ";r;" or Col ";c;" is greater than 5"
goto [loop]
end if
input "Change Row ";r;" Col ";c;" from ";csvData$(r,c);" to ";d$
csvData$(r,c) = d$
for r = 1 to 5
for c = 1 to 5
print cma$;csvData$(r,c);
cma$ = ","
next c
cma$ = ""
print
next r |
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.
| #Rust | Rust | use std::error::Error;
use std::num::ParseIntError;
use csv::{Reader, Writer};
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = Reader::from_path("data.csv")?;
let mut writer = Writer::from_path("output.csv")?;
// headers() returns an immutable reference, so clone() before appending
let mut headers = reader.headers()?.clone();
headers.push_field("SUM");
writer.write_record(headers.iter())?;
for row in reader.records() {
let mut row = row?;
// `sum` needs the type annotation so that `parse::<i64>` knows what error type to return
let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| {
Ok(accum + s.parse::<i64>()?)
});
row.push_field(&sum?.to_string());
writer.write_record(row.iter())?;
}
writer.flush()?;
Ok(())
} |
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.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
PRINT "25th of December will be a Sunday in the following years: "
LOOP year=2008,2121
SET dayofweek = DATE (number,25,12,year,nummer)
IF (dayofweek==7) PRINT year
ENDLOOP
|
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.
| #TypeScript | TypeScript |
// Find years with Sunday Christmas
var f = 2008;
var t = 2121;
console.log(`Sunday Christmases ${f} - ${t}`);
for (y = f; y <= t; y++) {
var x = (y * 365) + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 6;
if (x % 7 == 0)
process.stdout.write(`${y}\t`);
}
process.stdout.write("\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.
| #Oz | Oz | declare
%% Read width and height from stdin
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
Width = {String.toInt {StdIn getS($)}}
Height = {String.toInt {StdIn getS($)}}
%% create array
Arr = {Array.new 1 Width unit}
in
for X in 1..Width do
Arr.X := {Array.new 1 Height 0}
end
%% set and read element
Arr.1.1 := 42
{Show Arr.1.1} |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #PARI.2FGP | PARI/GP | tmp(m,n)={
my(M=matrix(m,n,i,j,0));
M[1,1]=1;
M[1,1]
}; |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ooRexx | ooRexx | sdacc = .SDAccum~new
x = .array~of(2,4,4,4,5,5,7,9)
sd = 0
do i = 1 to x~size
sd = sdacc~value(x[i])
Say '#'i 'value =' x[i] 'stdev =' sd
end
::class SDAccum
::method sum attribute
::method sum2 attribute
::method count attribute
::method init
self~sum = 0.0
self~sum2 = 0.0
self~count = 0
::method value
expose sum sum2 count
parse arg x
sum = sum + x
sum2 = sum2 + x*x
count = count + 1
return self~stddev
::method mean
expose sum count
return sum/count
::method variance
expose sum2 count
m = self~mean
return sum2/count - m*m
::method stddev
return self~sqrt(self~variance)
::method sqrt
arg n
if n = 0 then return 0
ans = n / 2
prev = n
do until prev = ans
prev = ans
ans = ( prev + ( n / prev ) ) / 2
end
return ans |
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
| #VBScript | VBScript |
dim crctbl(255)
const crcc =&hEDB88320
sub gencrctable
for i= 0 to 255
k=i
for j=1 to 8
if k and 1 then
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
k=k xor crcc
else
k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
end if
next ' j
crctbl(i)=k
next
end sub
function crc32 (buf)
dim r,r1,i
r=&hffffffff
for i=1 to len(buf)
r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255)
next
crc32=r xor &hffffffff
end function
'414FA339
gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
|
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #Visual_Basic | Visual Basic | Option Explicit
Declare Function RtlComputeCrc32 Lib "ntdll.dll" _
(ByVal dwInitial As Long, pData As Any, ByVal iLen As Long) As Long
'--------------------------------------------------------------------
Sub Main()
Dim s As String
Dim b() As Byte
Dim l As Long
s = "The quick brown fox jumps over the lazy dog"
b() = StrConv(s, vbFromUnicode) 'convert Unicode to ASCII
l = RtlComputeCrc32(0&, b(0), Len(s))
Debug.Assert l = &H414FA339
End Sub |
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.
| #Mercury | Mercury | :- module coins.
:- interface.
:- import_module int, io.
:- type coin ---> quarter; dime; nickel; penny.
:- type purse ---> purse(int, int, int, int).
:- pred sum_to(int::in, purse::out) is nondet.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module solutions, list, string.
:- func value(coin) = int.
value(quarter) = 25.
value(dime) = 10.
value(nickel) = 5.
value(penny) = 1.
:- pred supply(coin::in, int::in, int::out) is multi.
supply(C, Target, N) :- upto(Target div value(C), N).
:- pred upto(int::in, int::out) is multi.
upto(N, R) :- ( nondet_int_in_range(0, N, R0) -> R = R0 ; R = 0 ).
sum_to(To, Purse) :-
Purse = purse(Q, D, N, P),
sum(Purse) = To,
supply(quarter, To, Q),
supply(dime, To, D),
supply(nickel, To, N),
supply(penny, To, P).
:- func sum(purse) = int.
sum(purse(Q, D, N, P)) =
value(quarter) * Q + value(dime) * D +
value(nickel) * N + value(penny) * P.
main(!IO) :-
solutions(sum_to(100), L),
show(L, !IO),
io.format("There are %d ways to make change for a dollar.\n",
[i(length(L))], !IO).
:- pred show(list(purse)::in, io::di, io::uo) is det.
show([], !IO).
show([P|T], !IO) :-
io.write(P, !IO), io.nl(!IO),
show(T, !IO). |
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.
| #Nim | Nim | proc changes(amount: int, coins: openArray[int]): int =
var ways = @[1]
ways.setLen(amount+1)
for coin in coins:
for j in coin..amount:
ways[j] += ways[j-coin]
ways[amount]
echo changes(100, [1, 5, 10, 25])
echo changes(100000, [1, 5, 10, 25, 50, 100]) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #langur | langur | writeln len indices q(th), q(the three truths)
writeln len indices q(abab), q(ababababab) |
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
| #Lasso | Lasso | define countSubstring(str::string, substr::string)::integer => {
local(i = 1, foundpos = -1, found = 0)
while(#i < #str->size && #foundpos != 0) => {
protect => {
handle_error => { #foundpos = 0 }
#foundpos = #str->find(#substr, -offset=#i)
}
if(#foundpos > 0) => {
#found += 1
#i = #foundpos + #substr->size
else
#i++
}
}
return #found
}
define countSubstring_bothways(str::string, substr::string)::integer => {
local(found = countSubstring(#str,#substr))
#str->reverse
local(found2 = countSubstring(#str,#substr))
#found > #found2 ? return #found | return #found2
}
countSubstring_bothways('the three truths','th')
//3
countSubstring_bothways('ababababab','abab')
//2 |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Liberty_BASIC | Liberty BASIC |
'the method used here uses the base-conversion from RC Non-decimal radices/Convert
'to terminate hit <CTRL<BRK>
global alphanum$
alphanum$ ="01234567"
i =0
while 1
print toBase$( 8, i)
i =i +1
wend
end
function toBase$( base, number) ' Convert decimal variable to number string.
maxIntegerBitSize =len( str$( number))
toBase$ =""
for i =10 to 1 step -1
remainder =number mod base
toBase$ =mid$( alphanum$, remainder +1, 1) +toBase$
number =int( number /base)
if number <1 then exit for
next i
toBase$ =right$( " " +toBase$, 10)
end function
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #Logo | Logo | to increment_octal :n
ifelse [empty? :n] [
output 1
] [
local "last
make "last last :n
local "butlast
make "butlast butlast :n
make "last sum :last 1
ifelse [:last < 8] [
output word :butlast :last
] [
output word (increment_octal :butlast) 0
]
]
end
make "oct 0
while ["true] [
print :oct
make "oct increment_octal :oct
] |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Java | Java | public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
} |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Java | Java | public class HTML {
public static String array2HTML(Object[][] array){
StringBuilder html = new StringBuilder(
"<table>");
for(Object elem:array[0]){
html.append("<th>" + elem.toString() + "</th>");
}
for(int i = 1; i < array.length; i++){
Object[] row = array[i];
html.append("<tr>");
for(Object elem:row){
html.append("<td>" + elem.toString() + "</td>");
}
html.append("</tr>");
}
html.append("</table>");
return html.toString();
}
public static void main(String[] args){
Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}};
System.out.println(array2HTML(ints));
}
} |
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
SET dayofweek = DATE (today,day,month,year,number)
SET months=*
DATA January
DATA Februari
DATA March
DATA April
DATA Mai
DATA June
DATA July
DATA August
DATA September
DATA October
DATA November
DATA December
SET days="Monday'Tuesday'Wendsday'Thursday'Fryday'Saturday'Sonday"
SET nameofday =SELECT (days,#dayofweek)
SET nameofmonth=SELECT (months,#month)
SET format1=JOIN (year,"-",month,day)
SET format2=CONCAT (nameofday,", ",nameofmonth," ",day, ", ",year)
PRINT format1
PRINT format2
|
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
| #UNIX_Shell | UNIX Shell | date +"%Y-%m-%d"
date +"%A, %B %d, %Y" |
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.
| #Maple | Maple |
FileTools:-Text:-WriteFile("output.txt", ""); # make empty file in current dir
FileTools:-MakeDirectory("docs"); # make empty dir in current dir
FileTools:-Text:-WriteFile("/output.txt", ""); # make empty file in root dir
FileTools:-MakeDirectory("/docs"); # make empty dir in root dir
|
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
SetDirectory@NotebookDirectory[];
t = OpenWrite["output.txt"]
Close[t]
s = OpenWrite[First@FileNameSplit[$InstallationDirectory] <> "\\output.txt"]
Close[s]
(*In root directory*)
CreateDirectory["\\docs"]
(*In current operating directory*)
CreateDirectory[Directory[]<>"\\docs"]
(*"left<>right" is shorthand for "StringJoin[left,right]"*)
|
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).
| #Maple | Maple | #A translation of the C code posted
html_table := proc(str)
local char;
printf("<table>\n<tr><td>");
for char in str do
if char = "\n" then
printf("</td></tr>\n<tr><td>")
elif char = "," then
printf("</td><td>")
elif char = "<" then
printf("<")
elif char = ">" then
printf(">")
elif char = "&" then
printf("&")
else
printf(char)
end if;
end do;
printf("</td></tr>\n</table>");
end proc;
html_table("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.
| #SAS | SAS | data _null_;
infile datalines dlm="," firstobs=2;
file "output.csv" dlm=",";
input c1-c5;
if _n_=1 then put "C1,C2,C3,C4,C5,Sum";
s=sum(of c1-c5);
put c1-c5 s;
datalines;
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
;
run; |
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.
| #Scala | Scala | import scala.io.Source
object parseCSV extends App {
val rawData = """|C1,C2,C3,C4,C5
|1,5,9,13,17
|2,6,10,14,18
|3,7,11,15,19
|20,21,22,23,24""".stripMargin
val data = Seq((Source.fromString(rawData).getLines()).map(_.split(",")).toSeq: _*)
val output = ((data.take(1).flatMap(x => x) :+ "SUM").mkString(",") +: // Header line
data.drop(1).map(_.map(_.toInt)). // Convert per line each array of String to array of integer
map(cells => (cells, cells.sum)). //Add sum column to assemble a tuple. Part 1 are original numbers, 2 is the sum
map(part => s"${part._1.mkString(",")},${part._2}")).mkString("\n")
println(output)
/* Outputs:
C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
20,21,22,23,24,110
*/
} |
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.
| #UNIX_Shell | UNIX Shell | #! /bin/bash
for (( i=2008; i<=2121; ++i ))
do
date -d "$i-12-25"
done |grep Sun
exit 0 |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Ursala | Ursala | #import std
#import nat
#import stt
christmases = time_to_string* string_to_time*TS 'Dec 25 0:0:0 '-*@hS %nP* nrange/2008 2121
#show+
sunday_years = ~&zS sep` * =]'Sun'*~ christmases |
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.
| #Pascal | Pascal | program array2d(input, output);
type
tArray2d(dim1, dim2: integer) = array[1 .. dim1, 1 .. dim2] of real;
pArray2D = ^tArray2D;
var
d1, d2: integer;
data: pArray2D;
begin
{ read values }
readln(d1, d2);
{ create array }
new(data, d1, d2);
{ write element }
data^[1,1] := 3.5;
{ output element }
writeln(data^[1,1]);
{ get rid of array }
dispose(data);
end. |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #PARI.2FGP | PARI/GP | newpoint(x)={
myT=x;
myS=0;
myN=1;
[myT,myS]/myN
};
addpoint(x)={
myT+=x;
myN++;
myS+=(myN*x-myT)^2/myN/(myN-1);
[myT,myS]/myN
};
addpoints(v)={
print(newpoint(v[1]));
for(i=2,#v,print(addpoint(v[i])));
print("Mean: ",myT/myN);
print("Standard deviation: ",sqrt(myS/myN))
};
addpoints([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
| #Visual_Basic_.NET | Visual Basic .NET | Public Class Crc32
' Table for pre-calculated values.
Shared table(255) As UInteger
' Initialize table
Shared Sub New()
For i As UInteger = 0 To table.Length - 1
Dim te As UInteger = i ' table entry
For j As Integer = 0 To 7
If (te And 1) = 1 Then te = (te >> 1) Xor &HEDB88320UI Else te >>= 1
Next
table(i) = te
Next
End Sub
' Return checksum calculation for Byte Array,
' optionally resuming (used when breaking a large file into read-buffer-sized blocks).
' Call with Init = False to continue calculation.
Public Shared Function cs(BA As Byte(), Optional Init As Boolean = True) As UInteger
Static crc As UInteger
If Init Then crc = UInteger.MaxValue
For Each b In BA
crc = (crc >> 8) Xor table((crc And &HFF) Xor b)
Next
Return Not crc
End Function
End Class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.