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.