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/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...
#Wren
Wren
import "/fmt" for Conv   class CRC32 { static init() { __table = List.filled(256, 0) for (i in 0..255) { var word = i for (j in 0..7) { if (word&1 == 1) { word = (word >> 1) ^ 0xedb88320 } else { word = w...
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...
#OCaml
OCaml
let changes amount coins = let ways = Array.make (amount + 1) 0L in ways.(0) <- 1L; List.iter (fun coin -> for j = coin to amount do ways.(j) <- Int64.add ways.(j) ways.(j - coin) done ) coins; ways.(amount)   let () = Printf.printf "%Ld\n" (changes 1_00 [25; 10; 5; 1]); Printf.printf "%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 cou...
#Liberty_BASIC
Liberty BASIC
  print countSubstring( "the three truths", "th") print countSubstring( "ababababab", "abab") end   function countSubstring( a$, s$) c =0 la =len( a$) ls =len( s$) for i =1 to la -ls if mid$( a$, i, ls) =s$ then c =c +1: i =i +ls -1 next i countSubstring =c end function  
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...
#Logtalk
Logtalk
  :- object(counting).   :- public(count/3).   count(String, SubString, Count) :- count(String, SubString, 0, Count).   count(String, SubString, Count0, Count) :- ( sub_atom(String, Before, Length, After, SubString) -> Count1 is Count0 + 1, Start is Before + Length,...
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...
#LOLCODE
LOLCODE
HAI 1.3   HOW IZ I octal YR num I HAS A digit, I HAS A oct ITZ "" IM IN YR octalizer digit R MOD OF num AN 8 oct R SMOOSH digit oct MKAY num R QUOSHUNT OF num AN 8 NOT num, O RLY? YA RLY, FOUND YR oct OIC IM OUTTA YR octalizer IF U SAY SO   IM IN YR printe...
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...
#Lua
Lua
for l=1,2147483647 do print(string.format("%o",l)) 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...
#JavaScript
JavaScript
for(i = 1; i <= 10; i++) console.log(i + " : " + factor(i).join(" x "));   function factor(n) { var factors = []; if (n == 1) return [1]; for(p = 2; p <= n; ) { if((n % p) == 0) { factors[factors.length] = p; n /= p; } else p++; } return factors; }
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...
#JavaScript
JavaScript
<html><head><title>Table maker</title><script type="application/javascript">   // normally, don't do this: at least name it something other than "a" Node.prototype.a = function (e) { this.appendChild(e); return this }   function ce(tag, txt) { var x = document.createElement(tag); x.textContent = (txt === undefined) ?...
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
#Ursa
Ursa
cygnus/x ursa v0.78 (default, release 0) [Oracle Corporation JVM 1.8.0_51 on Mac OS X 10.10.5 x86_64] > import "java.util.Date" > import "java.text.SimpleDateFormat" > decl java.text.SimpleDateFormat sdf > sdf.applyPattern "yyyy-MM-dd" > decl java.util.Date d > out (sdf.format d) endl console 2016-07-23 > sdf.applyPatt...
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
#Ursala
Ursala
#import std #import cli   months = ~&p/block3'JanFebMarAprMayJunJulAugSepOctNovDec' block2'010203040506070809101112'   completion =   -:~& ~&pllrTXS/block3'SunMonTueWedThuFriSat'--(~&lS months) -- ( --','* sep`, 'day,day,sday,nesday,rsday,day,urday', sep`, 'uary,ruary,ch,il,,e,y,ust,tember,ober,ember,ember')   te...
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.
#MATLAB_.2F_Octave
MATLAB / Octave
fid = fopen('output.txt','w'); fclose(fid); fid = fopen('/output.txt','w'); fclose(fid); 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.
#Maxima
Maxima
f: openw("/output.txt"); close(f);   f: openw("output.txt"); close(f);   /* Maxima has no function to create directories, but one can use the underlying Lisp system */   :lisp (mapcar #'ensure-directories-exist '("docs/" "/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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a="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!"; (*Naive*) StringJoin[...
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var file: input is STD_NULL; var array array string: csvData is 0 times 0 times ""; var integer: line is 0; begin input := open(dir(PROGRAM) & "/csvDataManipulation.in", "r"); while hasNext(input) do csvData &:= split(getln(input),...
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...
#SenseTalk
SenseTalk
  // For test purposes, start by creating (or re-creating) the data file put {{ 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 }} into file "myData.csv"   // Read the file as a list of lists (rather than as the default list of property lists) put CSVValue(file "myData.csv", asLists:Yes) into csvData ...
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 ...
#VBA
VBA
Option Explicit   Sub MainDayOfTheWeek() Debug.Print "Xmas will be a Sunday in : " & XmasSunday(2008, 2121) End Sub   Private Function XmasSunday(firstYear As Integer, lastYear As Integer) As String Dim i As Integer, temp$ For i = firstYear To lastYear If Weekday(CDate("25/12/" & i)) = vbSunday Then tem...
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 ...
#VBScript
VBScript
For year = 2008 To 2121 If Weekday(DateSerial(year, 12, 25)) = 1 Then WScript.Echo year End If Next
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 ...
#Perl
Perl
sub make_array($ $){ # get array sizes from provided params, but force numeric value my $x = ($_[0] =~ /^\d+$/) ? shift : 0; my $y = ($_[0] =~ /^\d+$/) ? shift : 0;   # define array, then add multi-dimensional elements my @array; $array[0][0] = 'X '; # first by first element $array[5][7] = 'X ' if (5 <= $...
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...
#Pascal
Pascal
program stddev; uses math; const n=8; var arr: array[1..n] of real =(2,4,4,4,5,5,7,9); function stddev(n: integer): real; var i: integer; s1,s2,variance,x: real; begin for i:=1 to n do begin x:=arr[i]; s1:=s1+power(x,2); s2:=s2+x end; variance:=((n*s1)-(power(s2,2)))/(power(n...
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#XPL0
XPL0
code HexOut=27; \intrinsic routine string 0; \use zero-terminated strings   func CRC32(Str, Len); \Return CRC-32 for given string char Str; int Len; \byte array, number of bytes int I, J, R, C; [R:= -1; \initialize with all 1's for J:= 0 to Len-1 do [C:= Str(J); for ...
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...
#zkl
zkl
var [const] ZLib=Import("zeelib"); ZLib.calcCRC32(Data(Void,"The quick brown fox jumps over the lazy dog")); //-->0x414fa339
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...
#PARI.2FGP
PARI/GP
coins(v)=prod(i=1,#v,1/(1-'x^v[i])); ways(v,n)=polcoeff(coins(v)+O('x^(n+1)),n); ways([1,5,10,25],100) ways([1,5,10,25,50,100],100000)
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...
#Perl
Perl
use 5.01; use Memoize;   sub cc { my $amount = shift; return 0 if !@_ || $amount < 0; return 1 if $amount == 0; my $first = shift; cc( $amount, @_ ) + cc( $amount - $first, $first, @_ ); } memoize 'cc';   # Make recursive algorithm run faster by sorting coins descending by value: sub cc_optimized { ...
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...
#Lua
Lua
function countSubstring(s1, s2) return select(2, s1:gsub(s2, "")) end   print(countSubstring("the three truths", "th")) print(countSubstring("ababababab", "abab"))
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...
#Maple
Maple
  f:=proc(s::string,c::string,count::nonnegint) local n; n:=StringTools:-Search(c,s); if n>0 then 1+procname(s[n+length(c)..],c,count); else 0; end if; end proc:   f("the three truths","th",0);   f("ababababab","abab",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...
#M4
M4
define(`forever', `ifelse($#,0,``$0'', `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',eval($2+$3),$3,`$4')')')dnl forever(`y',0,1, `eval(y,8) ')
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...
#Maple
Maple
  octcount := proc (n) seq(printf("%a \n", convert(i, octal)), i = 1 .. n); end proc;  
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...
#MACRO-10
MACRO-10
  title OCTAL - Count in octal. subttl PDP-10 assembly (MACRO-10 on TOPS-20). KJX 2022. search monsym,macsym   comment \ If you want to see the overflow happening without waiting for too long, change "movei b,1" to "move b,[377777,,777770]". \   a=: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...
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # Input: a non-negative integer determining when to stop def count_in_factors: "1: 1", (range(2;.) | "\(.): \([factors] | join("x"))");   def count_in_factors($m;$n): if . == 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...
#Julia
Julia
using Primes, Printf function strfactor(n::Integer) n > -2 || return "-1 × " * strfactor(-n) isprime(n) || n < 2 && return dec(n) f = factor(Vector{typeof(n)}, n) return join(f, " × ") end   lo, hi = -4, 40 println("Factor print $lo to $hi:") for n in lo:hi @printf("%5d = %s\n", n, strfactor(n)) end
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#jq
jq
def html_row: "<tr>", " \(.[] | "<td>\(.)</td>")", "</tr>";   def html_header: "<thead align = 'right'>", " \(html_row)", "</thead>";   def html_table(header): "<table>", " \(header | html_header)", " <tbody align = 'right'>", " \(.[] | html_row)", " </tbody", "</table>";   # Prepend 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
#VB-DOS
VB-DOS
  OPTION EXPLICIT   ' Months DATA "January", "February", "March", "April", "May", "June", "July" DATA "August", "September", "October", "November", "December"   ' Days of week DATA "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"   ' Var DIM dDate AS DOUBLE, sMonth(1 TO 12) AS STRING, sDay(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
#VBA
VBA
Function DateFormats() Debug.Print Format(Date, "yyyy-mm-dd") Debug.Print Format(Date, "dddd, mmmm dd yyyy") End Function
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.
#MAXScript
MAXScript
-- Here f = createFile "output.txt" close f makeDir (sysInfo.currentDir + "\docs") -- System root f = createFile "\output.txt" close f makeDir ("c:\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.
#Mercury
Mercury
:- module create_file. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   :- import_module dir.   main(!IO) :- create_file("output.txt", !IO), create_file("/output.txt", !IO), create_dir("docs", !IO), create_dir("/docs", !IO).   :- pred create_file(string::i...
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...
#MATLAB
MATLAB
  inputString = fileread(csvFileName); % using multiple regular expressions to clear up special chars htmlFriendly = regexprep(regexprep(regexprep(regexprep(inputString,... '&','&amp;'),... '"','&quot;'),... '<','&lt;'),... '>','&gt;'); % split string into cell array tableValues = regexp(r...
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Sidef
Sidef
# Read var csvfile = %f'data.csv'; var fh = csvfile.open_r; var header = fh.line.trim_end.split(','); var csv = fh.lines.map { .trim_end.split(',').map{.to_num} }; fh.close;   # Write var out = csvfile.open_w; out.say([header..., 'SUM'].join(',')); csv.each { |row| out.say([row..., row.sum].join(',')) }; out.close;
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...
#Stata
Stata
import delim input.csv, clear replace c5=c3+c4 egen sum=rowtotal(c*) drop if mod(c3,3)==0 export delim output.csv, replace
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 ...
#Vedit_macro_language
Vedit macro language
Buf_Switch(Buf_Free) for (#3 = 2008; #3 < 2122; #3++) { Reg_Set(10, "12/25/") Num_Str(#3, 10, LEFT+APPEND) if (JDate(@10) % 7 == 0) { Num_Ins(#3, NOCR) } }
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 ...
#Visual_Objects
Visual Objects
  local i as dword   for i := 2008 upto 2121 if DOW(ConDate(i, 12, 25)) = 1 ? AsString(i) endif next i  
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 ...
#Phix
Phix
-- demo\rosetta\Create2Darray.exw with javascript_semantics -- (layout/spacing leaves a little to be desired...) include pGUI.e Ihandle lab, tab, res, dlg function valuechanged_cb(Ihandle tab) string s = IupGetAttribute(tab,"VALUE") sequence r = scanf(s,"%d %d") if length(r)=1 then integer {height,...
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...
#Perl
Perl
{ package SDAccum; sub new { my $class = shift; my $self = {}; $self->{sum} = 0.0; $self->{sum2} = 0.0; $self->{num} = 0; bless $self, $class; return $self; } sub count { my $self = shift; return $self->{num}; } sub mean { my $self = shift; return ($self->{num}>0) ? $self->{sum}/$sel...
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...
#Phix
Phix
function coin_count(sequence coins, integer amount) sequence s = repeat(0,amount+1) s[1] = 1 for c=1 to length(coins) do for n=coins[c] to amount do s[n+1] += s[n-coins[c]+1] end for end for return s[amount+1] end function
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
StringPosition["the three truths","th",Overlaps->False]//Length 3 StringPosition["ababababab","abab",Overlaps->False]//Length 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...
#MATLAB_.2F_Octave
MATLAB / Octave
% Count occurrences of a substring without overlap length(findstr("ababababab","abab",0)) length(findstr("the three truths","th",0))   % Count occurrences of a substring with overlap length(findstr("ababababab","abab",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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
x=0; While[True,Print[BaseForm[x,8];x++]
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...
#MATLAB_.2F_Octave
MATLAB / Octave
n = 0; while (1) dec2base(n,8) n = n+1; 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 sequ...
#Mercury
Mercury
  :- module count_in_octal. :- interface. :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list, string.   main(!IO) :- count_in_octal(0, !IO).   :- pred count_in_octal(int::in, io::di, io::uo) is det.   count_in_octal(N, !IO) :- io.format("%o\n", [i(N)], !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...
#Kotlin
Kotlin
// version 1.1.2   fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true }   fun ...
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...
#Julia
Julia
function tag(x::Pair, attr::Pair...) t, b = x attrstr = join(" $n=\"$p\"" for (n, p) in attr) return "<$t$attrstr>$b</$t>" end   colnames = split(",X,Y,Z", ',')   header = join(tag(:th => txt) for txt in colnames) * "\n" rows = collect(tag(:tr => join(tag(:td => i, :style => "font-weight: bold;") * join(t...
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#VBScript
VBScript
  'YYYY-MM-DD format WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2)   'Weekday_Name, Month_Name DD, YYYY format WScript.StdOut.WriteLine FormatDateTime(Now,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
#Vedit_macro_language
Vedit macro language
Date(REVERSE+NOMSG+VALUE, '-')
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.
#Mirah
Mirah
import java.io.File   File.new('output.txt').createNewFile() File.new('docs').mkdir() File.new("docs#{File.separator}output.txt").createNewFile()  
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.
#Modula-3
Modula-3
MODULE FileCreation EXPORTS Main;   IMPORT FS, File, OSError, IO, Stdio;   VAR file: File.T;   BEGIN TRY file := FS.OpenFile("output.txt"); file.close(); FS.CreateDirectory("docs"); file := FS.OpenFile("/output.txt"); file.close(); FS.CreateDirectory("/docs"); EXCEPT | OSError.E => IO.Put(...
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...
#Maxima
Maxima
infile: "input.csv"; outfile: "table.html"; instream: openr(infile); outstream: openw(outfile);   printf(outstream, "<TABLE border=\"1\">~%"); nr: 0; while (line: readline(instream))#false do ( nr: nr + 1, line: ssubst("&lt;", "<", line), line: ssubst("&gt;", ">", line), value_list: map(lambda([f], strim(" ", f...
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...
#Tcl
Tcl
package require struct::matrix package require csv   proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix]   # Load the CSV in set f [open $filename] csv::read2matrix $f $m "," auto close $f   # Add the column with the sums set sumcol [$m columns] $m add column $title f...
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 ...
#Vlang
Vlang
import time   fn main() { for year := 2008; year <= 2121; year++ { date := time.parse('${year}-12-25 00:00:00') or { continue } if date.long_weekday_str() == 'Sunday' { println('December 25 ${year} is a ${date.long_weekday_str()}') } } }
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 ...
#VTL-2
VTL-2
1000 #=2000 1010 R=! 1020 N=M 1030 X=Y 1040 #=N>3*1070 1050 N=N+12 1060 X=X-1 1070 J=X/100 1080 K=% 1090 W=N+1*26/10+D+K+(K/4)+(J/4)+(5*J)/7*0+% 1100 #=R 2000 ?="25th of December is a Sunday in"; 2010 Y=2008 2020 M=12 2030 D=25 2040 #=1010 2050 #=W=1=0*2080 2060 $=32 2070 ?=Y 2080 Y=Y+1 2090 #=Y<2121*2040 2100 ?=""
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 ...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   "Enter height: " input tonum nl "Enter width: " input tonum nl 0 swap repeat swap repeat /# create two dimensional array/list. All zeroes #/ -1 get 99 -1 set -1 set /# set the last element o last dimension #/ pstack /# show the content of the stack #/ -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 ...
#Picat
Picat
import util.   go => print("Input the number of rows and columns: "), [Rows,Cols]=split(read_line()).map(to_int), X=new_array(Rows,Cols), X[1,1] = Rows*Cols+1, println(X[1,1]).
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Phix
Phix
with javascript_semantics atom sdn = 0, sdsum = 0, sdsumsq = 0 procedure sdadd(atom n) sdn += 1 sdsum += n sdsumsq += n*n end procedure function sdavg() return sdsum/sdn end function function sddev() return sqrt(sdsumsq/sdn - power(sdsum/sdn,2)) end function --test code: constant testset = ...
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...
#Picat
Picat
go => Problems = [[ 1*100, [25,10,5,1]],  % 1 dollar [ 100*100, [100,50,25,10,5,1]],  % 100 dollars [ 1_000*100, [100,50,25,10,5,1]],  % 1000 dollars [ 10_000*100, [100,50,25,10,5,1]], % 10000 dollars [100_000*100, [100,50,25,10,5,1]] % 10000...
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...
#PicoLisp
PicoLisp
(de coins (Sum Coins) (let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev) (do Sum (zero Prev) (for L Buf (inc (rot L) Prev) (setq Prev (car L)) ) ) Prev ) )
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...
#Maxima
Maxima
scount(e, s) := block( [n: 0, k: 1], while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1), n )$   scount("na", "banana"); 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...
#MiniScript
MiniScript
string.count = function(s) return self.split(s).len - 1 end function   print "the three truths".count("th") print "ababababab".count("abab")
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#min
min
( (dup 0 ==) (pop () 0 shorten) (((8 mod) (8 div)) cleave) 'cons linrec reverse 'print! foreach newline ) :octal   0 (dup octal succ) 9.223e18 int times ; close to max int value
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
ИП0 П1 1 0 / [x] П1 Вx {x} 1 0 * 7 - x=0 21 ИП1 x#0 28 БП 02 ИП0 1 + П0 С/П БП 00 ИП0 lg [x] 1 + 10^x П0 С/П БП 00
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...
#Modula-2
Modula-2
MODULE octal;   IMPORT InOut;   VAR num : CARDINAL;   BEGIN num := 0; REPEAT InOut.WriteOct (num, 12); InOut.WriteLn; INC (num) UNTIL num = 0 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 {\di...
#Liberty_BASIC
Liberty BASIC
  'see Run BASIC solution for i = 1000 to 1016 print i;" = "; factorial$(i) next wait function factorial$(num) if num = 1 then factorial$ = "1" fct = 2 while fct <= num if (num mod fct) = 0 then factorial$ = factorial$ ; x$ ; fct x$ = " x " num = num / fct else fct = fct + 1 end if wend end funct...
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...
#Lua
Lua
function factorize( n ) if n == 1 then return {1} end   local k = 2 res = {} while n > 1 do while n % k == 0 do res[#res+1] = k n = n / k end k = k + 1 end return res end   for i = 1, 22 do io.write( i, ": " ) fac = factorize( i ) io.write( fac[1] ) for j = 2, #fa...
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...
#Kotlin
Kotlin
// version 1.1.3   import java.util.Random   fun main(args: Array<String>) { val r = Random() val sb = StringBuilder() val i = " " // indent with (sb) { append("<html>\n<head>\n") append("<style>\n") append("table, th, td { border: 1px solid black; }\n") append("th, t...
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Vlang
Vlang
import time   fn main() { println(time.now().custom_format("YYYY-MM-DD")) println(time.now().custom_format("dddd, MMMM D, YYYY")) }
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Wren
Wren
import "os" for Process import "/date" for Date   var args = Process.arguments if (args.count != 1) { Fiber.abort("Please pass just the current date in yyyy-mm-dd format.") } var current = Date.parse(args[0]) System.print(current.format(Date.isoDate)) System.print(current.format("dddd|, |mmmm| |d|, |yyyy"))
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Nanoquery
Nanoquery
import Nanoquery.IO   f = new(File) f.create("output.txt") f.createDir("docs")   // in the root directory f.create("/output.txt") f.createDir("/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.
#Nemerle
Nemerle
using System; using System.IO;   module CreateFile { Main() : void { unless (File.Exists("output.txt")) File.Create("output.txt"); // here // returns a FileStream object which we're ignoring try { unless (File.Exists(@"\output.txt")) File.Create(@"\output.txt"); // ro...
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...
#ML.2FI
ML/I
MCSKIP "WITH" NL "" CSV to HTML "" assumes macros on input stream 1, terminal on stream 2 MCSKIP MT,[] MCSKIP SL WITH ~ MCINS %. "" C1=th before header output, td afterwards MCCVAR 1,2 MCSET C1=[th] "" HTML escapes MCDEF < AS [[&lt;]] MCDEF > AS [[&gt;]] MCDEF & AS [[&amp;]] "" Main line processing MCDEF SL N1 OPT , N1...
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...
#TUSCRIPT
TUSCRIPT
  $$ MODE DATA $$ csv=* 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 $$ MODE TUSCRIPT LOOP/CLEAR n,line=csv IF (n==1) THEN line=CONCAT (line,",SUM") ELSE lineadd=EXCHANGE(line,":,:':") sum=SUM(lineadd) line=JOIN(line,",",sum) ENDIF csv=APPEND(csv,line) ENDLOOP  
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...
#TXR
TXR
@(coll)@{name /[^,]+/}@(end) @(collect :vars (value sum)) @ (bind sum 0) @ (coll)@{value /[^,]+/}@(set sum @(+ sum (int-str value)))@(end) @(end) @(output) @ (rep)@name,@(last)SUM@(end) @ (repeat) @ (rep)@value,@(last)@sum@(end) @ (end) @(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 ...
#Wortel
Wortel
!-&y = 0 `.getDay. @new Date[y 11 25] @range[2008 2121]
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 ...
#Wren
Wren
import "/date" for Date   System.print("Years between 2008 and 2121 when 25th December falls on Sunday:") for (year in 2008..2121) { if (Date.new(year, 12, 25).dayOfWeek == 7) System.print(year) }
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 ...
#PicoLisp
PicoLisp
(de 2dimTest (DX DY) (let A (make (do DX (link (need DY)))) (set (nth A 3 3) 999) # Set A[3][3] to 999 (mapc println A) # Print all (get A 3 3) ) ) # Return A[3][3]   (2dimTest 5 5)
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 ...
#PL.2FI
PL/I
  /* First way using a controlled variable: */   declare A(*,*) float controlled; get list (m, n); allocate A(m,n); get list (A); put skip list (A);   /* The array remains allocated until the program terminates, */ /* or until explicitly destroyed using a FREE statement. */   free A;  
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...
#PHP
PHP
<?php class sdcalc { private $cnt, $sumup, $square;   function __construct() { $this->reset(); } # callable on an instance function reset() { $this->cnt=0; $this->sumup=0; $this->square=0; } function add($f) { $this->cnt++; $this->sumup += $f; $this->s...
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...
#Prolog
Prolog
:- use_module(library(clpfd)).   % Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny coins(Q, D, N, P, T) :- [Q,D,N,P] ins 0..T, T #= (Q * 25) + (D * 10) + (N * 5) + P.   coins_for(T) :- coins(Q,D,N,P,T), maplist(indomain, [Q,D,N,P]).
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...
#Python
Python
def changes(amount, coins): ways = [0] * (amount + 1) ways[0] = 1 for coin in coins: for j in xrange(coin, amount + 1): ways[j] += ways[j - coin] return ways[amount]   print changes(100, [1, 5, 10, 25]) print changes(100000, [1, 5, 10, 25, 50, 100])
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Mirah
Mirah
import java.util.regex.Pattern import java.util.regex.Matcher   #The "remove and count the difference" method def count_substring(pattern:string, source:string) (source.length() - source.replace(pattern, "").length()) / pattern.length() end   puts count_substring("th", "the three truths") # ==> 3 puts count_su...
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...
#Nanoquery
Nanoquery
def countSubstring(str, subStr) return int((len(str) - len(str.replace(subStr, ""))) / len(subStr)) 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 sequ...
#Nanoquery
Nanoquery
i = 0 while i < 2^64 println format("%o", i) i += 1 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 sequ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import java.math.BigInteger   -- allow an option to change the output radix. parse arg radix . if radix.length() == 0 then radix = 8 k_ = BigInteger k_ = BigInteger.ZERO   loop forever say k_.toString(int radix) k_ = k_.add(BigInteger.ONE)...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Count_in_factors { Inventory Known1=2@, 3@ IsPrime=lambda Known1 (x as decimal) -> { =0=1 if exist(Known1, x) then =1=1 : exit if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x  : =1=1 Break} if frac(x/2) else exit if frac(x/3) else exit x1=sqrt(x):d = 5@ {if fr...
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...
#M4
M4
define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl define(`by', `ifelse($1,$2, $1, `ifelse(eval($1%$2==0),1, `$2 x by(eval($1/$2),$2)', `by($1,eval($2+1))') ') ')dnl define(`wby', `$1 = ifelse(...
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...
#Lambdatalk
Lambdatalk
  {table {@ style="background:#ffe; width:50%;"} {tr {@ style="text-align:right; font:bold 1.0em arial;"} {td } {td X} {td Y} {td Z}} {map {lambda {:i} {tr {td {b :i}} {map {lambda {_} {td {@ style="text-align:right; font:italic 1.0em courier;"} {floor {* {random...
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
#XPL0
XPL0
include c:\cxpl\codes; int CpuReg, Year, Month, Day, DName, MName, WDay; [CpuReg:= GetReg; \access CPU registers CpuReg(0):= $2A00; \DOS system call SoftInt($21); Year:= CpuReg(2); Month:= CpuReg(3) >> 8; Day:= CpuReg(3) & $FF; WDay:= CpuReg(0) & $FF; IntOut(0, Year); ChOut(0, ^-); if Month<10 then ChOut(0,...
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
#Yabasic
Yabasic
dim n$(1)   n = token(date$, n$(), "-")   print n$(4), "-", n$(2), "-", n$(3) print nDay$(n$(5)), ", ", nMonth$(n$(6)), " ", n$(3), ", ", n$(4)   sub nDay$(n$) switch n$ case "Mon": case "Fri": case "Sun": break case "Tue": n$ = n$ + "s" : break case "Wed": n$ = n$ + "nes" : break case "Thu": n$ = n$ + "rs" : brea...
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   fName = ''; fName[0] = 2; fName[1] = '.' || File.separator || 'output.txt'; fName[2] = File.separator || 'output.txt' dName = ''; dName[0] = 2; dName[1] = '.' || File.separator || 'docs'; dName[2] = File.separator || 'docs'   do loop...
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...
#Nanoquery
Nanoquery
// a method that converts a csv row into a html table row as a string def toHtmlRow(record, tag) htmlrow = "\t<tr>\n"   // loop through the values in the current csv row for i in range(1, len(record)) htmlrow = htmlrow + "\t\t<" + tag + ">" + (record ~ i) + "</" + tag + ">\n" end for   return htmlrow + "\t</tr>\...
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#UNIX_Shell
UNIX Shell
cat csv | while read S; do [ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc` done
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...
#uBasic.2F4tH
uBasic/4tH
if set (a, open ("yourcsv.csv", "r")) < 0 then print "Cannot open \qyourcsv.csv\q" ' open file a for reading end ' abort on file opening errors endif   if set (b, open ("mycsv.csv", "w")) < 0 then print "Cannot open \qmycsv.csv\q" ' open file a for writing 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 ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func WeekDay(Year, Month, Day); \Return day of week (0=Sat 1=Sun..6=Fri) int Year, Month, Day; [if Month<=2 then [Month:= Month+12; Year:= Year-1]; return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7); ]; ...
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 ...
#Yabasic
Yabasic
sub wd(m, d, y) If m < 3 Then // If m = 1 Or m = 2 Then m = m + 12 y = y - 1 End If Return mod((y + int(y / 4) - int(y / 100) + int(y / 400) + d + int((153 * m + 8) / 5)), 7) End sub   // ------=< MAIN >=------   For yr = 2008 To 2121 If wd(12, 25, yr) = 0 Then Print "Dec 25 ", yr EndIf Nex...