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_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.
|
#AppleScript
|
AppleScript
|
set R to text returned of (display dialog "Enter number of rows:" default answer 2) as integer
set c to text returned of (display dialog "Enter number of columns:" default answer 2) as integer
set array to {}
repeat with i from 1 to R
set temp to {}
repeat with j from 1 to c
set temp's end to 0
end repeat
set array's end to temp
end repeat
-- Address the first column of the first row:
set array's item 1's item 1 to -10
-- Negative index values can be used to address from the end:
set array's item -1's item -1 to 10
-- Access an item (row 2 column 1):
set x to array's item 2's item 1
return array
-- Destroy array (typically unnecessary since it'll automatically be destroyed once script ends).
set array to {}
|
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
|
#D
|
D
|
import std.stdio, std.math;
struct StdDev {
real sum = 0.0, sqSum = 0.0;
long nvalues;
void addNumber(in real input) pure nothrow {
nvalues++;
sum += input;
sqSum += input ^^ 2;
}
real getStdDev() const pure nothrow {
if (nvalues == 0)
return 0.0;
immutable real mean = sum / nvalues;
return sqrt(sqSum / nvalues - mean ^^ 2);
}
}
void main() {
StdDev stdev;
foreach (el; [2.0, 4, 4, 4, 5, 5, 7, 9]) {
stdev.addNumber(el);
writefln("%e", stdev.getStdDev());
}
}
|
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
|
#Clojure
|
Clojure
|
(let [crc (new java.util.zip.CRC32)
str "The quick brown fox jumps over the lazy dog"]
(. crc update (. str getBytes))
(printf "CRC-32('%s') = %s\n" str (Long/toHexString (. crc getValue))))
|
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
|
#COBOL
|
COBOL
|
*> tectonics: cobc -xj crc32-zlib.cob -lz
identification division.
program-id. rosetta-crc32.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 crc32-initial usage binary-c-long.
01 crc32-result usage binary-c-long unsigned.
01 crc32-input.
05 value "The quick brown fox jumps over the lazy dog".
01 crc32-hex usage pointer.
procedure division.
crc32-main.
*> libz crc32
call "crc32" using
by value crc32-initial
by reference crc32-input
by value length(crc32-input)
returning crc32-result
on exception
display "error: no crc32 zlib linkage" upon syserr
end-call
call "printf" using "checksum: %lx" & x"0a" by value crc32-result
*> GnuCOBOL pointers are displayed in hex by default
set crc32-hex up by crc32-result
display 'crc32 of "' crc32-input '" is ' crc32-hex
goback.
end program rosetta-crc32.
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
write(map(&date,"/","-"))
write(&dateline ? tab(find(&date[1:5])+4))
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.
|
#Action.21
|
Action!
|
PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
PROC CreateFile(CHAR ARRAY fname)
BYTE dev=[1]
Close(dev)
Open(dev,fname,8)
Close(dev)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*", fname="D:OUTPUT.TXT"
PrintF("Dir ""%S""%E",filter)
Dir(filter)
PrintF("Create file ""%S""%E%E",fname)
CreateFile(fname)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN
|
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.
|
#Ada
|
Ada
|
with Ada.Streams.Stream_IO, Ada.Directories;
use Ada.Streams.Stream_IO, Ada.Directories;
procedure File_Creation is
File_Handle : File_Type;
begin
Create (File_Handle, Out_File, "output.txt");
Close (File_Handle);
Create_Directory("docs");
Create (File_Handle, Out_File, "/output.txt");
Close (File_Handle);
Create_Directory("/docs");
end File_Creation;
|
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).
|
#AutoHotkey
|
AutoHotkey
|
CSVData =
(
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!
)
TableData := "<table>"
Loop Parse, CSVData,`n
{
TableData .= "`n <tr>"
Loop Parse, A_LoopField, CSV
TableData .= "<td>" HTMLEncode(A_LoopField) "</td>"
TableData .= "</tr>"
}
TableData .= "`n</table>"
HTMLEncode(str){
static rep := "&<lt;>gt;""quot"
Loop Parse, rep,;
StringReplace, str, str, % SubStr(A_LoopField, 1, 1), % "&" . SubStr(A_LoopField, 2) . ";", All
return str
}
MsgBox % clipboard := TableData
|
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.
|
#ECL
|
ECL
|
// Assumes a CSV file exists and has been sprayed to a Thor cluster
MyFileLayout := RECORD
STRING Field1;
STRING Field2;
STRING Field3;
STRING Field4;
STRING Field5;
END;
MyDataset := DATASET ('~Rosetta::myCSVFile', MyFileLayout,CSV(SEPARATOR(',')));
MyFileLayout Appended(MyFileLayout pInput):= TRANSFORM
SELF.Field1 := pInput.Field1 +'x';
SELF.Field2 := pInput.Field2 +'y';
SELF.Field3 := pInput.Field3 +'z';
SELF.Field4 := pInput.Field4 +'a';
SELF.Field5 := pInput.Field5 +'b';
END ;
MyNewDataset := PROJECT(MyDataset,Appended(LEFT));
OUTPUT(myNewDataset,,'~Rosetta::myNewCSVFile',CSV,OVERWRITE);
|
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.
|
#Elixir
|
Elixir
|
defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
|
http://rosettacode.org/wiki/Damm_algorithm
|
Damm algorithm
|
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
|
#Nim
|
Nim
|
from algorithm import reverse
const Table = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]
type Digit = range[0..9]
func isValid(digits: openArray[Digit]): bool =
## Apply Damm algorithm to check validity of a digit sequence.
var interim = 0
for d in digits:
interim = Table[interim][d]
result = interim == 0
proc toDigits(n: int): seq[Digit] =
## Return the digits of a number.
var n = n
while true:
result.add(n mod 10)
n = n div 10
if n == 0:
break
result.reverse()
proc checkData(digits: openArray[Digit]) =
## Check if a digit sequence if valid.
if isValid(digits):
echo "Sequence ", digits, " is valid."
else:
echo "Sequence ", digits, " is invalid."
checkData(5724.toDigits)
checkData(5727.toDigits)
checkData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 1])
checkData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 8])
|
http://rosettacode.org/wiki/Damm_algorithm
|
Damm algorithm
|
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
|
#Objeck
|
Objeck
|
class DammAlgorithm {
@table : static : Int[,];
function : Main(args : String[]) ~ Nil {
@table := [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2]
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3]
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9]
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6]
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8]
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1]
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4]
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7]
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5]
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0]];
numbers := [ 5724, 5727, 112946, 112949 ];
each (i : numbers) {
number := numbers[i];
isValid := Damm(number->ToString());
if (isValid) {
"{$number} is valid"->PrintLine();
}
else {
"{$number} is invalid"->PrintLine();
};
};
}
function : Damm(s : String) ~ Bool {
interim := 0;
each (i : s) {
interim := @table[interim, s->Get(i) - '0'];
};
return interim = 0;
}
}
|
http://rosettacode.org/wiki/Cuban_primes
|
Cuban primes
|
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
|
#Haskell
|
Haskell
|
import Data.Numbers.Primes (isPrime)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
cubans :: [Int]
cubans = filter isPrime . map (\x -> (succ x ^ 3) - (x ^ 3)) $ [1 ..]
main :: IO ()
main = do
mapM_ (\row -> mapM_ (printf "%10s" . thousands) row >> printf "\n") $ rows cubans
printf "\nThe 100,000th cuban prime is: %10s\n" $ thousands $ cubans !! 99999
where
rows = chunksOf 10 . take 200
thousands = reverse . intercalate "," . chunksOf 3 . reverse . show
|
http://rosettacode.org/wiki/Cuban_primes
|
Cuban primes
|
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
|
#J
|
J
|
isPrime =: 1&p:
assert 1 0 -: isPrime 3 9
NB. difference, but first cube, of incremented y with y
dcc =: -&(^&3)~ >:
assert ((8 9 13^3)-7 8 12^3) -: dcc 7 8 12
Filter =: (#~`)(`:6)
assert 2 3 5 7 11 13 -: isPrime Filter i. 16
cubanPrime =: [: isPrime Filter dcc
assert 7 19 37 61 127 271 331 397 547 631 919 -: cubanPrime i. 20
NB. comatose copies with comma fill
comatose =: (#!.','~ (1 1 1j1 1 1 1j1 1 1 1j1 1 1 1j1 1 1 1j1 1 1 1j1 1 1 1 {.~ -@:#))@:":&>
assert (comatose 1000 1238 12 989832) -: [;._2 ] 0 :0
1,000
1,238
12
989,832
)
CP =: cubanPrime i. 800000x
# CP NB. tally, I've stored more than 100000 cuban primes
103278
NB. granted, I used wolframalpha Solve[(n+1)^3-n^3==1792617147127,n]
9!:17]2 2 NB. specify bottom right position in box
comatose&.> 10 20 $ CP
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│ 7│ 19│ 37│ 61│ 127│ 271│ 331│ 397│ 547│ 631│ 919│ 1,657│ 1,801│ 1,951│ 2,269│ 2,437│ 2,791│ 3,169│ 3,571│ 4,219│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 4,447│ 5,167│ 5,419│ 6,211│ 7,057│ 7,351│ 8,269│ 9,241│ 10,267│ 11,719│ 12,097│ 13,267│ 13,669│ 16,651│ 19,441│ 19,927│ 22,447│ 23,497│ 24,571│ 25,117│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 26,227│ 27,361│ 33,391│ 35,317│ 42,841│ 45,757│ 47,251│ 49,537│ 50,311│ 55,897│ 59,221│ 60,919│ 65,269│ 70,687│ 73,477│ 74,419│ 75,367│ 81,181│ 82,171│ 87,211│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 88,237│ 89,269│ 92,401│ 96,661│ 102,121│ 103,231│ 104,347│ 110,017│ 112,327│ 114,661│ 115,837│ 126,691│ 129,169│ 131,671│ 135,469│ 140,617│ 144,541│ 145,861│ 151,201│ 155,269│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 163,567│ 169,219│ 170,647│ 176,419│ 180,811│ 189,757│ 200,467│ 202,021│ 213,067│ 231,019│ 234,361│ 241,117│ 246,247│ 251,431│ 260,191│ 263,737│ 267,307│ 276,337│ 279,991│ 283,669│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 285,517│ 292,969│ 296,731│ 298,621│ 310,087│ 329,677│ 333,667│ 337,681│ 347,821│ 351,919│ 360,187│ 368,551│ 372,769│ 374,887│ 377,011│ 383,419│ 387,721│ 398,581│ 407,377│ 423,001│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 436,627│ 452,797│ 459,817│ 476,407│ 478,801│ 493,291│ 522,919│ 527,941│ 553,411│ 574,219│ 584,767│ 590,077│ 592,741│ 595,411│ 603,457│ 608,851│ 611,557│ 619,711│ 627,919│ 650,071│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 658,477│ 666,937│ 689,761│ 692,641│ 698,419│ 707,131│ 733,591│ 742,519│ 760,537│ 769,627│ 772,669│ 784,897│ 791,047│ 812,761│ 825,301│ 837,937│ 847,477│ 863,497│ 879,667│ 886,177│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│ 895,987│ 909,151│ 915,769│ 925,741│ 929,077│ 932,419│ 939,121│ 952,597│ 972,991│ 976,411│ 986,707│ 990,151│ 997,057│1,021,417│1,024,921│1,035,469│1,074,607│1,085,407│1,110,817│1,114,471│
├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤
│1,125,469│1,155,061│1,177,507│1,181,269│1,215,397│1,253,887│1,281,187│1,285,111│1,324,681│1,328,671│1,372,957│1,409,731│1,422,097│1,426,231│1,442,827│1,451,161│1,480,519│1,484,737│1,527,247│1,570,357│
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘
NB. the one hundred thousandth cuban prime
comatose (<: 100000) { CP
1,792,617,147,127
cubanPrime f. NB. cubanPrime with fixed adverbs
[: (#~ 1&p:) (-&(^&3)~ >:)
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Ring
|
Ring
|
# Project : Currency
nhamburger = "4000000000"
phamburger = "5.50"
nmilkshakes = "2"
pmilkshakes = "2.86"
taxrate = "0.0765"
price = nhamburger * phamburger + nmilkshakes * pmilkshakes
tax = price * taxrate
see "total price before tax : " + price + nl
see "tax thereon @ 7.65 : " + tax + nl
see "total price after tax : " + (price + tax) + nl
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Ruby
|
Ruby
|
require 'bigdecimal/util'
before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d
tax = (before_tax * 0.0765.to_d).round(2)
total = before_tax + tax
puts "Before tax: $#{before_tax.to_s('F')}
Tax: $#{tax.to_s('F')}
Total: $#{total.to_s('F')}"
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Rust
|
Rust
|
extern crate num_bigint; // 0.3.0
extern crate num_rational; // 0.3.0
use num_bigint::BigInt;
use num_rational::BigRational;
use std::ops::{Add, Mul};
use std::fmt;
fn main() {
let hamburger = Currency::new(5.50);
let milkshake = Currency::new(2.86);
let pre_tax = hamburger * 4_000_000_000_000_000 + milkshake * 2;
println!("Price before tax: {}", pre_tax);
let tax = pre_tax.calculate_tax();
println!("Tax: {}", tax);
let post_tax = pre_tax + tax;
println!("Price after tax: {}", post_tax);
}
#[derive(Debug)]
struct Currency {
amount: BigRational,
}
impl Add for Currency {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
amount: self.amount + other.amount,
}
}
}
impl Mul<u64> for Currency {
type Output = Self;
fn mul(self, other: u64) -> Self {
Self {
amount: self.amount * BigInt::from(other),
}
}
}
impl fmt::Display for Currency {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let cents = (&self.amount * BigInt::from(100)).to_integer();
write!(f, "${}.{}", ¢s / 100, ¢s % 100)
}
}
impl Currency {
fn new(num: f64) -> Self {
Self {
amount: BigRational::new(((num * 100.0) as i64).into(), 100.into())
}
}
fn calculate_tax(&self) -> Self {
let tax_val = BigRational::new(765.into(), 100.into());// 7,65 -> 0.0765 after the next line
let amount = (&self.amount * tax_val).ceil() / BigInt::from(100);
Self {
amount
}
}
}
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#PARI.2FGP
|
PARI/GP
|
curriedPlus(x)=y->x+y;
curriedPlus(1)(2)
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#Perl
|
Perl
|
sub curry{
my ($func, @args) = @_;
sub {
#This @_ is later
&$func(@args, @_);
}
}
sub plusXY{
$_[0] + $_[1];
}
my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n";
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#Python
|
Python
|
import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3] # format can't handle "EST" for some reason
tdelta = datetime.timedelta(hours=12) # twelve hours..
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#R
|
R
|
time <- strptime("March 7 2009 7:30pm EST", "%B %d %Y %I:%M%p %Z") # "2009-03-07 19:30:00"
isotime <- ISOdatetime(1900 + time$year, time$mon, time$mday,
time$hour, time$min, time$sec, "EST") # "2009-02-07 19:30:00 EST"
twelvehourslater <- isotime + 12 * 60 * 60 # "2009-02-08 07:30:00 EST"
timeincentraleurope <- format(isotime, tz="CET", usetz=TRUE) #"2009-02-08 01:30:00 CET"
|
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.
|
#Lasso
|
Lasso
|
loop(-From=2008, -to=2121) => {^
local(tDate = date('12/25/' + loop_count))
#tDate->dayOfWeek == 1 ? '\r' + #tDate->format('%D') + ' 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.
|
#Liberty_BASIC
|
Liberty BASIC
|
count = 0
for year = 2008 to 2121
dateString$="12/25/";year
dayNumber=date$(dateString$)
if dayNumber mod 7 = 5 then
count = count + 1
print dateString$
end if
next year
print count; " years when Christmas Day falls on a Sunday"
end
|
http://rosettacode.org/wiki/CUSIP
|
CUSIP
|
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
|
#PicoLisp
|
PicoLisp
|
(de cusip (Str)
(let (Str (mapcar char (chop Str)) S 0)
(for (I . C) (head 8 Str)
(let V
(cond
((<= 48 C 57) (- C 48))
((<= 65 C 90) (+ 10 (- C 65)))
((= C 42) 36)
((= C 64) 37)
((= C 35) 38) )
(or
(bit? 1 I)
(setq V (>> -1 V)) )
(inc
'S
(+ (/ V 10) (% V 10)) ) ) )
(=
(- (last Str) 48)
(% (- 10 (% S 10)) 10) ) ) )
(println
(mapcar
cusip
(quote
"037833100"
"17275R102"
"38259P508"
"68389X106"
"68389X105" ) ) )
|
http://rosettacode.org/wiki/CUSIP
|
CUSIP
|
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
|
#PowerShell
|
PowerShell
|
function Get-CheckDigitCUSIP {
[CmdletBinding()]
[OutputType([int])]
Param ( # Validate input
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )] # @#*
[ValidateScript({$_.Length -eq 9})]
[string]
$cusip
)
$sum = 0
0..7 | ForEach { $c = $cusip[$_] ; $v = $null
if ([Char]::IsDigit($c)) { $v = [char]::GetNumericValue($c) }
if ([Char]::IsLetter($c)) { $v = [int][char]$c - [int][char]'A' +10 }
if ($c -eq '*') { $v = 36 }
if ($c -eq '@') { $v = 37 }
if ($c -eq '#') { $v = 38 }
if($_ % 2){ $v += $v }
$sum += [int][Math]::Floor($v / 10 ) + ($v % 10)
}
[int]$checkDigit_calculated = ( 10 - ($sum % 10) ) % 10
return( $checkDigit_calculated )
}
function Test-IsCUSIP {
[CmdletBinding()]
[OutputType([bool])]
Param (
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )]
[ValidateScript({$_.Length -eq 9})]
[string]
$cusip
)
[int]$checkDigit_told = $cusip[-1].ToString()
$checkDigit_calculated = Get-CheckDigitCUSIP $cusip
($checkDigit_calculated -eq $checkDigit_told)
}
$data = @"
037833100`tApple Incorporated
17275R102`tCisco Systems
38259P508`tGoogle Incorporated
594918104`tMicrosoft Corporation
68389X106`tOracle Corporation (incorrect)
68389X105`tOracle Corporation
"@ -split "`n"
$data |%{ Test-IsCUSIP $_.Split("`t")[0] }
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
|
Create a two-dimensional array at runtime
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
|
#Arturo
|
Arturo
|
width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]
|
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
|
Create a two-dimensional array at runtime
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
|
#AutoHotkey
|
AutoHotkey
|
Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]
|
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
|
#Delphi
|
Delphi
|
def makeRunningStdDev() {
var sum := 0.0
var sumSquares := 0.0
var count := 0.0
def insert(v) {
sum += v
sumSquares += v ** 2
count += 1
}
/** Returns the standard deviation of the inputs so far, or null if there
have been no inputs. */
def stddev() {
if (count > 0) {
def meanSquares := sumSquares/count
def mean := sum/count
def variance := meanSquares - mean**2
return variance.sqrt()
}
}
return [insert, stddev]
}
|
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
|
#CoffeeScript
|
CoffeeScript
|
crc32 = do ->
table =
for n in [0..255]
for [0..7]
if n & 1
n = 0xEDB88320 ^ n >>> 1
else
n >>>= 1
n
(str, crc = -1) ->
for c in str
crc = crc >>> 8 ^ table[(crc ^ c.charCodeAt 0) & 255]
(crc ^ -1) >>> 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
|
#Common_Lisp
|
Common Lisp
|
(ql:quickload :ironclad)
(defun string-to-digest (str digest)
"Return the specified digest for the ASCII string as a hex string."
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence digest
(ironclad:ascii-string-to-byte-array str))))
(string-to-digest "The quick brown fox jumps over the lazy dog" :crc32)
|
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.
|
#11l
|
11l
|
UInt32 seed = 0
F nonrandom(n)
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) % n
F rand9999()
R nonrandom(9000) + 1000
F tag(tag, txt, attr = ‘’)
R ‘<’tag‘’attr‘>’txt‘</’tag‘>’
V header = tag(‘tr’, ‘,X,Y,Z’.split(‘,’).map(txt -> tag(‘th’, txt)).join(‘’))"\n"
V rows = (1..5).map(i -> tag(‘tr’, tag(‘td’, i, ‘ style="font-weight: bold;"’)‘’(0.<3).map(j -> tag(‘td’, rand9999())).join(‘’))).join("\n")
V table = tag(‘table’, "\n"header‘’rows"\n")
print(table)
|
http://rosettacode.org/wiki/Date_format
|
Date format
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
|
#J
|
J
|
6!:0 'YYYY-MM-DD'
2010-08-19
|
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
|
#Java
|
Java
|
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import java.text.DateFormat;
public class Dates{
public static void main(String[] args){
Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed
DateFormatSymbols symbols = new DateFormatSymbols(); //names for our months and weekdays
//plain numbers way
System.out.println(now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE));
//words way
System.out.print(symbols.getWeekdays()[now.get(Calendar.DAY_OF_WEEK)] + ", ");
System.out.print(symbols.getMonths()[now.get(Calendar.MONTH)] + " ");
System.out.println(now.get(Calendar.DATE) + ", " + now.get(Calendar.YEAR));
}
}
|
http://rosettacode.org/wiki/Cramer%27s_rule
|
Cramer's rule
|
linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
|
#11l
|
11l
|
F det(mm)
V m = copy(mm)
V result = 1.0
L(j) 0 .< m.len
V imax = j
L(i) j + 1 .< m.len
I m[i][j] > m[imax][j]
imax = i
I imax != j
swap(&m[imax], &m[j])
result = -result
I abs(m[j][j]) < 1e-12
R Float.infinity
L(i) j + 1 .< m.len
V mult = -m[i][j] / m[j][j]
L(k) 0 .< m.len
m[i][k] += mult * m[j][k]
L(i) 0 .< m.len
result *= m[i][i]
R result
F cramerSolve(aa, detA, b, col)
V a = copy(aa)
L(i) 0 .< a.len
a[i][col] = b[i]
R det(a) / detA
V A = [[2.0, -1.0, 5.0, 1.0],
[3.0, 2.0, 2.0, -6.0],
[1.0, 3.0, 3.0, -1.0],
[5.0, -2.0, -3.0, 3.0]]
V B = [-3.0, -32.0, -47.0, 49.0]
V detA = det(A)
L(i) 0 .< A.len
print(‘#3.3’.format(cramerSolve(A, detA, B, i)))
|
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.
|
#Aikido
|
Aikido
|
var sout = openout ("output.txt") // in current dir
sout.close()
var sout1 = openout ("/output.txt") // in root dir
sout1.close()
mkdir ("docs")
mkdir ("/docs")
|
http://rosettacode.org/wiki/Create_a_file
|
Create a file
|
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
|
#Aime
|
Aime
|
# Make a directory using the -mkdir- program
void
mkdir(text p)
{
sshell ss;
b_cast(ss_path(ss), "mkdir");
l_append(ss_argv(ss), "mkdir");
l_append(ss_argv(ss), p);
ss_link(ss);
}
void
create_file(text p)
{
file f;
f_open(f, p, OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644);
}
void
create_pair(text prefix)
{
create_file(cat(prefix, "output.txt"));
mkdir(cat(prefix, "docs"));
}
integer
main(void)
{
create_pair("");
create_pair("/");
return 0;
}
|
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).
|
#AutoIt
|
AutoIt
|
Local $ascarray[4] = [34,38,60,62]
$String = "Character,Speech" & @CRLF
$String &= "The multitude,The messiah! Show us the messiah!" & @CRLF
$String &= "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" & @CRLF
$String &= "The multitude,Who are you?" & @CRLF
$String &= "Brians mother,I'm his mother; that's who!" & @CRLF
$String &= "The multitude,Behold his mother! Behold his mother!"
For $i = 0 To UBound($ascarray) -1
$String = Stringreplace($String, chr($ascarray[$i]), "&#"&$ascarray[$i]&";")
Next
$newstring = "<table>" & @CRLF
$crlfsplit = StringSplit($String, @CRLF, 1)
For $i = 1 To $crlfsplit[0]
If $i = 1 Then $newstring &= "<thead>" & @CRLF
$newstring &= "<tr>" & @CRLF
$komsplit = StringSplit($crlfsplit[$i], ",")
For $k = 1 To $komsplit[0]
If $i = 1 Then
$newstring &= "<th>" &$komsplit[$k] & "</th>" & @CRLF
Else
$newstring &= "<td>" &$komsplit[$k] & "</td>" & @CRLF
EndIf
Next
$newstring &= "</tr>" & @CRLF
If $i = 1 Then $newstring &= "</thead>" & @CRLF
Next
$newstring &= "</table>"
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $newstring = ' & $newstring & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
|
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.
|
#Erlang
|
Erlang
|
-module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
|
http://rosettacode.org/wiki/Damm_algorithm
|
Damm algorithm
|
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
|
#Pascal
|
Pascal
|
program DammAlgorithm;
uses
sysutils;
TYPE TA = ARRAY[0..9,0..9] OF UInt8;
CONST table : TA =
((0,3,1,7,5,9,8,6,4,2),
(7,0,9,2,1,5,4,8,6,3),
(4,2,0,6,8,7,1,3,5,9),
(1,7,5,0,9,8,3,4,2,6),
(6,1,2,3,0,4,5,9,7,8),
(3,6,7,4,2,0,9,5,8,1),
(5,8,6,9,7,2,0,1,3,4),
(8,9,4,5,3,6,2,0,1,7),
(9,4,3,8,6,1,7,2,0,5),
(2,5,8,1,4,3,6,7,9,0));
function Damm(s : string) : BOOLEAN;
VAR
interim,i : UInt8;
BEGIN
interim := 0;
i := 1;
WHILE i <= length(s) DO
Begin
interim := table[interim,ORD(s[i])-ORD('0')];
INC(i);
END;
Damm := interim=0;
END;
PROCEDURE Print(number : Uint32);
VAR
isValid : BOOLEAN;
buf :string;
BEGIN
buf := IntToStr(number);
isValid := Damm(buf);
Write(buf);
IF isValid THEN
Write(' is valid')
ELSE
Write(' is invalid');
WriteLn;
END;
BEGIN
Print(5724);
Print(5727);
Print(112946);
Print(112949);
Readln;
END.
|
http://rosettacode.org/wiki/Cuban_primes
|
Cuban primes
|
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
|
#Java
|
Java
|
public class CubanPrimes {
private static int MAX = 1_400_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
preCompute();
cubanPrime(200, true);
for ( int i = 1 ; i <= 5 ; i++ ) {
int max = (int) Math.pow(10, i);
System.out.printf("%,d-th cuban prime = %,d%n", max, cubanPrime(max, false));
}
}
private static long cubanPrime(int n, boolean display) {
int count = 0;
long result = 0;
for ( long i = 0 ; count < n ; i++ ) {
long test = 1l + 3 * i * (i+1);
if ( isPrime(test) ) {
count++;
result = test;
if ( display ) {
System.out.printf("%10s%s", String.format("%,d", test), count % 10 == 0 ? "\n" : "");
}
}
}
return result;
}
private static boolean isPrime(long n) {
if ( n < MAX ) {
return primes[(int)n];
}
int max = (int) Math.sqrt(n);
for ( int i = 3 ; i <= max ; i++ ) {
if ( primes[i] && n % i == 0 ) {
return false;
}
}
return true;
}
private static final void preCompute() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Scala
|
Scala
|
import java.text.NumberFormat
import java.util.Locale
object SizeMeUp extends App {
val menu: Map[String, (String, Double)] = Map("burg" ->("Hamburger XL", 5.50), "milk" ->("Milkshake", 2.86))
val order = List((4000000000000000L, "burg"), (2L, "milk"))
Locale.setDefault(new Locale("ru", "RU"))
val (currSymbol, tax) = (NumberFormat.getInstance().getCurrency.getSymbol, 0.0765)
def placeOrder(order: List[(Long, String)]) = {
val totals = for ((qty, article) <- order) yield {
val (desc, itemPrize) = menu(article)
val (items, post) = (qty, qty * BigDecimal(itemPrize))
println(f"$qty%16d\t$desc%-16s\t$currSymbol%4s$itemPrize%6.2f\t$post%,25.2f")
(items, post)
}
totals.foldLeft((0L, BigDecimal(0))) { (acc, n) => (acc._1 + n._1, acc._2 + n._2)}
}
val (items, beforeTax) = placeOrder(order)
println(f"$items%16d\t${"ordered items"}%-16s${'\t' + " Subtotal" + '\t'}$beforeTax%,25.2f")
val taxation = beforeTax * tax
println(f"${" " * 16 + '\t' + " " * 16 + '\t' + f"${tax * 100}%5.2f%% tax" + '\t'}$taxation%,25.2f")
println(f"${" " * 16 + '\t' + " " * 16 + '\t' + "Amount due" + '\t'}${beforeTax + taxation}%,25.2f")
}
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#Phix
|
Phix
|
with javascript_semantics
sequence curries = {}
function create_curried(integer rid, sequence partial_args)
curries = append(curries,{rid,partial_args})
return length(curries) -- (return an integer id)
end function
function call_curried(integer id, sequence args)
{integer rid, sequence partial_args} = curries[id]
return call_func(rid,partial_args&args)
end function
function add(atom a, b)
return a+b
end function
integer curried = create_curried(routine_id("add"),{2})
printf(1,"2+5=%d\n",call_curried(curried,{5}))
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#PHP
|
PHP
|
<?php
function curry($callable)
{
if (_number_of_required_params($callable) === 0) {
return _make_function($callable);
}
if (_number_of_required_params($callable) === 1) {
return _curry_array_args($callable, _rest(func_get_args()));
}
return _curry_array_args($callable, _rest(func_get_args()));
}
function _curry_array_args($callable, $args, $left = true)
{
return function () use ($callable, $args, $left) {
if (_is_fullfilled($callable, $args)) {
return _execute($callable, $args, $left);
}
$newArgs = array_merge($args, func_get_args());
if (_is_fullfilled($callable, $newArgs)) {
return _execute($callable, $newArgs, $left);
}
return _curry_array_args($callable, $newArgs, $left);
};
}
function _number_of_required_params($callable)
{
if (is_array($callable)) {
$refl = new \ReflectionClass($callable[0]);
$method = $refl->getMethod($callable[1]);
return $method->getNumberOfRequiredParameters();
}
$refl = new \ReflectionFunction($callable);
return $refl->getNumberOfRequiredParameters();
}
function _make_function($callable)
{
if (is_array($callable))
return function() use($callable) {
return call_user_func_array($callable, func_get_args());
};
return $callable;
}
function _execute($callable, $args, $left)
{
if (! $left) {
$args = array_reverse($args);
}
$placeholders = _placeholder_positions($args);
if (0 < count($placeholders)) {
$n = _number_of_required_params($callable);
if ($n <= _last($placeholders[count($placeholders) - 1])) {
throw new \Exception('Argument Placeholder found on unexpected position!');
}
foreach ($placeholders as $i) {
$args[$i] = $args[$n];
array_splice($args, $n, 1);
}
}
return call_user_func_array($callable, $args);
}
function _placeholder_positions($args)
{
return array_keys(array_filter($args, '_is_placeholder'));
}
function _is_fullfilled($callable, $args)
{
$args = array_filter($args, function($arg) {
return ! _is_placeholder($arg);
});
return count($args) >= _number_of_required_params($callable);
}
function _is_placeholder($arg)
{
return $arg instanceof Placeholder;
}
function _rest(array $args)
{
return array_slice($args, 1);
}
function product($a, $b)
{
return $a * $b;
}
echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#Racket
|
Racket
|
#lang racket
(require srfi/19)
(define 12hours (make-time time-duration 0 (* 12 60 60)))
(define (string->time s)
(define t (date->time-utc (string->date s "~B~e~Y~H~M")))
(if (regexp-match "pm" s)
(add-duration t 12hours)
t))
(date->string
(time-utc->date
(add-duration
(string->time "March 7 2009 7:30pm est" )
12hours))
"~a ~d ~b ~Y ~H:~M")
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#Raku
|
Raku
|
my @month = <January February March April May June July August September October November December>;
my %month = flat (@month Z=> ^12), (@month».substr(0,3) Z=> ^12), 'Sept' => 8;
grammar US-DateTime {
rule TOP { <month> <day>','? <year>','? <time> <tz> }
token month {
(\w+)'.'? { make %month{$0} // die "Bad month name: $0" }
}
token day { (\d ** 1..2) { make +$0 } }
token year { (\d ** 1..4) { make +$0 } }
token time {
(\d ** 1..2) ':' (\d ** 2) \h* ( :i <[ap]> \.? m | '' )
{
my $h = $0 % 12;
my $m = $1;
$h += 12 if $2 and $2.substr(0,1).lc eq 'p';
make $h * 60 + $m;
}
}
token tz { # quick and dirty for this task
[
| EDT { make -4 }
| [ EST| CDT] { make -5 }
| [ CST| MDT] { make -6 }
| [ MST| PDT] { make -7 }
| [ PST|AKDT] { make -8 }
| [AKST|HADT] { make -9 }
| HAST
]
}
}
$/ = US-DateTime.parse('March 7 2009 7:30pm EST') or die "Can't parse date";
my $year = $<year>.ast;
my $month = $<month>.ast;
my $day = $<day>.ast;
my $hour = $<time>.ast div 60;
my $minute = $<time>.ast mod 60;
my $timezone = $<tz>.ast * 3600;
my $dt = DateTime.new(:$year, :$month, :$day, :$hour, :$minute, :$timezone).in-timezone(0);
$dt = $dt.later(hours => 12);
say "12 hours later, GMT: $dt";
say "12 hours later, PST: $dt.in-timezone(-8 * 3600)";
|
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.
|
#Lingo
|
Lingo
|
put "December 25 is a Sunday in:"
refDateObj = date(1905,1,2)
repeat with year = 2008 to 2121
dateObj = date(year, 12, 25)
dayOfWeek = ((dateObj - refDateObj) mod 7)+1 -- 1=Monday..7=Sunday
if dayOfWeek=7 then put year
end repeat
|
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.
|
#LiveCode
|
LiveCode
|
function xmasSunday startDate endDate
convert the long date to dateitems
put it into xmasDay
put 12 into item 2 of xmasDay
put 25 into item 3 of xmasDay
repeat with i = startDate to endDate
put i into item 1 of xmasDay
convert xmasDay to dateItems
if item 7 of xmasDay is 1 then put i & comma after xmasYear
end repeat
if the last char of xmasYear is comma then delete the last char of xmasYear
return xmasYear
end xmasSunday
|
http://rosettacode.org/wiki/CUSIP
|
CUSIP
|
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
|
#Python
|
Python
|
#!/usr/bin/env python3
import math
def cusip_check(cusip):
if len(cusip) != 9:
raise ValueError('CUSIP must be 9 characters')
cusip = cusip.upper()
total = 0
for i in range(8):
c = cusip[i]
if c.isdigit():
v = int(c)
elif c.isalpha():
p = ord(c) - ord('A') + 1
v = p + 9
elif c == '*':
v = 36
elif c == '@':
v = 37
elif c == '#':
v = 38
if i % 2 != 0:
v *= 2
total += int(v / 10) + v % 10
check = (10 - (total % 10)) % 10
return str(check) == cusip[-1]
if __name__ == '__main__':
codes = [
'037833100',
'17275R102',
'38259P508',
'594918104',
'68389X106',
'68389X105'
]
for code in codes:
print(f'{code} -> {cusip_check(code)}')
|
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.
|
#AutoIt
|
AutoIt
|
; == get dimensions from user input
$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. "5,3"')
$aDimension = StringSplit($sInput, ',', 2)
; == create array
Dim $a2D[ $aDimension[0] ][ $aDimension[1] ]
; == write value to last row/last column
$a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] = 'test string'
; == output this value to MsgBox
MsgBox(0, 'Output', 'row[' & UBound($a2D) -1 & '], col[' & UBound($a2D, 2) -1 & ']' & @CRLF & '= ' & $a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -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
|
#E
|
E
|
def makeRunningStdDev() {
var sum := 0.0
var sumSquares := 0.0
var count := 0.0
def insert(v) {
sum += v
sumSquares += v ** 2
count += 1
}
/** Returns the standard deviation of the inputs so far, or null if there
have been no inputs. */
def stddev() {
if (count > 0) {
def meanSquares := sumSquares/count
def mean := sum/count
def variance := meanSquares - mean**2
return variance.sqrt()
}
}
return [insert, stddev]
}
|
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
|
#Component_Pascal
|
Component Pascal
|
MODULE BbtComputeCRC32;
IMPORT ZlibCrc32,StdLog;
PROCEDURE Do*;
VAR
s: ARRAY 128 OF SHORTCHAR;
BEGIN
s := "The quick brown fox jumps over the lazy dog";
StdLog.IntForm(ZlibCrc32.CRC32(0,s,0,LEN(s$)),16,12,'0',TRUE);
StdLog.Ln;
END Do;
END BbtComputeCRC32.
|
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
|
#Crystal
|
Crystal
|
require "digest/crc32";
p Digest::CRC32.checksum("The quick brown fox jumps over the lazy dog").to_s(16)
|
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.
|
#360_Assembly
|
360 Assembly
|
* Create an HTML table 19/02/2017
CREHTML CSECT
USING CREHTML,R13
B 72(R15)
DC 17F'0'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 end of prolog
LA R8,RND
XPRNT PGBODY,64 <html><head></head><body>
XPRNT PGTAB,64 <table border=1 ... cellspacing=0>
SR R6,R6 row=0
DO WHILE=(C,R6,LE,NROWS) do row=0 to nrows
IF LTR,R6,Z,R6 THEN if row=0
XPRNT PGTRTH,64 <tr><th></th>
ELSE , else
XDECO R6,XDEC edit row
MVC PGTR+8(1),XDEC+11 output row heading
XPRNT PGTR,64 <tr><th>.</th>
ENDIF , endif
LA R7,1 col=1
DO WHILE=(C,R7,LE,NCOLS) do col=1 to ncols
IF LTR,R6,Z,R6 THEN if row=0
LR R1,R7 col
LA R4,TCAR-1(R1) tcar(col)
MVC PGTH+4(1),0(R4) output heading
XPRNT PGTH,64 <th>.</th>
ELSE , else
L R2,0(R8) value
XDECO R2,XDEC edit value
MVC PGTD+18(4),XDEC+8 output cell value
XPRNT PGTD,64 <td align="right">....</td>
LA R8,4(R8) next value
ENDIF , endif
LA R7,1(R7) col++
ENDDO , enddo col
XPRNT PGETR,64 </tr>
LA R6,1(R6) row++
ENDDO , enddo row
XPRNT PGETAB,64 </table>
XPRNT PGEBODY,64 </body></html>
L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15
BR R14 exit
NROWS DC F'4' number of rows
NCOLS DC F'3' number of columns
TCAR DC CL3'XYZ'
RND DC F'7055',F'5334',F'5795',F'2895',F'3019',F'7747'
DC F'140',F'7607',F'8144',F'7090',F'475',F'4140'
PGBODY DC CL64'<html><head></head><body>'
PGTAB DC CL64'<table border=1 cellpadding=10 cellspacing=0>'
PGTRTH DC CL64'<tr><th></th>'
PGTH DC CL64'<th>.</th>'
PGETR DC CL64'</tr>'
PGTR DC CL64'<tr><th>.</th>'
PGTD DC CL64'<td align="right">....</td>'
PGETAB DC CL64'</table>'
PGEBODY DC CL64'</body></html>'
XDEC DS CL12
YREGS
END CREHTML
|
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
|
#JavaScript
|
JavaScript
|
var now = new Date(),
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(),
fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear();
console.log(fmt1);
console.log(fmt2);
|
http://rosettacode.org/wiki/Cramer%27s_rule
|
Cramer's rule
|
linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
|
#Ada
|
Ada
|
with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
-- This is the type we want to use in the matrix and vector
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_Matrix;
V : in Real_Vector)
return Real_Vector
is
Denominator : Real;
Nom_Matrix : Real_Matrix (M'Range (1),
M'Range (2));
Numerator : Real;
Result : Real_Vector (M'Range (1));
begin
if
M'Length (2) /= V'Length or
M'Length (1) /= M'Length (2)
then
raise Constraint_Error with "Dimensions does not match";
end if;
Denominator := Determinant (M);
for Col in V'Range loop
Nom_Matrix := M;
-- Substitute column
for Row in V'Range loop
Nom_Matrix (Row, Col) := V (Row);
end loop;
Numerator := Determinant (Nom_Matrix);
Result (Col) := Numerator / Denominator;
end loop;
return Result;
end Solve_Cramer;
procedure Put (V : Real_Vector) is
use Ada.Text_IO;
package Real_IO is
new Ada.Text_IO.Float_IO (Real);
begin
Put ("[");
for E of V loop
Real_IO.Put (E, Exp => 0, Aft => 2);
Put (" ");
end loop;
Put ("]");
New_Line;
end Put;
M : constant Real_Matrix := ((2.0, -1.0, 5.0, 1.0),
(3.0, 2.0, 2.0, -6.0),
(1.0, 3.0, 3.0, -1.0),
(5.0, -2.0, -3.0, 3.0));
V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
R : constant Real_Vector := Solve_Cramer (M, V);
begin
Put (R);
end Cramers_Rules;
|
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.
|
#ALGOL_68
|
ALGOL 68
|
main:(
INT errno;
PROC touch = (STRING file name)INT:
BEGIN
FILE actual file;
INT errno := open(actual file, file name, stand out channel);
IF errno NE 0 THEN GO TO stop touch FI;
close(actual file); # detach the book and keep it #
errno
EXIT
stop touch:
errno
END;
errno := touch("input.txt");
errno := touch("/input.txt");
# ALGOL 68 has no concept of directories,
however a file can have multiple pages,
the pages are identified by page number only #
PROC mkpage = (STRING file name, INT page x)INT:
BEGIN
FILE actual file;
INT errno := open(actual file, file name, stand out channel);
IF errno NE 0 THEN GO TO stop mkpage FI;
set(actual file,page x,1,1); # skip to page x, line 1, character 1 #
close(actual file); # detach the new page and keep it #
errno
EXIT
stop mkpage:
errno
END;
errno := mkpage("input.txt",2);
)
|
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).
|
#AWK
|
AWK
|
#!/usr/bin/awk -f
BEGIN {
FS=","
print "<table>"
}
{
gsub(/</, "\\<")
gsub(/>/, "\\>")
gsub(/&/, "\\>")
print "\t<tr>"
for(f = 1; f <= NF; f++) {
if(NR == 1 && header) {
printf "\t\t<th>%s</th>\n", $f
}
else printf "\t\t<td>%s</td>\n", $f
}
print "\t</tr>"
}
END {
print "</table>"
}
|
http://rosettacode.org/wiki/CSV_data_manipulation
|
CSV data manipulation
|
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
|
#Euphoria
|
Euphoria
|
--- Read CSV file and add columns headed with 'SUM'
--- with trace
-- trace(0)
include get.e
include std/text.e
function split(sequence s, integer c)
sequence removables = " \t\n\r\x05\u0234\" "
sequence out
integer first, delim
out = {}
first = 1
while first <= length(s) do
delim = find_from(c,s,first)
if delim = 0 then
delim = length(s)+1
end if
out = append(out,trim(s[first..delim-1],removables))
first = delim + 1
end while
return out
end function
procedure main()
integer fn -- the file number
integer fn2 -- the output file number
integer e -- the number of lines read
object line -- the next line from the file
sequence data = {} -- parsed csv data row
sequence headerNames = {} -- array saving column names
atom sum = 0.0 -- sum for each row
sequence var -- holds numerical data read
-- First we try to open the file called "data.csv".
fn = open("data.csv", "r")
if fn = -1 then
puts(1, "Can't open data.csv\n")
-- abort();
end if
-- Then we create an output file for processed data.
fn2 = open("newdata.csv", "w")
if fn2 = -1 then
puts(1, "Can't create newdata.csv\n")
end if
-- By successfully opening the file we have established that
-- the file exists, and open() gives us a file number (or "handle")
-- that we can use to perform operations on the file.
e = 1
while 1 do
line = gets(fn)
if atom(line) then
exit
end if
data = split(line, ',')
if (e=1) then
-- Save the header labels and
-- write them to output file.
headerNames = data
for i=1 to length(headerNames) do
printf(fn2, "%s,", {headerNames[i]})
end for
printf(fn2, "SUM\n")
end if
-- Run a sum for the numerical data.
if (e >= 2) then
for i=1 to length(data) do
printf(fn2, "%s,", {data[i]})
var = value(data[i])
if var[1] = 0 then
-- data read is numerical
-- add to sum
sum = sum + var[2]
end if
end for
printf(fn2, "%g\n", {sum})
sum = 0.0
end if
e = e + 1
end while
close(fn)
close(fn2)
end procedure
main()
|
http://rosettacode.org/wiki/Damm_algorithm
|
Damm algorithm
|
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
|
#Perl
|
Perl
|
sub damm {
my(@digits) = split '', @_[0];
my @tbl =([< 0 3 1 7 5 9 8 6 4 2 >],
[< 7 0 9 2 1 5 4 8 6 3 >],
[< 4 2 0 6 8 7 1 3 5 9 >],
[< 1 7 5 0 9 8 3 4 2 6 >],
[< 6 1 2 3 0 4 5 9 7 8 >],
[< 3 6 7 4 2 0 9 5 8 1 >],
[< 5 8 6 9 7 2 0 1 3 4 >],
[< 8 9 4 5 3 6 2 0 1 7 >],
[< 9 4 3 8 6 1 7 2 0 5 >],
[< 2 5 8 1 4 3 6 7 9 0 >]
);
my $row = 0;
for my $col (@digits) { $row = $tbl[$row][$col] }
not $row
}
for (5724, 5727, 112946) {
print "$_:\tChecksum digit @{[damm($_) ? '' : 'in']}correct.\n"
}
|
http://rosettacode.org/wiki/Cuban_primes
|
Cuban primes
|
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
|
#jq
|
jq
|
# input should be a non-negative integer
def commatize:
def digits: tostring | explode | reverse;
[foreach digits[] as $d (-1; .+1;
(select(. > 0 and . % 3 == 0)|44), $d)] # "," is 44
| reverse | implode ;
def count(stream): reduce stream as $i (0; .+1);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
|
http://rosettacode.org/wiki/Cuban_primes
|
Cuban primes
|
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
|
#Julia
|
Julia
|
using Primes
function cubanprimes(N)
cubans = zeros(Int, N)
cube100k, cube1, count = 0, 1, 1
for i in Iterators.countfrom(1)
j = BigInt(i + 1)
cube2 = j^3
diff = cube2 - cube1
if isprime(diff)
count ≤ N && (cubans[count] = diff)
if count == 100000
cube100k = diff
break
end
count += 1
end
cube1 = cube2
end
println("The first $N cuban primes are: ")
foreach(x -> print(lpad(cubans[x] == 0 ? "" : cubans[x], 10), x % 8 == 0 ? "\n" : ""), 1:N)
println("\nThe 100,000th cuban prime is ", cube100k)
end
cubanprimes(200)
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Sidef
|
Sidef
|
struct Item {
name, price, quant
}
var check = %q{
Hamburger 5.50 4000000000000000
Milkshake 2.86 2
}.lines.grep(/\S/).map { Item(.words...) }
var tax_rate = 0.0765
var fmt = "%-10s %8s %18s %22s\n"
printf(fmt, %w(Item Price Quantity Extension)...)
var subtotal = check.map { |item|
var extension = Num(item.price)*Num(item.quant)
printf(fmt, item.name, item.price, item.quant, extension.round(-2))
extension
}.sum(0)
printf(fmt, '', '', '', '-----------------')
printf(fmt, '', '', 'Subtotal ', subtotal)
var tax = (subtotal * tax_rate -> round(-2))
printf(fmt, '', '', 'Tax ', tax)
var total = subtotal+tax
printf(fmt, '', '', 'Total ', total)
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Smalltalk
|
Smalltalk
|
check := #(
" amount name price "
(4000000000000000 'hamburger' 5.50s2 )
(2 'milkshakes' 2.86s2 )
).
tax := 7.65s2.
fmt := '%-10s %10P %22P %26P\n'.
totalSum := 0.
totalTax := 0.
Transcript clear.
Transcript printf:fmt withAll:#('Item' 'Price' 'Qty' 'Extension').
Transcript printCR:('-' ,* 72).
check do:[:entry|
|amount name price itemTotal itemTax|
amount := entry[1].
name := entry[2].
price := entry[3].
itemTotal := (price*amount).
itemTax := ((price*amount)*tax/100) roundedToScale.
totalSum := totalSum + itemTotal.
totalTax := totalTax + itemTax.
Transcript printf:fmt
withAll:{name . price . amount . itemTotal}.
].
Transcript printCR:('-' ,* 72).
Transcript printf:fmt withAll:{'' . '' . 'Subtotal' . totalSum}.
Transcript printf:fmt withAll:{'' . '' . 'Tax' . totalTax}.
Transcript printf:fmt withAll:{'' . '' . 'Total' . (totalSum+totalTax)}.
Transcript cr; printCR:('Enjoy your Meal & Thank You for Dining at Milliways')
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#PicoLisp
|
PicoLisp
|
: (de multiplier (@X)
(curry (@X) (N) (* @X N)) )
-> multiplier
: (multiplier 7)
-> ((N) (* 7 N))
: ((multiplier 7) 3)
-> 21
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#PowerShell
|
PowerShell
|
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#Prolog
|
Prolog
|
?- [library('lambda.pl')].
% library(lambda.pl) compiled into lambda 0,00 sec, 28 clauses
true.
?- N = 5, F = \X^Y^(Y is X+N), maplist(F, [1,2,3], L).
N = 5,
F = \X^Y^ (Y is X+5),
L = [6,7,8].
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#REBOL
|
REBOL
|
rebol [
Title: "Date Manipulation"
URL: http://rosettacode.org/wiki/Date_Manipulation
]
; Only North American zones here -- feel free to extend for your area.
zones: [
NST -3:30 NDT -2:30 AST -4:00 ADT -3:00 EST -5:00 EDT -4:00
CST -6:00 CDT -5:00 MST -7:00 MDT -6:00 PST -8:00 PDT -7:00 AKST -9:00
AKDT -8:00 HAST -10:00 HADT -9:00]
read-time: func [
text
/local m d y t z
][
parse load text [
set m word! (m: index? find system/locale/months to-string m)
set d integer! set y integer!
set t time! set tz word!]
to-date reduce [y m d t zones/:tz]
]
print 12:00 + read-time "March 7 2009 7:30pm EST"
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#Red
|
Red
|
d: 07-Mar-2009/19:30 + 12:00
print d
8-Mar-2009/7:30:00
d/timezone: 1
print d
8-Mar-2009/8:30:00+01:00
|
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.
|
#Logo
|
Logo
|
; Determine if a Gregorian calendar year is leap
to leap? :year
output (and
equal? 0 modulo :year 4
not member? modulo :year 400 [100 200 300]
)
end
; Convert Gregorian calendar date to a simple day count from
; day 1 = January 1, 1 CE
to day_number :year :month :day
local "elapsed make "elapsed difference :year 1
output (sum product 365 :elapsed
int quotient :elapsed 4
minus int quotient :elapsed 100
int quotient :elapsed 400
int quotient difference product 367 :month 362 12
ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2
:day)
end
; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday
to day_of_week :day_number
output modulo :day_number 7
end
; True if the given day is a Sunday
to sunday? :year :month :day
output equal? 0 day_of_week day_number :year :month :day
end
; Put it all together to answer the question posed in the problem
print filter [sunday? ? 12 25] iseq 2008 2121
bye
|
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.
|
#Lua
|
Lua
|
require("date")
for year=2008,2121 do
if date(year, 12, 25):getweekday() == 1 then
print(year)
end
end
|
http://rosettacode.org/wiki/CUSIP
|
CUSIP
|
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
|
#Quackery
|
Quackery
|
[ -1 split 0 peek char 0 -
swap 0 swap
witheach
[ [ dup char 0 char 9 1+ within iff
[ char 0 - ] done
dup char A char Z 1+ within iff
[ char A - 10 + ] done
dup char * = iff
[ drop 36 ] done
dup char @ = iff
[ drop 37 ] done
dup char # = iff
[ drop 38 ] done
$ "Unexpected character '" swap
join $ "' in CUSIP." join fail ]
i^ 1 & if [ 2 * ]
10 /mod + + ]
10 mod 10 swap - 10 mod = ] is cusip ( $ --> b )
[ dup echo$ cusip iff
[ say " is correct." ]
else [ say " is incorrect." ]
cr ] is task ( $ --> )
$ "037833100 17275R102 38259P508 594918104 68389X106 68389X105"
nest$ witheach task
|
http://rosettacode.org/wiki/CUSIP
|
CUSIP
|
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
|
#Racket
|
Racket
|
#lang racket
(require srfi/14)
(define 0-char (char->integer #\0))
(define A-char (char->integer #\A))
(define (cusip-value c)
(cond
[(char-set-contains? char-set:digit c)
(- (char->integer c) 0-char)]
[(char-set-contains? char-set:upper-case c)
(+ 10 (- (char->integer c) A-char))]
[(char=? c #\*) 36]
[(char=? c #\@) 37]
[(char=? c #\#) 38]))
(define (cusip-check-digit cusip)
(modulo
(- 10
(modulo
(for/sum
((i (sequence-map add1 (in-range 8))) (c (in-string cusip)))
(let* ((v (cusip-value c)) (v′ (if (even? i) (* v 2) v)))
(+ (quotient v′ 10) (modulo v′ 10)))) 10)) 10))
(define (CUSIP? s)
(char=? (string-ref s (sub1 (string-length s)))
(integer->char (+ 0-char (cusip-check-digit s)))))
(module+ test
(require rackunit)
(check-true (CUSIP? "037833100"))
(check-true (CUSIP? "17275R102"))
(check-true (CUSIP? "38259P508"))
(check-true (CUSIP? "594918104"))
(check-false (CUSIP? "68389X106"))
(check-true (CUSIP? "68389X105")))
|
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.
|
#AWK
|
AWK
|
/[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
# how to scan "multidim" array as explained in the GNU AWK manual
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}
|
http://rosettacode.org/wiki/Cumulative_standard_deviation
|
Cumulative standard deviation
|
Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
|
#Elixir
|
Elixir
|
defmodule Standard_deviation do
def add_sample( pid, n ), do: send( pid, {:add, n} )
def create, do: spawn_link( fn -> loop( [] ) end )
def destroy( pid ), do: send( pid, :stop )
def get( pid ) do
send( pid, {:get, self()} )
receive do
{ :get, value, _pid } -> value
end
end
def task do
pid = create()
for x <- [2,4,4,4,5,5,7,9], do: add_print( pid, x, add_sample(pid, x) )
destroy( pid )
end
defp add_print( pid, n, _add ) do
IO.puts "Standard deviation #{ get(pid) } when adding #{ n }"
end
defp loop( ns ) do
receive do
{:add, n} -> loop( [n | ns] )
{:get, pid} ->
send( pid, {:get, loop_calculate( ns ), self()} )
loop( ns )
:stop -> :ok
end
end
defp loop_calculate( ns ) do
average = loop_calculate_average( ns )
:math.sqrt( loop_calculate_average( for x <- ns, do: :math.pow(x - average, 2) ) )
end
defp loop_calculate_average( ns ), do: Enum.sum( ns ) / length( ns )
end
Standard_deviation.task
|
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
|
#D
|
D
|
void main() {
import std.stdio, std.digest.crc;
"The quick brown fox jumps over the lazy dog"
.crc32Of.crcHexString.writeln;
}
|
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
|
#Delphi
|
Delphi
|
program CalcCRC32;
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.ZLib;
var
Data: AnsiString = 'The quick brown fox jumps over the lazy dog';
CRC: UInt32;
begin
CRC := crc32(0, @Data[1], Length(Data));
WriteLn(Format('CRC32 = %8.8X', [CRC]));
end.
|
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.
|
#11l
|
11l
|
F changes(amount, coins)
V ways = [Int64(0)] * (amount + 1)
ways[0] = 1
L(coin) coins
L(j) coin .. amount
ways[j] += ways[j - coin]
R ways[amount]
print(changes(100, [1, 5, 10, 25]))
print(changes(100000, [1, 5, 10, 25, 50, 100]))
|
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.
|
#Action.21
|
Action!
|
DEFINE ROW_COUNT="4"
DEFINE COL_COUNT="3"
PROC Main()
CHAR ARRAY headers=[0 'X 'Y 'Z]
BYTE row,col
INT v
PrintE("<html>")
PrintE("<head></head>")
PrintE("<body>")
PrintE("<table border=1>")
PrintE("<thead align=""center"">")
Print("<tr><th></th>")
FOR col=1 TO COL_COUNT
DO
PrintF("<th>%C</th>",headers(col))
OD
PrintE("</tr>")
PrintE("</thead>")
PrintE("<tbody align=""right"">")
FOR row=1 TO ROW_COUNT
DO
PrintF("<tr><th>%B</th>",row)
FOR col=1 TO COL_COUNT
DO
v=800+Rand(0)*5
PrintF("<td>%I</td>",v)
OD
PrintE("</tr>")
OD
PrintE("</tbody>")
PrintE("</table>")
PrintE("</body>")
PrintE("</html>")
RETURN
|
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
|
#Joy
|
Joy
|
DEFINE weekdays == [ "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday" ];
months == [ "January" "February" "March" "April" "May" "June" "July" "August"
"September" "October" "November" "December" ].
time localtime [ [0 at 'd 4 4 format] ["-"] [1 at 'd 2 2 format] ["-"] [2 at 'd 2 2 format] ]
[i] map [putchars] step '\n putch pop.
time localtime [ [8 at pred weekdays of] [", "] [1 at pred months of] [" "] [2 at 'd 1 1 format]
[", "] [0 at 'd 4 4 format] ] [i] map [putchars] step '\n putch pop.
|
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
|
#jq
|
jq
|
$ jq -n 'now | (strftime("%Y-%m-%d"), strftime("%A, %B %d, %Y"))'
"2015-07-02"
"Thursday, July 02, 2015"
|
http://rosettacode.org/wiki/Cramer%27s_rule
|
Cramer's rule
|
linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.}
which in matrix format is
[
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
]
[
x
y
z
]
=
[
d
1
d
2
d
3
]
.
{\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.}
Then the values of
x
,
y
{\displaystyle x,y}
and
z
{\displaystyle z}
can be found as follows:
x
=
|
d
1
b
1
c
1
d
2
b
2
c
2
d
3
b
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
y
=
|
a
1
d
1
c
1
a
2
d
2
c
2
a
3
d
3
c
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
,
and
z
=
|
a
1
b
1
d
1
a
2
b
2
d
2
a
3
b
3
d
3
|
|
a
1
b
1
c
1
a
2
b
2
c
2
a
3
b
3
c
3
|
.
{\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.}
Task
Given the following system of equations:
{
2
w
−
x
+
5
y
+
z
=
−
3
3
w
+
2
x
+
2
y
−
6
z
=
−
32
w
+
3
x
+
3
y
−
z
=
−
47
5
w
−
2
x
−
3
y
+
3
z
=
49
{\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}}
solve for
w
{\displaystyle w}
,
x
{\displaystyle x}
,
y
{\displaystyle y}
and
z
{\displaystyle z}
, using Cramer's rule.
|
#ALGOL_68
|
ALGOL 68
|
# returns the solution of a.x = b via Cramer's rule #
# this is for REAL arrays, could define additional operators #
# for INT, COMPL, etc. #
PRIO CRAMER = 1;
OP CRAMER = ( [,]REAL a, []REAL b )[]REAL:
IF 1 UPB a /= 2 UPB a
OR 1 LWB a /= 2 LWB a
OR 1 UPB a /= UPB b
THEN
# the array sizes and bounds do not match #
print( ( "Invaid parameters to CRAMER", newline ) );
stop
ELIF REAL deta = DET a;
det a = 0
THEN
# a is singular #
print( ( "Singular matrix for CRAMER", newline ) );
stop
ELSE
# the arrays have matching bounds #
[ LWB b : UPB b ]REAL result;
FOR col FROM LWB b TO UPB b DO
# form a matrix from a with the col'th column replaced by b #
[ 1 LWB a : 1 UPB a, 2 LWB a : 2 UPB a ]REAL m := a;
m[ : , col ] := b[ : AT 1 ];
# col'th result elemet as per Cramer's rule #
result[ col ] := DET m / det a
OD;
result
FI; # CRAMER #
# test CRAMER using the matrix and column vector specified in the task #
[,]REAL a = ( ( 2, -1, 5, 1 )
, ( 3, 2, 2, -6 )
, ( 1, 3, 3, -1 )
, ( 5, -2, -3, 3 )
);
[]REAL b = ( -3
, -32
, -47
, 49
);
[]REAL solution = a CRAMER b;
FOR c FROM LWB solution TO UPB solution DO
print( ( " ", fixed( solution[ c ], -8, 4 ) ) )
OD;
print( ( newline ) )
|
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.
|
#APL
|
APL
|
'output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
'\output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
⎕mkdir 'Docs'
⎕mkdir '\Docs'
|
http://rosettacode.org/wiki/Create_a_file
|
Create a file
|
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
|
#AppleScript
|
AppleScript
|
close (open for access "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).
|
#Batch_File
|
Batch File
|
::Batch Files are terrifying when it comes to string processing.
::But well, a decent implementation!
@echo off
REM Below is the CSV data to be converted.
REM Exactly three colons must be put before the actual line.
:::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!
setlocal disabledelayedexpansion
echo ^<table^>
for /f "delims=" %%A in ('findstr "^:::" "%~f0"') do (
set "var=%%A"
setlocal enabledelayedexpansion
REM The next command removes the three colons...
set "var=!var:~3!"
REM The following commands to the substitions per line...
set "var=!var:&=&!"
set "var=!var:<=<!"
set "var=!var:>=>!"
set "var=!var:,=</td><td>!"
echo ^<tr^>^<td^>!var!^</td^>^</tr^>
endlocal
)
echo ^</table^>
|
http://rosettacode.org/wiki/CSV_data_manipulation
|
CSV data manipulation
|
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
|
#F.23
|
F#
|
open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
|
http://rosettacode.org/wiki/Damm_algorithm
|
Damm algorithm
|
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
|
#Phix
|
Phix
|
constant tbl = sq_add(1,{{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0}})
function damm(string s)
integer interim = 1
for i=1 to length(s) do
integer nxt = s[i]-'0'+1
if nxt<1 or nxt>10 then return 0 end if
interim = tbl[interim][nxt]
end for
return interim == 1
end function
constant tests = {"5724", "5727", "112946", "112949"}
for i=1 to length(tests) do
string ti = tests[i]
printf(1,"%7s is %svalid\n",{ti,iff(damm(ti)?"":"in")})
end for
|
http://rosettacode.org/wiki/Cuban_primes
|
Cuban primes
|
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
|
#Kotlin
|
Kotlin
|
import kotlin.math.ceil
import kotlin.math.sqrt
fun main() {
val primes = mutableListOf(3L, 5L)
val cutOff = 200
val bigUn = 100_000
val chunks = 50
val little = bigUn / chunks
println("The first $cutOff cuban primes:")
var showEach = true
var c = 0
var u = 0L
var v = 1L
var i = 1L
while (i > 0) {
var found = false
u += 6
v += u
val mx = ceil(sqrt(v.toDouble())).toInt()
for (item in primes) {
if (item > mx) break
if (v % item == 0L) {
found = true
break
}
}
if (!found) {
c++
if (showEach) {
var z = primes.last() + 2
while (z <= v - 2) {
var fnd = false
for (item in primes) {
if (item > mx) break
if (z % item == 0L) {
fnd = true
break
}
}
if (!fnd) {
primes.add(z)
}
z += 2
}
primes.add(v)
print("%11d".format(v))
if (c % 10 == 0) println()
if (c == cutOff) {
showEach = false
print("\nProgress to the ${bigUn}th cuban prime: ")
}
}
if (c % little == 0) {
print(".")
if (c == bigUn) break
}
}
i++
}
println("\nThe %dth cuban prime is %17d".format(c, v))
}
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Swift
|
Swift
|
import Foundation
extension Decimal {
func rounded(_ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
var result = Decimal()
var localCopy = self
NSDecimalRound(&result, &localCopy, scale, roundingMode)
return result
}
}
let costHamburgers = Decimal(4000000000000000) * Decimal(5.50)
let costMilkshakes = Decimal(2) * Decimal(2.86)
let totalBeforeTax = costMilkshakes + costHamburgers
let taxesToBeCollected = (Decimal(string: "0.0765")! * totalBeforeTax).rounded(2, .bankers)
print("Price before tax: $\(totalBeforeTax)")
print("Total tax to be collected: $\(taxesToBeCollected)")
print("Total with taxes: $\(totalBeforeTax + taxesToBeCollected)")
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#Tcl
|
Tcl
|
package require math::decimal
namespace import math::decimal::*
set hamburgerPrice [fromstr 5.50]
set milkshakePrice [fromstr 2.86]
set taxRate [/ [fromstr 7.65] [fromstr 100]]
set burgers 4000000000000000
set shakes 2
set net [+ [* [fromstr $burgers] $hamburgerPrice] [* [fromstr $shakes] $milkshakePrice]]
set tax [round_up [* $net $taxRate] 2]
set total [+ $net $tax]
puts "net=[tostr $net], tax=[tostr $tax], total=[tostr $total]"
|
http://rosettacode.org/wiki/Currency
|
Currency
|
Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
|
#VBA
|
VBA
|
Public Sub currency_task()
'4000000000000000 hamburgers at $5.50 each
Dim number_of_hamburgers As Variant
number_of_hamburgers = CDec(4E+15)
Dim price_of_hamburgers As Currency
price_of_hamburgers = 5.5
'2 milkshakes at $2.86 each, and
Dim number_of_milkshakes As Integer
number_of_milkshakes = 2
Dim price_of_milkshakes As Currency
price_of_milkshakes = 2.86
'a tax rate of 7.65%.
Dim tax_rate As Single
tax_rate = 0.0765
'the total price before tax
Dim total_price_before_tax As Variant
total_price_before_tax = number_of_hamburgers * price_of_hamburgers
total_price_before_tax = total_price_before_tax + number_of_milkshakes * price_of_milkshakes
Debug.Print "Total price before tax "; Format(total_price_before_tax, "Currency")
'the tax
Dim tax As Variant
tax = total_price_before_tax * tax_rate
Debug.Print "Tax "; Format(tax, "Currency")
'the total with tax
Debug.Print "Total with tax "; Format(total_price_before_tax + tax, "Currency")
End Sub
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#Python
|
Python
|
def addN(n):
def adder(x):
return x + n
return adder
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#Quackery
|
Quackery
|
[ ' [ ' ] swap nested join
]'[ nested join ] is curried ( x --> [ )
|
http://rosettacode.org/wiki/Currying
|
Currying
|
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
|
#Racket
|
Racket
|
#lang racket
(((curry +) 3) 2) ; =>5
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#REXX
|
REXX
|
/*REXX program adds 12 hours to a given date and time, displaying the before and after.*/
aDate = 'March 7 2009 7:30pm EST' /*the original or base date to be used.*/
parse var aDate mon dd yyyy hhmm tz . /*obtain the various parts and pieces. */
mins = time('M', hhmm, "C") /*get the number minutes past midnight.*/
mins = mins + (12*60) /*add twelve hours to the timestamp.*/
nMins = mins // 1440 /*compute number min into same/next day*/
days = mins % 1440 /*compute number of days added to dats.*/
aBdays = date('B', dd left(mon,3) yyyy) /*number of base days since REXX epoch.*/
nBdays = aBdays + days /*now, add the number of days added. */
nDate = date(,nBdays, 'B') /*calculate the new date (maybe). */
nTime = time('C', nMins, "M") /* " " " time " */
say aDate ' + 12 hours ───► ' ndate ntime tz /*display the new timestamp to console.*/
/*stick a fork in it, we're all done. */
|
http://rosettacode.org/wiki/Date_manipulation
|
Date manipulation
|
Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
|
#Ring
|
Ring
|
# Project : Date manipulation
load "stdlib.ring"
dateorigin = "March 7 2009 7:30pm EST"
monthname = "January February March April May June July August September October November December"
for i = 1 to 12
if dateorigin[1] = monthname[i]
monthnum = i
ok
next
thedate = str2list(substr(dateorigin, " ", nl))
t = thedate[4]
t1 = substr(t,"pm", "")
t2 = substr(t1,":",".")
t3 = number(t2)
if right(t,2) = "pm"
t3 = t3+ 12
ok
ap = "pm"
d = "07/03/2009"
if t3 + 12 > 24
d = adddays("07/03/2009",1)
ap = "am"
ok
see "Original - " + dateorigin + nl
see "Manipulated - " + d + " " + t1 + ap + nl
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Print "December 25 is a Sunday in:"
For Year=2008 to 2121 {
if Str$(Date("25/12/"+str$(Year,"")),"w")="1" Then {
Print Year
}
}
\\ is the same with this:
Print "December 25 is a Sunday in:"
For Year=2008 to 2121 {
if Str$(Date(str$(Year,"")+"-12-25"),"w")="1" Then {
Print 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.
|
#M4
|
M4
|
divert(-1)
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
dnl julian day number corresponding to December 25th of given year
define(`julianxmas',
`define(`yrssince0',eval($1+4712))`'define(`noOfLpYrs',
eval((yrssince0+3)/4))`'define(`jd',
eval(365*yrssince0+noOfLpYrs-10-($1-1501)/100+($1-1201)/400+334+25-1))`'
ifelse(eval($1%4==0 && ($1%100!=0 || $1%400==0)),1,
`define(`jd',incr(jd))')`'jd')
divert
for(`yr',2008,2121,
`ifelse(eval(julianxmas(yr)%7==6),1,`yr ')')
|
http://rosettacode.org/wiki/CUSIP
|
CUSIP
|
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
|
#Raku
|
Raku
|
sub divmod ($v, $r) { $v div $r, $v mod $r }
my %chr = (flat 0..9, 'A'..'Z', <* @ #>) Z=> 0..*;
sub cuisp-check ($cuisp where *.chars == 9) {
my ($code, $chk) = $cuisp.comb(8);
my $sum = [+] $code.comb.kv.map: { [+] (($^k % 2 + 1) * %chr{$^v}).&divmod(10) };
so (10 - $sum mod 10) mod 10 eq $chk;
}
# TESTING
say "$_: ", $_.&cuisp-check for <
037833100
17275R102
38259P508
594918104
68389X106
68389X105
>
|
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.
|
#BASIC
|
BASIC
|
10 INPUT "ENTER TWO INTEGERS:"; X%, Y%
20 DIM A%(X% - 1, Y% - 1)
30 X% = RND(1) * X%
40 Y% = RND(1) * Y%
50 A%(X%, Y%) = -32767
60 PRINT A%(X%, Y%)
70 CLEAR
|
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.
|
#BQN
|
BQN
|
#!/usr/bin/env bqn
# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# (BQNcrate phrase).
Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢
# Natural number from base-10 digits (BQNcrate phrase).
Base10 ← 10⊸×⊸+˜´∘⌽
# Parse any number of space-separated numbers from string 𝕩.
ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}
# •GetLine is a nonstandard CBQN extension.
•Show ⥊⟜(↕×´) ParseNums •GetLine@
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.