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/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.
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************   ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC.   INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL.     DATA DIVISION.   FILE SECTION.   FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64).   FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80).   WORKING-STORAGE SECTION.   01 Eof PIC X VALUE 'F'.   01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5).   01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4).   PROCEDURE DIVISION.   Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN.   Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ.   Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line.   Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line.   END-PROGRAM.  
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.
#jq
jq
def checkdigit: [[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]] as $m | tostring | explode # "0" is 48 | 0 == reduce (.[] - 48) as $d (0; $m[.][$d] );   # The task: 5724, 5727, 112946, 112949 | checkdigit as $d | [., $d]  
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.
#Delphi
Delphi
  // Generate cuban primes. Nigel Galloway: June 9th., 2019 let cubans=Seq.unfold(fun n->Some(n*n*n,n+1L)) 1L|>Seq.pairwise|>Seq.map(fun(n,g)->g-n)|>Seq.filter(isPrime64) let cL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:int64)->n.ToString("N0",g))  
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.
#F.23
F#
  // Generate cuban primes. Nigel Galloway: June 9th., 2019 let cubans=Seq.unfold(fun n->Some(n*n*n,n+1L)) 1L|>Seq.pairwise|>Seq.map(fun(n,g)->g-n)|>Seq.filter(isPrime64) let cL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:int64)->n.ToString("N0",g))  
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#UNIX_Shell
UNIX Shell
#!/bin/sh cd # Make our home directory current echo "Hello World!" > hello.jnk # Create a junk file # tape rewind # Uncomment this to rewind the tape tar c hello.jnk # Traditional archivers use magnetic tape by default # tar c hello.jnk > /dev/tape # With newer archivers redirection is needed
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Wren
Wren
import "os" for Platform import "io" for File   var fileName = (Platform.isWindows) ? "TAPE.FILE" : "/dev/tape" File.create(fileName) { |file| file.writeBytes("Hello World!\n") }
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#ZX_Spectrum_Basic
ZX Spectrum Basic
SAVE "TAPEFILE" CODE 16384,6912
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.
#OCaml
OCaml
#require "bignum" ;;   let p1 = Bignum.((of_string "4000000000000000") * (of_float_decimal 5.50)) ;; let p2 = Bignum.((of_int 2) * (of_float_decimal 2.86)) ;;   let r1 = Bignum.(p1 + p2) ;; let r2 = Bignum.(r1 * (of_float_decimal (7.65 /. 100.))) ;; let r3 = Bignum.(r1 + r2) ;;   let my_to_string v = Bignum.(v |> round_decimal ~dir:`Nearest ~digits:2 |> to_string_hum ~decimals:2) ;;   let () = Printf.printf "before tax: %s\n" (my_to_string r1); Printf.printf "tax:  %s\n" (my_to_string r2); Printf.printf "total:  %s\n" (my_to_string r3); ;;
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.
#Perl
Perl
use Math::Decimal qw(dec_canonise dec_add dec_mul dec_rndiv_and_rem);   @check = ( [<Hamburger 5.50 4000000000000000>], [<Milkshake 2.86 2>] );   my $fmt = "%-10s %8s %18s %22s\n"; printf $fmt, <Item Price Quantity Extension>;   my $subtotal = dec_canonise(0); for $line (@check) { ($item,$price,$quant) = @$line; $dp = dec_canonise($price); $dq = dec_canonise($quant); my $extension = dec_mul($dp,$dq); $subtotal = dec_add($subtotal, $extension); printf $fmt, $item, $price, $quant, rnd($extension); }   my $rate = dec_canonise(0.0765); my $tax = dec_mul($subtotal,$rate); my $total = dec_add($subtotal,$tax);   printf $fmt, '', '', '', '-----------------'; printf $fmt, '', '', 'Subtotal ', rnd($subtotal); printf $fmt, '', '', 'Tax ', rnd($tax); printf $fmt, '', '', 'Total ', rnd($total);   sub rnd { ($q, $r) = dec_rndiv_and_rem("FLR", @_[0], 1); $q . substr((sprintf "%.2f", $r), 1, 3); }
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.
#Lambdatalk
Lambdatalk
  1) just define function a binary function: {def power {lambda {:a :b} {pow :a :b}}} -> power   2) and use it: {power 2 8} // power is a function waiting for two numbers -> 256   {{power 2} 8} // {power 2} is a function waiting for the missing number -> 256   {S.map {power 2} {S.serie 1 10}} // S.map applies the {power 2} unary function -> 2 4 8 16 32 64 128 256 512 1024 // to a sequence of numbers from 1 to 10  
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.
#Latitude
Latitude
addN := { takes '[n]. { $1 + n. }. }.   add3 := addN 3. add3 (4). ;; 7
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.
#Pascal
Pascal
use DateTime; use DateTime::Format::Strptime 'strptime'; use feature 'say';   my $input = 'March 7 2009 7:30pm EST'; $input =~ s{EST}{America/New_York};   say strptime('%b %d %Y %I:%M%p %O', $input) ->add(hours => 12) ->set_time_zone('America/Edmonton') ->format_cldr('MMMM d yyyy h:mma zzz');
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.
#J
J
load 'dates' NB. provides verb 'weekday' xmasSunday=: #~ 0 = [: weekday 12 25 ,~"1 0 ] NB. returns years where 25 Dec is a Sunday xmasSunday 2008 + i.114 NB. check years from 2008 to 2121 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118
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
#Nanoquery
Nanoquery
def cusip_checksum(cusip) alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" num = "0123456789" sum = 0   for i in range(1, 8) c = cusip[i - 1] v = 0 if c in num v = int(c) else if c in alpha p = alpha[c] + 1 v = p + 9 else if c in "*@#" v = "*@#"[c] + 36 end if (i % 2) = 0 v *= 2 end   sum += int(v / 10) + (v % 10) end   return (10 - (sum % 10)) % 10 end   if main codes = {"037833100", "17275R102", "38259P508",\ "594918104", "68389X106", "68389X105"}   for code in codes if int(code[len(code) - 1]) = cusip_checksum(code) println code + " is valid" else println code + " is invalid" end end end
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#Action.21
Action!
SET EndProg=*
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
#CoffeeScript
CoffeeScript
  class StandardDeviation constructor: -> @sum = 0 @sumOfSquares = 0 @values = 0 @deviation = 0   include: ( n ) -> @values += 1 @sum += n @sumOfSquares += n * n mean = @sum / @values mean *= mean @deviation = Math.sqrt @sumOfSquares / @values - mean   dev = new StandardDeviation values = [ 2, 4, 4, 4, 5, 5, 7, 9 ] tmp = []   for value in values tmp.push value dev.include value console.log """ Values: #{ tmp } Standard deviation: #{ dev.deviation }   """  
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
#Arturo
Arturo
print crc "The quick brown fox jumps over the lazy dog"
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string: The quick brown fox jumps over the lazy dog
#ALGOL_68
ALGOL 68
  [0:255]BITS crc_table; BOOL crc_table_computed := FALSE;   PROC make_crc_table = VOID: BEGIN INT n, k; FOR n FROM 0 TO 255 DO BITS c := BIN n; FOR k TO 8 DO c := IF 32 ELEM c THEN 16redb88320 XOR (c SHR 1) ELSE c SHR 1 FI OD; crc_table[n] := c OD; crc_table_computed := TRUE END;   PROC update_crc = (BITS crc, STRING buf) BITS: BEGIN BITS c := crc XOR 16rffffffff; INT n;   IF NOT crc_table_computed THEN make_crc_table FI; FOR n TO UPB buf DO c := crc_table[ABS ((c XOR BIN ABS buf[n]) AND 16rff)] XOR (c SHR 8) OD ; c XOR 16rffffffff END;   PROC hex = (BITS x) STRING : BEGIN PROC hexdig = (BITS x) CHAR: REPR (IF ABS x ≤ 9 THEN ABS x + ABS "0" ELSE ABS x - 10 + ABS "a" FI); STRING h := ""; IF x = 16r0 THEN h := "0" ELSE BITS n := x; WHILE h := hexdig (n AND 16rf) + h; n ≠ 16r0 DO n := n SHR 4 OD FI; h END;   PROC crc = (STRING buf) BITS: update_crc(16r0, buf);   STRING s = "The quick brown fox jumps over the lazy dog"; print(("CRC32 OF ", s, " is: ", hex (crc (s)), newline))  
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
#Frink
Frink
  println[now[] -> ### yyyy-MM-dd ###] println[now[] -> ### EEEE, MMMM d, yyyy ###]  
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#FunL
FunL
println( format('%tF', $date) ) println( format('%1$tA, %1$tB %1$td, %1$tY', $date) )
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).
#Ada
Ada
with Ada.Strings.Fixed; with Ada.Text_IO; with Templates_Parser;   procedure Csv2Html is use type Templates_Parser.Vector_Tag;   Chars : Templates_Parser.Vector_Tag; Speeches : Templates_Parser.Vector_Tag;   CSV_File : Ada.Text_IO.File_Type; begin -- read the csv data Ada.Text_IO.Open (File => CSV_File, Mode => Ada.Text_IO.In_File, Name => "data.csv");   -- fill the tags while not Ada.Text_IO.End_Of_File (CSV_File) loop declare Whole_Line : String := Ada.Text_IO.Get_Line (CSV_File); Comma_Pos : Natural := Ada.Strings.Fixed.Index (Whole_Line, ","); begin Chars := Chars & Whole_Line (Whole_Line'First .. Comma_Pos - 1); Speeches := Speeches & Whole_Line (Comma_Pos + 1 .. Whole_Line'Last); end; end loop;   Ada.Text_IO.Close (CSV_File);   -- build translation table and output html declare Translations : constant Templates_Parser.Translate_Table := (1 => Templates_Parser.Assoc ("CHAR", Chars), 2 => Templates_Parser.Assoc ("SPEECH", Speeches)); begin Ada.Text_IO.Put_Line (Templates_Parser.Parse ("table.tmplt", Translations)); end; end Csv2Html;
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.
#Common_Lisp
Common Lisp
  (defun csvfile-to-nested-list (filename delim-char) "Reads the csv to a nested list, where each sublist represents a line." (with-open-file (input filename) (loop :for line := (read-line input nil) :while line :collect (read-from-string (substitute #\SPACE delim-char (format nil "(~a)~%" line))))))   (defun sublist-sum-list (nested-list) "Return a list with the sum of each list of numbers in a nested list." (mapcar (lambda (l) (if (every #'numberp l) (reduce #'+ l) nil)) nested-list))   (defun append-each-sublist (nested-list1 nested-list2) "Horizontally append the sublists in two nested lists. Used to add columns." (mapcar #'append nested-list1 nested-list2))   (defun nested-list-to-csv (nested-list delim-string) "Converts the nested list back into a csv-formatted string." (format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}") nested-list))   (defun main () (let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt") (result-path #p"results.txt") (data-list (csvfile-to-nested-list csvfile-path #\,)) (list-of-sums (sublist-sum-list data-list)) (result-header "C1,C2,C3,C4,C5,SUM"))   (setf data-list ; add list of sums as additional column (rest ; remove old header (append-each-sublist data-list (mapcar #'list list-of-sums)))) ;; write to output-file (with-open-file (output result-path :direction :output :if-exists :supersede) (format output "~a~%~a" result-header (nested-list-to-csv data-list ","))))) (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.
#Julia
Julia
function checkdigit(n) matrix = ( (0, 3, 1, 7, 5, 9, 8, 6, 4, 2), (7, 0, 9, 2, 1, 5, 4, 8, 6, 3), (4, 2, 0, 6, 8, 7, 1, 3, 5, 9), (1, 7, 5, 0, 9, 8, 3, 4, 2, 6), (6, 1, 2, 3, 0, 4, 5, 9, 7, 8), (3, 6, 7, 4, 2, 0, 9, 5, 8, 1), (5, 8, 6, 9, 7, 2, 0, 1, 3, 4), (8, 9, 4, 5, 3, 6, 2, 0, 1, 7), (9, 4, 3, 8, 6, 1, 7, 2, 0, 5), (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)) row = 0 for d in string(n) row = matrix[row + 1][d - '0' + 1] end return row end   foreach(i -> println("$i validates as: ", checkdigit(string(i)) == 0), [5724, 5727, 112946])  
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.
#Kotlin
Kotlin
// version 1.1.2   val table = arrayOf( intArrayOf(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), intArrayOf(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), intArrayOf(4, 2, 0, 6, 8, 7, 1, 3, 5, 9), intArrayOf(1, 7, 5, 0, 9, 8, 3, 4, 2, 6), intArrayOf(6, 1, 2, 3, 0, 4, 5, 9, 7, 8), intArrayOf(3, 6, 7, 4, 2, 0, 9, 5, 8, 1), intArrayOf(5, 8, 6, 9, 7, 2, 0, 1, 3, 4), intArrayOf(8, 9, 4, 5, 3, 6, 2, 0, 1, 7), intArrayOf(9, 4, 3, 8, 6, 1, 7, 2, 0, 5), intArrayOf(2, 5, 8, 1, 4, 3, 6, 7, 9, 0) )   fun damm(s: String): Boolean { var interim = 0 for (c in s) interim = table[interim][c - '0'] return interim == 0 }   fun main(args: Array<String>) { val numbers = intArrayOf(5724, 5727, 112946, 112949) for (number in numbers) { val isValid = damm(number.toString()) println("${"%6d".format(number)} is ${if (isValid) "valid" else "invalid"}") } }
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.
#Factor
Factor
USING: formatting grouping io kernel lists lists.lazy math math.primes sequences tools.memory.private ; IN: rosetta-code.cuban-primes   : cuban-primes ( n -- seq ) 1 lfrom [ [ 3 * ] [ 1 + * ] bi 1 + ] <lazy-map> [ prime? ] <lazy-filter> ltake list>array ;   200 cuban-primes 10 <groups> [ [ commas ] map [ "%10s" printf ] each nl ] each nl   1e5 cuban-primes last commas "100,000th cuban prime is: %s\n" printf
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.
#Forth
Forth
  include ./miller-rabin.fs   \ commatized print \ : d.,r ( d n -- ) \ write double precision int, commatized. >r tuck dabs <# begin 2dup 1.000 d> while # # # [char] , hold repeat #s rot sign #> r> over - spaces type ;   : .,r ( n1 n2 -- ) \ write integer commatized. >r s>d r> d.,r ;     \ generate and print cuban primes \ : sq s" dup *" evaluate ; immediate : next-cuban ( n -- n' p ) begin 1+ dup sq 3 * 1+ dup 3 and 0= \ first check == 0 (mod 4) if 2 rshift dup prime? if exit else drop then else drop then again ;   : task1 1 20 0 do cr 10 0 do next-cuban 12 .,r loop loop drop ;   : task2 cr ." The 100,000th cuban prime is " 1 99999 0 do next-cuban drop loop next-cuban 0 .,r drop ;     task1 cr task2 cr bye  
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.
#Phix
Phix
with javascript_semantics requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed) include mpfr.e mpfr_set_default_precision(-20) -- ensure accuracy to at least 20 d.p. mpfr total_price = mpfr_init("4000000000000000"), tmp = mpfr_init("5.5"), tax = mpfr_init("0.0765"), total = mpfr_init() mpfr_mul(total_price,total_price,tmp) mpfr_set_str(tmp,"2.86") mpfr_mul_si(tmp,tmp,2) mpfr_add(total_price,total_price,tmp) mpfr_mul(tax,total_price,tax) mpfr_add(total,total_price,tax) printf(1,"Total before tax:%21s\n",{mpfr_get_fixed(total_price,2)}) printf(1," Tax:%21s\n",{mpfr_get_fixed(tax,2)}) printf(1," Total:%21s\n",{mpfr_get_fixed(total,2)})
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.
#PicoLisp
PicoLisp
(scl 2) (let (Before (+ (* 4000000000000000 5.50) (* 2 2.86) ) Tax (*/ Before 7.65 100.00) Total (+ Before Tax) Fmt (17 27) ) (tab Fmt "Total before tax:" (format Before *Scl "." ",")) (tab Fmt "Tax:" (format Tax *Scl "." ",")) (tab Fmt "Total:" (format Total *Scl "." ",")) )
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.
#LFE
LFE
(defun curry (f arg) (lambda (x) (apply f (list arg 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.
#Logtalk
Logtalk
  | ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T). T = 625 yes  
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.
#Perl
Perl
use DateTime; use DateTime::Format::Strptime 'strptime'; use feature 'say';   my $input = 'March 7 2009 7:30pm EST'; $input =~ s{EST}{America/New_York};   say strptime('%b %d %Y %I:%M%p %O', $input) ->add(hours => 12) ->set_time_zone('America/Edmonton') ->format_cldr('MMMM d yyyy h:mma zzz');
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.
#Phix
Phix
include builtins\timedate.e set_timedate_formats({"Mmmm d yyyy h:mmpm tz"}) timedate td = parse_date_string("March 7 2009 7:30pm EST") atom twelvehours = timedelta(hours:=12) td = adjust_timedate(td,twelvehours) ?format_timedate(td) td = change_timezone(td,"ACDT") -- extra credit ?format_timedate(td) td = adjust_timedate(td,timedelta(days:=31*4)) ?format_timedate(td)
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.
#Java
Java
import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar;   public class Yuletide{ public static void main(String[] args) { for(int i = 2008;i<=2121;i++){ Calendar cal = new GregorianCalendar(i, Calendar.DECEMBER, 25); if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){ System.out.println(cal.getTime()); } } } }
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
#Nim
Nim
import strutils   proc cusipCheck(cusip: string): bool = if cusip.len != 9: return false   var sum, v = 0 for i, c in cusip[0 .. ^2]: if c.isDigit: v = parseInt($c) elif c.isUpperAscii: v = ord(c) - ord('A') + 10 elif c == '*': v = 36 elif c == '@': v = 37 elif c == '#': v = 38   if i mod 2 == 1: v *= 2   sum += v div 10 + v mod 10 let check = (10 - (sum mod 10)) mod 10 return $check == $cusip[^1]   proc main = let codes = [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" ]   for code in codes: echo code, ": ", if cusipCheck(code): "Valid" else: "Invalid"   main()
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
#Objeck
Objeck
class Cusip { function : native : IsCusip(s : String) ~ Bool { if(s->Size() <> 9) { return false; };   sum := 0; for(i := 0; i < 7; i+=1;) { c := s->Get(i);   v : Int; if (c >= '0' & c <= '9') { v := c - 48; } else if (c >= 'A' & c <= 'Z') { v := c - 55; # lower case letters apparently invalid } else if (c = '*') { v := 36; } else if (c = '@') { v := 37; } else if (c = '#') { v := 38; } else { return false; };   # check if odd as using 0-based indexing if(i % 2 = 1) { v *= 2; };   sum += v / 10 + v % 10; };   return s->Get(8) - 48 = (10 - (sum % 10)) % 10; }   function : Main(args : String[]) ~ Nil { candidates := [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" ];   each(i : candidates) { candidate := candidates[i]; "{$candidate} => "->Print(); if(IsCusip(candidate)) { "correct"->PrintLine(); } else { "incorrect"->PrintLine(); }; }; } }
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.
#Ada
Ada
  with Ada.Text_Io; with Ada.Float_Text_Io; with Ada.Integer_Text_Io;   procedure Two_Dimensional_Arrays is type Matrix_Type is array(Positive range <>, Positive range <>) of Float; Dim_1 : Positive; Dim_2 : Positive; begin Ada.Integer_Text_Io.Get(Item => Dim_1); Ada.Integer_Text_Io.Get(Item => Dim_2); -- Create an inner block with the correctly sized array declare Matrix : Matrix_Type(1..Dim_1, 1..Dim_2); begin Matrix(1, Dim_2) := 3.14159; Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0); Ada.Text_Io.New_Line; end; -- The variable Matrix is popped off the stack automatically end Two_Dimensional_Arrays;
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
#Common_Lisp
Common Lisp
(defun running-stddev () (let ((sum 0) (sq 0) (n 0)) (lambda (x) (incf sum x) (incf sq (* x x)) (incf n) (/ (sqrt (- (* n sq) (* sum sum))) n))))   CL-USER> (loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do (format t "~a ~a~%" i (funcall f i))) NIL 2 0.0 4 1.0 4 0.94280905 4 0.8660254 5 0.97979593 5 1.0 7 1.3997085 9 2.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
#Applesoft_BASIC
Applesoft BASIC
0 DIM D$(1111):D$(0)="0":D$(1)="1":D$(10)="2":D$(11)="3":D$(100)="4":D$(101)="5":D$(110)="6":D$(111)="7":D$(1000)="8":D$(1001)="9":D$(1010)="A":D$(1011)="B":D$(1100)="C":D$(1101)="D":D$(1110)="E":D$(1111)="F" 1 Z$ = CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) + CHR$ (8) 100 C$ = "00000000000000000000000000000000" 110 S$ = "The quick brown fox jumps over the lazy dog" 120 GOSUB 200"CRC32 130 PRINT D$( VAL ( MID$ (C$,1,4)))D$( VAL ( MID$ (C$,5,4)))D$( VAL ( MID$ (C$,9,4)))D$( VAL ( MID$ (C$,13,4)))D$( VAL ( MID$ (C$,17,4)))D$( VAL ( MID$ (C$,21,4)))D$( VAL ( MID$ (C$,25,4)))D$( VAL ( MID$ (C$,29,4)))" "; 140 END 200 IF LEN (S$) = 0 THEN RETURN 210 GOSUB 280"XOR #$FFFFFFFF 220 FOR I = 1 TO LEN (S$) 230 R$ = "00000000" + MID$ (C$,1,24) 235 PRINT D$( VAL ( MID$ (C$,1,4)))D$( VAL ( MID$ (C$,5,4)))D$( VAL ( MID$ (C$,9,4)))D$( VAL ( MID$ (C$,13,4))); 236 PRINT D$( VAL ( MID$ (C$,17,4)))D$( VAL ( MID$ (C$,21,4)))D$( VAL ( MID$ (C$,25,4)))D$( VAL ( MID$ (C$,29,4)))" " MID$ (S$,I,1)Z$; 240 C = ASC ( MID$ (S$,I,1)):O$ = "": FOR B = 1 TO 8:K = INT (C / 2):O$ = STR$ (C - K * 2) + O$:C = K: NEXT B 250 A = ( MID$ (C$,25,1) < > MID$ (O$,1,1)) * 128 + ( MID$ (C$,26,1) < > MID$ (O$,2,1)) * 64 + ( MID$ (C$,27,1) < > MID$ (O$,3,1)) * 32 + ( MID$ (C$,28,1) < > MID$ (O$,4,1)) * 16 251 A = ( MID$ (C$,29,1) < > MID$ (O$,5,1)) * 8 + ( MID$ (C$,30,1) < > MID$ (O$,6,1)) * 4 + ( MID$ (C$,31,1) < > MID$ (O$,7,1)) * 2 + ( MID$ (C$,32,1) < > MID$ (O$,8,1)) + A: GOSUB 300 260 C$ = STR$ (( MID$ (R$,1,1) < > MID$ (T$,1,1))) + STR$ (( MID$ (R$,2,1) < > MID$ (T$,2,1))) + STR$ (( MID$ (R$,3,1) < > MID$ (T$,3,1))) + STR$ (( MID$ (R$,4,1) < > MID$ (T$,4,1))) 261 C$ = C$ + STR$ (( MID$ (R$,5,1) < > MID$ (T$,5,1))) + STR$ (( MID$ (R$,6,1) < > MID$ (T$,6,1))) + STR$ (( MID$ (R$,7,1) < > MID$ (T$,7,1))) + STR$ (( MID$ (R$,8,1) < > MID$ (T$,8,1))) 262 C$ = C$ + STR$ (( MID$ (R$,9,1) < > MID$ (T$,9,1))) + STR$ (( MID$ (R$,10,1) < > MID$ (T$,10,1))) + STR$ (( MID$ (R$,11,1) < > MID$ (T$,11,1))) + STR$ (( MID$ (R$,12,1) < > MID$ (T$,12,1))) 263 C$ = C$ + STR$ (( MID$ (R$,13,1) < > MID$ (T$,13,1))) + STR$ (( MID$ (R$,14,1) < > MID$ (T$,14,1))) + STR$ (( MID$ (R$,15,1) < > MID$ (T$,15,1))) + STR$ (( MID$ (R$,16,1) < > MID$ (T$,16,1))) 264 C$ = C$ + STR$ (( MID$ (R$,17,1) < > MID$ (T$,17,1))) + STR$ (( MID$ (R$,18,1) < > MID$ (T$,18,1))) + STR$ (( MID$ (R$,19,1) < > MID$ (T$,19,1))) + STR$ (( MID$ (R$,20,1) < > MID$ (T$,20,1))) 265 C$ = C$ + STR$ (( MID$ (R$,21,1) < > MID$ (T$,21,1))) + STR$ (( MID$ (R$,22,1) < > MID$ (T$,22,1))) + STR$ (( MID$ (R$,23,1) < > MID$ (T$,23,1))) + STR$ (( MID$ (R$,24,1) < > MID$ (T$,24,1))) 266 C$ = C$ + STR$ (( MID$ (R$,25,1) < > MID$ (T$,25,1))) + STR$ (( MID$ (R$,26,1) < > MID$ (T$,26,1))) + STR$ (( MID$ (R$,27,1) < > MID$ (T$,27,1))) + STR$ (( MID$ (R$,28,1) < > MID$ (T$,28,1))) 267 C$ = C$ + STR$ (( MID$ (R$,29,1) < > MID$ (T$,29,1))) + STR$ (( MID$ (R$,30,1) < > MID$ (T$,30,1))) + STR$ (( MID$ (R$,31,1) < > MID$ (T$,31,1))) + STR$ (( MID$ (R$,32,1) < > MID$ (T$,32,1))) 270 NEXT I 280 B$ = "": FOR B = 1 TO 32:B$ = B$ + STR$ (( MID$ (C$,B,1) < > "1")): NEXT B:C$ = B$ 290 RETURN 300 IF NOT T THEN DIM T$(255): FOR T = 0 TO 38: READ J: READ T$(J): NEXT T 310 IF LEN (T$(A)) THEN T$ = T$(A): RETURN 320 R = A:T$ = "": FOR B = 1 TO 8:N = INT (R / 2):T$ = MID$ ("01",R - N * 2 + 1,1) + T$:R = N: NEXT B:T$ = "000000000000000000000000" + T$ 330 FOR J = 0 TO 7 340 X = VAL ( MID$ (T$,32,1)) 350 T$ = "0" + MID$ (T$,1,31) 360 IF X THEN B$ = "": FOR B = 1 TO 32:B$ = B$ + MID$ ("01",( MID$ (T$,B,1) < > MID$ ("11101101101110001000001100100000",B,1)) + 1,1): NEXT B:T$ = B$ 370 NEXT J 380 T$(A) = T$:T = T + 1 390 RETURN 600 DATA171,01000001000001000111101001100000 610 DATA247,00100011110110010110011110111111 620 DATA95,11111011110101000100110001100101 630 DATA217,11111111000011110110101001110000 640 DATA213,11110110101110010010011001011011 650 DATA179,01010010011010001110001000110110 660 DATA141,10010011000010011111111110011101 670 DATA90,10001011101111101011100011101010 680 DATA224,10100000000010101110001001111000 690 DATA187,01011100101100110110101000000100 700 DATA169,10101111000010100001101101001100 710 DATA60,00101111011011110111110010000111 720 DATA128,11101101101110001000001100100000 730 DATA36,00111100000000111110010011010001 740 DATA235,00110111110110000011101111110000 750 DATA229,11010000011000000001011011110111 760 DATA77,00001000011011010011110100101101 770 DATA167,01001000101100100011011001001011 780 DATA1,01110111000001110011000010010110 790 DATA119,11001110011000011110010010011111 800 DATA96,01001101101100100110000101011000 810 DATA158,00010111101101111011111001000011 820 DATA68,01110001101100011000010110001001 830 DATA56,00101000000000101011100010011110 840 DATA193,11101100011000111111001000100110 850 DATA87,11110101000011111100010001010111 860 DATA160,11010110110101101010001111101000 870 DATA2,11101110000011100110000100101100 880 DATA30,11111010000011110011110101100011 890 DATA7,10011110011001001001010110100011 900 DATA26,11111101011000101111100101111010 910 DATA85,00011011000000011010010101111011 920 DATA15,10010000101111110001110110010001 930 DATA201,11100010101110000111101000010100 940 DATA188,11000010110101111111111110100111 950 DATA0,00000000000000000000000000000000 960 DATA238,01000111101100101100111101111111 970 DATA181,10111011000010110100011100000011 980 DATA114,10111110000010110001000000010000
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
#AutoHotkey
AutoHotkey
CRC32(str, enc = "UTF-8") { l := (enc = "CP1200" || enc = "UTF-16") ? 2 : 1, s := (StrPut(str, enc) - 1) * l VarSetCapacity(b, s, 0) && StrPut(str, &b, floor(s / l), enc) CRC32 := DllCall("ntdll.dll\RtlComputeCrc32", "UInt", 0, "Ptr", &b, "UInt", s) return Format("{:#x}", CRC32) }   MsgBox % CRC32("The quick brown fox jumps over the lazy dog")
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
#FutureBasic
FutureBasic
window 1   print date(@"yyyy-MM-dd") print date(@"EEEE, MMMM dd, yyyy")   HandleEvents
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
#Gambas
Gambas
Public Sub Main()   Print Format(Now, "yyyy - mm - dd") Print Format(Now, "dddd, mmmm dd, yyyy")   End
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   [6]STRING rows := []STRING( "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!" );   [max abs char]STRING encoded; FOR i TO UPB encoded DO encoded[i]:=REPR i OD; # encoded[ABS""""] := "&quot;"; optional # encoded[ABS "&"] := "&amp;"; encoded[ABS "<"] := "&lt;"; # encoded[ABS ">"] := "&gt;"; optional #   OP ENCODE = (STRING s)STRING: ( STRING out := ""; FOR i TO UPB s DO out+:= encoded[ABS s[i]] OD; out );   PROC head = (STRING title)VOID: ( printf(( $"<HEAD>"l$, $"<TITLE>"g"</TITLE>"l$, title, $"<STYLE type=""text/css"">"l$, $"TD {background-color:#ddddff; }"l$, $"thead TD {background-color:#ddffdd; text-align:center; }"l$, $"</STYLE>"l$, $"</HEAD>"l$ )) );   # define HTML tags using Algol68's "reverent" block structuring # PROC html = VOID: print(("<HTML>", new line)), body = VOID: print(("<BODY>", new line)), table = VOID: print(("<TABLE>", new line)), table row = VOID: print(("<TR>")), th = (STRING s)VOID: printf(($"<TH>"g"</TH>"$, s)), td = (STRING s)VOID: printf(($"<TD>"g"</TD>"$, s)), elbat row = VOID: print(("</TR>", new line)), elbat = VOID: print(("</TABLE>", new line)), ydob = VOID: print(("</BODY>", new line)), lmth = VOID: print(("</HTML>", new line));   FILE row input; STRING row; CHAR ifs = ","; associate(row input, row); make term(row input, ifs);   html; head("CSV to HTML translation - Extra Credit"); body; table; FOR nr TO UPB rows DO row := rows[nr]; table row; on logical file end(row input, (REF FILE row input)BOOL: row end); FOR nf DO STRING field; get(row input,field); (nr=1|th|td)(ENCODE field); get(row input, space) OD; row end: reset(row input); elbat row OD; elbat; ydob; lmth
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.
#D
D
void main() { import std.stdio, std.csv, std.file, std.typecons, std.array, std.algorithm, std.conv, std.range;   auto rows = "csv_data_in.csv".File.byLine; auto fout = "csv_data_out.csv".File("w"); fout.writeln(rows.front); fout.writef("%(%(%d,%)\n%)", rows.dropOne .map!(r => r.csvReader!int.front.map!(x => x + 1))); }
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.
#Liberty_BASIC
Liberty BASIC
Dim DT(9, 9)   For y = 0 To 9 For x = 0 To 9 Read val DT(x, y) = val Next x Next y   Input check$ While (check$ <> "") D = 0 For i = 1 To Len(check$) D = DT(Val(Mid$(check$, i, 1)), D) Next i If D Then Print "Invalid" Else Print "Valid" End If Input check$ Wend End   DATA 0,3,1,7,5,9,8,6,4,2 DATA 7,0,9,2,1,5,4,8,6,3 DATA 4,2,0,6,8,7,1,3,5,9 DATA 1,7,5,0,9,8,3,4,2,6 DATA 6,1,2,3,0,4,5,9,7,8 DATA 3,6,7,4,2,0,9,5,8,1 DATA 5,8,6,9,7,2,0,1,3,4 DATA 8,9,4,5,3,6,2,0,1,7 DATA 9,4,3,8,6,1,7,2,0,5 DATA 2,5,8,1,4,3,6,7,9,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.
#Lua
Lua
local tab = { {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 check( n ) local idx, a = 0, tonumber( n:sub( 1, 1 ) ) for i = 1, #n do a = tonumber( n:sub( i, i ) ) if a == nil then return false end idx = tab[idx + 1][a + 1] end return idx == 0 end local n, r while( true ) do io.write( "Enter the number to check: " ) n = io.read(); if n == "0" then break end r = check( n ); io.write( n, " is " ) if not r then io.write( "in" ) end io.write( "valid!\n" ) 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.
#FreeBASIC
FreeBASIC
function isprime( n as ulongint ) as boolean if n mod 2 = 0 then return false for i as uinteger = 3 to int(sqr(n))+1 step 2 if n mod i = 0 then return false next i return true end function   function diff_cubes( n as uinteger ) as ulongint return 3*n*(n+1) + 1 end function   function padto( n as uinteger, s as integer ) as string dim as string outstr="" dim as integer k = len(str(n)) for i as integer = 1 to s-k outstr = " " + outstr next i return outstr + str(n) end function   dim as integer nc = 0, i = 1, di while nc < 100000 di = diff_cubes(i) if isprime(di) then nc += 1 if nc <= 200 then print padto(di,8);" "; if nc mod 10 = 0 then print end if if nc = 100000 then print : print : print di exit while end if end if i += 1 wend
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.
#Python
Python
from decimal import Decimal as D from collections import namedtuple   Item = namedtuple('Item', 'price, quant')   items = dict( hamburger=Item(D('5.50'), D('4000000000000000')), milkshake=Item(D('2.86'), D('2')) ) tax_rate = D('0.0765')   fmt = "%-10s %8s %18s %22s" print(fmt % tuple('Item Price Quantity Extension'.upper().split()))   total_before_tax = 0 for item, (price, quant) in sorted(items.items()): ext = price * quant print(fmt % (item, price, quant, ext)) total_before_tax += ext print(fmt % ('', '', '', '--------------------')) print(fmt % ('', '', 'subtotal', total_before_tax))   tax = (tax_rate * total_before_tax).quantize(D('0.00')) print(fmt % ('', '', 'Tax', tax))   total = total_before_tax + tax print(fmt % ('', '', '', '--------------------')) print(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.
#Racket
Racket
#lang racket (define (cents-* x y) (/ (round (* 100 x y)) 100))   (struct item (name count price))   (define (string-pad-right len . strs) (define all (apply string-append strs)) (string-append all (make-string (- len (string-length all)) #\space)))   (define (string-pad-left len . strs) (define all (apply string-append strs)) (string-append (make-string (- len (string-length all)) #\space) all))   (define (show-formated name count price total) (printf "~a ~a ~a -> ~a\n" (string-pad-right 10 name) (string-pad-left 18 count) (string-pad-left 8 price) (string-pad-left 23 total) ))   (define (show-item it) (show-formated (item-name it) (~r (item-count it)) (string-append "$" (~r (item-price it) #:precision '(= 2))) (string-append "$" (~r (cents-* (item-count it) (item-price it)) #:precision '(= 2))) ))   (define (show-total all tax-rate) (define net (for/sum ([it (in-list all)]) (cents-* (item-count it) (item-price it)))) (define tax (cents-* net tax-rate)) (show-formated "" "" "net" (string-append "$" (~r net #:precision '(= 2)))) (show-formated "" "" "tax" (string-append "$" (~r tax #:precision '(= 2)))) (show-formated "" "" "total" (string-append "$" (~r (+ net tax) #:precision '(= 2)))) )   (define hamburger (item "hamburger" 4000000000000000 #e5.50)) (define milkshake (item "milkshake" 2 #e2.86)) (define all (list hamburger milkshake))   (for-each show-item all) (newline) (show-total all (/ #e7.65 100))
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.
#Lua
Lua
  function curry2(f) return function(x) return function(y) return f(x,y) end end end   function add(x,y) return x+y end   local adder = curry2(add) assert(adder(3)(4) == 3+4) local add2 = adder(2) assert(add2(3) == 2+3) assert(add2(5) == 2+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.
#M2000_Interpreter
M2000 Interpreter
  Module LikeCpp { divide=lambda (x, y)->x/y partsof120=lambda divide ->divide(![], 120) Print "half of 120 is ";partsof120(2) Print "a third is ";partsof120(3) Print "and a quarter is ";partsof120(4) } LikeCpp   Module Joke { \\ we can call F1(), with any number of arguments, and always read one and then \\ call itself passing the remain arguments \\ ![] take stack of values and place it in the next call. F1=lambda -> { if empty then exit Read x =x+lambda(![]) }   Print F1(F1(2),2,F1(-4))=0 Print F1(-4,F1(2),2)=0 Print F1(2, F1(F1(2),2))=F1(F1(F1(2),2),2) Print F1(F1(F1(2),2),2)=6 Print F1(2, F1(2, F1(2),2))=F1(F1(F1(2),2, F1(2)),2) Print F1(F1(F1(2),2, F1(2)),2)=8 Print F1(2, F1(10, F1(2, F1(2),2)))=F1(F1(F1(2),2, F1(2)),2, 10) Print F1(F1(F1(2),2, F1(2)),2, 10)=18 Print F1(2,2,2,2,10)=18 Print F1()=0   Group F2 { Sum=0 Function Add (x){ .Sum+=x =x } } Link F2.Add() to F2() Print F1(F1(F1(F2(2)),F2(2), F1(F2(2))),F2(2))=8 Print F2.Sum=8 } Joke  
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.
#PHP
PHP
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
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.
#PicoLisp
PicoLisp
(de timePlus12 (Str) (use (@Mon @Day @Year @Time @Zone) (and (match '(@Mon " " @Day " " @Year " " @Time " " @Zone) (chop Str) ) (setq @Mon (index (pack @Mon) *MonFmt)) (setq @Day (format @Day)) (setq @Year (format @Year)) (setq @Time (case (tail 2 @Time) (("a" "m") ($tim (head -2 @Time))) (("p" "m") (+ `(time 12 0) ($tim (head -2 @Time)))) (T ($tim @Time)) ) ) (let? Date (date @Year @Mon @Day) (when (>= (inc '@Time `(time 12 0)) 86400) (dec '@Time 86400) (inc 'Date) ) (pack (dat$ Date "-") " " (tim$ @Time T) " " @Zone) ) ) ) )
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.
#JavaScript
JavaScript
for (var year = 2008; year <= 2121; year++){ var xmas = new Date(year, 11, 25) if ( xmas.getDay() === 0 ) console.log(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.
#jq
jq
# Use Zeller's Congruence to determine the day of the week, given # year, month and day as integers in the conventional way. # If iso == "iso" or "ISO", then emit an integer in 1 -- 7 where # 1 represents Monday, 2 Tuesday, etc; # otherwise emit 0 for Saturday, 1 for Sunday, etc. # def day_of_week(year; month; day; iso): if month == 1 or month == 2 then [month + 12, year - 1] else [month, year] end | day + (13*(.[0] + 1)/5|floor) + (.[1]%100) + ((.[1]%100)/4|floor) + (.[1]/400|floor) - 2*(.[1]/100|floor) | if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7) else . % 7 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
#Perl
Perl
$cv{$_} = $i++ for '0'..'9', 'A'..'Z', '*', '@', '#';   sub cusip_check_digit { my @cusip = split m{}xms, shift; my $sum = 0;   for $i (0..7) { return 'Invalid character found' unless $cusip[$i] =~ m{\A [[:digit:][:upper:]*@#] \z}xms; $v = $cv{ $cusip[$i] }; $v *= 2 if $i%2; $sum += int($v/10) + $v%10; }   $check_digit = (10 - ($sum%10)) % 10; $check_digit == $cusip[8] ? '' : ' (incorrect)'; }   my %test_data = ( '037833100' => 'Apple Incorporated', '17275R102' => 'Cisco Systems', '38259P508' => 'Google Incorporated', '594918104' => 'Microsoft Corporation', '68389X106' => 'Oracle Corporation', '68389X105' => 'Oracle Corporation', );   print "$_ $test_data{$_}" . cusip_check_digit($_) . "\n" for sort keys %test_data;
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.
#ALGOL_60
ALGOL 60
begin comment Create a two-dimensional array at runtime - Algol 60; integer n,m; ininteger(0,m); ininteger(0,n); begin integer array a[1:m,1:n]; a[m,n] := 99; outinteger(1,a[m,n]); outstring(1,"\n") end; comment array a : out of scope; end
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#ALGOL_68
ALGOL 68
main:( print("Input two positive whole numbers separated by space and press newline:"); [read int,read int] INT array; array[1,1]:=42; print (array[1,1]) )
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used. Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population. Test case Use this to compute the standard deviation of this demonstration set, { 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 } {\displaystyle \{2,4,4,4,5,5,7,9\}} , which is 2 {\displaystyle 2} . Related tasks Random numbers Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Component_Pascal
Component Pascal
  MODULE StandardDeviation; IMPORT StdLog, Args,Strings,Math;   PROCEDURE Mean(x: ARRAY OF REAL; n: INTEGER; OUT mean: REAL); VAR i: INTEGER; total: REAL; BEGIN total := 0.0; FOR i := 0 TO n - 1 DO total := total + x[i] END; mean := total /n END Mean;   PROCEDURE SDeviation(x : ARRAY OF REAL;n: INTEGER): REAL; VAR i: INTEGER; mean,sum: REAL; BEGIN Mean(x,n,mean); sum := 0.0; FOR i := 0 TO n - 1 DO sum:= sum + ((x[i] - mean) * (x[i] - mean)); END; RETURN Math.Sqrt(sum/n); END SDeviation;   PROCEDURE Do*; VAR p: Args.Params; x: POINTER TO ARRAY OF REAL; i,done: INTEGER; BEGIN Args.Get(p); IF p.argc > 0 THEN NEW(x,p.argc); FOR i := 0 TO p.argc - 1 DO x[i] := 0.0 END; FOR i := 0 TO p.argc - 1 DO Strings.StringToReal(p.args[i],x[i],done); StdLog.Int(i + 1);StdLog.String(" :> ");StdLog.Real(SDeviation(x,i + 1));StdLog.Ln END END END Do; END StandardDeviation.  
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
#C
C
#include <stdio.h> #include <string.h> #include <zlib.h>   int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s)));   return 0; }
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string: The quick brown fox jumps over the lazy dog
#C.23
C#
  /// <summary> /// Performs 32-bit reversed cyclic redundancy checks. /// </summary> public class Crc32 { #region Constants /// <summary> /// Generator polynomial (modulo 2) for the reversed CRC32 algorithm. /// </summary> private const UInt32 s_generator = 0xEDB88320; #endregion   #region Constructors /// <summary> /// Creates a new instance of the Crc32 class. /// </summary> public Crc32() { // Constructs the checksum lookup table. Used to optimize the checksum. m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion   #region Methods /// <summary> /// Calculates the checksum of the byte stream. /// </summary> /// <param name="byteStream">The byte stream to calculate the checksum for.</param> /// <returns>A 32-bit reversed checksum.</returns> public UInt32 Get<T>(IEnumerable<T> byteStream) { try { // Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum. return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion   #region Fields /// <summary> /// Contains a cache of calculated checksum chunks. /// </summary> private readonly UInt32[] m_checksumTable;   #endregion }  
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
#Go
Go
package main   import "time" import "fmt"   func main() { fmt.Println(time.Now().Format("2006-01-02")) fmt.Println(time.Now().Format("Monday, January 2, 2006")) }
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
#Groovy
Groovy
def isoFormat = { date -> date.format("yyyy-MM-dd") } def longFormat = { date -> date.format("EEEE, MMMM dd, yyyy") }
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.
#11l
11l
L(directory) [‘/’, ‘./’] File(directory‘output.txt’, ‘w’) // create /output.txt, then ./output.txt fs:create_dir(directory‘docs’) // create directory /docs, then ./docs
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#ANTLR
ANTLR
  // Create an HTML Table from comma seperated values // Nigel Galloway - June 2nd., 2013 grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;  
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
#Delphi
Delphi
  program CSV_data_manipulation;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IoUtils, System.Types;   type TStringDynArrayHelper = record helper for TStringDynArray function Sum: Integer; end;   { TStringDynArrayHelper }   function TStringDynArrayHelper.Sum: Integer; var value: string; begin Result := 0; for value in self do Result := Result + StrToIntDef(value, 0); end;   const FILENAME = './Data.csv';   var i: integer; Input, Row: TStringDynArray;   begin Input := TFile.ReadAllLines(FILENAME); for i := 0 to High(Input) do begin if i = 0 then Input[i] := Input[i] + ',SUM' else begin Row := Input[i].Split([',']); Input[i] := Input[i] + ',' + row.Sum.ToString; end; end; TFile.WriteAllLines(FILENAME, Input); end.
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#M2000_Interpreter
M2000 Interpreter
  Module Damm_Algorithm{ Function Prepare { function OperationTable { data (0, 3, 1, 7, 5, 9, 8, 6, 4, 2) data (7, 0, 9, 2, 1, 5, 4, 8, 6, 3) data (4, 2, 0, 6, 8, 7, 1, 3, 5, 9) data (1, 7, 5, 0, 9, 8, 3, 4, 2, 6) data (6, 1, 2, 3, 0, 4, 5, 9, 7, 8) data (3, 6, 7, 4, 2, 0, 9, 5, 8, 1) data (5, 8, 6, 9, 7, 2, 0, 1, 3, 4) data (8, 9, 4, 5, 3, 6, 2, 0, 1, 7) data (9, 4, 3, 8, 6, 1, 7, 2, 0, 5) data (2, 5, 8, 1, 4, 3, 6, 7, 9, 0) =array([]) } Digits= Lambda (d) ->{ d$=str$(d,"") for i=1 to len(d$) data val(mid$(d$,i,1)) next =Array([]) } =Lambda a()=OperationTable(), Digits (N) -> { dim b() b()=Digits(N) m=0 for i=0 to len(b())-1 m=a(m)(b(i)) next i =m } } Damm=Prepare() Data 5724, 5727, 112946, 112940 while not empty over ' double the top of stack over Print number, Damm(number), Damm(number)=0 End While } Damm_Algorithm  
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.
#MAD
MAD
NORMAL MODE IS INTEGER   R VERIFY DAMM CHECKSUM OF NUMBER INTERNAL FUNCTION(CKNUM) VECTOR VALUES DAMMIT = 0 0,3,1,7,5,9,8,6,4,2 1 , 7,0,9,2,1,5,4,8,6,3 2 , 4,2,0,6,8,7,1,3,5,9 3 , 1,7,5,0,9,8,3,4,2,6 4 , 6,1,2,3,0,4,5,9,7,8 5 , 3,6,7,4,2,0,9,5,8,1 6 , 5,8,6,9,7,2,0,1,3,4 7 , 8,9,4,5,3,6,2,0,1,7 8 , 9,4,3,8,6,1,7,2,0,5 9 , 2,5,8,1,4,3,6,7,9,0 DIMENSION DAMDGT(10) ENTRY TO DAMM. TMP=CKNUM THROUGH GETDGT, FOR NDGT=0, 1, TMP.E.0 DAMDGT(NDGT) = TMP-TMP/10*10 GETDGT TMP = TMP/10 INTRM = 0 THROUGH CKDGT, FOR NDGT=NDGT, -1, NDGT.L.0 CKDGT INTRM = DAMMIT(INTRM*10 + DAMDGT(NDGT)) FUNCTION RETURN INTRM.E.0 END OF FUNCTION   R TEST SOME NUMBERS THROUGH TEST, FOR VALUES OF N = 5724,5727,112946,112949 WHENEVER DAMM.(N) PRINT FORMAT VALID,N OTHERWISE PRINT FORMAT INVAL,N TEST END OF CONDITIONAL   VECTOR VALUES VALID = $I9,S1,5HVALID*$ VECTOR VALUES INVAL = $I9,S1,7HINVALID*$ END OF PROGRAM  
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.
#Go
Go
package main   import ( "fmt" "math/big" )   func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s }   func main() { var z big.Int var cube1, cube2, cube100k, diff uint64 cubans := make([]string, 200) cube1 = 1 count := 0 for i := 1; ; i++ { j := i + 1 cube2 = uint64(j * j * j) diff = cube2 - cube1 z.SetUint64(diff) if z.ProbablyPrime(0) { // 100% accurate for z < 2 ^ 64 if count < 200 { cubans[count] = commatize(diff) } count++ if count == 100000 { cube100k = diff break } } cube1 = cube2 } fmt.Println("The first 200 cuban primes are:-") for i := 0; i < 20; i++ { j := i * 10 fmt.Printf("%9s\n", cubans[j : j+10]) // 10 per line say } fmt.Println("\nThe 100,000th cuban prime is", commatize(cube100k)) }
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.
#Raku
Raku
my @check = q:to/END/.lines.map: { [.split(/\s+/)] }; Hamburger 5.50 4000000000000000 Milkshake 2.86 2 END   my $tax-rate = 0.0765;   my $fmt = "%-10s %8s %18s %22s\n";   printf $fmt, <Item Price Quantity Extension>;   my $subtotal = [+] @check.map: -> [$item,$price,$quant] { my $extension = $price * $quant; printf $fmt, $item, $price, $quant, fix2($extension); $extension; }   printf $fmt, '', '', '', '-----------------'; printf $fmt, '', '', 'Subtotal ', $subtotal;   my $tax = ($subtotal * $tax-rate).round(0.01); printf $fmt, '', '', 'Tax ', $tax;   my $total = $subtotal + $tax; printf $fmt, '', '', 'Total ', $total;   # make up for lack of a Rat fixed-point printf format sub fix2($x) { ($x + 0.001).subst(/ <?after \.\d\d> .* $ /, '') }
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
In[1]:= plusFC = Function[{x},Function[{y},Plus[x,y]]];
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.
#Nemerle
Nemerle
using System; using System.Console;   module Curry { Curry[T, U, R](f : T * U -> R) : T -> U -> R { fun (x) { fun (y) { f(x, y) } } }   Main() : void { def f(x, y) { x + y } def g = Curry(f); def h = Curry(f)(12); // partial application WriteLine($"$(Curry(f)(20)(22))"); WriteLine($"$(g(21)(21))"); WriteLine($"$(h(30))") } }
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.
#Nim
Nim
proc addN[T](n: T): auto = (proc(x: T): T = x + n)   let add2 = addN(2) echo add2(7)
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.
#Pike
Pike
> (Calendar.dwim_time("March 7 2009 7:30pm EST")+Calendar.Hour()*12)->set_timezone("CET")->format_ext_time(); Result: "Saturday, 7 March 2009 12:30:00"
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.
#PL.2FI
PL/I
/* The PL/I date functions handle dates and time in 49 */ /* different formats, but not that particular one. For any of the */ /* standard formats, the following date manipulation will add */ /* 12 hours to the current date/time. */   seconds = SECS(DATETIME()); seconds = seconds + 12*60*60; put list (SECSTODATE(seconds));
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.
#Jsish
Jsish
/* Day of the week, December 25th on a Sunday */ for (var year = 2008; year <= 2121; year++) { var xmas = strptime(year + '/12/25', '%Y/%m/%d'); var weekDay = strftime(xmas, '%w'); if (weekDay == 0) puts(year); }   /* =!EXPECTSTART!= 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118 =!EXPECTEND!= */
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.
#Julia
Julia
using Dates   lo, hi = 2008, 2121 xmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25)) filter!(xmas) do dt dayofweek(dt) == Dates.Sunday end   println("Years from $lo to $hi having Christmas on Sunday: ") foreach(println, year.(xmas))
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
#Phix
Phix
sequence cch = {} function CusipCheckDigit(string cusip) integer s = 0, c, v if length(cch)=0 then cch = repeat(-1,256) for i='0' to '9' do cch[i] = i-'0' end for for i='A' to 'Z' do cch[i] = i-55 end for cch['*'] = 36 cch['@'] = 37 cch['#'] = 38 end if if length(cusip)!=9 or find('\0',cusip) then return 0 end if for i=1 to 8 do c := cusip[i] v := cch[c] if v=-1 then return 0 end if if remainder(i,2)=0 then v *= 2 end if s += floor(v/10)+mod(v,10) end for return cusip[9]=mod(10-mod(s,10),10)+'0' end function sequence tests = {"037833100", -- Apple Incorporated "17275R102", -- Cisco Systems "38259P508", -- Google Incorporated "594918104", -- Microsoft Corporation "68389X106", -- Oracle Corporation (incorrect) "68389X105"} -- Oracle Corporation for i=1 to length(tests) do string ti = tests[i] printf(1,"%s : %s\n",{ti,{"invalid","valid"}[CusipCheckDigit(ti)+1]}) end for
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.
#ALGOL_W
ALGOL W
begin integer dimension1UpperBound, dimension2UpperBound; write( "upper bound for dimension 1: " ); read( dimension1UpperBound ); write( "upper bound for dimension 2: " ); read( dimension2UpperBound );   begin  % we start a new block because declarations must precede statements %  % and variables in array bounds must be from outside the block  % integer array matrix ( 1 :: dimension1UpperBound , 1 :: dimension2UpperBound );  % set the first element - the program will crash if the user input  %  % upper bounds less than 1  % matrix( 1, 1 ) := 3;  % write it  % write( matrix( 1, 1 ) );  % the array is automatically deleted when the block ends  % end   end.
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#Amazing_Hopper
Amazing Hopper
  #include <flow.h> #import lib/input.bas.lib #include include/flow-input.h   DEF-MAIN CLR-SCR MSET(nRow, nCol) LOCATE( 2,5 ), PRN("Input size rows :") LOC-COL( 23 ), LET( nRow := ABS(VAL(READ-NUMBER( nRow ) ))) LOCATE( 3,5 ), PRN("Input size cols :") LOC-COL( 23 ), LET( nCol := ABS(VAL(READ-NUMBER( nCol ) )))   COND( IS-NOT-ZERO?( MUL(nRow,nCol) ) ) DIM(nRow, nCol) AS-VOID( array ) BLK-[1,1], {100} PUT(array) PRNL("\tElement at position 1,1 : ", GET(array) ) CLEAR(array) /* destroy array */ CEND END SUBRUTINES  
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
#Crystal
Crystal
class StdDevAccumulator def initialize @n, @sum, @sum2 = 0, 0.0, 0.0 end   def <<(num) @n += 1 @sum += num @sum2 += num**2 Math.sqrt (@sum2 * @n - @sum**2) / @n**2 end end   sd = StdDevAccumulator.new i = 0 [2,4,4,4,5,5,7,9].each { |n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }
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
#C.2B.2B
C++
#include <algorithm> #include <array> #include <cstdint> #include <numeric>   // These headers are only needed for main(), to demonstrate. #include <iomanip> #include <iostream> #include <string>   // Generates a lookup table for the checksums of all 8-bit values. std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept { auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};   // This is a function object that calculates the checksum for a value, // then increments the value, starting from zero. struct byte_checksum { std::uint_fast32_t operator()() noexcept { auto checksum = static_cast<std::uint_fast32_t>(n++);   for (auto i = 0; i < 8; ++i) checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);   return checksum; }   unsigned n = 0; };   auto table = std::array<std::uint_fast32_t, 256>{}; std::generate(table.begin(), table.end(), byte_checksum{});   return table; }   // Calculates the CRC for any sequence of values. (You could use type traits and a // static assert to ensure the values can be converted to 8 bits.) template <typename InputIterator> std::uint_fast32_t crc(InputIterator first, InputIterator last) { // Generate lookup table only on first use then cache it - this is thread-safe. static auto const table = generate_crc_lookup_table();   // Calculate the checksum - make sure to clip to 32 bits, for systems that don't // have a true (fast) 32-bit type. return std::uint_fast32_t{0xFFFFFFFFuL} & ~std::accumulate(first, last, ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL}, [](std::uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); }   int main() { auto const s = std::string{"The quick brown fox jumps over the lazy dog"};   std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n'; }  
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Haskell
Haskell
import Data.Time (FormatTime, formatTime, defaultTimeLocale, utcToLocalTime, getCurrentTimeZone, getCurrentTime)   formats :: FormatTime t => [t -> String] formats = (formatTime defaultTimeLocale) <$> ["%F", "%A, %B %d, %Y"]   main :: IO () main = do t <- pure utcToLocalTime <*> getCurrentTimeZone <*> getCurrentTime putStrLn $ unlines (formats <*> pure t)
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
#HicEst
HicEst
CHARACTER string*40   WRITE(Text=string, Format='UCCYY-MM-DD') 0 ! string: 2010-03-13   ! the U-format to write date and time uses ',' to separate additional output formats ! we therefore use ';' in this example and change it to ',' below: WRITE(Text=string,Format='UWWWWWWWWW; MM DD; CCYY') 0 ! string = "Saturday ; 03 13; 2010" READ(Text=string) month ! first numeric value = 3 (no literal month name available) EDIT(Text='January,February,March,April,May,June,July,August,September,October,November,December', ITeM=month, Parse=cMonth) ! cMonth = "March" ! change now string = "Saturday ; 03 13; 2010" to "Saturday, March 13, 2010": EDIT(Text=string, Right=' ', Mark1, Right=';', Right=3, Mark2, Delete, Insert=', '//cMonth, Right=';', RePLaceby=',')   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.
#4DOS_Batch
4DOS Batch
echos > output.txt mkdir docs   echos > \output.txt 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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program createDirFic64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ MKDIRAT, 0x22 // Linux Syscall create directory .equ CHGDIR, 0x31 // Linux Syscall change directory   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessCreateDirOk: .asciz "Create directory Ok.\n" szMessErrCreateDir: .asciz "Unable create directory. \n" szMessErrChangeDir: .asciz "Unable change directory. \n" szMessCreateFileOk: .asciz "Create file Ok.\n" szMessErrCreateFile: .asciz "Unable create file. \n" szMessErrCloseFile: .asciz "Unable close file. \n"   szNameDir: .asciz "Dix1" szNameFile: .asciz "file1.txt"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program // create directory mov x0,AT_FDCWD ldr x1,qAdrszNameDir // directory name mov x2,0775 // mode (in octal zero is important !!) mov x8,MKDIRAT // code call system create directory svc 0 // call systeme cbnz x0,99f // error ?   // display message ok directory ldr x0,qAdrszMessCreateDirOk bl affichageMess // change directory ldr x0,qAdrszNameDir // directory name mov x8, #CHGDIR // code call system change directory svc #0 // call systeme cbnz x0,98f // error ? // create file mov x0,AT_FDCWD // current directory ldr x1,qAdrszNameFile // directory name mov x2,O_CREAT|O_WRONLY // flags mov x3,0644 // this zone is Octal number (0 before) mov x8,OPEN // code call system open file svc #0 // call systeme cmp x0,#0 // error ? ble 97f mov x19,x0 // save File Descriptor // display message ok file ldr x0,qAdrszMessCreateFileOk bl affichageMess   // close file mov x0,x19 // Fd mov x8,CLOSE // close file svc 0 cbnz x0,96f // error ? mov x0,0 // return code Ok b 100f // end Ok 96: // display error message close file ldr x0,qAdrszMessErrCloseFile bl affichageMess mov x0,1 // return code error b 100f 97: // display error message create file ldr x0,qAdrszMessErrCreateFile bl affichageMess mov x0,1 // return code error b 100f 98: // display error message change directory ldr x0,qAdrszMessErrChangeDir bl affichageMess mov x0,1 // return code error b 100f 99: // display error message create directory ldr x0,qAdrszMessErrCreateDir bl affichageMess mov x0,1 // return code error b 100f 100: // standard end of the program mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszMessCreateDirOk: .quad szMessCreateDirOk qAdrszMessErrCreateDir: .quad szMessErrCreateDir qAdrszMessErrChangeDir: .quad szMessErrChangeDir qAdrszMessCreateFileOk: .quad szMessCreateFileOk qAdrszNameFile: .quad szNameFile qAdrszMessErrCreateFile: .quad szMessErrCreateFile qAdrszMessErrCloseFile: .quad szMessErrCloseFile qAdrszNameDir: .quad szNameDir /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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).
#Arturo
Arturo
in: { 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! }   table: function [content] -> join @["<table>" join content "</table>"]   row: function [data] -> join @[ "<tr><td>" escape.xml first data "</td>" "<td>" escape.xml last data "</td></tr>" ]   print table map read.csv in => row
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.
#EchoLisp
EchoLisp
  ;; CSV -> LISTS (define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line ","))) (define (csv->table csv) (map csv->row (string-split csv "\n")))   ;; LISTS -> CSV (define (row->csv row) (string-join row ",")) (define (table->csv header rows) (string-join (cons (row->csv header) (for/list ((row rows)) (row->csv row))) "\n"))     (define (task file) (let* ((table (csv->table file)) (header (first table)) (rows (rest table)))   (table->csv (append header "SUM") ;; add last column (for/list ((row rows)) (append row (apply + row))))))      
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
matrix = {{0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}}; Damm[num_Integer] := Module[{row}, row = 0; Do[ row = matrix[[row + 1, d + 1]] , {d, IntegerDigits[num]} ]; row == 0 ] Damm /@ {5724, 5727, 112946}
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.
#Modula-2
Modula-2
MODULE DammAlgorithm; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE TA = ARRAY[0..9],[0..9] OF INTEGER; 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} };   PROCEDURE Damm(s : ARRAY OF CHAR) : BOOLEAN; VAR interim,i : INTEGER; BEGIN interim := 0;   i := 0; WHILE s[i] # 0C DO interim := table[interim,INT(s[i])-INT('0')]; INC(i); END; RETURN interim=0; END Damm;   PROCEDURE Print(number : INTEGER); VAR isValid : BOOLEAN; buf : ARRAY[0..16] OF CHAR; BEGIN FormatString("%i", buf, number); isValid := Damm(buf); WriteString(buf); IF isValid THEN WriteString(" is valid"); ELSE WriteString(" is invalid"); END; WriteLn; END Print;   BEGIN Print(5724); Print(5727); Print(112946); Print(112949);   ReadChar; END DammAlgorithm.
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.
#Groovy
Groovy
class CubanPrimes { private static int MAX = 1_400_000 private static boolean[] primes = new boolean[MAX]   static void main(String[] args) { preCompute() cubanPrime(200, true) for (int i = 1; i <= 5; i++) { int max = (int) Math.pow(10, i) 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) { 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.
#REXX
REXX
/*REXX program shows a method of computing the total price and tax for purchased items.*/ numeric digits 200 /*support for gihugic numbers.*/ taxRate= 7.65 /*number is: nn or nn% */ if right(taxRate, 1)\=='%' then taxRate= taxRate / 100 /*handle plain tax rate number*/ taxRate= strip(taxRate, , '%') /*strip the  % (if present).*/ item. =; items= 0 /*zero out the register. */ item.1 = '4000000000000000 $5.50 hamburger' /*the first item purchased. */ item.2 = ' 2 $2.86 milkshake' /* " second " " */ say center('quantity', 22) center("item", 22) center('price', 22) hdr= center('', 27, "─") center('', 20, "─") center('', 27, "─") say hdr; total= 0 do j=1 while item.j\=='' /*calculate the total and tax.*/ parse var item.j quantity price thing /*ring up an item on register.*/ items = items + quantity /*tally the number of items. */ price = translate(price, , '$') /*maybe scrub out the $ symbol*/ subtotal = quantity * price /*calculate the sub-total.*/ total = total + subtotal /* " " running total.*/ say right(quantity, 27) left(thing, 20) show$(subtotal) end /*j*/ say /*display a blank line for separator. */ say translate(hdr, '═', "─") /*display the separator part of the hdr*/ tax= format(total * taxRate, , 2) /*round the total tax for all the items*/ say right(items "(items)", 35) right('total=', 12) show$(total) say right('tax at' (taxRate * 100 / 1)"%=", 48) show$(tax) say say right('grand total=', 48) show$(total+tax) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show$: return right( '$'arg(1), 27) /*right─justify and format a number. */
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.
#OCaml
OCaml
let addnums x y = x+y (* declare a curried function *)   let add1 = addnums 1 (* bind the first argument to get another function *) add1 42 (* apply to actually compute a result, 43 *)
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.
#Oforth
Oforth
2 #+ curry => 2+ 5 2+ . 7 ok
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.
#Ol
Ol
  (define (addN n) (lambda (x) (+ x n)))   (let ((add10 (addN 10)) (add20 (addN 20))) (print "(add10 4) ==> " (add10 4)) (print "(add20 4) ==> " (add20 4)))  
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.
#PowerShell
PowerShell
$date = [DateTime]::Parse("March 7 2009 7:30pm -5" ) write-host $date write-host $date.AddHours(12) write-host [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($date.AddHours(12),"Vladivostok Standard Time")
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.
#PureBasic
PureBasic
  EnableExplicit   Procedure.i ToPBDate(Date$, *zone.String) Protected year, month, day, hour, minute Protected month$, temp$, time$, pm$, zone$ month$ = StringField(date$, 1, " ") day = Val(StringField(date$, 2, " ")) year = Val(StringField(date$, 3, " ")) time$ = StringField(date$, 4, " ") zone$ = StringField(date$, 5, " ")   Select month$ Case "January"  : month = 1 Case "February"  : month = 2 Case "March"  : month = 3 Case "April"  : month = 4 Case "May"  : month = 5 Case "June"  : month = 6 Case "July"  : month = 7 Case "August"  : month = 8 Case "September" : month = 9 Case "October"  : month = 10 Case "November"  : month = 11 Case "December"  : month = 12 EndSelect   hour = Val(StringField(time$, 1, ":")) temp$ = StringField(time$, 2, ":") minute = Val(Left(temp$, 2)) pm$ = Right(temp$, 2)   If pm$ = "am" If hour = 12 : hour = 0 : EndIf Else If hour <> 12 : hour + 12 : EndIf EndIf   *zone\s = zone$ ProcedureReturn Date(year, month, day, hour, minute, 0) EndProcedure   Procedure.s FromPBDate(Date, zone$) Protected year$ = Str(Year(Date)) Protected month = Month(Date) Protected day$ = Str(Day(Date)) Protected hour = Hour(Date) Protected minute = Minute(Date) Protected month$, time$, pm$, result$   Select month Case 1  : month$ = "January" Case 2  : month$ = "February" Case 3  : month$ = "March" Case 4  : month$ = "April" Case 5  : month$ = "May" Case 6  : month$ = "June" Case 7  : month$ = "July" Case 8  : month$ = "August" Case 9  : month$ = "September" Case 10 : month$ = "October" Case 11 : month$ = "November" Case 12 : month$ = "December" EndSelect   If hour > 12 hour - 12 pm$ = "pm" ElseIf hour = 12 pm$ = "pm" Else If hour = 0 : hour = 12 : EndIf pm$ = "am" EndIf   time$ = Str(hour) + ":" + RSet(Str(minute), 2, "0") + pm$ result$ = month$ + " " + day$ + " " + year$ + " " + time$ + " " + zone$ ProcedureReturn result$ EndProcedure   Define date Define date1$, date2$ Define zone.String   If OpenConsole() date1$ = "March 7 2009 7:30pm EST" PrintN("Starting date/time : " + date1$) date = ToPBDate(date1$, @zone) date = AddDate(date, #PB_Date_Hour, 12); add 12 hours date2$ = FromPBDate(date, zone\s) PrintN("12 hours later  : " + date2$) date = AddDate(date, #PB_Date_Hour, 5); adjust to GMT date2$ = FromPBDate(date, "GMT") PrintN("Or in GMT timezone : " + date2$) PrintN("") PrintN("Press any key to close the console") Repeat: Delay(10) : Until Inkey() <> "" CloseConsole() EndIf  
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.
#K
K
wd:{(__jd x)!7} / Julian day count, Sun=6 y@&6={wd 1225+x*10000}'y:2008+!114 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118  
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.
#Kotlin
Kotlin
// version 1.0.6   import java.util.*   fun main(args: Array<String>) { println("Christmas day in the following years falls on a Sunday:\n") val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25) for (year in 2008..2121) { if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year) calendar.add(Calendar.YEAR, 1) } }
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
#PHP
PHP
function IsCusip(string $s) { if (strlen($s) != 9) return false; $sum = 0; for ($i = 0; $i <= 7; $i++) { $c = $s[$i]; if (ctype_digit($c)) { // if character is numeric, get character's numeric value $v = intval($c); } elseif (ctype_alpha($c)) { // if character is alphabetic, get character's ordinal position in alphabet $position = ord(strtoupper($c)) - ord('A') + 1; $v = $position + 9; } elseif ($c == "*") { $v = 36; } elseif ($c == "@") { $v = 37; } elseif ($c == "#") { $v = 38; } else { return false; } // is this character position even? if ($i % 2 == 1) { $v *= 2; } // calculate the checksum digit $sum += floor($v / 10 ) + ( $v % 10 ); } return ord($s[8]) - 48 == (10 - ($sum % 10)) % 10; }   $cusips = array("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105");   foreach ($cusips as $cusip) echo $cusip . " -> " . (IsCusip($cusip) ? "valid" : "invalid") . "\n";
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#APL
APL
array←m n ⍴ 0 ⍝ array of zeros with shape of m by n.   array[1;1]←73 ⍝ assign a value to location 1;1.   array[1;1] ⍝ read the value back out   ⎕ex 'array' ⍝ erase the array