task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#Clean
Clean
import StdEnv   Start :: *World -> { {Real} } Start world # (console, world) = stdio world (_, dim1, console) = freadi console (_, dim2, console) = freadi console = createArray dim1 (createArray dim2 1.0)
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#Clojure
Clojure
(let [rows (Integer/parseInt (read-line)) cols (Integer/parseInt (read-line)) a (to-array-2d (repeat rows (repeat cols nil)))] (aset a 0 0 12) (println "Element at 0,0:" (aget a 0 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
#Forth
Forth
: f+! ( x addr -- ) dup f@ f+ f! ;   : st-count ( stats -- n ) f@ ; : st-sum ( stats -- sum ) float+ f@ ; : st-sumsq ( stats -- sum*sum ) 2 floats + f@ ;   : st-mean ( stats -- mean ) dup st-sum st-count f/ ;   : st-variance ( stats -- var ) dup st-sumsq dup st-mean fdup f* dup st-count f* f- st-count f/ ;   : st-stddev ( stats -- stddev ) st-variance fsqrt ;   : st-add ( fnum stats -- ) dup 1e dup f+! float+ fdup dup f+! float+ fdup f* f+! std-stddev ;
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string: The quick brown fox jumps over the lazy dog
#FreeBASIC
FreeBASIC
' version 18-03-2017 ' compile with: fbc -s console   Function crc32(buf As String) As UInteger<32>   Static As UInteger<32> table(256) Static As UInteger<32> have_table Dim As UInteger<32> crc, k Dim As ULong i, j   If have_table = 0 Then For i = 0 To 255 k = i For j = 0 To 7 If (k And 1) Then k Shr= 1 k Xor= &Hedb88320 Else k Shr= 1 End If table(i) = k Next Next have_table = 1 End If   crc = Not crc ' crc = &Hffffffff   For i = 0 To Len(buf) -1 crc = (crc Shr 8) Xor table((crc And &hff) Xor buf[i]) Next   Return Not crc   End Function   ' ------=< MAIN >=------   Dim As String l = "The quick brown fox jumps over the lazy dog" Dim As UInteger<32> crc   Print "input = "; l print Print "The CRC-32 checksum = "; Hex(crc32(l), 8)   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#AutoHotkey
AutoHotkey
countChange(amount){ return cc(amount, 4) }   cc(amount, kindsOfCoins){ if ( amount == 0 ) return 1 if ( amount < 0 ) || ( kindsOfCoins == 0 ) return 0 return cc(amount, kindsOfCoins-1) + cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins) }   firstDenomination(kindsOfCoins){ return [1, 5, 10, 25][kindsOfCoins] } MsgBox % countChange(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
#8086_Assembly
8086 Assembly
cpu 8086 org 100h section .text jmp demo ;;; Count non-overlapping substrings [ES:DI] in [DS:SI] ;;; Return count in AX subcnt: xor ax,ax ; Set count to 0 xor dl,dl ; Zero to compare to mov bp,di ; Keep copy of substring pointer .scan: cmp dl,[si] ; End of string? je .out ; Then we're done mov bx,si ; Keep copy of search position mov di,bp ; Start at beginning of substring .cmp: xor cx,cx dec cx repe cmpsb ; Scan until no match dec si ; Go to first non-match dec di cmp dl,[es:di] ; Reached end of substring? je .match ; Then we found a match mov si,bx ; If not, continue searching one inc si ; position further jmp .scan .match: inc ax ; Found a match - increment count jmp .scan .out: ret ;;; Test the routine on a few examples demo: mov si,pairs .loop: lodsw ; Load string pointer test ax,ax ; If 0, stop jz .out xchg dx,ax lodsw ; Load substring pointer xchg di,ax push si ; Keep example pointer xchg si,dx call subcnt ; Count substrings call prax ; Print amount of substrings pop si ; Restore example pointer jmp .loop .out: ret ;;; Print AX as number prax: mov bx,num ; Pointer to end of number string mov cx,10 ; Divisor .dgt: xor dx,dx ; Divide by 10 div cx add dl,'0' ; Add ASCII 0 to remainder dec bx ; Store digit mov [bx],dl test ax,ax ; If number not zero yet jnz .dgt ; Find rest of digits mov dx,bx ; Print number string mov ah,9 int 21h ret section .data db '*****' ; Output number placeholder num: db ' $' ;;; Examples 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.
#8080_Assembly
8080 Assembly
  ;------------------------------------------------------- ; useful equates ;------------------------------------------------------- bdos equ 5 ; CP/M BDOS entry conout equ 2 ; BDOS console output function cr equ 13 ; ASCII carriage return lf equ 10 ; ASCII line feed ;------------------------------------------------------ ; main code begins here ;------------------------------------------------------ org 100h ; start of tpa under CP/M lxi h,0 ; save CP/M's stack dad sp shld oldstk lxi sp,stack ; set our own stack lxi h,1 ; start counting at 1 count: call putoct call crlf inx h mov a,h ; check for overflow (hl = 0) ora l jnz count ; ; all finished. clean up and exit. ; lhld oldstk ; get CP/M's stack back sphl ; restore it ret ; back to the ccp w/o warm booting ;------------------------------------------------------ ; Console output routine ; print character in A register to console ;------------------------------------------------------ putchr: push h push d push b mov e,a ; character to E for CP/M mvi c,2 ; console output function call bdos ; call on BDOS to perform pop b pop d pop h ret ;------------------------------------------------------ ; output CRLF to console ;------------------------------------------------------ crlf: mvi a,cr call putchr mvi a,lf call putchr ret ;------------------------------------------------------ ; Octal output routine ; entry: hl = number to output on console in octal ; this is a recursive routine and uses 6 bytes of stack ; space for each digit ;------------------------------------------------------ putoct: push b push d push h mvi b,3 ; hl = hl >> 3 div2: call shlr dcr b jnz div2 mov a,l ; test if hl = 0 ora h cnz putoct pop h ; get unshifted hl back push h mov a,l ; get low byte ani 7 ; a = a mod 8 adi '0' ; make printable call putchr pop h pop d pop b ret ;------------------------------------------------------- ; logical shift of 16-bit value in HL right by one bit ;------------------------------------------------------- shlr: ora a ; clear carry mov a,h ; begin with most significant byte rar ; bit 0 goes into carry mov h,a ; put shifted byte back mov a,l ; get least significant byte rar ; bit 0 of MSB has shifted in mov l,a ret ;------------------------------------------------------- ; data area ;------------------------------------------------------- oldstk: dw 1 stack equ $+128 ; 64 level stack ; end  
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program countOctal64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .ascii "Count : " sMessValeur: .fill 11, 1, ' ' // size => 11 szCarriageReturn: .asciz "\n"     /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program mov x20,0 // loop indice 1: // begin loop mov x0,x20 ldr x1,qAdrsMessValeur bl conversion8 // call conversion octal ldr x0,qAdrsMessResult bl affichageMess // display message add x20,x20,1 cmp x20,64 ble 1b     100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsMessValeur: .quad sMessValeur qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult     /******************************************************************/ /* Converting a register to octal */ /******************************************************************/ /* x0 contains value and x1 address area */ /* x0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion8: stp x1,lr,[sp,-16]! // save registers mov x3,x1 mov x2,LGZONECAL   1: // start loop mov x1,x0 lsr x0,x0,3 // / by 8 lsl x4,x0,3 sub x1,x1,x4 // compute remainder x1 - (x0 * 8) add x1,x1,48 // digit strb w1,[x3,x2] // store digit on area cmp x0,0 // stop if quotient = 0 sub x4,x2,1 csel x2,x4,x2,ne bne 1b // and loop // and move digit from left of area mov x4,0 2: ldrb w1,[x3,x2] strb w1,[x3,x4] add x2,x2,1 add x4,x4,1 cmp x2,LGZONECAL ble 2b // and move spaces in end on area mov x0,x4 // result length mov x1,' ' // space 3: strb w1,[x3,x4] // store space in area add x4,x4,1 // next position cmp x4,LGZONECAL ble 3b // loop if x4 <= area size   100:   ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#360_Assembly
360 Assembly
* Count in factors 24/03/2017 COUNTFAC CSECT assist plig\COUNTFAC USING COUNTFAC,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability L R6,=F'1' i=1 DO WHILE=(C,R6,LE,=F'40') do i=1 to 40 LR R7,R6 n=i MVI F,X'01' f=true MVC PG,=CL80' ' clear buffer LA R10,PG pgi=0 XDECO R6,XDEC edit i MVC 0(12,R10),XDEC output i LA R10,12(R10) pgi=pgi+12 MVC 0(1,R10),=C'=' output '=' LA R10,1(R10) pgi=pgi+1 IF C,R7,EQ,=F'1' THEN if n=1 then MVI 0(R10),C'1' output n ELSE , else LA R8,2 p=2 DO WHILE=(CR,R8,LE,R7) do while p<=n LR R4,R7 n SRDA R4,32 ~ DR R4,R8 /p IF LTR,R4,Z,R4 THEN if n//p=0 then IF CLI,F,EQ,X'00' THEN if not f then MVC 0(1,R10),=C'*' output '*' LA R10,1(R10) pgi=pgi+1 ELSE , else MVI F,X'00' f=false ENDIF , endif CVD R8,PP convert bin p to packed pp MVC WORK12,MASX12 in fact L13 EDMK WORK12,PP+2 edit and mark LA R9,WORK12+12 end of string(p) SR R9,R1 li=lengh(p) {r1 from edmk} MVC EDIT12,WORK12 L12<-L13 LA R4,EDIT12+12 source+12 SR R4,R9 -lengh(p) LR R5,R9 lengh(p) LR R2,R10 target ix LR R3,R9 lengh(p) MVCL R2,R4 f=f||p AR R10,R9 ix=ix+lengh(p) LR R4,R7 n SRDA R4,32 ~ DR R4,R8 /p LR R7,R5 n=n/p ELSE , else LA R8,1(R8) p=p+1 ENDIF , endif ENDDO , enddo while ENDIF , endif XPRNT PG,L'PG print buffer LA R6,1(R6) i++ ENDDO , enddo i L R13,4(0,R13) restore previous savearea pointer LM R14,R12,12(R13) restore previous context XR R15,R15 rc=0 BR R14 exit F DS X flag first factor DS 0D alignment for cvd PP DS PL8 packed CL8 EDIT12 DS CL12 target CL12 WORK12 DS CL13 char CL13 MASX12 DC X'40',9X'20',X'212060' CL13 XDEC DS CL12 temp PG DS CL80 buffer YREGS END COUNTFAC
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
#Action.21
Action!
PROC PrintFactors(CARD a) BYTE notFirst CARD p   IF a=1 THEN PrintC(a) RETURN FI   p=2 notFirst=0 WHILE p<=a DO IF a MOD p=0 THEN IF notFirst THEN Put('x) FI notFirst=1 PrintC(p) a==/p ELSE p==+1 FI OD RETURN   PROC Main() CARD i   FOR i=1 TO 1000 DO PrintC(i) Put('=) PrintFactors(i) PutE() OD RETURN
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.
#AutoHotkey
AutoHotkey
out = <table style="text-align:center; border: 1px solid"><th></th><th>X</th><th>Y</th><th>Z</th><tr> Loop 4 out .= "`r`n<tr><th>" A_Index "</th><td>" Rand() "</td><td>" Rand() "</td><td>" Rand() "</tr>" out .= "`r`n</table>" MsgBox % clipboard := out   Rand(u=1000){ Random, n, 1, % u return n }
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Lua
Lua
print( os.date( "%Y-%m-%d" ) ) print( os.date( "%A, %B %d, %Y" ) )
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
#M2000_Interpreter
M2000 Interpreter
  Print str$(today, "yyyy-mm-dd") Print str$(today, "dddd, mmm, dd, yyyy")  
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.
#D
D
import std.array : array, uninitializedArray; import std.range : iota; import std.stdio : writeln; import std.typecons : tuple;   alias vector = double[4]; alias matrix = vector[4];   auto johnsonTrotter(int n) { auto p = iota(n).array; auto q = iota(n).array; auto d = uninitializedArray!(int[])(n); d[] = -1; auto sign = 1; int[][] perms; int[] signs;   void permute(int k) { if (k >= n) { perms ~= p.dup; signs ~= sign; sign *= -1; return; } permute(k + 1); foreach (i; 0..k) { auto z = p[q[k] + d[k]]; p[q[k]] = z; p[q[k] + d[k]] = k; q[z] = q[k]; q[k] += d[k]; permute(k + 1); } d[k] *= -1; }   permute(0); return tuple!("sigmas", "signs")(perms, signs); }   auto determinant(matrix m) { auto jt = johnsonTrotter(m.length); auto sum = 0.0; foreach (i,sigma; jt.sigmas) { auto prod = 1.0; foreach (j,s; sigma) { prod *= m[j][s]; } sum += jt.signs[i] * prod; } return sum; }   auto cramer(matrix m, vector d) { auto divisor = determinant(m); auto numerators = uninitializedArray!(matrix[])(m.length); foreach (i; 0..m.length) { foreach (j; 0..m.length) { foreach (k; 0..m.length) { numerators[i][j][k] = m[j][k]; } } } vector v; foreach (i; 0..m.length) { foreach (j; 0..m.length) { numerators[i][j][i] = d[j]; } } foreach (i; 0..m.length) { v[i] = determinant(numerators[i]) / divisor; } return v; }   void main() { matrix m = [ [2.0, -1.0, 5.0, 1.0], [3.0, 2.0, 2.0, -6.0], [1.0, 3.0, 3.0, -1.0], [5.0, -2.0, -3.0, 3.0] ]; vector d = [-3.0, -32.0, -47.0, 49.0]; auto wxyz = cramer(m, d); writeln("w = ", wxyz[0], ", x = ", wxyz[1], ", y = ", wxyz[2], ", z = ", wxyz[3]); }
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.
#BBC_BASIC
BBC BASIC
CLOSE #OPENOUT("output.txt") CLOSE #OPENOUT("\output.txt") *MKDIR docs *MKDIR \docs
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Blue
Blue
global _start   : syscall ( num:eax -- result:eax ) syscall ;   : exit ( status:edi -- noret ) 60 syscall ; : bye ( -- noret ) 0 exit ; : die ( err:eax -- noret ) neg exit ;   : unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ; : ordie ( result -- ) unwrap drop ;   : open ( pathname:edi flags:esi mode:edx -- fd:eax ) 2 syscall unwrap ; : close ( fd:edi -- ) 3 syscall ordie ;   : mkdir ( pathname:edi mode:esi -- ) 83 syscall ordie ;   00001 const for-writing 00100 const create 01000 const truncate   : create-file ( pathname -- ) create for-writing or truncate or 0640 open close ;   : make-directory ( pathname -- ) 0750 mkdir ;   : create-output-file ( -- ) s" output.txt" drop create-file ; : make-docs-directory ( -- ) s" docs" drop make-directory ;   : _start ( -- noret ) create-output-file make-docs-directory bye ;
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.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Net;   class Program { private static string ConvertCsvToHtmlTable(string csvText) { //split the CSV, assume no commas or line breaks in text List<List<string>> splitString = new List<List<string>>(); List<string> lineSplit = csvText.Split('\n').ToList(); foreach (string line in lineSplit) { splitString.Add(line.Split(',').ToList()); }   //encode text safely, and create table string tableResult = "<table>"; foreach(List<string> splitLine in splitString) { tableResult += "<tr>"; foreach(string splitText in splitLine) { tableResult += "<td>" + WebUtility.HtmlEncode(splitText) + "</td>"; } tableResult += "</tr>"; } tableResult += "</table>"; return tableResult; } }  
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.
#Go
Go
package main   import ( "encoding/csv" "log" "os" "strconv" )   func main() { rows := readSample() appendSum(rows) writeChanges(rows) }   func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows }   func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } }   func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) }   func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
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.
#Python
Python
def damm(num: int) -> bool: row = 0 for digit in str(num): row = _matrix[row][int(digit)] return row == 0   _matrix = ( (0, 3, 1, 7, 5, 9, 8, 6, 4, 2), (7, 0, 9, 2, 1, 5, 4, 8, 6, 3), (4, 2, 0, 6, 8, 7, 1, 3, 5, 9), (1, 7, 5, 0, 9, 8, 3, 4, 2, 6), (6, 1, 2, 3, 0, 4, 5, 9, 7, 8), (3, 6, 7, 4, 2, 0, 9, 5, 8, 1), (5, 8, 6, 9, 7, 2, 0, 1, 3, 4), (8, 9, 4, 5, 3, 6, 2, 0, 1, 7), (9, 4, 3, 8, 6, 1, 7, 2, 0, 5), (2, 5, 8, 1, 4, 3, 6, 7, 9, 0) )   if __name__ == '__main__': for test in [5724, 5727, 112946]: print(f'{test}\t Validates as: {damm(test)}')
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.
#Phix
Phix
with javascript_semantics include mpfr.e integer np = 0, i = 2 mpz p3 = mpz_init(1*1*1), i3 = mpz_init(), p = mpz_init(), pn = mpz_init() printf(1,"The first 200 cuban primes are:\n") sequence first200 = {} atom t0 = time() constant lim = iff(platform()=JS?10000:100000) while np<lim do mpz_ui_pow_ui(i3,i,3) mpz_sub(p,i3,p3) if mpz_prime(p) then mpz_set(pn,p) np += 1 if np<=200 then first200 = append(first200,sprintf("%,9d",mpz_get_integer(pn))) if mod(np,10)=0 then printf(1,"%s\n",join(first200[-10..-1])) end if end if end if mpz_set(p3,i3) i += 1 end while printf(1,"\nThe %,dth cuban prime is %s\n",{np,mpz_get_str(pn,comma_fill:=true)}) {p3,i3,p} = mpz_free({p3,i3,p}) ?elapsed(time()-t0)
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.
#TXR
TXR
(op - 10 @1 @2 5)
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
#Vala
Vala
delegate double Dbl_Op(double d);   Dbl_Op curried_add(double a) { return (b) => a + b; }   void main() { print(@"$(curried_add(3.0)(4.0))\n"); double sum2 = curried_add(2.0) (curried_add(3.0)(4.0)); //sum2 = 9 print(@"$sum2\n"); }
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.
#Visual_Basic_.NET
Visual Basic .NET
Option Explicit On Option Infer On Option Strict On   Module Currying ' The trivial curry. Function Curry(Of T1, TResult)(func As Func(Of T1, TResult)) As Func(Of T1, TResult) ' At least satisfy the implicit contract that the result isn't reference-equal to the original function. Return Function(a) func(a) End Function   Function Curry(Of T1, T2, TResult)(func As Func(Of T1, T2, TResult)) As Func(Of T1, Func(Of T2, TResult)) Return Function(a) Function(b) func(a, b) End Function   Function Curry(Of T1, T2, T3, TResult)(func As Func(Of T1, T2, T3, TResult)) As Func(Of T1, Func(Of T2, Func(Of T3, TResult))) Return Function(a) Function(b) Function(c) func(a, b, c) End Function   ' And so on. End Module
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.
#Smalltalk
Smalltalk
DateTime extend [ setYear: aNum [ year := aNum ] ].   Object subclass: DateTimeTZ [ |dateAndTime timeZoneDST timeZoneName timeZoneVar|   DateTimeTZ class >> new [ ^(super basicNew) ]   DateTimeTZ class >> readFromWithMeridian: aStream andTimeZone: aDict [ |me| me := self new. ^ me initWithMeridian: aStream andTimeZone: aDict ]   initWithMeridian: aStream andTimeZone: aDict [ |s| dateAndTime := DateTime readFrom: aStream copy. s := aStream collection asString. s =~ '[pP][mM]' ifMatched: [ :m | dateAndTime := dateAndTime + (Duration days: 0 hours: 12 minutes: 0 seconds: 0) ]. aDict keysAndValuesDo: [ :k :v | s =~ k ifMatched: [ :x | dateAndTime := dateAndTime setOffset: (v at: 1). timeZoneDST := (v at: 2) setOffset: (v at: 1). timeZoneVar := (v at: 3). timeZoneDST setYear: (self year). "ignore the year" timeZoneName := k ] ]. ^ self ]   setYear: aNum [ dateAndTime setYear: aNum ] year [ ^ dateAndTime year ]   timeZoneName [ ^timeZoneName ]   + aDuration [ |n| n := dateAndTime + aDuration. (n > timeZoneDST) ifTrue: [ n := n + timeZoneVar ]. ^ (self copy dateTime: n) ]   dateTime [ ^dateAndTime ] dateTime: aDT [ dateAndTime := aDT ]   ].
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.
#MUMPS
MUMPS
  DOWHOLIDAY  ;In what years between 2008 and 2121 will December 25 be a Sunday?  ;Uses the VA's public domain routine %DTC (Part of the Kernel) named here DIDTC NEW BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y  ;BDT - the beginning year to check  ;EDT - the end year to check  ;BDT and EDT are year offsets from the epoch date 1/1/1700  ;CHECK - the month and day to look at  ;CHKFOR - what day of the week to look for  ;LIST - list of years in which the condition is true  ;I - the year currently being checked  ;X - the date in an "internal" format, for input to DOW^DIDTC  ;Y - the output from DOW^DIDTC SET BDT=308,EDT=421,CHECK="1225",CHKFOR=0,LIST="" FOR I=BDT:1:EDT SET X=I_CHECK D DOW^DIDTC SET:(Y=0) LIST=$SELECT($LENGTH(LIST):LIST_", ",1:"")_(I+1700) IF $LENGTH(LIST)=0 WRITE !,"There are no years that have Christmas on a Sunday in the given range." IF $LENGTH(LIST) WRITE !,"The following years have Christmas on a Sunday: ",LIST KILL BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y QUIT  
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.
#Nanoquery
Nanoquery
import Nanoquery.Util   // loop through the years 2008 through 2121 for year in range(2008, 2121) if (new(Date,"12/25/" + str(year)).getDayOfWeek() = "Sunday") println "In " + year + ", December 25th is a Sunday." end if end for
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
#Tcl
Tcl
proc ordinal-of-alpha {c} { ;# returns ordinal position of c in the alphabet (A=1, B=2...) lsearch {_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z} [string toupper $c] }   proc Cusip-Check-Digit {cusip} { ;# algorithm Cusip-Check-Digit(cusip) is if {[string length $cusip] != 8} { ;# Input: an 8-character CUSIP return false }   set sum 0 ;# sum := 0 for {set i 1} {$i <= 8} {incr i} { ;# for 1 ≤ i ≤ 8 do set c [string index $cusip $i-1] ;# c := the ith character of cusip if {[string is digit $c]} { ;# if c is a digit then set v $c ;# v := numeric value of the digit c } elseif {[string is alpha $c]} { ;# else if c is a letter then set p [ordinal-of-alpha $c] ;# p := ordinal position of c in the alphabet (A=1, B=2...) set v [expr {$p + 9}] ;# v := p + 9 } elseif {$c eq "*"} { ;# else if c = "*" then set v 36 ;# v := 36 } elseif {$c eq "@"} { ;# else if c = "@" then set v 37 ;# v := 37 } elseif {$c eq "#"} { ;# else if c = "#" then set v 38 ;# v := 38 } ;# end if if {$i % 2 == 0} { ;# if i is even then set v [expr {$v * 2}] ;# v := v × 2 } ;# end if   incr sum [expr {$v / 10 + $v % 10}] ;# sum := sum + int ( v div 10 ) + v mod 10 } ;# repeat   expr {(10 - ($sum % 10)) % 10} ;# return (10 - (sum mod 10)) mod 10 } proc check-cusip {cusip} { set last [string index $cusip end] set cusip [string range $cusip 0 end-1] expr {$last eq [Cusip-Check-Digit $cusip]} }
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.
#CLU
CLU
prompt = proc (s: string) returns (int) stream$puts(stream$primary_output(), s) return(int$parse(stream$getl(stream$primary_input()))) end prompt   start_up = proc () po: stream := stream$primary_output()    % Ask for width and height width: int := prompt("Width? ") height: int := prompt("Height? ")    % Create an array of arrays.  % In order to actually create separate arrays, rather than repeating  % a reference to the same array over and over, fill_copy must be used. arr: array[array[int]] := array[array[int]]$fill_copy(1, width, array[int]$fill(1, height, 0))    % Set a value x: int := 1+width/2 y: int := 1+height/2 arr[x][y] := 123    % Retrieve the value stream$putl(po, "arr[" || int$unparse(x) || "][" || int$unparse(y) || "] = " || int$unparse(arr[x][y]))    % The array will be automatically garbage-collected once there  % are no more references to it. end start_up
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.
#Common_Lisp
Common Lisp
(let ((d1 (read)) (d2 (read))) (assert (and (typep d1 '(integer 1)) (typep d2 '(integer 1))) (d1 d2)) (let ((array (make-array (list d1 d2) :initial-element nil)) (p1 0) (p2 (floor d2 2))) (setf (aref array p1 p2) t) (print (aref array p1 p2))))
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
#Fortran
Fortran
  program standard_deviation implicit none integer(kind=4), parameter :: dp = kind(0.0d0)   real(kind=dp), dimension(:), allocatable :: vals integer(kind=4) :: i   real(kind=dp), dimension(8) :: sample_data = (/ 2, 4, 4, 4, 5, 5, 7, 9 /)   do i = lbound(sample_data, 1), ubound(sample_data, 1) call sample_add(vals, sample_data(i)) write(*, fmt='(''#'',I1,1X,''value = '',F3.1,1X,''stddev ='',1X,F10.8)') & i, sample_data(i), stddev(vals) end do   if (allocated(vals)) deallocate(vals) contains ! Adds value :val: to array :population: dynamically resizing array subroutine sample_add(population, val) real(kind=dp), dimension(:), allocatable, intent (inout) :: population real(kind=dp), intent (in) :: val   real(kind=dp), dimension(:), allocatable :: tmp integer(kind=4) :: n   if (.not. allocated(population)) then allocate(population(1)) population(1) = val else n = size(population) call move_alloc(population, tmp)   allocate(population(n + 1)) population(1:n) = tmp population(n + 1) = val endif end subroutine sample_add   ! Calculates standard deviation for given set of values real(kind=dp) function stddev(vals) real(kind=dp), dimension(:), intent(in) :: vals real(kind=dp) :: mean integer(kind=4) :: n   n = size(vals) mean = sum(vals)/n stddev = sqrt(sum((vals - mean)**2)/n) end function stddev end program standard_deviation  
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string: The quick brown fox jumps over the lazy dog
#Go
Go
package main   import ( "fmt" "hash/crc32" )   func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
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
#Groovy
Groovy
def crc32(byte[] bytes) { new java.util.zip.CRC32().with { update bytes; value } }
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.
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { print cc(100) exit }   function cc(amount, coins, numPennies, numNickles, numQuarters, p, n, d, q, s, count) { numPennies = amount numNickles = int(amount / 5) numDimes = int(amount / 10) numQuarters = int(amount / 25)   count = 0 for (p = 0; p <= numPennies; p++) { for (n = 0; n <= numNickles; n++) { for (d = 0; d <= numDimes; d++) { for (q = 0; q <= numQuarters; q++) { s = p + n * 5 + d * 10 + q * 25; if (s == 100) count++; } } } } return count; }  
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
#Action.21
Action!
BYTE FUNC CountSubstring(CHAR ARRAY s,sub) BYTE i,j,res,found   i=1 res=0 WHILE i-1+sub(0)<=s(0) DO found=1 FOR j=1 TO sub(0) DO IF s(j+i-1)#sub(j) THEN found=0 EXIT FI OD   IF found=1 THEN i==+sub(0) res==+1 ELSE i==+1 FI OD RETURN (res)   PROC Test(CHAR ARRAY s,sub) BYTE c   c=CountSubstring(s,sub) PrintF("%B ""%S"" in ""%S""%E",c,sub,s) RETURN   PROC Main() Test("the three truths","th") Test("ababababab","abab") Test("11111111","11") Test("abcdefg","123") RETURN
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
#Ada
Ada
with Ada.Strings.Fixed, Ada.Integer_Text_IO;   procedure Substrings is begin Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "the three truths", Pattern => "th")); Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab", Pattern => "abab")); end Substrings;
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.
#Action.21
Action!
PROC PrintOctal(CARD v) CHAR ARRAY a(6) BYTE i=[0]   DO a(i)=(v&7)+'0 i==+1 v=v RSH 3 UNTIL v=0 OD   DO i==-1 Put(a(i)) UNTIL i=0 OD RETURN   PROC Main() CARD i=[0]   DO PrintF("decimal=%U octal=",i) PrintOctal(i) PutE() i==+1 UNTIL i=0 OD RETURN
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.
#Ada
Ada
with Ada.Text_IO;   procedure Octal is package IIO is new Ada.Text_IO.Integer_IO(Integer); begin for I in 0 .. Integer'Last loop IIO.Put(I, Base => 8); Ada.Text_IO.New_Line; end loop; end Octal;
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
#Ada
Ada
with Ada.Command_Line, Ada.Text_IO, Prime_Numbers;   procedure Count is package Prime_Nums is new Prime_Numbers (Number => Natural, Zero => 0, One => 1, Two => 2); use Prime_Nums;   procedure Put (List : Number_List) is begin for Index in List'Range loop Ada.Text_IO.Put (Integer'Image (List (Index))); if Index /= List'Last then Ada.Text_IO.Put (" x"); end if; end loop; end Put;   N  : Natural := 1; Max_N : Natural := 15; -- the default for Max_N begin if Ada.Command_Line.Argument_Count = 1 then -- read Max_N from command line Max_N := Integer'Value (Ada.Command_Line.Argument (1)); end if; -- else use the default loop Ada.Text_IO.Put (Integer'Image (N) & ": "); Put (Decompose (N)); Ada.Text_IO.New_Line; N := N + 1; exit when N > Max_N; end loop; end Count;
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.
#AWK
AWK
#!/usr/bin/awk -f BEGIN { print "<table>\n <thead align = \"right\">" printf " <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = \"right\">\n" for (i=1; i<=10; i++) { printf " <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n",i, 10*i, 100*i, 1000*i-1 } print " </tbody>\n</table>\n" }
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Maple
Maple
  with(StringTools); FormatTime("%Y-%m-%d") FormatTime("%A,%B %d, %y")  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DateString[{"Year", "-", "Month", "-", "Day"}] DateString[{"DayName", ", ", "MonthName", " ", "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.
#EchoLisp
EchoLisp
  (lib 'matrix) (string-delimiter "") (define (cramer A B (X)) ;; --> vector X (define ∆ (determinant A)) (for/vector [(i (matrix-col-num A))] (set! X (matrix-set-col! (array-copy A) i B)) (// (determinant X) ∆)))   (define (task) (define A (list->array '( 2 -1 5 1 3 2 2 -6 1 3 3 -1 5 -2 -3 3) 4 4)) (define B #(-3 -32 -47 49)) (writeln "Solving A * X = B") (array-print A) (writeln "B = " B) (writeln "X = " (cramer A B)))  
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.
#Bracmat
Bracmat
put$(,"output.txt",NEW)
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.
#C
C
#include <stdio.h>   int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh);   return 0; }
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#C.2B.2B
C++
#include <string> #include <boost/regex.hpp> #include <iostream>   std::string csvToHTML( const std::string & ) ;   int main( ) { std::string text = "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!\n" ; std::cout << csvToHTML( text ) ; return 0 ; }   std::string csvToHTML( const std::string & csvtext ) { //the order of the regexes and the replacements is decisive! std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
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.
#Groovy
Groovy
def csv = [] def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } } def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }   loadCsv new File('csv.txt') csv[0][0] = 'Column0' (1..4).each { i -> csv[i][i] = i * 100 } saveCsv new File('csv_out.txt')
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.
#Quackery
Quackery
[ 0 swap witheach [ char 0 - dip [ 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 ] ] peek ] ] is damm ( $ --> n )   [ damm 0 = ] is dammvalid ( $ --> b )   [ dup echo$ say " is " dammvalid not if [ say "not " ] say "valid." cr ] is validate ( & --> )   $ "5724 5725 112946 112949" nest$ witheach validate
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.
#R
R
Damm_algo <- function(number){ row_i = 0   iterable = strsplit(toString(number), "")[[1]]   validation_matrix = matrix( c( 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), nrow = 10, ncol = 10, byrow = T )   for(digit in as.integer(iterable)){ row_i = validation_matrix[row_i + 1, digit + 1] #in R indexes start from 1 and not from zero }   test <- ifelse(row_i == 0, "VALID", "NOT VALID") message(paste("Number", number, "is", test)) }   for(number in c(5724, 5727, 112946, 112949)){ Damm_algo(number) }
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.
#Python
Python
  import datetime import math   primes = [ 3, 5 ]   cutOff = 200   bigUn = 100_000 chunks = 50 little = bigUn / chunks   tn = " cuban prime" print ("The first {:,}{}s:".format(cutOff, tn))   c = 0 showEach = True u = 0 v = 1 st = datetime.datetime.now()   for i in range(1, int(math.pow(2,20))): found = False u += 6 v += u mx = int(math.sqrt(v))   for item in primes: if (item > mx): break if (v % item == 0): found = True break   if (found == 0): c += 1 if (showEach): z = primes[-1] while (z <= v - 2): z += 2   fnd = False for item in primes: if (item > mx): break if (z % item == 0): fnd = True break   if (not fnd): primes.append(z)   primes.append(v) print("{:>11,}".format(v), end='')   if (c % 10 == 0): print(""); if (c == cutOff): showEach = False print ("Progress to the {:,}th {}:".format(bigUn, tn), end='') if (c % little == 0): print('.', end='') if (c == bigUn): break   print(""); print ("The {:,}th{} is {:,}".format(c, tn, v)) print("Computation time was {} seconds".format((datetime.datetime.now() - st).seconds))  
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.
#Wortel
Wortel
@let { addOne \+ 1 subtractFrom1 \- 1 subtract1 \~- 1   subtract1_2 &\- [. 1]   add ^+  ; partial apply to named functions addOne_2 \add 1    ; testing [[  !addOne 5 ; returns 6  !subtractFrom1 5 ; returns -4  !subtract1 5 ; returns 4  !subtract1_2 5 ; returns 4  !addOne_2 5 ; returns 6 ]] }
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.
#Wren
Wren
var addN = Fn.new { |n| Fn.new { |x| n + x } }   var adder = addN.call(40) System.print("The answer to life is %(adder.call(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.
#Z80_Assembly
Z80 Assembly
macro ResetCursors ld hl,&0101 call &BB75 endm
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.
#SQL
SQL
  -- March 7 2009 7:30pm EST   SELECT TO_TIMESTAMP_TZ( 'March 7 2009 7:30pm EST', 'MONTH DD YYYY HH:MIAM TZR' ) at TIME zone 'US/Eastern' orig_dt_time FROM dual;   -- 12 hours later DST change   SELECT (TO_TIMESTAMP_TZ( 'March 7 2009 7:30pm EST', 'MONTH DD YYYY HH:MIAM TZR' )+ INTERVAL '12' HOUR) at TIME zone 'US/Eastern' plus_12_dst FROM dual;   -- 12 hours later no DST change -- Arizona time, always MST   SELECT (TO_TIMESTAMP_TZ( 'March 7 2009 7:30pm EST', 'MONTH DD YYYY HH:MIAM TZR' )+ INTERVAL '12' HOUR) at TIME zone 'US/Arizona' plus_12_nodst FROM dual;  
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.
#Standard_ML
Standard ML
  val smltime= fn input => (* parse given format *) let val mth::day::year::itime::t = String.fields Char.isSpace input ; val tmp = String.fields (fn x=> x= #":") itime; val h = (valOf(Int.fromString (hd tmp) )) + (if String.isSuffix "pm" (hd(tl tmp)) then 12 else 0 ) ; val ms = (String.extract (hd (tl tmp), 0 ,SOME 2))^":00" ; val mth = String.extract (mth,0,SOME 3) in (* Sat is a dummy *) Date.fromString ("Sat "^mth ^" " ^ (StringCvt.padLeft #"0" 2 day) ^ " "^(StringCvt.padLeft #"0" 2 (Int.toString h))^":" ^ ms^" "^ year )   end;     local val date2real = Time.toReal o Date.toTime o valOf val onehour = date2real ( Date.fromString "Mon Jan 01 23:59:59 1973" ) - ( date2real ( Date.fromString "Mon Jan 01 22:59:59 1973" )) ; in val hoursFrom = fn hours => fn from => (Date.fromTimeLocal o Time.fromReal)( ( date2real from) + hours * onehour ); end;  
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   yearRanges = [int 2008, 2121] searchday = '' cal = Calendar   loop year = yearRanges[0] to yearRanges[1] cal = GregorianCalendar(year, Calendar.DECEMBER, 25) dayIndex = cal.get(Calendar.DAY_OF_WEEK) if dayIndex = Calendar.SUNDAY then searchday = searchday year end year   say 'Between' yearRanges[0] 'and' yearRanges[1]', Christmas day falls on a Sunday on the following years:' searchday = searchday.strip.changestr(' ', ',') say ' 'searchday   return  
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.
#Nim
Nim
import times   for year in 2008..2121: if getDayOfWeek(25, mDec, year) == dSun: stdout.write year, ' ' echo ""
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
#VBA
VBA
Private Function Cusip_Check_Digit(s As Variant) As Integer Dim Sum As Integer, c As String, v As Integer For i = 1 To 8 c = Mid(s, i, 1) If IsNumeric(c) Then v = Val(c) Else Select Case c Case "a" To "z" v = Asc(c) - Asc("a") + 10 Case "A" To "Z" v = Asc(c) - Asc("A") + 10 Case "*" v = 36 Case "@" v = 37 Case "#" v = 38 Case Else Debug.Print "not expected" End Select End If If i Mod 2 = 0 Then v = v * 2 Sum = Sum + Int(v \ 10) + v Mod 10 Next i Cusip_Check_Digit = (10 - (Sum Mod 10)) Mod 10 End Function
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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function IsCUSIP(s As String) As Boolean If s.Length <> 9 Then Return False End If   Dim sum = 0 For i = 0 To 7 Dim c = s(i)   Dim v As Integer If "0" <= c AndAlso c <= "9" Then v = Asc(c) - 48 ElseIf "A" <= c AndAlso c <= "Z" Then v = Asc(c) - 55 ' Lower case letters are apparently invalid ElseIf c = "*" Then v = 36 ElseIf c = "#" Then v = 38 Else Return False End If   If i Mod 2 = 1 Then v *= 2 ' check if odd as using 0-based indexing End If sum += v \ 10 + v Mod 10 Next Return Asc(s(8)) - 48 = (10 - (sum Mod 10)) Mod 10 End Function   Sub Main() Dim candidates As New List(Of String) From { "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" }   For Each candidate In candidates Console.WriteLine("{0} -> {1}", candidate, If(IsCUSIP(candidate), "correct", "incorrect")) Next End Sub   End Module
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.
#Component_Pascal
Component Pascal
  MODULE TestArray; (* Implemented in BlackBox Component Builder *)   IMPORT Out;   (* Open array *)   PROCEDURE DoTwoDim*; VAR d: POINTER TO ARRAY OF ARRAY OF INTEGER; BEGIN NEW(d, 5, 4); (* allocating array in memory *) d[1, 2] := 100; (* second row, third column element *) d[4, 3] := -100; (* fifth row, fourth column element *) Out.Int(d[1, 2], 0); Out.Ln; Out.Int(d[4, 3], 0); Out.Ln; END DoTwoDim;   END TestArray.
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function calcStandardDeviation(number As Double) As Double Static a() As Double Redim Preserve a(0 To UBound(a) + 1) Dim ub As UInteger = UBound(a) a(ub) = number Dim sum As Double = 0.0 For i As UInteger = 0 To ub sum += a(i) Next Dim mean As Double = sum / (ub + 1) Dim diff As Double sum = 0.0 For i As UInteger = 0 To ub diff = a(i) - mean sum += diff * diff Next Return Sqr(sum/ (ub + 1)) End Function   Dim a(0 To 7) As Double = {2, 4, 4, 4, 5, 5, 7, 9}   For i As UInteger = 0 To 7 Print "Added"; a(i); " SD now : "; calcStandardDeviation(a(i)) Next   Print Print "Press any key to quit" Sleep
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
#Haskell
Haskell
import Data.Bits ((.&.), complement, shiftR, xor) import Data.Word (Word32) import Numeric (showHex)   crcTable :: Word32 -> Word32 crcTable = (table !!) . fromIntegral where table = ((!! 8) . iterate xf) <$> [0 .. 255] shifted x = shiftR x 1 xf r | r .&. 1 == 1 = xor (shifted r) 0xedb88320 | otherwise = shifted r   charToWord :: Char -> Word32 charToWord = fromIntegral . fromEnum   calcCrc :: String -> Word32 calcCrc = complement . foldl cf (complement 0) where cf crc x = xor (shiftR crc 8) (crcTable $ xor (crc .&. 0xff) (charToWord x))   crc32 :: String -> String crc32 = flip showHex [] . calcCrc   main :: IO () main = putStrLn $ 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.
#BBC_BASIC
BBC BASIC
DIM uscoins%(3) uscoins%() = 1, 5, 10, 25 PRINT FNchange(100, uscoins%()) " ways of making $1" PRINT FNchange(1000, uscoins%()) " ways of making $10"   DIM ukcoins%(7) ukcoins%() = 1, 2, 5, 10, 20, 50, 100, 200 PRINT FNchange(100, ukcoins%()) " ways of making £1" PRINT FNchange(1000, ukcoins%()) " ways of making £10" END   DEF FNchange(sum%, coins%()) LOCAL C%, D%, I%, N%, P%, Q%, S%, table() C% = 0 N% = DIM(coins%(),1) + 1 FOR I% = 0 TO N% - 1 D% = coins%(I%) IF D% <= sum% IF D% >= C% C% = D% + 1 NEXT C% *= N% DIM table(C%-1) FOR I% = 0 TO N%-1 : table(I%) = 1 : NEXT   P% = N% FOR S% = 1 TO sum% FOR I% = 0 TO N% - 1 IF I% = 0 IF P% >= C% P% = 0 IF coins%(I%) <= S% THEN Q% = P% - coins%(I%) * N% IF Q% >= 0 table(P%) = table(Q%) ELSE table(P%) = table(Q% + C%) ENDIF IF I% table(P%) += table(P% - 1) P% += 1 NEXT NEXT = table(P%-1)  
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h>   // ad hoc 128 bit integer type; faster than using GMP because of low // overhead typedef struct { uint64_t x[2]; } i128;   // display in decimal void show(i128 v) { uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32}; int i, j = 0, len = 4; char buf[100]; do { uint64_t c = 0; for (i = len; i--; ) { c = (c << 32) + x[i]; x[i] = c / 10, c %= 10; }   buf[j++] = c + '0'; for (len = 4; !x[len - 1]; len--); } while (len);   while (j--) putchar(buf[j]); putchar('\n'); }   i128 count(int sum, int *coins) { int n, i, k; for (n = 0; coins[n]; n++);   i128 **v = malloc(sizeof(int*) * n); int *idx = malloc(sizeof(int) * n);   for (i = 0; i < n; i++) { idx[i] = coins[i]; // each v[i] is a cyclic buffer v[i] = calloc(sizeof(i128), coins[i]); }   v[0][coins[0] - 1] = (i128) {{1, 0}};   for (k = 0; k <= sum; k++) { for (i = 0; i < n; i++) if (!idx[i]--) idx[i] = coins[i] - 1;   i128 c = v[0][ idx[0] ];   for (i = 1; i < n; i++) { i128 *p = v[i] + idx[i];   // 128 bit addition p->x[0] += c.x[0]; p->x[1] += c.x[1]; if (p->x[0] < c.x[0]) // carry p->x[1] ++; c = *p; } }   i128 r = v[n - 1][idx[n-1]];   for (i = 0; i < n; i++) free(v[i]); free(v); free(idx);   return r; }   // simple recursive method; slow int count2(int sum, int *coins) { if (!*coins || sum < 0) return 0; if (!sum) return 1; return count2(sum - *coins, coins) + count2(sum, coins + 1); }   int main(void) { int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 }; int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 };   show(count( 100, us_coins + 2)); show(count( 1000, us_coins));   show(count( 1000 * 100, us_coins)); show(count( 10000 * 100, us_coins)); show(count(100000 * 100, us_coins));   putchar('\n');   show(count( 1 * 100, eu_coins)); show(count( 1000 * 100, eu_coins)); show(count( 10000 * 100, eu_coins)); show(count(100000 * 100, eu_coins));   return 0; }
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
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PROC count string in string = (STRING needle, haystack)INT: ( INT start:=LWB haystack, next, out:=0; FOR count WHILE string in string(needle, next, haystack[start:]) DO start+:=next+UPB needle-LWB needle; out:=count OD; out );   printf(($d" "$, count string in string("th", "the three truths"), # expect 3 # count string in string("abab", "ababababab"), # expect 2 # count string in string("a*b", "abaabba*bbaba*bbab"), # expect 2 # $l$ ))
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
#Apex
Apex
  String substr = 'ABC'; String str = 'ABCZZZABCYABCABCXXABC'; Integer substrLen = substr.length(); Integer count = 0; Integer index = str.indexOf(substr); while (index >= 0) { count++; str = str.substring(index+substrLen); index = str.indexOf(substr); } System.debug('Count String : '+count);  
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.
#Aime
Aime
integer o;   o = 0; do { o_xinteger(8, o); o_byte('\n'); o += 1; } while (0 < o);
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.
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   INT oct width = (bits width-1) OVER 3 + 1; main: ( FOR i TO 17 # max int # DO printf(($"8r"8r n(oct width)dl$, BIN i)) OD )
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
#ALGOL_68
ALGOL 68
OP +:= = (REF FLEX []INT a, INT b) VOID: BEGIN [⌈a + 1] INT c; c[:⌈a] := a; c[⌈a+1:] := b; a := c END;     PROC factorize = (INT nn) []INT: BEGIN IF nn = 1 THEN (1) ELSE INT k := 2, n := nn; FLEX[0]INT result; WHILE n > 1 DO WHILE n MOD k = 0 DO result +:= k; n := n % k OD; k +:= 1 OD; result FI END;   FLEX[0]INT factors; FOR i TO 22 DO factors := factorize (i); print ((whole (i, 0), " = ")); FOR j TO UPB factors DO (j /= 1 | print (" × ")); print ((whole (factors[j], 0))) OD; print ((new line)) OD
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.
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion :: It's easier and neater to create the variables holding the random 4 digit numbers ahead of time for /l %%i in (1,1,12) do set /a rand%%i=!random! %% 9999 :: The command output of everything within the brackets is sent to the file "table.html", overwriting anything already in there ( echo ^<html^>^<head^>^</head^>^<body^> echo ^<table border=1 cellpadding=10 cellspacing=0^> echo ^<tr^>^<th^>^</th^> echo ^<th^>X^</th^> echo ^<th^>Y^</th^> echo ^<th^>Z^</th^> echo ^</tr^> echo ^<tr^>^<th^>1^</th^> echo ^<td align="right"^>%rand1%^</td^> echo ^<td align="right"^>%rand2%^</td^> echo ^<td align="right"^>%rand3%^</td^> echo ^</tr^> echo ^<tr^>^<th^>2^</th^> echo ^<td align="right"^>%rand4%^</td^> echo ^<td align="right"^>%rand5%^</td^> echo ^<td align="right"^>%rand6%^</td^> echo ^</tr^> echo ^<tr^>^<th^>3^</th^> echo ^<td align="right"^>%rand7%^</td^> echo ^<td align="right"^>%rand8%^</td^> echo ^<td align="right"^>%rand9%^</td^> echo ^</tr^> echo ^<tr^>^<th^>4^</th^> echo ^<td align="right"^>%rand10%^</td^> echo ^<td align="right"^>%rand11%^</td^> echo ^<td align="right"^>%rand12%^</td^> echo ^</tr^> echo ^</table^> echo ^</body^>^</html^> ) > table.html start table.html  
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
#MATLAB_.2F_Octave
MATLAB / Octave
>> datestr(now,'yyyy-mm-dd')   ans =   2010-06-18   >> datestr(now,'dddd, mmmm dd, yyyy')   ans =   Friday, June 18, 2010
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
#min
min
("YYYY-MM-dd" "dddd, MMMM dd, YYYY") ('timestamp dip tformat puts!) foreach
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.
#Factor
Factor
USING: kernel math math.matrices.laplace prettyprint sequences ; IN: rosetta-code.cramers-rule   : replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;   : solve ( m v -- seq ) dup length <iota> [ rot [ replace-col ] keep [ determinant ] bi@ / ] 2with map ;   : cramers-rule-demo ( -- ) { { 2 -1 5 1 } { 3 2 2 -6 } { 1 3 3 -1 } { 5 -2 -3 3 } } { -3 -32 -47 49 } solve . ;   MAIN: cramers-rule-demo
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.
#Fortran
Fortran
DATA A/2, -1, 5, 1 1 3, 2, 2, -6 2 1, 3, 3, -1 3 5, -2, -3, 3/
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.
#C.23
C#
using System; using System.IO;   class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt");   Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\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.
#C.2B.2B
C++
#include <direct.h> #include <fstream>   int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close();   _mkdir("docs"); _mkdir("/docs");   return 0; }
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#Clojure
Clojure
  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.
#Haskell
Haskell
import Data.Array (Array(..), (//), bounds, elems, listArray) import Data.List (intercalate) import Control.Monad (when) import Data.Maybe (isJust)   delimiters :: String delimiters = ",;:"   fields :: String -> [String] fields [] = [] fields xs = let (item, rest) = break (`elem` delimiters) xs (_, next) = break (`notElem` delimiters) rest in item : fields next   unfields :: Maybe (Array (Int, Int) String) -> [String] unfields Nothing = [] unfields (Just a) = every fieldNumber $ elems a where ((_, _), (_, fieldNumber)) = bounds a every _ [] = [] every n xs = let (y, z) = splitAt n xs in intercalate "," y : every n z   fieldArray :: [[String]] -> Maybe (Array (Int, Int) String) fieldArray [] = Nothing fieldArray xs = Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs   fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String)) fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile   fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO () fieldsToFile f = writeFile f . unlines . unfields   someChanges :: Maybe (Array (Int, Int) String) -> Maybe (Array (Int, Int) String) someChanges = fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])   main :: IO () main = do a <- fieldsFromFile "example.txt" when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
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.
#Racket
Racket
#lang racket/base (require racket/match)   (define operation-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)))   (define (integer->digit-list n) (let loop ((n n) (a null)) (if (zero? n) a (let-values (([q r] (quotient/remainder n 10))) (loop q (cons r a))))))   (define/match (check-digit n) [((list ds ...)) (foldl (λ (d interim) (vector-ref (vector-ref operation-table interim) d)) 0 ds)] [((? integer? i)) (check-digit (integer->digit-list i))])   (define/match (valid-number? n) [((? integer? i)) (valid-number? (integer->digit-list i))] [((list ds ...)) (zero? (check-digit ds))])   (module+ test (require rackunit) (check-equal? (integer->digit-list 572) '(5 7 2)) (check-equal? (check-digit 572) 4) (check-equal? (check-digit '(5 7 2)) 4) (check-true (valid-number? 5724)) (check-false (valid-number? 5274)) (check-true (valid-number? 112946)))
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Raku
Raku
sub damm ( *@digits ) { my @tbl = [0, 3, 1, 7, 5, 9, 8, 6, 4, 2], [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], [5, 8, 6, 9, 7, 2, 0, 1, 3, 4], [8, 9, 4, 5, 3, 6, 2, 0, 1, 7], [9, 4, 3, 8, 6, 1, 7, 2, 0, 5], [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]; my $row = 0; for @digits -> $col { $row = @tbl[$row][$col] } not $row }   # Testing for 5724, 5727, 112946 { say "$_:\tChecksum digit { damm( $_.comb ) ?? '' !! 'in' }correct." }
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.
#Racket
Racket
#lang racket   (require math/number-theory racket/generator)   (define (make-cuban-prime-generator) (generator () (let loop ((y 1) (y3 1)) (let* ((x (+ y 1)) (x3 (expt x 3)) (p (quotient (- x3 y3) (- x y)))) (when (prime? p) (yield p)) (loop x x3)))))   (define (tabulate l (line-width 80)) (let* ((w (add1 (string-length (argmax string-length (map ~a l))))) (cols (quotient line-width w))) (for ((n (in-range 1 (add1 (length l)))) (i l)) (display (~a i #:width w #:align 'right)) (when (zero? (modulo n cols)) (newline)))))   (define (progress-report x) (when (zero? (modulo x 1000)) (eprintf (if (zero? (modulo x 10000)) "|" ".")) (flush-output (current-error-port))))   (let ((200-cuban-primes (for/list ((_ 200) (p (in-producer (make-cuban-prime-generator)))) p))) (tabulate 200-cuban-primes))   (begin0 (for/last ((x 100000) (p (in-producer (make-cuban-prime-generator)))) (progress-report x) p) (newline))
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.
#Raku
Raku
use Lingua::EN::Numbers; use ntheory:from<Perl5> <:all>;   my @cubans = lazy (1..Inf).map({ ($_+1)³ - .³ }).grep: *.&is_prime;   put @cubans[^200]».&comma».fmt("%9s").rotor(10).join: "\n";   put '';   put @cubans[99_999].&comma; # zero indexed
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.
#zkl
zkl
addOne:= Op("+").fp(1); addOne(5) //-->6 minusOne:=Op("-").fp1(1); minusOne(5) //-->4, note that this fixed 1 as the second parameter // fix first and third parameters: foo:=String.fpM("101","<foo>","</foo>"); foo("zkl"); //-->"<foo>zkl</foo>" fcn g(x){x+1} f:=fcn(f,x){f(x)+x}.fp(g); f(5); //-->11 f:=fcn(f,x){f(x)+x}.fp(fcn(x){x+1}); // above with lambdas all the way down
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.
#Swift
Swift
import Foundation   let formatter = DateFormatter()   formatter.dateFormat = "MMMM dd yyyy hh:mma zzz"   guard let date = formatter.date(from: "March 7 2009 7:30pm EST") else { fatalError() }   print(formatter.string(from: date)) print(formatter.string(from: date + 60 * 60 * 12))
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.
#Tcl
Tcl
set date "March 7 2009 7:30pm EST" set epoch [clock scan $date -format "%B %d %Y %I:%M%p %z"] set later [clock add $epoch 12 hours] puts [clock format $later] ;# Sun Mar 08 08:30:00 EDT 2009 puts [clock format $later -timezone :Asia/Shanghai] ;# Sun Mar 08 20:30:00 CST 2009
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.
#Oberon-2
Oberon-2
  MODULE DayOfWeek; IMPORT NPCT:Dates, Out; VAR year: INTEGER; date: Dates.Date; BEGIN FOR year := 2008 TO 2121 DO date := Dates.NewDate(25,12,year); IF date.DayOfWeek() = Dates.sunday THEN Out.Int(date.year,4);Out.Ln END END END DayOfWeek.  
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
#Vlang
Vlang
fn is_cusip(s string) bool { if s.len != 9 { return false } mut sum := 0 for i in 0..8 { c := s[i] mut v :=0 match true { c >= '0'[0] && c <= '9'[0] { v = c - 48 } c >= 'A'[0] && c <= 'Z'[0] { v = c - 55 } c == '*'[0] { v = 36 } c == '@'[0] { v = 37 } c == '#'[0] { v = 38 } else { return false } } if i % 2 == 1 { v *= 2 } // check if odd as using 0-based indexing sum += v/10 + v%10 } return int(s[8]) - 48 == (10 - (sum%10)) % 10 }   fn main() { candidates := [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105", ]   for candidate in candidates { mut b :=' ' if is_cusip(candidate) { b = "correct" } else { b = "incorrect" } println("$candidate -> $b") } }
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
#Wren
Wren
var isCusip = Fn.new { |s| if (s.count != 9) return false var sum = 0 for (i in 0..7) { var c = s[i].bytes[0] var v if (c >= 48 && c <= 57) { // '0' to '9' v = c - 48 } else if (c >= 65 && c <= 90) { // 'A' to 'Z' v = c - 55 } else if (s[i] == "*") { v = 36 } else if (s[i] == "@") { v = 37 } else if (s[i] == "#") { v = 38 } else { return false } if (i%2 == 1) v = v * 2 // check if odd as using 0-based indexing sum = sum + (v/10).floor + v%10 } return s[8].bytes[0] - 48 == (10 - (sum%10)) % 10 }   var candidates = [ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" ] for (candidate in candidates) { var b = (isCusip.call(candidate)) ? "correct" : "incorrect" System.print("%(candidate) -> %(b)") }
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.
#Crystal
Crystal
require "random"   first = gets.not_nil!.to_i32 second = gets.not_nil!.to_i32   arr = Array(Array(Int32)).new(first, Array(Int32).new second, 0)   random = Random.new   first = random.rand 0..(first - 1) second = random.rand 0..(second - 1)   arr[first][second] = random.next_int puts arr[first][second]
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
#Go
Go
package main   import ( "fmt" "math" )   func newRsdv() func(float64) float64 { var n, a, q float64 return func(x float64) float64 { n++ a1 := a+(x-a)/n q, a = q+(x-a)*(x-a1), a1 return math.Sqrt(q/n) } }   func main() { r := newRsdv() for _, x := range []float64{2,4,4,4,5,5,7,9} { fmt.Println(r(x)) } }
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
#Haxe
Haxe
using StringTools;   class Main { static function main() { var data = haxe.io.Bytes.ofString("The quick brown fox jumps over the lazy dog"); var crc = haxe.crypto.Crc32.make(data); Sys.println(crc.hex()); } }
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
#Icon_and_Unicon
Icon and Unicon
link hexcvt,printf   procedure main() s := "The quick brown fox jumps over the lazy dog" a := "414FA339" printf("crc(%i)=%s - implementation is %s\n", s,r := crc32(s),if r == a then "correct" else "in error") end   procedure crc32(s) #: return crc-32 (ISO 3309, ITU-T V.42, Gzip, PNG) of s static crcL,mask initial { crcL := list(256) # crc table p := [0,1,2,4,5,7,8,10,11,12,16,22,23,26] # polynomial terms mask := 2^32-1 # word size mask every (poly := 0) := ior(poly,ishift(1,31-p[1 to *p])) every c := n := 0 to *crcL-1 do { # table every 1 to 8 do c := iand(mask, if iand(c,1) = 1 then ixor(poly,ishift(c,-1)) else ishift(c,-1) ) crcL[n+1] := c } }   crc := ixor(0,mask) # invert bits every crc := iand(mask, ixor(crcL[iand(255,ixor(crc,ord(!s)))+1],ishift(crc,-8))) return hexstring(ixor(crc,mask)) # return hexstring end
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#C.23
C#
  // Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ class Program { static long Count(int[] C, int m, int n) { var table = new long[n + 1]; table[0] = 1; for (int i = 0; i < m; i++) for (int j = C[i]; j <= n; j++) table[j] += table[j - C[i]]; return table[n]; } static void Main(string[] args) { var C = new int[] { 1, 5, 10, 25 }; int m = C.Length; int n = 100; Console.WriteLine(Count(C, m, n)); //242 Console.ReadLine(); } }  
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
#APL
APL
csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵}
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
#AppleScript
AppleScript
use framework "OSAKit"   on run {countSubstring("the three truths", "th"), ¬ countSubstring("ababababab", "abab")} end run   on countSubstring(str, subStr) return evalOSA("JavaScript", "var matches = '" & str & "'" & ¬ ".match(new RegExp('" & subStr & "', 'g'));" & ¬ "matches ? matches.length : 0") as integer end countSubstring   -- evalOSA :: ("JavaScript" | "AppleScript") -> String -> String on evalOSA(strLang, strCode)   set ca to current application set oScript to ca's OSAScript's alloc's initWithSource:strCode ¬ |language|:(ca's OSALanguage's languageForName:(strLang))   set {blnCompiled, oError} to oScript's compileAndReturnError:(reference)   if blnCompiled then set {oDesc, oError} to oScript's executeAndReturnError:(reference) if (oError is missing value) then return oDesc's stringValue as text end if   return oError's NSLocalizedDescription as text end evalOSA
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.
#ALGOL_W
ALGOL W
begin string(12) r; string(8) octDigits; integer number; octDigits := "01234567"; number  := -1; while number < MAXINTEGER do begin integer v, cPos; number := number + 1; v  := number;  % build a string of octal digits in r, representing number %  % Algol W uses 32 bit integers, so r should be big enough  %  % the most significant digit is on the right  % cPos  := 0; while begin r( cPos // 1 ) := octDigits( v rem 8 // 1 ); v := v div 8; ( v > 0 ) end do begin cPos := cPos + 1 end while_v_gt_0;  % show most significant digit on a newline % write( r( cPos // 1 ) );  % continue the line with the remaining digits (if any) % for c := cPos - 1 step -1 until 0 do writeon( r( c // 1 ) ) end while_r_lt_MAXINTEGER end.
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.
#APL
APL
10⊥¨8∘⊥⍣¯1¨⍳100000
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program countFactors.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc" .equ NBFACT, 33 .equ MAXI, 1<<31   //.equ NOMBRE, 65537 //.equ NOMBRE, 99999999 .equ NOMBRE, 2144 //.equ NOMBRE, 529 /*********************************/ /* Initialized data */ /*********************************/ .data szMessNumber: .asciz "Number @ : " szMessResultFact: .asciz "@ " szCarriageReturn: .asciz "\n" szErrorGen: .asciz "Program error !!!\n" szMessPrime: .asciz "This number is prime.\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 tbZoneDecom: .skip 8 * NBFACT // factor 4 bytes, number of each factor 4 bytes /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r7,iNombre @ number mov r0,r7 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessNumber ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message mov r0,r7 ldr r1,iAdrtbZoneDecom bl decompFact cmp r0,#-1 beq 98f @ error ? mov r1,r0 ldr r0,iAdrtbZoneDecom bl displayDivisors   b 100f 98: ldr r0,iAdrszErrorGen bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call iAdrszCarriageReturn: .int szCarriageReturn iAdrszMessResultFact: .int szMessResultFact iAdrszErrorGen: .int szErrorGen iAdrsZoneConv: .int sZoneConv iAdrtbZoneDecom: .int tbZoneDecom iAdrszMessNumber: .int szMessNumber iNombre: .int NOMBRE /******************************************************************/ /* display divisors function */ /******************************************************************/ /* r0 contains address of divisors area */ /* r1 contains the number of area items */ displayDivisors: push {r2-r8,lr} @ save registers cmp r1,#0 beq 100f mov r2,r1 mov r3,#0 @ indice mov r4,r0 1: add r5,r4,r3,lsl #3 ldr r7,[r5] @ load factor ldr r6,[r5,#4] @ load number of factor mov r8,#0 @ display factor counter 2: mov r0,r7 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessResultFact ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message add r8,#1 @ increment counter cmp r8,r6 @ same factors number ? blt 2b add r3,#1 @ other ithem cmp r3,r2 @ items maxi ? blt 1b ldr r0,iAdrszCarriageReturn bl affichageMess b 100f   100: pop {r2-r8,lr} @ restaur registers bx lr @ return /******************************************************************/ /* factor decomposition */ /******************************************************************/ /* r0 contains number */ /* r1 contains address of divisors area */ /* r0 return divisors items in table */ decompFact: push {r1-r8,lr} @ save registers mov r5,r1 mov r8,r0 @ save number bl isPrime @ prime ? cmp r0,#1 beq 98f @ yes is prime mov r4,#0 @ raz indice mov r1,#2 @ first divisor mov r6,#0 @ previous divisor mov r7,#0 @ number of same divisors 2: mov r0,r8 @ dividende bl division @ r1 divisor r2 quotient r3 remainder cmp r3,#0 bne 5f @ if remainder <> zero -> no divisor mov r8,r2 @ else quotient -> new dividende cmp r1,r6 @ same divisor ? beq 4f @ yes cmp r6,#0 @ no but is the first divisor ? beq 3f @ yes str r6,[r5,r4,lsl #2] @ else store in the table add r4,r4,#1 @ and increment counter str r7,[r5,r4,lsl #2] @ store counter add r4,r4,#1 @ next item mov r7,#0 @ and raz counter 3: mov r6,r1 @ new divisor 4: add r7,r7,#1 @ increment counter b 7f @ and loop   /* not divisor -> increment next divisor */ 5: cmp r1,#2 @ if divisor = 2 -> add 1 addeq r1,#1 addne r1,#2 @ else add 2 b 2b   /* divisor -> test if new dividende is prime */ 7: mov r3,r1 @ save divisor cmp r8,#1 @ dividende = 1 ? -> end beq 10f mov r0,r8 @ new dividende is prime ? mov r1,#0 bl isPrime @ the new dividende is prime ? cmp r0,#1 bne 10f @ the new dividende is not prime   cmp r8,r6 @ else dividende is same divisor ? beq 9f @ yes cmp r6,#0 @ no but is the first divisor ? beq 8f @ yes it is a first str r6,[r5,r4,lsl #2] @ else store in table add r4,r4,#1 @ and increment counter str r7,[r5,r4,lsl #2] @ and store counter add r4,r4,#1 @ next item 8: mov r6,r8 @ new dividende -> divisor prec mov r7,#0 @ and raz counter 9: add r7,r7,#1 @ increment counter b 11f   10: mov r1,r3 @ current divisor = new divisor cmp r1,r8 @ current divisor > new dividende ? ble 2b @ no -> loop   /* end decomposition */ 11: str r6,[r5,r4,lsl #2] @ store last divisor add r4,r4,#1 str r7,[r5,r4,lsl #2] @ and store last number of same divisors add r4,r4,#1 lsr r0,r4,#1 @ return number of table items mov r3,#0 str r3,[r5,r4,lsl #2] @ store zéro in last table item add r4,r4,#1 str r3,[r5,r4,lsl #2] @ and zero in counter same divisor b 100f     98: ldr r0,iAdrszMessPrime bl affichageMess mov r0,#1 @ return code b 100f 99: ldr r0,iAdrszErrorGen bl affichageMess mov r0,#-1 @ error code b 100f 100: pop {r1-r8,lr} @ restaur registers bx lr iAdrszMessPrime: .int szMessPrime   /***************************************************/ /* check if a number is prime */ /***************************************************/ /* r0 contains the number */ /* r0 return 1 if prime 0 else */ @2147483647 @4294967297 @131071 isPrime: push {r1-r6,lr} @ save registers cmp r0,#0 beq 90f cmp r0,#17 bhi 1f cmp r0,#3 bls 80f @ for 1,2,3 return prime cmp r0,#5 beq 80f @ for 5 return prime cmp r0,#7 beq 80f @ for 7 return prime cmp r0,#11 beq 80f @ for 11 return prime cmp r0,#13 beq 80f @ for 13 return prime cmp r0,#17 beq 80f @ for 17 return prime 1: tst r0,#1 @ even ? beq 90f @ yes -> not prime mov r2,r0 @ save number sub r1,r0,#1 @ exposant n - 1 mov r0,#3 @ base bl moduloPuR32 @ compute base power n - 1 modulo n cmp r0,#1 bne 90f @ if <> 1 -> not prime   mov r0,#5 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#7 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#11 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#13 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#17 bl moduloPuR32 cmp r0,#1 bne 90f 80: mov r0,#1 @ is prime b 100f 90: mov r0,#0 @ no prime 100: @ fin standard de la fonction pop {r1-r6,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /* */ /********************************************************/ /* r0 nombre */ /* r1 exposant */ /* r2 modulo */ /* r0 return result */ moduloPuR32: push {r1-r7,lr} @ save registers cmp r0,#0 @ verif <> zero beq 100f cmp r2,#0 @ verif <> zero beq 100f @ 1: mov r4,r2 @ save modulo mov r5,r1 @ save exposant mov r6,r0 @ save base mov r3,#1 @ start result   mov r1,#0 @ division de r0,r1 par r2 bl division32R mov r6,r2 @ base <- remainder 2: tst r5,#1 @ exposant even or odd beq 3f umull r0,r1,r6,r3 mov r2,r4 bl division32R mov r3,r2 @ result <- remainder 3: umull r0,r1,r6,r6 mov r2,r4 bl division32R mov r6,r2 @ base <- remainder   lsr r5,#1 @ left shift 1 bit cmp r5,#0 @ end ? bne 2b mov r0,r3 100: @ fin standard de la fonction pop {r1-r7,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr   /***************************************************/ /* division number 64 bits in 2 registers by number 32 bits */ /***************************************************/ /* r0 contains lower part dividende */ /* r1 contains upper part dividende */ /* r2 contains divisor */ /* r0 return lower part quotient */ /* r1 return upper part quotient */ /* r2 return remainder */ division32R: push {r3-r9,lr} @ save registers mov r6,#0 @ init upper upper part remainder  !! mov r7,r1 @ init upper part remainder with upper part dividende mov r8,r0 @ init lower part remainder with lower part dividende mov r9,#0 @ upper part quotient mov r4,#0 @ lower part quotient mov r5,#32 @ bits number 1: @ begin loop lsl r6,#1 @ shift upper upper part remainder lsls r7,#1 @ shift upper part remainder orrcs r6,#1 lsls r8,#1 @ shift lower part remainder orrcs r7,#1 lsls r4,#1 @ shift lower part quotient lsl r9,#1 @ shift upper part quotient orrcs r9,#1 @ divisor sustract upper part remainder subs r7,r2 sbcs r6,#0 @ and substract carry bmi 2f @ négative ?   @ positive or equal orr r4,#1 @ 1 -> right bit quotient b 3f 2: @ negative orr r4,#0 @ 0 -> right bit quotient adds r7,r2 @ and restaur remainder adc r6,#0 3: subs r5,#1 @ decrement bit size bgt 1b @ end ? mov r0,r4 @ lower part quotient mov r1,r9 @ upper part quotient mov r2,r7 @ remainder 100: @ function end pop {r3-r9,lr} @ restaur registers bx lr     /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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.
#BBC_BASIC
BBC BASIC
ncols% = 3 nrows% = 4   *spool temp.htm   PRINT "<html><head></head><body>" PRINT "<table border=1 cellpadding=10 cellspacing=0>"   FOR row% = 0 TO nrows% IF row% = 0 THEN PRINT "<tr><th></th>" ; ELSE PRINT "<tr><th>" ; row% "</th>" ; ENDIF FOR col% = 1 TO ncols% IF row% = 0 THEN PRINT "<th>" CHR$(87 + col%) "</th>" ; ELSE PRINT "<td align=""right"">" ; RND(9999) "</td>" ; ENDIF NEXT col% PRINT "</tr>" NEXT row%   PRINT "</table>" PRINT "</body></html>"   *spool   SYS "ShellExecute", @hwnd%, 0, "temp.htm", 0, 0, 1  
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
#mIRC_Scripting_Language
mIRC Scripting Language
echo -ag $time(yyyy-mm-dd) echo -ag $time(dddd $+ $chr(44) mmmm dd $+ $chr(44) 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
#MUMPS
MUMPS
DTZ WRITE !,"Date format 3: ",$ZDATE($H,3) WRITE !,"Or ",$ZDATE($H,12),", ",$ZDATE($H,9) QUIT