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 cha...
#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. ** ...
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, ...
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 - ...
#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 - ...
#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 redir...
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 qu...
#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 |> rou...
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 qu...
#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,$pri...
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 la...
#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...
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 la...
#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 ...
#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 20...
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 A...
#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 "*@#" ...
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 ...
#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 langu...
#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 @sumOfSquare...
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...
#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...
#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...
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 st...
#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_Fil...
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 cha...
#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 ...
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), ...
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), ...
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 - ...
#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"...
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 - ...
#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...
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 qu...
#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() m...
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 qu...
#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 la...
#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 la...
#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_timed...
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 ...
#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){ Sys...
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 A...
#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...
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 A...
#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; ...
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 ...
#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); ...
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 langu...
#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 ...
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...
#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$ ...
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...
#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 ...
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 st...
#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 ...
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 cha...
#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!(...
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 ...
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:s...
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#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( ...
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 qu...
#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 ...
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 qu...
#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 str...
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 la...
#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 la...
#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 a...
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 ...
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 ...
#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 ...
#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; is...
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 A...
#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; ...
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 ...
#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 ...
#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 langu...
#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...
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...
#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...
#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 = ...
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 st...
#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>...
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 cha...
#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 R...
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...
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...
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 - ...
#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 := ma...
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 qu...
#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 = $...
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 la...
#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 la...
#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))...
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 la...
#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 (SECS...
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#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...
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 ...
#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 A...
#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 ...
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 ...
#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 %  ...
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 ...
#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...
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 langu...
#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 << ...
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...
#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...
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 <*>...
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 = ...
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 "../includeConstante...
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 st...
#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 mo...
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 cha...
#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) (fo...
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...
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, ...
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 - ...
#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...
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 qu...
#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= taxRa...
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 la...
#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 la...
#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 la...
#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$ = Stri...
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 ...
#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 ...
#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) ...
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 A...
#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)) { // ...
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 ...
#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