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/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
#Emacs_Lisp
Emacs Lisp
(defun running-std (items) (let ((running-sum 0) (running-len 0) (running-squared-sum 0) (result 0)) (dolist (item items) (setq running-sum (+ running-sum item)) (setq running-len (1+ running-len)) (setq running-squared-sum (+ running-squared-sum (* item item))) (setq result (sqrt (- (/ running-squared-sum (float running-len)) (/ (* running-sum running-sum) (float (* running-len running-len)))))) (message "%f" result)) result))   (running-std '(2 4 4 4 5 5 7 9))
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string: The quick brown fox jumps over the lazy dog
#Elixir
Elixir
defmodule Test do def crc32(str) do IO.puts :erlang.crc32(str) |> Integer.to_string(16) end end   Test.crc32("The quick brown fox jumps over the lazy dog")
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string: The quick brown fox jumps over the lazy dog
#Erlang
Erlang
  -module(crc32). -export([test/0]). test() -> io:fwrite("~.16#~n",[erlang:crc32(<<"The quick brown fox jumps over the lazy dog">>)]).  
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#360_Assembly
360 Assembly
* count the coins 04/09/2015 COINS CSECT USING COINS,R12 LR R12,R15 L R8,AMOUNT npenny=amount L R4,AMOUNT SRDA R4,32 D R4,=F'5' LR R9,R5 nnickle=amount/5 L R4,AMOUNT SRDA R4,32 D R4,=F'10' LR R10,R5 ndime=amount/10 L R4,AMOUNT SRDA R4,32 D R4,=F'25' LR R11,R5 nquarter=amount/25 SR R1,R1 count=0 SR R4,R4 p=0 LOOPP CR R4,R8 do p=0 to npenny BH ELOOPP SR R5,R5 n=0 LOOPN CR R5,R9 do n=0 to nnickle BH ELOOPN SR R6,R6 LOOPD CR R6,R10 do d=0 to ndime BH ELOOPD SR R7,R7 q=0 LOOPQ CR R7,R11 do q=0 to nquarter BH ELOOPQ LR R3,R5 n MH R3,=H'5' LR R2,R4 p AR R2,R3 LR R3,R6 d MH R3,=H'10' AR R2,R3 LR R3,R7 q MH R3,=H'25' AR R2,R3 s=p+n*5+d*10+q*25 C R2,=F'100' if s=100 BNE NOTOK LA R1,1(R1) count=count+1 NOTOK LA R7,1(R7) q=q+1 B LOOPQ ELOOPQ LA R6,1(R6) d=d+1 B LOOPD ELOOPD LA R5,1(R5) n=n+1 B LOOPN ELOOPN LA R4,1(R4) p=p+1 B LOOPP ELOOPP XDECO R1,PG+0 edit count XPRNT PG,12 print count XR R15,R15 BR R14 AMOUNT DC F'100' start value in cents PG DS CL12 YREGS END COINS
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#Ada
Ada
with Ada.Text_IO;   procedure Count_The_Coins is   type Counter_Type is range 0 .. 2**63-1; -- works with gnat type Coin_List is array(Positive range <>) of Positive;   function Count(Goal: Natural; Coins: Coin_List) return Counter_Type is Cnt: array(0 .. Goal) of Counter_Type := (0 => 1, others => 0); -- 0 => we already know one way to choose (no) coins that sum up to zero -- 1 .. Goal => we do not (yet) other ways to choose coins begin for C in Coins'Range loop for Amount in 1 .. Cnt'Last loop if Coins(C) <= Amount then Cnt(Amount) := Cnt(Amount) + Cnt(Amount-Coins(C)); -- Amount-Coins(C) plus Coins(C) sums up to Amount; end if; end loop; end loop; return Cnt(Goal); end Count;   procedure Print(C: Counter_Type) is begin Ada.Text_IO.Put_Line(Counter_Type'Image(C)); end Print;   begin Print(Count( 1_00, (25, 10, 5, 1))); Print(Count(1000_00, (100, 50, 25, 10, 5, 1))); end Count_The_Coins;
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Ada
Ada
with Ada.Strings.Unbounded;   generic type Item_Type is private; with function To_String(Item: Item_Type) return String is <>; with procedure Put(S: String) is <>; with procedure Put_Line(Line: String) is <>; package HTML_Table is   subtype U_String is Ada.Strings.Unbounded.Unbounded_String; function Convert(S: String) return U_String renames Ada.Strings.Unbounded.To_Unbounded_String;   type Item_Array is array(Positive range <>, Positive range <>) of Item_Type; type Header_Array is array(Positive range <>) of U_String;   procedure Print(Items: Item_Array; Column_Heads: Header_Array);   end HTML_Table;
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Julia
Julia
ts = Dates.today()   println("Today's date is:") println("\t$ts") println("\t", Dates.format(ts, "E, U dd, 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
#Kotlin
Kotlin
// version 1.0.6   import java.util.GregorianCalendar   fun main(args: Array<String>) { val now = GregorianCalendar() println("%tF".format(now)) println("%tA, %1\$tB %1\$te, %1\$tY".format(now)) }
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.} which in matrix format is [ a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 ] [ x y z ] = [ d 1 d 2 d 3 ] . {\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.} Then the values of x , y {\displaystyle x,y} and z {\displaystyle z} can be found as follows: x = | d 1 b 1 c 1 d 2 b 2 c 2 d 3 b 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | , y = | a 1 d 1 c 1 a 2 d 2 c 2 a 3 d 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | ,  and  z = | a 1 b 1 d 1 a 2 b 2 d 2 a 3 b 3 d 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | . {\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.} Task Given the following system of equations: { 2 w − x + 5 y + z = − 3 3 w + 2 x + 2 y − 6 z = − 32 w + 3 x + 3 y − z = − 47 5 w − 2 x − 3 y + 3 z = 49 {\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}} solve for w {\displaystyle w} , x {\displaystyle x} , y {\displaystyle y} and z {\displaystyle z} , using Cramer's rule.
#C
C
#include <math.h> #include <stdio.h> #include <stdlib.h>   typedef struct { int n; double **elems; } SquareMatrix;   SquareMatrix init_square_matrix(int n, double elems[n][n]) { SquareMatrix A = { .n = n, .elems = malloc(n * sizeof(double *)) }; for(int i = 0; i < n; ++i) { A.elems[i] = malloc(n * sizeof(double)); for(int j = 0; j < n; ++j) A.elems[i][j] = elems[i][j]; }   return A; }   SquareMatrix copy_square_matrix(SquareMatrix src) { SquareMatrix dest; dest.n = src.n; dest.elems = malloc(dest.n * sizeof(double *)); for(int i = 0; i < dest.n; ++i) { dest.elems[i] = malloc(dest.n * sizeof(double)); for(int j = 0; j < dest.n; ++j) dest.elems[i][j] = src.elems[i][j]; }   return dest; }   double det(SquareMatrix A) { double det = 1;   for(int j = 0; j < A.n; ++j) { int i_max = j; for(int i = j; i < A.n; ++i) if(A.elems[i][j] > A.elems[i_max][j]) i_max = i;   if(i_max != j) { for(int k = 0; k < A.n; ++k) { double tmp = A.elems[i_max][k]; A.elems[i_max][k] = A.elems[j][k]; A.elems[j][k] = tmp; }   det *= -1; }   if(abs(A.elems[j][j]) < 1e-12) { puts("Singular matrix!"); return NAN; }   for(int i = j + 1; i < A.n; ++i) { double mult = -A.elems[i][j] / A.elems[j][j]; for(int k = 0; k < A.n; ++k) A.elems[i][k] += mult * A.elems[j][k]; } }   for(int i = 0; i < A.n; ++i) det *= A.elems[i][i];   return det; }   void deinit_square_matrix(SquareMatrix A) { for(int i = 0; i < A.n; ++i) free(A.elems[i]); free(A.elems); }   double cramer_solve(SquareMatrix A, double det_A, double *b, int var) { SquareMatrix tmp = copy_square_matrix(A); for(int i = 0; i < tmp.n; ++i) tmp.elems[i][var] = b[i];   double det_tmp = det(tmp); deinit_square_matrix(tmp);   return det_tmp / det_A; }   int main(int argc, char **argv) { #define N 4 double elems[N][N] = { { 2, -1, 5, 1}, { 3, 2, 2, -6}, { 1, 3, 3, -1}, { 5, -2, -3, 3} }; SquareMatrix A = init_square_matrix(N, elems);   SquareMatrix tmp = copy_square_matrix(A); int det_A = det(tmp); deinit_square_matrix(tmp);   double b[] = {-3, -32, -47, 49};   for(int i = 0; i < N; ++i) printf("%7.3lf\n", cramer_solve(A, det_A, b, i));   deinit_square_matrix(A); return EXIT_SUCCESS; }
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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program createDirFic.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall exit Program .equ WRITE, 4 @ Linux syscall write FILE .equ MKDIR, 0x27 @ Linux Syscal create directory .equ CHGDIR, 0xC @ Linux Syscal change directory .equ CREATE, 0x8 @ Linux Syscal create file .equ CLOSE, 0x6 @ Linux Syscal close file /* 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 "Dir1" szNameFile: .asciz "file1.txt"     /* UnInitialized data */ .bss   /* code section */ .text .global main main: @ entry of program push {fp,lr} @ saves registers @ create directory ldr r0,iAdrszNameDir @ directory name mov r1,#0775 @ mode (in octal zero is important !!) mov r7, #MKDIR @ code call system create directory swi #0 @ call systeme cmp r0,#0 @ error ? bne 99f   @ display message ok directory ldr r0,iAdrszMessCreateDirOk bl affichageMess @ change directory ldr r0,iAdrszNameDir @ directory name mov r7, #CHGDIR @ code call system change directory swi #0 @ call systeme cmp r0,#0 @ error ? bne 98f @ create file ldr r0,iAdrszNameFile @ directory name mov r1,#0755 @ mode (in octal zero is important !!) mov r2,#0 mov r7,#CREATE @ code call system create file swi #0 @ call systeme cmp r0,#0 @ error ? ble 97f mov r8,r0 @ save File Descriptor @ display message ok file ldr r0,iAdrszMessCreateFileOk bl affichageMess   @ close file mov r0,r8 @ Fd mov r7, #CLOSE @ close file swi 0 cmp r0,#0 bne 96f @ end Ok b 100f 96: @ display error message close file ldr r0,iAdrszMessErrCloseFile bl affichageMess b 100f 97: @ display error message create file ldr r0,iAdrszMessErrCreateFile bl affichageMess b 100f 98: @ display error message change directory ldr r0,iAdrszMessErrChangeDir bl affichageMess b 100f 99: @ display error message create directory ldr r0,iAdrszMessErrCreateDir bl affichageMess b 100f 100: @ standard end of the program mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrszMessCreateDirOk: .int szMessCreateDirOk iAdrszMessErrCreateDir: .int szMessErrCreateDir iAdrszMessErrChangeDir: .int szMessErrChangeDir iAdrszMessCreateFileOk: .int szMessCreateFileOk iAdrszNameFile: .int szNameFile iAdrszMessErrCreateFile: .int szMessErrCreateFile iAdrszMessErrCloseFile: .int szMessErrCloseFile   iAdrszNameDir: .int szNameDir /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */      
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).
#BBC_BASIC
BBC BASIC
DATA "Character,Speech" DATA "The multitude,The messiah! Show us the messiah!" DATA "Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" DATA "The multitude,Who are you?" DATA "Brian's mother,I'm his mother; that's who!" DATA "The multitude,Behold his mother! Behold his mother!" DATA "***"   *SPOOL CSVtoHTML.htm PRINT "<HTML>" PRINT "<HEAD>" PRINT "</HEAD>" PRINT "<BODY>" PRINT "<table border=1 cellpadding =10 cellspacing=0>"   header% = TRUE REPEAT READ csv$ IF csv$ = "***" THEN EXIT REPEAT   IF header% PRINT "<tr><th>"; ELSE PRINT "<tr><td>"; FOR i% = 1 TO LEN(csv$) c$ = MID$(csv$, i%, 1) CASE c$ OF WHEN ",": IF header% PRINT "</th><th>"; ELSE PRINT "</td><td>"; WHEN "<": PRINT "&lt;"; WHEN ">": PRINT "&gt;"; WHEN "&": PRINT "&amp;"; OTHERWISE: PRINT c$; ENDCASE NEXT i% IF header% PRINT "</th></tr>" ELSE PRINT "</td></tr>"   header% = FALSE UNTIL FALSE   PRINT "</table>" PRINT "</BODY>" PRINT "</HTML>" *spool   SYS "ShellExecute", @hwnd%, 0, "CSVtoHTML.htm", 0, 0, 1  
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.
#Factor
Factor
USING: csv io.encodings.utf8 kernel math.parser sequences ; IN: rosetta-code.csv-manipulation   : append-sum ( seq -- seq' ) dup [ string>number ] map-sum number>string suffix ;   : csv-sums ( seq -- seq' ) [ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;   "example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
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.
#Forth
Forth
\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues \ USAGE: \ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv   CHAR , CONSTANT SEPARATOR 3 CONSTANT DECIMALS 1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE   : colsum ( ca u -- F: -- sum ;return SUM from CSV-string ) 0E0 OVER SWAP BOUNDS  ?DO ( a ) I C@ SEPARATOR = IF ( a ) I TUCK OVER - >FLOAT IF F+ THEN 1+ THEN LOOP DROP ; : f>string ( -- ca u F: x -- ) FSCALE F* F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #> ; : rowC!+ ( offs char -- u+1  ;store CHAR at here+OFFS,increment offset ) OVER HERE + C! 1+ ; : row$!+ ( offs ca u -- offs+u ;store STRING at here+OFFS,update offset ) ROT 2DUP + >R HERE + SWAP MOVE R> ; \ If run program with '-m 4G'option, we have practically 4G to store a row : csvsum ( fo fi --  ;write into FILEID-OUTPUT processed input from FILEID-INPUT ) 2DUP HERE UNUSED ROT READ-LINE THROW IF ( fo fi fo u ) HERE SWAP ( fo fi fo ca u ) SEPARATOR rowC!+ s\" SUM" row$!+ ( fo fi fo ca u' ) ROT WRITE-LINE THROW BEGIN ( fo fi ) 2DUP HERE UNUSED ROT READ-LINE THROW WHILE ( fo fi fo u ) HERE SWAP ( fo fi fo ca u ) SEPARATOR rowC!+ HERE OVER colsum f>string ( fo fi fo ca u ca' u' ) row$!+ ( fo fi fo ca u'+u ) ROT WRITE-LINE THROW REPEAT THEN 2DROP 2DROP ;
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.
#PHP
PHP
<?php function lookup($r,$c) { $table = array( array(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), array(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), array(4, 2, 0, 6, 8, 7, 1, 3, 5, 9), array(1, 7, 5, 0, 9, 8, 3, 4, 2, 6), array(6, 1, 2, 3, 0, 4, 5, 9, 7, 8), array(3, 6, 7, 4, 2, 0, 9, 5, 8, 1), array(5, 8, 6, 9, 7, 2, 0, 1, 3, 4), array(8, 9, 4, 5, 3, 6, 2, 0, 1, 7), array(9, 4, 3, 8, 6, 1, 7, 2, 0, 5), array(2, 5, 8, 1, 4, 3, 6, 7, 9, 0), ); return $table[$r][$c]; }   function isDammValid($input) { return array_reduce(str_split($input), "lookup", 0) == 0; }   foreach(array("5724", "5727", "112946", "112949") as $i) { echo "{$i} is ".(isDammValid($i) ? "valid" : "invalid")."<br>"; } ?>
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.
#Lua
Lua
local primes = {3, 5} local cutOff = 200 local bigUn = 100000 local chunks = 50 local little = math.floor(bigUn / chunks) local tn = " cuban prime" print(string.format("The first %d%ss", cutOff, tn)) local showEach = true local c = 0 local u = 0 local v = 1 for i=1,10000000000000 do local found = false u = u + 6 v = v + u local mx = math.ceil(math.sqrt(v)) --for _,item in pairs(primes) do -- why: latent traversal bugfix (and performance), 6/11/2020 db for _,item in ipairs(primes) do if item > mx then break end if v % item == 0 then --print("[DEBUG] :( i = " .. i .. "; v = " .. v) found = true break end end if not found then --print("[DEBUG] :) i = " .. i .. "; v = " .. v) c = c + 1 if showEach then --local z = primes[table.getn(primes)] + 2 -- why: modernize (deprecated), 6/11/2020 db local z = primes[#primes] + 2 while z <= v - 2 do local fnd = false --for _,item in pairs(primes) do -- why: latent traversal bugfix (and performance), 6/11/2020 db for _,item in ipairs(primes) do if item > mx then break end if z % item == 0 then fnd = true break end end if not fnd then table.insert(primes, z) end z = z + 2 end table.insert(primes, v) io.write(string.format("%11d", v)) if c % 10 == 0 then print() end if c == cutOff then showEach = false io.write(string.format("\nProgress to the %dth%s: ", bigUn, tn)) end end if c % little == 0 then io.write(".") if c == bigUn then break end end end end --print(string.format("\nThe %dth%s is %17d", c, tn, v)) -- why: correcting reported inaccuracy in output, 6/11/2020 db print(string.format("\nThe %dth%s is %.0f", c, tn, v))
http://rosettacode.org/wiki/Currency
Currency
Task Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. Note The IEEE 754 binary floating point representations of numbers like   2.86   and   .0765   are not exact. For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. Use the values: 4000000000000000 hamburgers at $5.50 each       (four quadrillion burgers) 2 milkshakes at $2.86 each, and a tax rate of 7.65%. (That number of hamburgers is a 4 with 15 zeros after it.   The number is contrived to exclude naïve task solutions using 64 bit floating point types.) Compute and output (show results on this page): the total price before tax the tax the total with tax The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. The output must show dollars and cents with a decimal point. The three results displayed should be: 22000000000000005.72 1683000000000000.44 23683000000000006.16 Dollar signs and thousands separators are optional.
#Wren
Wren
import "/big" for BigRat   var hamburgers = BigRat.new("4000000000000000") var milkshakes = BigRat.two var price1 = BigRat.fromFloat(5.5) var price2 = BigRat.fromFloat(2.86) var taxPc = BigRat.fromFloat(0.0765) var totalPc = BigRat.fromFloat(1.0765) var totalPreTax = hamburgers*price1 + milkshakes*price2 var totalTax = taxPc * totalPreTax var totalAfterTax = totalPreTax + totalTax System.print("Total price before tax : %((totalPreTax).toDecimal(2))") System.print("Tax  :  %((totalTax).toDecimal(2))") System.print("Total price after tax  : %((totalAfterTax).toDecimal(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.
#zkl
zkl
var priceList=Dictionary("hamburger",550, "milkshake",286); var taxRate=765; // percent*M const M=0d10_000;   fcn toBucks(n){ "$%,d.%02d".fmt(n.divr(100).xplode()) } fcn taxIt(n) { d,c:=n.divr(M).apply('*(taxRate)); d + (c+5000)/M; } fcn calcTab(items){ // (hamburger,15), (milkshake,100) ... items=vm.arglist; fmt:="%-10s %8s %18s %26s"; fmt.fmt("Item Price Quantity Extension".split().xplode()).println();   totalBeforeTax:=0; foreach item,n in (items.sort(fcn(a,b){ a[0]<b[0] })){ price:=priceList[item]; t:=price*n; fmt.fmt(item,toBucks(price),n,toBucks(t)).println(); totalBeforeTax+=t; } fmt.fmt("","","","--------------------").println(); fmt.fmt("","","subtotal",toBucks(totalBeforeTax)).println();   tax:=taxIt(totalBeforeTax); fmt.fmt("","","Tax",toBucks(tax)).println();   fmt.fmt("","","","--------------------").println(); fmt.fmt("","","Total",toBucks(totalBeforeTax + tax)).println(); }
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.
#Raku
Raku
my &negative = &infix:<->.assuming(0); say negative 1;
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.
#REXX
REXX
/*REXX program demonstrates a REXX currying method to perform addition. */ say 'add 2 to 3: ' add(2, 3) say 'add 2 to 3 (curried):' add2(3) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ add: procedure; $= arg(1); do j=2 to arg(); $= $ + arg(j); end; return $ add2: procedure; return add( arg(1), 2)
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.
#Ruby
Ruby
require 'time' d = "March 7 2009 7:30pm EST" t = Time.parse(d) puts t.rfc2822 puts t.zone   new = t + 12*3600 puts new.rfc2822 puts new.zone   # another timezone require 'rubygems' require 'active_support' zone = ActiveSupport::TimeZone['Beijing'] remote = zone.at(new) # or, remote = new.in_time_zone('Beijing') puts remote.rfc2822 puts remote.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.
#Maple
Maple
xmas:= proc() local i, dt; for i from 2008 to 2121 by 1 do dt := Date(i, 12, 25); if (Calendar:-DayOfWeek(dt) = 1) then print(i); end if; end do; end proc;   xmas();
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Reap[If[DateString[{#,12,25},"DayName"]=="Sunday",Sow[#]]&/@Range[2008,2121]][[2,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
#REXX
REXX
/*REXX program validates that the last digit (the check digit) of a CUSIP is valid. */ @.= parse arg @.1 . if @.1=='' | @.1=="," then do; @.1= 037833100 /* Apple Incorporated */ @.2= 17275R102 /* Cisco Systems */ @.3= 38259P508 /* Google Incorporated */ @.4= 594918104 /* Microsoft Corporation */ @.5= 68389X106 /* Oracle Corporation (incorrect)*/ @.6= 68389X105 /* Oracle Corporation */ end   do j=1 while @.j\=''; chkDig=CUSIPchk(@.j) /*calculate check digit from func*/ OK=word("isn't is", 1 + (chkDig==right(@.j,1) ) ) /*validate check digit with func*/ say 'CUSIP ' @.j right(OK, 6) "valid." /*display the CUSIP and validity.*/ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ CUSIPchk: procedure; arg x 9; $=0; abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' do k=1 for 8 y=substr(x, k, 1) select when datatype(y,'W') then #=y when datatype(y,'U') then #=pos(y, abc) + 9 when y=='*' then #=36 when y=='@' then #=37 when y=='#' then #=38 otherwise return 0 /*invalid character.*/ end /*select*/ if k//2==0 then #=#+# /*K even? Double it*/ $=$ + #%10 + #//10 end /*k*/ return (10- $//10) // 10
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.
#C
C
#include <stdio.h>   int main(int argc, char **argv) {   int user1 = 0, user2 = 0; printf("Enter two integers. Space delimited, please: "); scanf("%d %d",&user1, &user2); int array[user1][user2]; array[user1/2][user2/2] = user1 + user2; printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);   return 0; }
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used. Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population. Test case Use this to compute the standard deviation of this demonstration set, { 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 } {\displaystyle \{2,4,4,4,5,5,7,9\}} , which is 2 {\displaystyle 2} . Related tasks Random numbers Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#Erlang
Erlang
  -module( standard_deviation ).   -export( [add_sample/2, create/0, destroy/1, get/1, task/0] ).   -compile({no_auto_import,[get/1]}).   add_sample( Pid, N ) -> Pid ! {add, N}.   create() -> erlang:spawn_link( fun() -> loop( [] ) end ).   destroy( Pid ) -> Pid ! stop.   get( Pid ) -> Pid ! {get, erlang:self()}, receive {get, Value, Pid} -> Value end.   task() -> Pid = create(), [add_print(Pid, X, add_sample(Pid, X)) || X <- [2,4,4,4,5,5,7,9]], destroy( Pid ).   add_print( Pid, N, _Add ) -> io:fwrite( "Standard deviation ~p when adding ~p~n", [get(Pid), N] ).   loop( Ns ) -> receive {add, N} -> loop( [N | Ns] ); {get, Pid} -> Pid ! {get, loop_calculate( Ns ), erlang:self()}, loop( Ns ); stop -> ok end.   loop_calculate( Ns ) -> Average = loop_calculate_average( Ns ), math:sqrt( loop_calculate_average([math:pow(X - Average, 2) || X <- Ns]) ).   loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).  
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
#F.23
F#
  module Crc32 =   open System   // Generator polynomial (modulo 2) for the reversed CRC32 algorithm. let private s_generator = uint32 0xEDB88320   // Generate lookup table let private lutIntermediate input = if (input &&& uint32 1) <> uint32 0 then s_generator ^^^ (input >>> 1) else input >>> 1   let private lutEntry input = {0..7} |> Seq.fold (fun acc x -> lutIntermediate acc) input   let private crc32lut = [uint32 0 .. uint32 0xFF] |> List.map lutEntry   let crc32byte (register : uint32) (byte : byte) = crc32lut.[Convert.ToInt32((register &&& uint32 0xFF) ^^^ Convert.ToUInt32(byte))] ^^^ (register >>> 8)   // CRC32 of a byte array let crc32 (input : byte[]) = let result = Array.fold crc32byte (uint32 0xFFFFFFFF) input ~~~result   // CRC32 from ASCII string let crc32OfAscii (inputAscii : string) = let bytes = System.Text.Encoding.ASCII.GetBytes(inputAscii) crc32 bytes   // Test let testString = "The quick brown fox jumps over the lazy dog" printfn "ASCII Input: %s" testString let result = crc32OfAscii testString printfn "CRC32: 0x%x" result  
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#ALGOL_68
ALGOL 68
  # Rosetta Code "Count the coins" This is a direct translation of the "naive" Haskell version, using an array rather than a list. LWB, UPB, and array slicing makes the mapping very simple:   LWB > UPB <=> [] LWB = UPB <=> [x] a[LWB a] <=> head xs a[LWB a + 1:] <=> tail xs #   BEGIN PROC ways to make change = ([] INT denoms, INT amount) INT : BEGIN IF amount = 0 THEN 1 ELIF LWB denoms > UPB denoms THEN 0 ELIF LWB denoms = UPB denoms THEN (amount MOD denoms[LWB denoms] = 0 | 1 | 0) ELSE INT sum := 0; FOR i FROM 0 BY denoms[LWB denoms] TO amount DO sum +:= ways to make change(denoms[LWB denoms + 1:], amount - i) OD; sum FI END; [] INT denoms = (25, 10, 5, 1); print((ways to make change(denoms, 100), newline)) END  
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Agena
Agena
notNumbered  := 0; # possible values for html table row numbering numberedLeft  := 1; # " " " " " " " numberedRight  := 2; # " " " " " " "   alignCentre  := 0; # possible values for html table column alignment alignLeft  := 1; # " " " " " " " alignRight  := 2; # " " " " " " "   # write an html table to a file writeHtmlTable := proc( fh, t :: table ) is local align := "align='"; case t.columnAlignment of alignLeft then align := align & "left'" of alignRight then align := align & "right'" else align := align & "center'" esac; local put  := proc( text  :: string ) is io.write( fh, text & "\n" ) end; local thElement := proc( content :: string ) is put( "<th " & align & ">" & content & "</th>" ) end; local tdElement := proc( content ) is put( "<td " & align & ">" & content & "</td>" ) end; # table element put( "<table" & " cellspacing='" & t.cellSpacing & "'" & " colspacing='" & t.colSpacing & "'" & " border='" & t.border & "'" & ">" ); # table headings put( "<tr>" ); if t.rowNumbering = numberedLeft then thElement( "" ) fi; for col to size t.headings do thElement( t.headings[ col ] ) od; if t.rowNumbering = numberedRight then thElement( "" ) fi; put( "</tr>" ); # table rows for row to size t.data do put( "<tr>" ); if t.rowNumbering = numberedLeft then thElement( row & "" ) fi; for col to size t.data[ row ] do tdElement( t.data[ row, col ] ) od; if t.rowNumbering = numberedRight then thElement( row & "" ) fi; put( "</tr>" ) od; # end of table put( "</table>" ) end ;   # create an html table and print it to standard output scope local t := []; t.cellSpacing, t.colSpacing := 0, 0; t.border  := 1; t.columnAlignment := alignRight; t.rowNumbering  := numberedLeft; t.headings  := [ "A", "B", "C" ]; t.data  := [ [ 1001, 1002, 1003 ], [ 21, 22, 23 ], [ 201, 202, 203 ] ]; writeHtmlTable( io.stdout, t ) epocs
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
#langur
langur
var .now = dt// var .format1 = "2006-01-02" var .format2 = "Monday, January 2, 2006" writeln $"\.now:dt.format1;" writeln $"\.now:dt.format2;"
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Lasso
Lasso
  date('11/10/2007')->format('%Q') // 2007-11-10 date('11/10/2007')->format('EEEE, MMMM d, YYYY') //Saturday, November 10, 2007    
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.} which in matrix format is [ a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 ] [ x y z ] = [ d 1 d 2 d 3 ] . {\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.} Then the values of x , y {\displaystyle x,y} and z {\displaystyle z} can be found as follows: x = | d 1 b 1 c 1 d 2 b 2 c 2 d 3 b 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | , y = | a 1 d 1 c 1 a 2 d 2 c 2 a 3 d 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | ,  and  z = | a 1 b 1 d 1 a 2 b 2 d 2 a 3 b 3 d 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | . {\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.} Task Given the following system of equations: { 2 w − x + 5 y + z = − 3 3 w + 2 x + 2 y − 6 z = − 32 w + 3 x + 3 y − z = − 47 5 w − 2 x − 3 y + 3 z = 49 {\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}} solve for w {\displaystyle w} , x {\displaystyle x} , y {\displaystyle y} and z {\displaystyle z} , using Cramer's rule.
#C.23
C#
using System; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class CramersRule { public static void Main() { var equations = new [] { new [] { 2, -1, 5, 1, -3 }, new [] { 3, 2, 2, -6, -32 }, new [] { 1, 3, 3, -1, -47 }, new [] { 5, -2, -3, 3, 49 } }; var solution = SolveCramer(equations); Console.WriteLine(solution.DelimitWith(", ")); }   public static int[] SolveCramer(int[][] equations) { int size = equations.Length; if (equations.Any(eq => eq.Length != size + 1)) throw new ArgumentException($"Each equation must have {size+1} terms."); int[,] matrix = new int[size, size]; int[] column = new int[size]; for (int r = 0; r < size; r++) { column[r] = equations[r][size]; for (int c = 0; c < size; c++) { matrix[r, c] = equations[r][c]; } } return Solve(new SubMatrix(matrix, column)); }   private static int[] Solve(SubMatrix matrix) { int det = matrix.Det(); if (det == 0) throw new ArgumentException("The determinant is zero.");   int[] answer = new int[matrix.Size]; for (int i = 0; i < matrix.Size; i++) { matrix.ColumnIndex = i; answer[i] = matrix.Det() / det; } return answer; }   //Extension method from library. static string DelimitWith<T>(this IEnumerable<T> source, string separator = " ") => string.Join(separator ?? " ", source ?? Empty<T>());   private class SubMatrix { private int[,] source; private SubMatrix prev; private int[] replaceColumn;   public SubMatrix(int[,] source, int[] replaceColumn) { this.source = source; this.replaceColumn = replaceColumn; this.prev = null; this.ColumnIndex = -1; Size = replaceColumn.Length; }   private SubMatrix(SubMatrix prev, int deletedColumnIndex = -1) { this.source = null; this.prev = prev; this.ColumnIndex = deletedColumnIndex; Size = prev.Size - 1; }   public int ColumnIndex { get; set; } public int Size { get; }   public int this[int row, int column] { get { if (source != null) return column == ColumnIndex ? replaceColumn[row] : source[row, column]; return prev[row + 1, column < ColumnIndex ? column : column + 1]; } }   public int Det() { if (Size == 1) return this[0, 0]; if (Size == 2) return this[0, 0] * this[1, 1] - this[0, 1] * this[1, 0]; SubMatrix m = new SubMatrix(this); int det = 0; int sign = 1; for (int c = 0; c < Size; c++) { m.ColumnIndex = c; int d = m.Det(); det += this[0, c] * d * sign; sign = -sign; } return det; }   public void Print() { for (int r = 0; r < Size; r++) { Console.WriteLine(Range(0, Size).Select(c => this[r, c]).DelimitWith(", ")); } Console.WriteLine(); } }   }
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.
#Arturo
Arturo
output: "output.txt" docs: "docs"   write output "" write.directory docs ø   write join.path ["/" output] "" write.directory join.path ["/" 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.
#AutoHotkey
AutoHotkey
FileAppend,,output.txt FileCreateDir, docs FileAppend,,c:\output.txt FileCreateDir, c:\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).
#Befunge
Befunge
<v_>#!,#:< "<table>" \0 +55 v >0>::65*1+`\"~"`!*#v_4-5v > v>#^~^<v"<tr><td>" < \v-1/<>">elb" <^ >:#,_$10 |!:<>\#v_ vv"ta" v-",":\-"&":\-"<":\<>5#05#<v+ >"/"v >#v_$$$0">dt<>dt/<"vv"tr>"+<5 v"<"< >^>\#v_$$0";pma&" v>"/<>d"v5 v , < $ > \#v_$0";tl&"v v"</t"<0 > : | ^_>#!,#:<>#<0#<\#<<< >:#,_$#^_v@ $<
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.
#Fortran
Fortran
program rowsum implicit none character(:), allocatable :: line, name, a(:) character(20) :: fmt double precision, allocatable :: v(:) integer :: n, nrow, ncol, i   call get_command_argument(1, length=n) allocate(character(n) :: name) call get_command_argument(1, name) open(unit=10, file=name, action="read", form="formatted", access="stream") deallocate(name)   call get_command_argument(2, length=n) allocate(character(n) :: name) call get_command_argument(2, name) open(unit=11, file=name, action="write", form="formatted", access="stream") deallocate(name)   nrow = 0 ncol = 0 do while (readline(10, line)) nrow = nrow + 1   call split(line, a)   if (nrow == 1) then ncol = size(a) write(11, "(A)", advance="no") line write(11, "(A)") ",Sum" allocate(v(ncol + 1)) write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, "," else if (size(a) /= ncol) then print "(A,' ',G0)", "Invalid number of values on row", nrow stop end if   do i = 1, ncol read(a(i), *) v(i) end do v(ncol + 1) = sum(v(1:ncol)) write(11, fmt) v end if end do close(10) close(11) contains function readline(unit, line) use iso_fortran_env logical :: readline integer :: unit, ios, n character(:), allocatable :: line character(10) :: buffer   line = "" readline = .false. do read(unit, "(A)", advance="no", size=n, iostat=ios) buffer if (ios == iostat_end) return readline = .true. line = line // buffer(1:n) if (ios == iostat_eor) return end do end function   subroutine split(line, array, separator) character(*) line character(:), allocatable :: array(:) character, optional :: separator character :: sep integer :: n, m, p, i, k   if (present(separator)) then sep = separator else sep = "," end if   n = len(line) m = 0 p = 1 k = 1 do i = 1, n if (line(i:i) == sep) then p = p + 1 m = max(m, i - k) k = i + 1 end if end do m = max(m, n - k + 1)   if (allocated(array)) deallocate(array) allocate(character(m) :: array(p))   p = 1 k = 1 do i = 1, n if (line(i:i) == sep) then array(p) = line(k:i-1) p = p + 1 k = i + 1 end if end do array(p) = line(k:n) end subroutine 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.
#PicoLisp
PicoLisp
(setq *D (quote (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) ) ) (de damm? (N) (let R 1 (for N (mapcar format (chop N)) (setq R (inc (get *D R (inc N)))) ) (= 1 R) ) ) (println (damm? 5724)) (println (damm? 5727)) (println (damm? 112946)) (println (damm? 112940))
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.
#PL.2FM
PL/M
100H:   /* DAMM CHECKSUM FOR DECIMAL NUMBER IN GIVEN STRING */ CHECK$DAMM: PROCEDURE (PTR) BYTE; DECLARE PTR ADDRESS, CH BASED PTR BYTE; DECLARE DAMM DATA ( 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 ); DECLARE I BYTE; I = 0; DO WHILE CH <> '$'; I = DAMM((I*10) + (CH-'0')); PTR = PTR + 1; END; RETURN I = 0; END CHECK$DAMM;   /* CP/M BDOS CALLS */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;   PRINT: PROCEDURE (STR); DECLARE STR ADDRESS; CALL BDOS(9, STR); END PRINT;   /* TESTS */ DECLARE TEST (4) ADDRESS; TEST(0) = .'5724$'; TEST(1) = .'5727$'; TEST(2) = .'112946$'; TEST(3) = .'112949$';   DECLARE N BYTE; DO N = 0 TO LAST(TEST); CALL PRINT(TEST(N)); CALL PRINT(.': $'); IF CHECK$DAMM(TEST(N)) THEN CALL PRINT(.'PASS$'); ELSE CALL PRINT(.'FAIL$'); CALL PRINT(.(13,10,'$')); END;   CALL BDOS(0,0); EOF
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.
#Maple
Maple
CubanPrimes := proc(n) local i, cp; cp := Array([]); for i by 2 while numelems(cp) < n do if isprime(3/4*i^2 + 1/4) then ArrayTools:-Append(cp, 3/4*i^2 + 1/4); end if; end do; return cp; end proc;
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
cubans[m_Integer] := Block[{n = 1, result = {}, candidate}, While[Length[result] < m, n++; candidate = n^3 - (n - 1)^3; If[PrimeQ[candidate], AppendTo[result, candidate]]]; result] cubans[200] NumberForm[Last[cubans[100000]], NumberSeparator -> ",", DigitBlock -> 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.
#Ruby
Ruby
  b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } p b.curry[1][2][3] #=> 6 p b.curry[1, 2][3, 4] #=> 6 p b.curry(5)[1][2][3][4][5] #=> 6 p b.curry(5)[1, 2][3, 4][5] #=> 6 p b.curry(1)[1] #=> 1   b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } p b.curry[1][2][3] #=> 6 p b.curry[1, 2][3, 4] #=> 10 p b.curry(5)[1][2][3][4][5] #=> 15 p b.curry(5)[1, 2][3, 4][5] #=> 15 p b.curry(1)[1] #=> 1  
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.
#Run_BASIC
Run BASIC
theDate$ = "March 7 2009 7:30pm EST"   monthName$ = "January February March April May June July August September October November December" for i = 1 to 12 if word$(theDate$,1) = word$(monthName$,i) then monthNum = i ' turn month name to number next i d = val(date$(monthNum;"/";word$(theDate$,2);"/";word$(theDate$,3))) ' days since Jan 1 1901 t$ = word$(theDate$,4) ' get time from theDate$ t1$ = word$(t$,1,"pm") ' strip pm t2$ = word$(t1$,1,":") + "." + word$(t1$,2,":") ' replace : with . t = val(t2$) if right$(t$,2) = "pm" then t = t + 12 ap$ = "pm" if t + 12 > 24 then d = d + 1 ' if over 24 hours add 1 to days since 1/1/1901 ap$ = "am" end if print date$(d);" ";t1$;ap$
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.
#Rust
Rust
  use chrono::prelude::*; use chrono::Duration;   fn main() { // Chrono allows parsing time zone abbreviations like "EST", but // their meaning is ignored due to a lack of standardization. // // This solution compromises by augmenting the parsed datetime // with the timezone using the IANA abbreviation. let ndt = NaiveDateTime::parse_from_str("March 7 2009 7:30pm EST", "%B %e %Y %l:%M%P %Z").unwrap();   // add TZ manually let dt = chrono_tz::EST.from_local_datetime(&ndt).unwrap(); println!("Date parsed: {:?}", dt);   let new_date = dt + Duration::hours(12); println!("+12 hrs in EST: {:?}", new_date); println!( "+12 hrs in CET: {:?}", new_date.with_timezone(&chrono_tz::CET) ); }    
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of December be a Sunday? Using any standard date handling libraries of your programming language; compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to   y2k   type problems.
#MATLAB_.2F_Octave
MATLAB / Octave
t = datenum([[2008:2121]',repmat([12,25,0,0,0], 2121-2007, 1)]); t = t(strmatch('Sunday', datestr(t,'dddd')), :); datestr(t,'yyyy')  
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
#Ring
Ring
  # Project : CUSIP   inputstr = list(6) inputstr[1] = "037833100" inputstr[2] = "17275R102" inputstr[3] = "38259P508" inputstr[4] = "594918104" inputstr[5] = "68389X106" inputstr[6] = "68389X105" for n = 1 to len(inputstr) cusip(inputstr[n]) next   func cusip(inputstr) if len(inputstr) != 9 see " length is incorrect, invalid cusip" return ok v = 0 sum = 0 for i = 1 to 8 flag = 0 x = ascii(inputstr[i]) if x >= ascii("0") and x <= ascii("9") v = x - ascii("0") flag = 1 ok if x >= ascii("A") and x <= ascii("Z") v = x - 55 flag = 1 ok if x = ascii("*") v= 36 flag = 1 ok if x = ascii("@") v = 37 flag = 1 ok if x = ascii("#") v = 38 flag = 1 ok if flag = 0 see " found a invalid character, invalid cusip" + nl ok if (i % 2) = 0 v = v * 2 ok sum = sum + floor(v / 10) + v % 10 next sum = (10 - (sum % 10)) % 10 if sum = (ascii(inputstr[9]) - ascii("0")) see inputstr + " is valid" + nl else see inputstr + " is invalid" + nl ok  
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
#Ruby
Ruby
  #!/usr/bin/env ruby   def check_cusip(cusip) abort('CUSIP must be 9 characters') if cusip.size != 9   sum = 0 cusip.split('').each_with_index do |char, i| next if i == cusip.size - 1 case when char.scan(/\D/).empty? v = char.to_i when char.scan(/\D/).any? pos = char.upcase.ord - 'A'.ord + 1 v = pos + 9 when char == '*' v = 36 when char == '@' v = 37 when char == '#' v = 38 end   v *= 2 unless (i % 2).zero? sum += (v/10).to_i + (v % 10) end   check = (10 - (sum % 10)) % 10 return 'VALID' if check.to_s == cusip.split('').last 'INVALID' end   CUSIPs = %w[ 037833100 17275R102 38259P508 594918104 68389X106 68389X105 ]   CUSIPs.each do |cusip| puts "#{cusip}: #{check_cusip(cusip)}" 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.
#C.23
C#
  class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine();   int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]);   Console.ReadLine(); } }
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
#Factor
Factor
USING: accessors io kernel math math.functions math.parser sequences ; IN: standard-deviator   TUPLE: standard-deviator sum sum^2 n ;   : <standard-deviator> ( -- standard-deviator ) 0.0 0.0 0 standard-deviator boa ;   : current-std ( standard-deviator -- std ) [ [ sum^2>> ] [ n>> ] bi / ] [ [ sum>> ] [ n>> ] bi / sq ] bi - sqrt ;   : add-value ( value standard-deviator -- ) [ nip [ 1 + ] change-n drop ] [ [ + ] change-sum drop ] [ [ [ sq ] dip + ] change-sum^2 drop ] 2tri ;   : main ( -- ) { 2 4 4 4 5 5 7 9 } <standard-deviator> [ [ add-value ] curry each ] keep current-std number>string print ;
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
#Factor
Factor
IN: scratchpad USING: checksums checksums.crc32 ; IN: scratchpad "The quick brown fox jumps over the lazy dog" crc32 checksum-bytes hex-string . "414fa339"
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
#FBSL
FBSL
#APPTYPE CONSOLE   PRINT HEX(CHECKSUM("The quick brown fox jumps over the lazy dog"))   PAUSE
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#AppleScript
AppleScript
-- All input values must be integers and multiples of the same monetary unit. on countCoins(amount, denominations) -- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros. script o property counters : {1} end script repeat amount times set end of o's counters to 0 end repeat   -- Less labour-intensive alternative to the following repeat's c = 1 iteration. set coinValue to beginning of denominations repeat with n from (coinValue + 1) to (amount + 1) by coinValue set item n of o's counters to 1 end repeat   repeat with c from 2 to (count denominations) set coinValue to item c of denominations repeat with n from (coinValue + 1) to (amount + 1) set item n of o's counters to (item n of o's counters) + (item (n - coinValue) of o's counters) end repeat end repeat   return end of o's counters end countCoins   -- Task calls: set c1 to countCoins(100, {25, 10, 5, 1}) set c2 to countCoins(1000 * 100, {100, 50, 25, 10, 5, 1}) return {c1, c2}
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer count. print countSubstring("the three truths","th") 3   // do not count substrings that overlap with previously-counted substrings: print countSubstring("ababababab","abab") 2 The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left   (see proof on talk page). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
print(‘the three truths’.count(‘th’)) print(‘ababababab’.count(‘abab’))
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequence   is a similar task without the use of octal numbers.
#0815
0815
}:l:> Start loop, enqueue Z (initially 0). }:o: Treat the queue as a stack and <:8:= accumulate the octal digits /=>&~ of the current number. ^:o:   <:0:- Get a sentinel negative 1. &>@ Enqueue it between the digits and the current number. { Dequeue the first octal digit.   }:p: ~%={+ Rotate each octal digit into place and print it. ^:p:   <:a:~$ Output a newline. <:1:x{+ Dequeue the current number and increment it. ^:l:
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#ALGOL_68
ALGOL 68
INT not numbered = 0; # possible values for HTMLTABLE row numbering # INT numbered left = 1; # " " " " " " # INT numbered right = 2; # " " " " " " #   INT align centre = 0; # possible values for HTMLTABLE column alignment # INT align left = 1; # " " " " " " # INT align right = 2; # " " " " " " #   # allowable content for the HTML table - extend the UNION and TOSTRING # # operator to add additional modes # MODE HTMLTABLEDATA = UNION( INT, REAL, STRING ); OP TOSTRING = ( HTMLTABLEDATA content )STRING: CASE content IN ( INT i ): whole( i, 0 ) , ( REAL r ): fixed( r, 0, 0 ) , ( STRING s ): s OUT "Unsupported HTMLTABLEDATA content" ESAC; # MODE to hold an html table # MODE HTMLTABLE = STRUCT( FLEX[ 0 ]STRING headings , FLEX[ 0, 0 ]HTMLTABLEDATA data , INT row numbering , INT column alignment , INT cell spacing , INT col spacing , INT border ); # write an html table to a file # PROC write html table = ( REF FILE f, HTMLTABLE t )VOID: BEGIN STRING align = "align=""" + CASE column alignment OF t IN "left", "right" OUT "center" ESAC + """"; PROC th element = ( REF FILE f, HTMLTABLE t, STRING content )VOID: put( f, ( "<th " + align + ">" + content + "</th>", newline ) ); PROC td element = ( REF FILE f, HTMLTABLE t, HTMLTABLEDATA content )VOID: put( f, ( "<td " + align + ">" + TOSTRING content + "</td>", newline ) );   # table element # put( f, ( "<table" + " cellspacing=""" + whole( cell spacing OF t, 0 ) + """" + " colspacing=""" + whole( col spacing OF t, 0 ) + """" + " border=""" + whole( border OF t, 0 ) + """" + ">" , newline ) ); # table headings # put( f, ( "<tr>", newline ) ); IF row numbering OF t = numbered left THEN th element( f, t, "" ) FI; FOR col FROM LWB headings OF t TO UPB headings OF t DO th element( f, t, ( headings OF t )[ col ] ) OD; IF row numbering OF t = numbered right THEN th element( f, t, "" ) FI; put( f, ( "</tr>", newline ) ); # table rows # FOR row FROM 1 LWB data OF t TO 1 UPB data OF t DO put( f, ( "<tr>", newline ) ); IF row numbering OF t = numbered left THEN th element( f, t, whole( row, 0 ) ) FI; FOR col FROM 2 LWB data OF t TO 2 UPB data OF t DO td element( f, t, ( data OF t )[ row, col ] ) OD; IF row numbering OF t = numbered right THEN th element( f, t, whole( row, 0 ) ) FI; put( f, ( "</tr>", newline ) ) OD; # end of table # put( f, ( "</table>", newline ) ) END # write html table # ;   # create an HTMLTABLE and print it to standard output # HTMLTABLE t; cell spacing OF t := col spacing OF t := 0; border OF t := 1; column alignment OF t := align right; row numbering OF t := numbered left; headings OF t := ( "A", "B", "C" ); data OF t := ( ( 1001, 1002, 1003 ), ( 21, 22, 23 ), ( 201, 202, 203 ) ); write html table( stand out, 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
#Liberty_BASIC
Liberty BASIC
'Display the current date in the formats of "2007-11-10" d$=date$("yyyy/mm/dd") print word$(d$,1,"/")+"-"+word$(d$,2,"/")+"-"+word$(d$,3,"/")   'and "Sunday, November 10, 2007". day$(0)="Tuesday" day$(1)="Wednesday" day$(2)="Thursday" day$(3)="Friday" day$(4)="Saturday" day$(5)="Sunday" day$(6)="Monday" theDay = date$("days") mod 7 print day$(theDay);", ";date$()   ' month in full year=val(word$(d$,1,"/")) month=val(word$(d$,2,"/")) day=val(word$(d$,3,"/")) weekDay$="Tuesday Wednesday Thursday Friday Saturday Sunday Monday" monthLong$="January February March April May June July August September October November December"   print word$(weekDay$,theDay+1);", ";word$(monthLong$,month);" ";day;", ";year
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.} which in matrix format is [ a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 ] [ x y z ] = [ d 1 d 2 d 3 ] . {\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.} Then the values of x , y {\displaystyle x,y} and z {\displaystyle z} can be found as follows: x = | d 1 b 1 c 1 d 2 b 2 c 2 d 3 b 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | , y = | a 1 d 1 c 1 a 2 d 2 c 2 a 3 d 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | ,  and  z = | a 1 b 1 d 1 a 2 b 2 d 2 a 3 b 3 d 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | . {\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.} Task Given the following system of equations: { 2 w − x + 5 y + z = − 3 3 w + 2 x + 2 y − 6 z = − 32 w + 3 x + 3 y − z = − 47 5 w − 2 x − 3 y + 3 z = 49 {\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}} solve for w {\displaystyle w} , x {\displaystyle x} , y {\displaystyle y} and z {\displaystyle z} , using Cramer's rule.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector>   class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1;   public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); }   SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; }   SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; }   int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; }   size_t size() const { return sz; }   double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } }   double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } };   std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); }   std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; }   std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); }   std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } }   SubMatrix sm(matrix, column); return solve(sm); }   template<typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend();   os << '['; if (it != end) { os << *it++; } while (it != end) { os << ", " << *it++; }   return os << ']'; }   int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, };   auto solution = solveCramer(equations); std::cout << solution << '\n';   return 0; }
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.
#AWK
AWK
BEGIN { printf "" > "output.txt" close("output.txt") printf "" > "/output.txt" close("/output.txt") system("mkdir docs") system("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.
#Axe
Axe
GetCalc("appvOUTPUT",0)
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#Bracmat
Bracmat
( ( CSVtoHTML = p q Character Speech swor rows row . 0:?p & :?swor:?rows & ( @( !arg  :  ? ( [!p ?Character "," ?Speech \n [?q ? & !q:?p & (tr.,(th.,!Character) (th.,!Speech))  !swor  : ?swor & ~ ) ) | whl ' ( !swor:%?row %?swor & !row \n !rows:?rows ) & toML $ (table.,(thead.,!swor) \n (tbody.,!rows)) ) ) & CSVtoHTML $ "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! " )  
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Open "manip.csv" For Input As #1 ' existing CSV file Open "manip2.csv" For Output As #2 ' new CSV file for writing changed data   Dim header As String Line Input #1, header header += ",SUM" Print #2, header   Dim As Integer c1, c2, c3, c4, c5, sum   While Not Eof(1) Input #1, c1, c2, c3, c4, c5 sum = c1 + c2 + c3 + c4 + c5 Write #2, c1, c2, c3, c4, c5, sum Wend   Close #1 Close #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.
#PowerShell
PowerShell
  $table = ( (0, 3, 1, 7, 5, 9, 8, 6, 4, 2), (7, 0, 9, 2, 1, 5, 4, 8, 6, 3), (4, 2, 0, 6, 8, 7, 1, 3, 5, 9), (1, 7, 5, 0, 9, 8, 3, 4, 2, 6), (6, 1, 2, 3, 0, 4, 5, 9, 7, 8), (3, 6, 7, 4, 2, 0, 9, 5, 8, 1), (5, 8, 6, 9, 7, 2, 0, 1, 3, 4), (8, 9, 4, 5, 3, 6, 2, 0, 1, 7), (9, 4, 3, 8, 6, 1, 7, 2, 0, 5), (2, 5, 8, 1, 4, 3, 6, 7, 9, 0) )   function Test-Damm([string]$s) { $interim = 0 foreach ($c in $s.ToCharArray()) { $interim = $table[$interim][[int]$c - [int][char]'0'] } return $interim -eq 0 }   foreach ($number in 5724, 5727, 112946, 112949) { $validity = if (Test-Damm $number) {'valid'} else {'invalid'} '{0,6} is {1}' -f $number, $validity }  
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.
#Nim
Nim
import strformat import strutils import math   const cutOff = 200 const bigUn = 100000 const chunks = 50 const little = bigUn div chunks   echo fmt"The first {cutOff} cuban primes" var primes: seq[int] = @[3, 5] var c, u = 0 var showEach: bool = true var v = 1 for i in 1..high(BiggestInt): var found: bool inc u, 6 inc v, u var mx = int(ceil(sqrt(float(v)))) for item in primes: if item > mx: break if v mod item == 0: found = true break if not found: inc c if showEach: for z in countup(primes[^1] + 2, v - 2, step=2): var fnd: bool = false for item in primes: if item > mx: break if z mod item == 0: fnd = true break if not fnd: primes.add(z) primes.add(v) write(stdout, fmt"{insertSep($v, ','):>11}") if c mod 10 == 0: write(stdout, "\n") if c == cutOff: showEach = false write(stdout, fmt"Progress to the {bigUn}th cuban prime: ") stdout.flushFile if c mod little == 0: write(stdout, ".") stdout.flushFile if c == bigUn: break write(stdout, "\n") echo fmt"The {c}th cuban prime is {insertSep($v, ',')}"
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.
#Pascal
Pascal
program CubanPrimes; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,Regvar,PEEPHOLE,CSE,ASMCSE} {$CODEALIGN proc=32} {$ENDIF} uses primTrial; const COLUMNCOUNT = 10*10;   procedure FormOut(Cuban:Uint64;ColSize:Uint32); var s : String; pI,pJ :pChar; i,j : NativeInt; Begin str(Cuban,s); i := length(s); If i>3 then Begin //extend s by the count of comma to be inserted j := i+ (i-1) div 3; setlength(s,j); pI := @s[i]; pJ := @s[j]; while i > 3 do Begin // copy 3 digits pJ^ := pI^;dec(pJ);dec(pI); pJ^ := pI^;dec(pJ);dec(pI); pJ^ := pI^;dec(pJ);dec(pI); // insert comma pJ^ := ',';dec(pJ); dec(i,3); end; //the digits in front are in the right place end; write(s:ColSize); end;   procedure OutFirstCntCubPrimes(Cnt : Int32;ColCnt : Int32); var cbDelta1, cbDelta2 : Uint64; ClCnt,ColSize : NativeInt; Begin If Cnt <= 0 then EXIT; IF ColCnt <= 0 then ColCnt := 1; ColSize := COLUMNCOUNT DIV ColCnt; dec(ColCnt);   ClCnt := ColCnt; cbDelta1 := 0; cbDelta2 := 1;   repeat if isPrime(cbDelta2) then Begin FormOut(cbDelta2,ColSize); dec(Cnt);   dec(ClCnt); If ClCnt < 0 then Begin Writeln; ClCnt := ColCnt; end; end; inc(cbDelta1,6);// 0,6,12,18... inc(cbDelta2,cbDelta1);//1,7,19,35... until Cnt<= 0;   writeln; end;   procedure OutNthCubPrime(n : Int32); var cbDelta1, cbDelta2 : Uint64; Begin If n <= 0 then EXIT; cbDelta1 := 0; cbDelta2 := 1;   repeat inc(cbDelta1,6); inc(cbDelta2,cbDelta1); if isPrime(cbDelta2) then dec(n); until n<=0;   FormOut(cbDelta2,20); writeln; end;   Begin OutFirstCntCubPrimes(200,10); OutNthCubPrime(100000); end.
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.
#Rust
Rust
fn add_n(n : i32) -> impl Fn(i32) -> i32 { move |x| n + x }   fn main() { let adder = add_n(40); println!("The answer to life is {}.", adder(2)); }
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
#Scala
Scala
  def add(a: Int)(b: Int) = a + b val add5 = add(5) _ add5(2)  
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
#Sidef
Sidef
var adder = 1.method(:add); say adder(3); #=> 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.
#Scala
Scala
import java.text.SimpleDateFormat import java.util.{Calendar, Locale, TimeZone}   object DateManipulation { def main(args: Array[String]): Unit = { val input="March 7 2009 7:30pm EST" val df=new SimpleDateFormat("MMMM d yyyy h:mma z", Locale.ENGLISH) val c=Calendar.getInstance() c.setTime(df.parse(input))   c.add(Calendar.HOUR_OF_DAY, 12) println(df.format(c.getTime))   df.setTimeZone(TimeZone.getTimeZone("GMT")) println(df.format(c.getTime)) } }
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i"; include "duration.s7i";   const func time: parseDate (in string: dateStri) is func result var time: aTime is time.value; local const array string: monthNames is [] ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var array string: dateParts is 0 times ""; var integer: month is 0; var string: timeStri is ""; begin dateParts := split(dateStri, ' '); aTime.year := integer parse (dateParts[3]); aTime.month := 1; while monthNames[aTime.month] <> dateParts[1] do incr(aTime.month); end while; aTime.day := integer parse (dateParts[2]); timeStri := dateParts[4]; if endsWith(timeStri, "am") then aTime.hour := integer parse (timeStri[.. pred(pos(timeStri, ':'))]); elsif endsWith(timeStri, "pm") then aTime.hour := integer parse (timeStri[.. pred(pos(timeStri, ':'))]) + 12; else raise RANGE_ERROR; end if; aTime.minute := integer parse (timeStri[succ(pos(timeStri, ':')) .. length(timeStri) - 2]); if dateParts[5] <> "UTC" then aTime.timeZone := 60 * integer parse (dateParts[5][4 ..]); end if; end func;   const proc: main is func local var time: aTime is time.value; begin aTime := parseDate("March 7 2009 7:30pm UTC-05"); writeln("Given: " <& aTime); aTime +:= 1 . DAYS; writeln("A day later: " <& aTime); aTime := toUTC(aTime); writeln("In UTC: " <& aTime); end func;
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.
#Maxima
Maxima
weekday(year, month, day) := block([m: month, y: year, k], if m < 3 then (m: m + 12, y: y - 1), k: 1 + remainder(day + quotient((m + 1)*26, 10) + y + quotient(y, 4) + 6*quotient(y, 100) + quotient(y, 400) + 5, 7), ['monday, 'tuesday, 'wednesday, 'thurdsday, 'friday, 'saturday, 'sunday][k] )$   sublist(makelist(i, i, 2008, 2121), lambda([y], weekday(y, 12, 25) = 'sunday)); /* [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.
#.D0.9C.D0.9A-61.2F52
МК-61/52
П9 7 П7 1 П8 НОП ИП8 2 2 - 1 0 / [x] П6 ИП9 + 1 8 9 9 - 3 6 5 , 2 5 * [x] ИП8 ИП6 1 2 * - 1 4 - 3 0 , 5 9 * [x] + 2 9 + ИП7 + П4 ИП4 7 / [x] 7 * - x=0 64 ИП9 С/П ИП9 1 + П9 БП 06
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
#Rust
Rust
fn cusip_check(cusip: &str) -> bool { if cusip.len() != 9 { return false; }   let mut v = 0; let capital_cusip = cusip.to_uppercase(); let char_indices = capital_cusip.as_str().char_indices().take(7);   let total = char_indices.fold(0, |total, (i, c)| { v = match c { '*' => 36, '@' => 37, '#' => 38, _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8, _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9, _ => v, };   if i % 2 != 0 { v *= 2 } total + (v / 10) + v % 10 });   let check = (10 - (total % 10)) % 10; (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap() }   fn main() { let codes = [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105", ]; for code in &codes { println!("{} -> {}", code, cusip_check(code)) } }
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
#Scala
Scala
object Cusip extends App {   val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")   for (candidate <- candidates) printf(f"$candidate%s -> ${if (isCusip(candidate)) "correct" else "incorrect"}%s%n")   private def isCusip(s: String): Boolean = { if (s.length != 9) false else { var sum = 0 for (i <- 0 until 7) { val c = s(i) var v = 0 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 if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing sum += v / 10 + v % 10 } s(8) - 48 == (10 - (sum % 10)) % 10 } }   }
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.
#C.2B.2B
C++
#include <iostream>   int main() { // read values int dim1, dim2; std::cin >> dim1 >> dim2;   // create array double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i;   // write element array[0][0] = 3.5;   // output element std::cout << array[0][0] << std::endl;   // get rid of array delete[] array; delete[] array_data;   return 0; }
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used. Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population. Test case Use this to compute the standard deviation of this demonstration set, { 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 } {\displaystyle \{2,4,4,4,5,5,7,9\}} , which is 2 {\displaystyle 2} . Related tasks Random numbers Tasks for calculating statistical measures in one go moving (sliding window) moving (cumulative) Mean Arithmetic Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means Averages/Simple moving average Geometric Averages/Pythagorean means Harmonic Averages/Pythagorean means Quadratic Averages/Root mean square Circular Averages/Mean angle Averages/Mean time of day Median Averages/Median Mode Averages/Mode Standard deviation Statistics/Basic Cumulative standard deviation
#FOCAL
FOCAL
01.01 C-- TEST SET 01.10 S T(1)=2;S T(2)=4;S T(3)=4;S T(4)=4 01.20 S T(5)=5;S T(6)=5;S T(7)=7;S T(8)=9 01.30 D 2.1 01.35 T %6.40 01.40 F I=1,8;S A=T(I);D 2.2;T "VAL",A;D 2.3;T " SD",A,! 01.50 Q   02.01 C-- RUNNING STDDEV 02.02 C-- 2.1: INITIALIZE 02.03 C-- 2.2: INSERT VALUE A 02.04 C-- 2.3: A = CURRENT STDDEV 02.10 S XN=0;S XS=0;S XQ=0 02.20 S XN=XN+1;S XS=XS+A;S XQ=XQ+A*A 02.30 S A=FSQT(XQ/XN - (XS/XN)^2)
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
#Forth
Forth
  : crc/ ( n -- n ) 8 0 do dup 1 rshift swap 1 and if $edb88320 xor then loop ;   : crcfill 256 0 do i crc/ , loop ;   create crctbl crcfill   : crc+ ( crc n -- crc' ) over xor $ff and cells crctbl + @ swap 8 rshift xor ;   : crcbuf ( crc str len -- crc ) bounds ?do i c@ crc+ loop ;   $ffffffff s" The quick brown fox jumps over the lazy dog" crcbuf $ffffffff xor hex. bye \ $414FA339  
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
#Fortran
Fortran
module crc32_m use iso_fortran_env implicit none integer(int32) :: crc_table(0:255) contains subroutine update_crc(a, crc) integer :: n, i character(*) :: a integer(int32) :: crc   crc = not(crc) n = len(a) do i = 1, n crc = ieor(shiftr(crc, 8), crc_table(iand(ieor(crc, iachar(a(i:i))), 255))) end do crc = not(crc) end subroutine   subroutine init_table integer :: i, j integer(int32) :: k   do i = 0, 255 k = i do j = 1, 8 if (btest(k, 0)) then k = ieor(shiftr(k, 1), -306674912) else k = shiftr(k, 1) end if end do crc_table(i) = k end do end subroutine end module   program crc32 use crc32_m implicit none integer(int32) :: crc = 0 character(*), parameter :: s = "The quick brown fox jumps over the lazy dog" call init_table call update_crc(s, crc) print "(Z8)", crc end program
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#Arturo
Arturo
changes: function [amount coins][ ways: map 0..amount+1 [x]-> 0 ways\0: 1   loop coins 'coin [ loop coin..amount 'j -> set ways j (get ways j) + get ways j-coin ]   ways\[amount] ]   print changes 100 [1 5 10 25] print changes 100000 [1 5 10 25 50 100]
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer count. print countSubstring("the three truths","th") 3   // do not count substrings that overlap with previously-counted substrings: print countSubstring("ababababab","abab") 2 The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left   (see proof on talk page). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#360_Assembly
360 Assembly
* Count occurrences of a substring 05/07/2016 COUNTSTR CSECT USING COUNTSTR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " MVC HAYSTACK,=CL32'the three truths' MVC LENH,=F'17' lh=17 MVC NEEDLE,=CL8'th' needle='th' MVC LENN,=F'2' ln=2 BAL R14,SHOW call show MVC HAYSTACK,=CL32'ababababab' MVC LENH,=F'11' lh=11 MVC NEEDLE,=CL8'abab' needle='abab' MVC LENN,=F'4' ln=4 BAL R14,SHOW call show L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit HAYSTACK DS CL32 haystack NEEDLE DS CL8 needle LENH DS F length(haystack) LENN DS F length(needle) *------- ---- show--------------------------------------------------- SHOW ST R14,SAVESHOW save return address BAL R14,COUNT count(haystack,needle) LR R11,R0 ic=count(haystack,needle) MVC PG(20),HAYSTACK output haystack MVC PG+20(5),NEEDLE output needle XDECO R11,PG+25 output ic XPRNT PG,80 print buffer L R14,SAVESHOW restore return address BR R14 return to caller SAVESHOW DS A return address of caller PG DC CL80' ' buffer *------- ---- count-------------------------------------------------- COUNT ST R14,SAVECOUN save return address SR R7,R7 n=0 LA R6,1 istart=1 L R10,LENH lh S R10,LENN ln LA R10,1(R10) lh-ln+1 LOOPI CR R6,R10 do istart=1 to lh-ln+1 BH ELOOPI LA R8,NEEDLE @needle L R9,LENN ln LA R4,HAYSTACK-1 @haystack[0] AR R4,R6 +istart LR R5,R9 ln CLCL R4,R8 if substr(haystack,istart,ln)=needle BNE NOTEQ LA R7,1(R7) n=n+1 A R6,LENN istart=istart+ln NOTEQ LA R6,1(R6) istart=istart+1 B LOOPI ELOOPI LR R0,R7 return(n) L R14,SAVECOUN restore return address BR R14 return to caller SAVECOUN DS A return address of caller * ---- ------------------------------------------------------- YREGS END COUNTSTR
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer count. print countSubstring("the three truths","th") 3   // do not count substrings that overlap with previously-counted substrings: print countSubstring("ababababab","abab") 2 The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left   (see proof on talk page). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;; Count non-overlapping substrings (BC) in string (HL) ;;; Returns amount of matches in DE subcnt: lxi d,0 ; Amount of matches s_scan: mov a,m ; Get current character ana a ; End of string? rz ; Then stop push b ; Keep start of substring search push h ; Keep current location in string s_cmp: ldax b ; Get character from substring cmp m ; Compare to curent charracter of search string inx b ; Advance pointers inx h jz s_cmp ; Keep going if they were equal ana a ; Did we reach the end of the substring? jz s_find ; If so, we found a match pop h ; Otherwise, no match - restore search position pop b ; Restore start of substring inx h ; Try next position jmp s_scan s_find: inx d ; We found a match pop b ; Discard start of the search, keep going after match pop b ; Restore start of substring dcx h ; The comparison routine overshoots by one jmp s_scan ;;; Test on a few strings demo: lxi h,pairs loop: mov e,m ; Load string pointer inx h mov d,m inx h mov a,d ; If 0, stop ora e rz mov c,m ; Load substring pointer inx h mov b,m inx h push h ; Save example pointer xchg ; Put string pointer in HL call subcnt ; Count substrings mvi a,'0' ; Assuming output is <10, print output add e ; (This is true for all examples, and a proper numeric mov e,a ; output routine is big and not relevant.) mvi c,2 ; CP/M character output call 5 pop h ; Restore example pointer jmp loop pairs: dw str1,sub1,str2,sub2,str3,sub3,0 str1: db 'the three truths',0 sub1: db 'th',0 ; result should be 3 str2: db 'ababababab',0 sub2: db 'abab',0 ; result should be 2 str3: db 'cat',0 sub3: db 'dog',0 ; result should be 0
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequence   is a similar task without the use of octal numbers.
#360_Assembly
360 Assembly
* Octal 04/07/2016 OCTAL CSECT USING OCTAL,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " LA R6,0 i=0 LOOPI LR R2,R6 x=i LA R9,10 j=10 LA R4,PG+23 @pg LOOP LR R3,R2 save x SLL R2,29 shift left 32-3 SRL R2,29 shift right 32-3 CVD R2,DW convert octal(j) to pack decimal OI DW+7,X'0F' prepare unpack UNPK 0(1,R4),DW packed decimal to zoned printable LR R2,R3 restore x SRL R2,3 shift right 3 BCTR R4,0 @pg=@pg-1 BCT R9,LOOP j=j-1 CVD R2,DW binary to pack decimal OI DW+7,X'0F' prepare unpack UNPK 0(1,R4),DW packed decimal to zoned printable CVD R6,DW convert i to pack decimal MVC ZN12,EM12 load mask ED ZN12,DW+2 packed decimal (PL6) to char (CL12) MVC PG(12),ZN12 output i XPRNT PG,80 print buffer C R6,=F'2147483647' if i>2**31-1 (integer max) BE ELOOPI then exit loop on i LA R6,1(R6) i=i+1 B LOOPI loop on i ELOOPI L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit LTORG PG DC CL80' ' buffer DW DS 0D,PL8 15num ZN12 DS CL12 EM12 DC X'40',9X'20',X'2120' mask CL12 11num YREGS END OCTAL
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequence   is a similar task without the use of octal numbers.
#6502_Assembly
6502 Assembly
  define SRC_LO $00 define SRC_HI $01   define DEST_LO $02 define DEST_HI $03   define temp $04 ;temp storage used by foo   ;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.   SET_TABLE: TXA STA $1000,X INX BNE SET_TABLE ;stores the identity table at memory address $1000-$10FF   CLEAR_TABLE: LDA #0 STA $1200,X INX BNE CLEAR_TABLE ;fills the range $1200-$12FF with zeroes.     LDA #$10 STA SRC_HI LDA #$00 STA SRC_LO ;store memory address $1000 in zero page   LDA #$12 STA DEST_HI LDA #$00 STA DEST_LO ;store memory address $1200 in zero page     loop: LDA (SRC_LO),y  ;load accumulator from memory address $1000+y JSR foo ;convert accumulator to octal STA (DEST_LO),y ;store accumulator in memory address $1200+y   INY CPY #$40 BCC loop BRK   foo: sta temp  ;store input temporarily asl  ;bit shift, this places the top bit of the right nibble in the bottom of the left nibble. pha  ;back this value up lda temp and #$07  ;take the original input and remove everything except the bottom 3 bits. sta temp  ;store it for later. What used to be stored here is no longer needed. pla  ;get the pushed value back. and #$F0  ;clear the bottom 4 bits. ora temp  ;put the bottom 3 bits of the original input back. and #$7F  ;clear bit 7. rts
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\displaystyle 2\times 3} . 2144   is not prime;   it would be shown as   2 × 2 × 2 × 2 × 2 × 67 {\displaystyle 2\times 2\times 2\times 2\times 2\times 67} . Related tasks   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes
#11l
11l
F get_prime_factors(=li) I li == 1 R ‘1’ E V res = ‘’ V f = 2 L I li % f == 0 res ‘’= f li /= f I li == 1 L.break res ‘’= ‘ x ’ E f++ R res   L(x) 1..17 print(‘#4: #.’.format(x, get_prime_factors(x))) print(‘2144: ’get_prime_factors(2144))
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Arturo
Arturo
table: function [content] -> join @["<table>" join @content "</table>"]   header: function [cells] -> join @["<tr>" join @cells "</tr>"] th: function [lbl] -> join @["<th>" lbl "</th>"] row: function [no] -> join @[ "<tr><td style='font-weight:bold'>" no "</td>" "<td>" random 1000 9999 "</td>" "<td>" random 1000 9999 "</td>" "<td>" random 1000 9999 "</td></tr>" ]   print table [ header [th"" th"X" th"Y" th"Z"] row 1 row 2 row 3 row 4 row 5 ]
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
#LiveCode
LiveCode
on mouseUp pButtonNumber put the date into tDate convert tDate to dateItems put item 1 of tDate & "-" & item 2 of tDate & "-" & item 3 of tDate & return into tMyFormattedDate put tMyFormattedDate & the long date end mouseUp
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
#Logo
Logo
  print first shell [date +%F] print first shell [date +"%A, %B %d, %Y"]  
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1}}\\a_{2}x+b_{2}y+c_{2}z&={\color {red}d_{2}}\\a_{3}x+b_{3}y+c_{3}z&={\color {red}d_{3}}\end{matrix}}\right.} which in matrix format is [ a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 ] [ x y z ] = [ d 1 d 2 d 3 ] . {\displaystyle {\begin{bmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{bmatrix}}{\begin{bmatrix}x\\y\\z\end{bmatrix}}={\begin{bmatrix}{\color {red}d_{1}}\\{\color {red}d_{2}}\\{\color {red}d_{3}}\end{bmatrix}}.} Then the values of x , y {\displaystyle x,y} and z {\displaystyle z} can be found as follows: x = | d 1 b 1 c 1 d 2 b 2 c 2 d 3 b 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | , y = | a 1 d 1 c 1 a 2 d 2 c 2 a 3 d 3 c 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | ,  and  z = | a 1 b 1 d 1 a 2 b 2 d 2 a 3 b 3 d 3 | | a 1 b 1 c 1 a 2 b 2 c 2 a 3 b 3 c 3 | . {\displaystyle x={\frac {\begin{vmatrix}{\color {red}d_{1}}&b_{1}&c_{1}\\{\color {red}d_{2}}&b_{2}&c_{2}\\{\color {red}d_{3}}&b_{3}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}d_{1}}&c_{1}\\a_{2}&{\color {red}d_{2}}&c_{2}\\a_{3}&{\color {red}d_{3}}&c_{3}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}},{\text{ and }}z={\frac {\begin{vmatrix}a_{1}&b_{1}&{\color {red}d_{1}}\\a_{2}&b_{2}&{\color {red}d_{2}}\\a_{3}&b_{3}&{\color {red}d_{3}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}&c_{1}\\a_{2}&b_{2}&c_{2}\\a_{3}&b_{3}&c_{3}\end{vmatrix}}}.} Task Given the following system of equations: { 2 w − x + 5 y + z = − 3 3 w + 2 x + 2 y − 6 z = − 32 w + 3 x + 3 y − z = − 47 5 w − 2 x − 3 y + 3 z = 49 {\displaystyle {\begin{cases}2w-x+5y+z=-3\\3w+2x+2y-6z=-32\\w+3x+3y-z=-47\\5w-2x-3y+3z=49\\\end{cases}}} solve for w {\displaystyle w} , x {\displaystyle x} , y {\displaystyle y} and z {\displaystyle z} , using Cramer's rule.
#Common_Lisp
Common Lisp
(defun minor (m col) (loop with dim = (1- (array-dimension m 0)) with result = (make-array (list dim dim)) for i from 1 to dim for r = (1- i) do (loop with c = 0 for j to dim when (/= j col) do (setf (aref result r c) (aref m i j)) (incf c)) finally (return result)))   (defun det (m) (assert (= (array-rank m) 2)) (assert (= (array-dimension m 0) (array-dimension m 1))) (let ((dim (array-dimension m 0))) (if (= dim 1) (aref m 0 0) (loop for col below dim for sign = 1 then (- sign) sum (* sign (aref m 0 col) (det (minor m col)))))))   (defun replace-column (m col values) (let* ((dim (array-dimension m 0)) (result (make-array (list dim dim)))) (dotimes (r dim result) (dotimes (c dim) (setf (aref result r c) (if (= c col) (aref values r) (aref m r c)))))))   (defun solve (m v) (loop with dim = (array-dimension m 0) with det = (det m) for col below dim collect (/ (det (replace-column m col v)) det)))   (solve #2A((2 -1 5 1) (3 2 2 -6) (1 3 3 -1) (5 -2 -3 3)) #(-3 -32 -47 49))
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.
#BASIC
BASIC
OPEN "output.txt" FOR OUTPUT AS 1 CLOSE OPEN "\output.txt" FOR OUTPUT AS 1 CLOSE
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Batch_File
Batch File
copy nul output.txt copy nul \output.txt
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#C
C
#include <stdio.h>   const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!";   int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>");   return 0; }
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.
#FunL
FunL
import io.{lines, PrintWriter}   data Table( header, rows )   def read( file ) = l = lines( file )   def next = vector( l.next().split(',') )   if l.isEmpty() then return Table( vector(), [] )   header = next() rows = seq()   while l.hasNext() rows += next()   Table( header, rows.toList() )   def write( table, out ) = w = if out is String then PrintWriter( out ) else out   w.println( table.header.mkString(',') )   for r <- table.rows w.println( r.mkString(',') )   if out is String w.close()   def updateRow( header, row, updates ) = r = dict( (header(i), row(i)) | i <- 0:header.length() ) updates( r ) vector( r(f) | f <- header )   def update( table, updates ) = Table( table.header, (updateRow(table.header, r, updates) | r <- table.rows).toList() )   def addColumn( table, column, updates ) = Table( table.header + [column], (updateRow(table.header + [column], r + [null], updates) | r <- table.rows).toList() )   t = addColumn( read('test.csv'), 'SUM', r -> r('SUM') = sum(int(v) | (_, v) <- r if v != null) ) write( t, 'test_out.csv' ) write( t, System.out )
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.
#Gambas
Gambas
Public Sub Form_Open() Dim sData As String = File.Load("data.csv") Dim sLine, sTemp As String Dim sOutput As New String[] Dim siCount As Short Dim bLine1 As Boolean   For Each sLine In Split(sData, gb.NewLine) If Not bLine1 Then sLine &= ",SUM" sOutput.Add(sLine) bLine1 = True Continue End If For Each sTemp In Split(sLine) siCount += Val(sTemp) Next sOutput.Add(sLine & "," & Str(siCount)) siCount = 0 Next   sData = ""   For Each sTemp In sOutput sData &= sTemp & gb.NewLine Print sTemp; Print Next   File.Save(User.home &/ "CSVData.csv", sData)   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.
#PureBasic
PureBasic
DataSection DT_Start: Data.b 0,3,1,7,5,9,8,6,4,2 Data.b 7,0,9,2,1,5,4,8,6,3 Data.b 4,2,0,6,8,7,1,3,5,9 Data.b 1,7,5,0,9,8,3,4,2,6 Data.b 6,1,2,3,0,4,5,9,7,8 Data.b 3,6,7,4,2,0,9,5,8,1 Data.b 5,8,6,9,7,2,0,1,3,4 Data.b 8,9,4,5,3,6,2,0,1,7 Data.b 9,4,3,8,6,1,7,2,0,5 Data.b 2,5,8,1,4,3,6,7,9,0 EndDataSection   Procedure.i Adr(Row,Col) : ProcedureReturn ?DT_Start+Row+10*Col : EndProcedure   Procedure.b CheckDamm(Value.s) *ipc.Character=@Value : it=0 While *ipc\c it=PeekB(Adr(*ipc\c-'0',it)) : *ipc+SizeOf(Character) Wend ProcedureReturn Bool(it) EndProcedure   If OpenConsole() Repeat Print("Check Damm: ") : i$=Input() If CheckDamm(i$) : PrintN(Space(12)+"FALSE") : Else : PrintN(Space(12)+"TRUE") : EndIf Until i$="" EndIf 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.
#Perl
Perl
use feature 'say'; use ntheory 'is_prime';   sub cuban_primes { my ($n) = @_;   my @primes; for (my $k = 1 ; ; ++$k) { my $p = 3 * $k * ($k + 1) + 1; if (is_prime($p)) { push @primes, $p; last if @primes >= $n; } }   return @primes; }   sub commify { scalar reverse join ',', unpack '(A3)*', reverse shift; }   my @c = cuban_primes(200);   while (@c) { say join ' ', map { sprintf "%9s", commify $_ } splice(@c, 0, 10); }   say ''; for my $n (1 .. 6) { say "10^$n-th cuban prime is: ", commify((cuban_primes(10**$n))[-1]); }
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.
#Standard_ML
Standard ML
fun addnums (x:int) y = x+y (* declare a curried function *)   val 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.
#Swift
Swift
func addN(n:Int)->Int->Int { return {$0 + n} }   var add2 = addN(2) println(add2) // (Function) println(add2(7)) // 9
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.
#Tcl
Tcl
interp alias {} addone {} ::tcl::mathop::+ 1 puts [addone 6]; # => 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.
#SenseTalk
SenseTalk
set date to "March 7 2009 7:30pm EST" insert "[month name] [day] [year] [hour12]:[min][pm] [timeZoneID]" into the timeInputFormat   put date + 12 hours  
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.
#Sidef
Sidef
var dt = frequire('DateTime::Format::Strptime')   var input = 'March 7 2009 7:30pm EST' input.sub!('EST', 'America/New_York')   say dt.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.
#Modula-3
Modula-3
MODULE Yule EXPORTS Main;   IMPORT IO, Fmt, Date, Time;   VAR date: Date.T; time: Time.T;   BEGIN FOR year := 2008 TO 2121 DO date.day := 25; date.month := Date.Month.Dec; date.year := year;   TRY time := Date.ToTime(date); EXCEPT | Date.Error => IO.Put(Fmt.Int(year) & " is the last year we can specify\n"); EXIT; END;   date := Date.FromTime(time);   IF date.weekDay = Date.WeekDay.Sun THEN IO.Put("25th of December " & Fmt.Int(year) & " is Sunday\n"); END; END; END Yule.
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
#SNOBOL4
SNOBOL4
#!/usr/local/bin/snobol4 -r * cusip.sno * -- Committee on Uniform Security Identification Procedures * -r : read data placed after the end label. * Verify check digit and size of cusip code.   define("cusipt()i")  :(cusipt_end) cusipt chars = &digits &ucase "*@#" cusipt = table() i = 0 cusipt_1 chars pos(i) len(1) . c  :f(return) cusipt[c] = i i = i + 1  :(cusipt_1) cusipt_end   define("check_cusip(line)c,i")  :(check_cusip_end) check_cusip eq(size(line), 9)  :f(freturn) check_cusip = 0 i = 0 check_cusip_1 line pos(i) len(1) . c value = t[c] value = eq(remdr(i, 2), 1) t[c] * 2 check_cusip = check_cusip + (value / 10) + remdr(value, 10) i = lt(i, 7) i + 1  :s(check_cusip_1) check_cusip = remdr(10 - remdr(check_cusip, 10), 10) eq(substr(line, 9, 1), check_cusip)  :s(return)f(freturn) check_cusip_end   *** main *** t = cusipt()   read line = input  :f(end) check_cusip(line)  :f(bad_cusip) output = line " valid."  :(read) bad_cusip output = line " not valid."  :(read) end 037833100 17275R102 38259P508 594918104 68389X106 68389X105 68389X10 68389X1059 68389x105
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6. Task Ensure the last digit   (i.e., the   check digit)   of the CUSIP code (the 1st column) is correct, against the following:   037833100       Apple Incorporated   17275R102       Cisco Systems   38259P508       Google Incorporated   594918104       Microsoft Corporation   68389X106       Oracle Corporation   (incorrect)   68389X105       Oracle Corporation Example pseudo-code below. algorithm Cusip-Check-Digit(cusip) is Input: an 8-character CUSIP   sum := 0 for 1 ≤ i ≤ 8 do c := the ith character of cusip if c is a digit then v := numeric value of the digit c else if c is a letter then p := ordinal position of c in the alphabet (A=1, B=2...) v := p + 9 else if c = "*" then v := 36 else if c = "@" then v := 37 else if' c = "#" then v := 38 end if if i is even then v := v × 2 end if   sum := sum + int ( v div 10 ) + v mod 10 repeat   return (10 - (sum mod 10)) mod 10 end function See related tasks SEDOL ISIN
#Swift
Swift
struct CUSIP { var value: String   private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")   init?(value: String) { if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) { self.value = value } else if value.count == 8, let checkDigit = CUSIP.checkDigit(cusipString: value) { self.value = value + checkDigit } else { return nil } }   static func checkDigit(cusipString: String) -> String? { guard cusipString.count == 8, cusipString.allSatisfy({ $0.isASCII }) else { return nil }   let sum = cusipString.uppercased().enumerated().reduce(0, {sum, pair in let (i, char) = pair var v: Int   switch char { case "*": v = 36 case "@": v = 37 case "#": v = 38 case _ where char.isNumber: v = char.wholeNumberValue! case _: v = Int(char.asciiValue! - 65) + 10 }   if i & 1 == 1 { v *= 2 }   return sum + (v / 10) + (v % 10) })   return String((10 - (sum % 10)) % 10) } }   let testCases = [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" ]   for potentialCUSIP in testCases { print("\(potentialCUSIP) -> ", terminator: "")   switch CUSIP(value: potentialCUSIP) { case nil: print("Invalid") case _: print("Valid") } }