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/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 pen...
#IS-BASIC
IS-BASIC
100 PROGRAM "Coins.bas" 110 LET MONEY=100 120 LET COUNT=0 125 PRINT "Count Pennies Nickles Dimes Quaters" 130 FOR QC=0 TO INT(MONEY/25) 150 FOR DC=0 TO INT((MONEY-QC*25)/10) 170 FOR NC=0 TO INT((MONEY-DC*10)/5) 190 FOR PC=0 TO MONEY-NC*5 STEP 5 200 LET S=PC+NC*5+DC*10+QC*25 210 IF S=MONEY T...
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 pen...
#J
J
merge=: ({:"1 (+/@:({."1),{:@{:)/. ])@; count=: {.@] <@,. {:@] - [ * [ i.@>:@<.@%~ {:@] init=: (1 ,. ,.)^:(0=#@$) nsplits=: 0 { [: +/ [: (merge@:(count"1) init)/ }.@/:~@~.@,
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 cou...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function countSubstring(s As String, search As String) As Integer If s = "" OrElse search = "" Then Return 0 Dim As Integer count = 0, length = Len(search) For i As Integer = 1 To Len(s) If Mid(s, i, length) = Search Then count += 1 i += length - 1 End If Next Return co...
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 cou...
#FunL
FunL
import util.Regex   def countSubstring( str, substr ) = Regex( substr ).findAllMatchIn( str ).length()   println( countSubstring("the three truths", "th") ) println( countSubstring("ababababab", "abab") )
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Fortran
Fortran
program Octal implicit none   integer, parameter :: i64 = selected_int_kind(18) integer(i64) :: n = 0   ! Will stop when n overflows from ! 9223372036854775807 to -92233720368547758078 (1000000000000000000000 octal) do while(n >= 0) write(*, "(o0)") n n = n + 1 end do end program
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 sequ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim ub As UByte = 0 ' only has a range of 0 to 255 Do Print Oct(ub, 3) ub += 1 Loop Until ub = 0 ' wraps around to 0 when reaches 256 Print Print "Press any key to quit" Sleep
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 {\di...
#Factor
Factor
USING: io kernel math.primes.factors math.ranges prettyprint sequences ;   : .factors ( n -- ) dup pprint ": " write factors [ " × " write ] [ pprint ] interleave nl ;   "1: 1" print 2 20 [a,b] [ .factors ] each
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 {\di...
#Forth
Forth
: .factors ( n -- ) 2 begin 2dup dup * >= while 2dup /mod swap if drop 1+ 1 or \ next odd number else -rot nip dup . ." x " then repeat drop . ;   : main ( n -- ) ." 1 : 1" cr 1+ 2 ?do i . ." : " i .factors cr loop ;   15 main bye
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...
#Forth
Forth
include random.hsf   \ parser routines : totag [char] < PARSE pad place \ parse input up to '<' char -1 >in +! \ move the interpreter pointer back 1 char pad count type  ;   : '"' [char] " emit ; : '"..' '"' space ; ...
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
#Run_BASIC
Run BASIC
'Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007". print date$("yyyy-mm-dd") print date$("dddd");", "; 'return full day of the week (eg. Wednesday print date$("mmmm");" "; 'return full month name (eg. March) print date$("dd, yyyy") ...
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Rust
Rust
fn main() { let now = chrono::Utc::now(); println!("{}", now.format("%Y-%m-%d")); println!("{}", now.format("%A, %B %d, %Y")); }
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Sidef
Sidef
func cramers_rule(A, terms) { gather { for i in ^A { var Ai = A.map{.map{_}} for j in ^terms { Ai[j][i] = terms[j] } take(Ai.det) } } »/» A.det }   var matrix = [ [2, -1, 5, 1], [3, 2, 2, -6], [1, 3, 3, -1], [5...
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.
#J
J
'' 1!:2 <'/output.txt' NB. write an empty file 1!:5 <'/docs' NB. create a directory
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.
#Java
Java
import java.io.*; public class CreateFileTest { public static void main(String args[]) { try { new File("output.txt").createNewFile(); new File(File.separator + "output.txt").createNewFile(); new File("docs").mkdir(); new File(File.separator + "docs").mkdir(); } catch (IOException e) { System.err.pr...
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#JavaScript
JavaScript
var csv = "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,B...
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Prolog
Prolog
test :- augment('test.csv', 'test.out.csv').   % augment( +InFileName, +OutFileName) augment(InFile, OutFile) :- open(OutFile, write, OutStream), ( ( csv_read_file_row(InFile, Row, [line(Line)]), % Row is of the form row( Item1, Item2, ....). addrow(Row, Out), csv_write_stream(OutStream, [Out], []),...
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 ...
#Scheme
Scheme
(define (day-of-week year month day) (if (< month 3) (begin (set! month (+ month 12)) (set! year (- year 1)))) (+ 1 (remainder (+ 5 day (quotient (* (+ 1 month) 13) 5) year (quotient year 4) (* (quotient year 100) 6) (quotient year 400)) 7)))   (define (task) (let loop ((y 2121) (v...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module CheckArray { Do { Input "A, B=", A% ,B% } Until A%>0 and B%>0   \\ 1@ is 1 Decimal addone=lambda N=1@ ->{=N : N++} Dim Base 1, Arr(A%,B%)<<addone() \\ pi also is decimal Arr(1,1)=pi Print Arr(1,1) Print Arr() \\ all variables/arrays/inner ...
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 ...
#Maple
Maple
> a := Array( 1 .. 3, 1 .. 4 ): # initialised to 0s > a[1,1] := 1: # assign an element > a[2,3] := 4: # assign an element > a; # display the array [1 0 0 0] [ ] [0 0 4 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 langu...
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П4 П5 П6 С/П П0 ИП5 + П5 ИП0 x^2 ИП6 + П6 КИП4 ИП6 ИП4 / ИП5 ИП4 / x^2 - КвКор БП 04
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...
#REXX
REXX
/*REXX program computes the CRC─32 (32 bit Cyclic Redundancy Check) checksum for a */ /*─────────────────────────────────given string [as described in ISO 3309, ITU─T V.42].*/ call show 'The quick brown fox jumps over the lazy dog' /*the 1st string.*/ call show 'Generate CRC32 Checksum For Byte Ar...
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 pen...
#Java
Java
import java.util.Arrays; import java.math.BigInteger;   class CountTheCoins { private static BigInteger countChanges(int amount, int[] coins){ final int n = coins.length; int cycle = 0; for (int c : coins) if (c <= amount && c >= cycle) cycle = c + 1; cycl...
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 cou...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main import ( "fmt" "strings" )   func main() { fmt.Println(strings.Count("the three truths", "th")) // says: 3 fmt.Println(strings.Count("ababababab", "abab")) // says: 2 }
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 cou...
#Go
Go
package main import ( "fmt" "strings" )   func main() { fmt.Println(strings.Count("the three truths", "th")) // says: 3 fmt.Println(strings.Count("ababababab", "abab")) // says: 2 }
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 sequ...
#Frink
Frink
i = 0 while true { println[i -> octal] i = i + 1 }
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 sequ...
#Futhark
Futhark
  fun octal(x: int): int = loop ((out,mult,x) = (0,1,x)) = while x > 0 do let digit = x % 8 let out = out + digit * mult in (out, mult * 10, x / 8) in out   fun main(n: int): [n]int = map octal (iota n)  
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 sequ...
#FutureBasic
FutureBasic
window 1, @"Count in Octal"   defstr word dim as short i text ,,,,, 50   print @"dec",@"oct" for i = 0 to 25 print i,oct(i) next   HandleEvents
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 {\di...
#Fortran
Fortran
  !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Thu Jun 6 23:29:06 ! !a=./f && make $a && echo -2 | OMP_NUM_THREADS=2 $a !gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f ! assert 1 = */ 1 ! assert 2 = */ ...
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...
#Fortran
Fortran
  MODULE PARAMETERS !Assorted oddities that assorted routines pick and choose from. CHARACTER*5 I AM !Assuage finicky compilers. PARAMETER (IAM = "Gnash") !I AM! INTEGER LUSERCODE !One day, I'll get around to devising some string protocol. CHARACTER*28 USERCODE !I'm not too sure how...
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
#Scala
Scala
val now=new Date() println("%tF".format(now)) println("%1$tA, %1$tB %1$td, %1$tY".format(now))
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
#Scheme
Scheme
(define short-date (lambda (lt) (strftime "%Y-%m-%d" (localtime lt))))   (define long-date (lambda (lt) (strftime "%A, %B %d, %Y" (localtime lt))))   (define main (lambda (args) ;; Current date (let ((dt (car (gettimeofday)))) ;; Short style (display (short-date dt))(newline) ;; ...
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...
#Tcl
Tcl
  package require math::linearalgebra namespace path ::math::linearalgebra   # Setting matrix to variable A and size to n set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] # Setting right side of equation set right {-3 -32 -47 49}   # Calculating determinant of A set detA [det $A] ...
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.
#JavaScript
JavaScript
const fs = require('fs');   function fct(err) { if (err) console.log(err); }   fs.writeFile("output.txt", "", fct); fs.writeFile("/output.txt", "", fct);   fs.mkdir("docs", fct); fs.mkdir("/docs", fct);
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.
#JCL
JCL
  // EXEC PGM=IEFBR14 //* CREATE EMPTY FILE NAMED "OUTPUT.TXT" (file names upper case only) //ANYNAME DD UNIT=SYSDA,SPACE=(0,0),DSN=OUTPUT.TXT,DISP=(,CATLG) //* CREATE DIRECTORY (PARTITIONED DATA SET) NAMED "DOCS" //ANYNAME DD UNIT=SYSDA,SPACE=(TRK,(1,...
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#jq
jq
jq -R . csv2html.csv | jq -r -s -f csv2html.jq  
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#PureBasic
PureBasic
  EnableExplicit   #Separator$ = ","   Define fInput$ = "input.csv"; insert path to input file Define fOutput$ = "output.csv"; insert path to output file Define header$, row$, field$ Define nbColumns, sum, i   If OpenConsole() If Not ReadFile(0, fInput$) PrintN("Error opening input file") Goto Finish EndI...
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 ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i";   const proc: main is func local var integer: year is 0; begin for year range 2008 to 2122 do if dayOfWeek(date(year, 12, 25)) = 7 then writeln("Christmas comes on a sunday in " <& year); end if; end for; end func;
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#SenseTalk
SenseTalk
// In what years between 2008 and 2121 will the 25th of December be a Sunday?   repeat with year = 2008 to 2121 set Christmas to "12/25/" & year if the WeekDayName of Christmas is Sunday then put "Christmas in " & year & " falls on a Sunday" end if end repeat
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]}, array[[1,1]]=RandomReal[]; array[[1,1]] ]
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 ...
#MATLAB_.2F_Octave
MATLAB / Octave
width = input('Array Width: '); height = input('Array Height: ');   array = zeros(width,height);   array(1,1) = 12;   disp(['Array element (1,1) = ' num2str(array(1,1))]);   clear array; % de-allocate (remove) array from workspace  
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Nanoquery
Nanoquery
class StdDev declare n declare sum declare sum2   def StdDev() n = 0 sum = 0 sum2 = 0 end   def sd(x) this.n += 1 this.sum += x this.sum2 += x*x   return sqrt(sum2/n - sum*sum/n/n) end end   testData = {2,4,4,4,5,5,7,9} sd = new(StdDev)   for x in testData println sd.sd(x) end
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...
#Ruby
Ruby
require 'zlib' printf "0x%08x\n", Zlib.crc32('The quick brown fox jumps over the lazy dog') # => 0x414fa339
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...
#Rust
Rust
  fn crc32_compute_table() -> [u32; 256] { let mut crc32_table = [0; 256];   for n in 0..256 { crc32_table[n as usize] = (0..8).fold(n as u32, |acc, _| { match acc & 1 { 1 => 0xedb88320 ^ (acc >> 1), _ => acc >> 1, } }); }   crc32_t...
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 pen...
#JavaScript
JavaScript
function countcoins(t, o) { 'use strict'; var targetsLength = t + 1; var operandsLength = o.length; t = [1];   for (var a = 0; a < operandsLength; a++) { for (var b = 1; b < targetsLength; b++) {   // initialise undefined target t[b] = t[b] ? t[b] : 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 cou...
#Groovy
Groovy
println (('the three truths' =~ /th/).count) println (('ababababab' =~ /abab/).count) println (('abaabba*bbaba*bbab' =~ /a*b/).count) println (('abaabba*bbaba*bbab' =~ /a\*b/).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 cou...
#Haskell
Haskell
import Data.Text hiding (length)   -- Return the number of non-overlapping occurrences of sub in str. countSubStrs str sub = length $ breakOnAll (pack sub) (pack str)   main = do print $ countSubStrs "the three truths" "th" print $ countSubStrs "ababababab" "abab"  
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Go
Go
package main   import ( "fmt" "math" )   func main() { for i := int8(0); ; i++ { fmt.Printf("%o\n", i) if i == math.MaxInt8 { break } } }
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 sequ...
#Groovy
Groovy
println 'decimal octal' for (def i = 0; i <= Integer.MAX_VALUE; i++) { printf ('%7d  %#5o\n', i, i) }
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 {\di...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub getPrimeFactors(factors() As UInteger, n As UInteger) If n < 2 Then Return Dim factor As UInteger = 2 Do If n Mod factor = 0 Then Redim Preserve factors(0 To UBound(factors) + 1) factors(UBound(factors)) = factor n \= factor If n = 1 Then Return Else f...
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...
#FreeBASIC
FreeBASIC
Dim As Integer ncols = 3, nrows = 4 Dim As Integer col, row   Print "<!DOCTYPE html>" & Chr(10) & "<html>" Print "<head></head>" & Chr(10) & "<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>" & ...
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
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i";   const proc: main is func local const array string: months is [] ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); const array string: days is [] ("Monday", "Tuesday", "Wednesday"...
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
#SenseTalk
SenseTalk
  put formattedTime( "[year]-[month]-[day]", the date)   put formattedTime( "[weekday], [month name] [day], [year]", the date)  
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...
#VBA
VBA
  Sub CramersRule() OrigM = [{2, -1, 5, 1; 3,2,2,-6;1,3,3,-1;5,-2,-3,3}] OrigD = [{-3;-32;-47;49}]   MatrixSize = UBound(OrigM) DetOrigM = WorksheetFunction.MDeterm(OrigM)   For i = 1 To MatrixSize ChangeM = OrigM   For j = 1 To MatrixSize ChangeM(j, i) = OrigD(j, 1) ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices Imports System.Linq.Enumerable   Module Module1 <Extension()> Function DelimitWith(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String Return String.Join(seperator, source) End Function   Private Class SubMatrix Private...
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.
#Julia
Julia
# many I/O functions have UNIX names   touch("output.txt") mkdir("docs")   # probably don't have permission try touch("/output.txt") mkdir("/docs") catch e warn(e) end
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#K
K
"output.txt" 1: "" "/output.txt" 1: "" \ mkdir docs \ mkdir /docs
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Jsish
Jsish
/* CSV to HTML, in Jsish */ var csv = "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 moth...
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Python
Python
import fileinput   changerow, changecolumn, changevalue = 2, 4, '"Spam"'   with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue l...
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 ...
#Sidef
Sidef
require('Time::Local')   for year in (2008 .. 2121) { var time = %S<Time::Local>.timelocal(0,0,0,25,11,year) var wd = Time(time).local.wday if (wd == 0) { say "25 Dec #{year} is Sunday" } }
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Simula
Simula
BEGIN INTEGER M,D,Y; M := 12; D := 25; FOR Y := 2008 STEP 1 UNTIL 2121 DO BEGIN INTEGER W,A,MM,YY; A := (14 - M)//12; MM := M + 12*A - 2; YY := Y - A; W := D + ((13*MM - 1)//5) + YY + (YY//4) - (YY//100) + (YY//400); W := MOD(W,7); IF W = 0 THEN ...
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 ...
#Maxima
Maxima
printf(true, "in the following terminate every number with semicolon `;'")$ n: readonly("Input x-size: ")$ m: readonly("Input y-size: ")$ a: make_array(fixnum, n, m)$ fillarray(a, makelist(i, i, 1, m*n))$   /* indexing starts from 0 */ print(a[0,0]); print(a[n-1,m-1]);
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 ...
#MAXScript
MAXScript
a = getKBValue prompt:"Enter first dimension:" b = getKBValue prompt:"Enter second dimension:" arr1 = #() arr2 = #() arr2[b] = undefined for i in 1 to a do ( append arr1 (deepCopy arr2) ) arr1[a][b] = 1 print arr1[a][b]
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Nim
Nim
import math, strutils   var sdSum, sdSum2, sdN = 0.0   proc sd(x: float): float = sdN += 1 sdSum += x sdSum2 += x * x sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))   for value in [float 2,4,4,4,5,5,7,9]: echo value, " ", formatFloat(sd(value), precision = -1)
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...
#Scala
Scala
import java.util.zip.CRC32 val crc=new CRC32 crc.update("The quick brown fox jumps over the lazy dog".getBytes) println(crc.getValue.toHexString) //> 414fa339
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "crc32.s7i";   const proc: main is func begin writeln(ord(crc32("The quick brown fox jumps over the lazy dog")) radix 16 lpad0 8); end func;
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 pen...
#jq
jq
# How many ways are there to make "target" cents, given a list of coin # denominations as input. # The strategy is to record at total[n] the number of ways to make n cents. def countcoins(target): . as $coin | reduce range(0; length) as $a ( [1]; # there is 1 way to make 0 cents reduce range(1; targ...
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 pen...
#Julia
Julia
function changes(amount::Int, coins::Array{Int})::Int128 ways = zeros(Int128, amount + 1) ways[1] = 1 for coin in coins, j in coin+1:amount+1 ways[j] += ways[j - coin] end return ways[amount + 1] end   @show changes(100, [1, 5, 10, 25]) @show changes(100000, [1, 5, 10, 25, 50, 100])
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Icon_and_Unicon
Icon and Unicon
procedure main() every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do write("The string ",image(A[2])," occurs as a non-overlapping substring ", countSubstring!A , " times in ",image(A[1])) end   procedure countSubstring(s1,s2) #: return count of non-overlapping substrings c := 0 s...
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 cou...
#J
J
require'strings' countss=: #@] %~ #@[ - [ #@rplc '';~]
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 sequ...
#Haskell
Haskell
import Numeric (showOct)   main :: IO () main = mapM_ (putStrLn . flip showOct "") [1 ..]
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 sequ...
#Icon_and_Unicon
Icon and Unicon
link convert # To get exbase10 method   procedure main() limit := 8r37777777777 every write(exbase10(seq(0)\limit, 8)) end
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 {\di...
#Frink
Frink
i = 1 while true { println[join[" x ", factorFlat[i]]] i = i + 1 }
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 {\di...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func main() { fmt.Println("1: 1") for i := 2; ; i++ { fmt.Printf("%d: ", i) var x string for n, f := i, 2; n != 1; f++ { for m := n % f; m == 0; m = n % f { fmt.Print(x, f) x = "×" n /= f ...
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...
#Go
Go
package main   import ( "fmt" "html/template" "os" )   type row struct { X, Y, Z int }   var tmpl = `<table> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> {{range $ix, $row := .}} <tr><td>{{$ix}}</td> <td>{{$row.X}}</td> <td>{{$row.Y}}</td> <td>{{$row.Z}}</td></tr> {{en...
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
#Shiny
Shiny
say time.format 'Y-m-d' time.now say time.format 'l, F j, Y' time.now
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
#Sidef
Sidef
var time = Time.local; say time.ctime; say time.strftime("%Y-%m-%d"); say time.strftime("%A, %B %d, %Y");
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Wren
Wren
import "/matrix" for Matrix   var cramer = Fn.new { |a, d| var n = a.numRows var x = List.filled(n, 0) var ad = a.det for (c in 0...n) { var aa = a.copy() for (r in 0...n) aa[r, c] = d[r, 0] x[c] = aa.det/ad } return x }   var a = Matrix.new([ [2, -1, 5, 1], [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.
#Kotlin
Kotlin
/* testing on Windows 10 which needs administrative privileges to create files in the root */   import java.io.File   fun main(args: Array<String>) { val filePaths = arrayOf("output.txt", "c:\\output.txt") val dirPaths = arrayOf("docs", "c:\\docs") var f: File for (path in filePaths) { f = F...
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.
#LabVIEW
LabVIEW
// create file local(f) = file handle => { #f->close } #f->openWriteOnly('output.txt')   // make directory, just like a file local(d = dir('docs')) #d->create   // create file in root file system (requires permissions at user OS level) local(f) = file handle => { #f->close } #f->openWriteOnly('//output.txt')   // creat...
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Julia
Julia
using DataFrames, CSV   using CSV, DataFrames   function csv2html(fname; header::Bool=false) csv = CSV.read(fname) @assert(size(csv, 2) > 0) str = """ <html>   <head> <style type="text/css"> body { margin: 2em; } h1 { text-align: center; } ...
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Q
Q
t:("IIIII";enlist ",")0: `:input.csv / Read CSV file input.csv into table t t:update SUM:sum value flip t from t / Add SUM column to t `:output.csv 0: csv 0: t / Write updated table as CSV to output.csv
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#R
R
  df <- read.csv(textConnection( "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"))   df$sum <- rowSums(df) write.csv(df,row.names = FALSE)  
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 ...
#Smalltalk
Smalltalk
2008 to: 2121 do: [ :year | |date| date := Date newDay: 25 monthIndex: 12 year: year. date dayName = #Sunday ifTrue: [ date displayNl ] ]
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 ...
#SQL
SQL
SELECT EXTRACT(YEAR FROM dt) AS year_with_xmas_on_sunday FROM ( SELECT add_months(DATE '2008-12-25', 12 * (level - 1)) AS dt FROM dual CONNECT BY level <= 2121 - 2008 + 1 ) WHERE to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun' ORDER BY 1 ;
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 ...
#MUMPS
MUMPS
  ARA2D NEW X,Y,A,I,J REARA WRITE !,"Please enter two positive integers" READ:10 !,"First: ",X READ:10 !,"Second: ",Y GOTO:(X\1'=X)!(X<0)!(Y\1'=Y)!(Y<0) REARA FOR I=1:1:X FOR J=1:1:Y SET A(I,J)=I+J WRITE !,"The corner of X and Y is ",A(X,Y) KILL X,Y,A,I,J QUIT  
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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   say "give me the X and Y dimensions as two positive integers:" parse ask xDim yDim xPos = xDim % 2 -- integer divide to get close to the middle of the array yPos = yDim % 2   arry = Rexx[xDim, yDim] arry[xPos, yPos] = xDim / yDim -- make up ...
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Objeck
Objeck
  use Structure;   bundle Default { class StdDev { nums : FloatVector;   New() { nums := FloatVector->New(); }   function : Main(args : String[]) ~ Nil { sd := StdDev->New(); test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]; each(i : test_data) { sd->AddNum(test_da...
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...
#Shell
Shell
#!/usr/bin/env bash declare -i -a CRC32_LOOKUP_TABLE   __generate_crc_lookup_table() { local -i -r LSB_CRC32_POLY=0xEDB88320 # The CRC32 polynomal LSB order local -i index byte lsb for index in {0..255}; do ((byte = 255 - index)) for _ in {0..7}; do # 8-bit lsb shift ((lsb = byte & 0x01, byte = ((by...
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 pen...
#Kotlin
Kotlin
// version 1.0.6   fun countCoins(c: IntArray, m: Int, n: Int): Long { val table = LongArray(n + 1) table[0] = 1 for (i in 0 until m) for (j in c[i]..n) table[j] += table[j - c[i]] return table[n] }   fun main(args: Array<String>) { val c = intArrayOf(1, 5, 10, 25, 50, 100) println(coun...
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 cou...
#Java
Java
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); }   public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("aba...
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 cou...
#JavaScript
JavaScript
function countSubstring(str, subStr) { var matches = str.match(new RegExp(subStr, "g")); return matches ? matches.length : 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 sequ...
#J
J
disp=.([echo) ' '(-.~":)8&#.inv (1+disp)^:_]0x
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 sequ...
#Java
Java
public class Count{ public static void main(String[] args){ for(int i = 0;i >= 0;i++){ System.out.println(Integer.toOctalString(i)); //optionally use "Integer.toString(i, 8)" } } }
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 {\di...
#Go
Go
package main   import "fmt"   func main() { fmt.Println("1: 1") for i := 2; ; i++ { fmt.Printf("%d: ", i) var x string for n, f := i, 2; n != 1; f++ { for m := n % f; m == 0; m = n % f { fmt.Print(x, f) x = "×" n /= f ...
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...
#Groovy
Groovy
import groovy.xml.MarkupBuilder   def createTable(columns, rowCount) { def writer = new StringWriter() new MarkupBuilder(writer).table(style: 'border:1px solid;text-align:center;') { tr { th() columns.each { title -> th(title)} } (1..rowCount).each { row -> ...
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
#Smalltalk
Smalltalk
| d | d := Date today. d printFormat: #(3 2 1 $- 1 1 2). (d weekday asString), ', ', (d monthName), ' ', (d dayOfMonth asString), ', ', (d year asString)
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
#SQL
SQL
  SELECT to_char(sysdate,'YYYY-MM-DD') date_fmt_1 FROM dual;   SELECT to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 FROM dual;  
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...
#XPL0
XPL0
  func Det(A, N); \Return value of determinate A, order N int A, N; int B, Sum, I, K, L, Term; [if N = 1 then return A(0, 0); B:= Reserve((N-1)*4\IntSize\); Sum:= 0; for I:= 0 to N-1 do [L:= 0; for K:= 0 to N-1 do if K # I then [B(L):= @A(K, 1); L:= L+1]; Term:= A(I, 0) * Det(B, N-1...
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...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) A:=GSL.Matrix(4,4).set(2,-1, 5, 1, 3, 2, 2,-6, 1, 3, 3,-1, 5,-2,-3, 3); b:=GSL.Vector(4).set(-3,-32,-47,49);
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Lasso
Lasso
// create file local(f) = file handle => { #f->close } #f->openWriteOnly('output.txt')   // make directory, just like a file local(d = dir('docs')) #d->create   // create file in root file system (requires permissions at user OS level) local(f) = file handle => { #f->close } #f->openWriteOnly('//output.txt')   // creat...