task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Pop11
Pop11
vars itemrep; incharitem(charin) -> itemrep; ;;; Read sizes vars n1 = itemrep(), n2= itemrep(); ;;; Create 0 based array vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0); ;;; Set element value 15 -> ar(0, 0); ;;; Print element value ar(0,0) => ;;; Make sure array is unreferenced 0 -> ar;
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 ...
#PowerShell
PowerShell
  function Read-ArrayIndex ([string]$Prompt = "Enter an integer greater than zero") { [int]$inputAsInteger = 0   while (-not [Int]::TryParse(([string]$inputString = Read-Host $Prompt), [ref]$inputAsInteger)) { $inputString = Read-Host "Enter an integer greater than zero" }   if ($inputAsInte...
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...
#PicoLisp
PicoLisp
(scl 2)   (de stdDev () (curry ((Data)) (N) (push 'Data N) (let (Len (length Data) M (*/ (apply + Data) Len)) (sqrt (*/ (sum '((N) (*/ (- N M) (- N M) 1.0)) Data ) 1.0 Len ) T ) ) ) )   (let...
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...
#Quackery
Quackery
[ stack ] is lim ( --> s )   [ swap dup 1+ lim put 1 0 rot of join swap witheach [ 0 over of swap negate temp put lim share times [ over i^ peek over temp share peek + join ] temp take negate split nip ni...
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...
#Racket
Racket
#lang racket (define (ways-to-make-change cents coins) (cond ((null? coins) 0) ((negative? cents) 0) ((zero? cents) 1) (else (+ (ways-to-make-change cents (cdr coins)) (ways-to-make-change (- cents (car coins)) coins)))))   (ways-to-make-change 100 '(25 10 5 1)) ; -> 242  
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...
#Nemerle
Nemerle
using System.Console;   module CountSubStrings { CountSubStrings(this text : string, target : string) : int { match (target) { |"" => 0 |_ => (text.Length - text.Replace(target, "").Length) / target.Length } }   Main() : void { def text1 = "the three t...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method countSubstring(inStr, findStr) public static return inStr.countstr(findStr)   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
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...
#NewLISP
NewLISP
; file: ocount.lsp ; url: http://rosettacode.org/wiki/Count_in_octal ; author: oofoe 2012-01-29   ; Although NewLISP itself uses a 64-bit integer representation, the ; format function relies on underlying C library's printf function, ; which can only handle a 32-bit octal number on this implementation.   (for (i 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...
#Nim
Nim
import strutils for i in 0 ..< int.high: echo toOct(i, 16)
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...
#Oberon-2
Oberon-2
  MODULE CountInOctal; IMPORT NPCT:Tools, Out := NPCT:Console; VAR i: INTEGER;   BEGIN FOR i := 0 TO MAX(INTEGER) DO; Out.String(Tools.IntToOct(i));Out.Ln END END CountInOctal.  
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...
#Maple
Maple
factorNum := proc(n) local i, j, firstNum; if n = 1 then printf("%a", 1); end if; firstNum := true: for i in ifactors(n)[2] do for j to i[2] do if firstNum then printf ("%a", i[1]); firstNum := false: else printf(" x %a", i[1]); end if; end do; end do; printf("\n"); return NULL; end p...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
n = 2; While[n < 100, Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]]; n++]
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...
#Lasso
Lasso
define rand4dig => integer_random(9999, 1)   local( output = '<table border=2 cellpadding=5 cellspace=0>\n<tr>' )   with el in ('&#160;,X,Y,Z') -> split(',') do { #output -> append('<th>' + #el + '</th>') } #output -> append('</tr>\n')   loop(5) => { #output -> append('<tr>\n<td style="font-weight: bold;">' + loop_...
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
#zkl
zkl
"%d-%02d-%02d".fmt(Time.Clock.localTime.xplode()).println() //--> "2014-02-28" (ISO format)
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
#zonnon
zonnon
  module Main; import System;   var now: System.DateTime; begin now := System.DateTime.Now; System.Console.WriteLine(now.ToString("yyyy-MM-dd"); System.Console.WriteLine("{0}, {1}",now.DayOfWeek,now.ToString("MMMM dd, yyyy")); end Main.  
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.
#Nim
Nim
import os   open("output.txt", fmWrite).close() createDir("docs")   open(DirSep & "output.txt", fmWrite).close() createDir(DirSep & "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.
#Objeck
Objeck
  use IO;   bundle Default { class FileExample { function : Main(args : String[]) ~ Nil { file := FileWriter->New("output.txt"); file->Close();   file := FileWriter->New("/output.txt"); file->Close();   Directory->Create("docs"); Directory->Create("/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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   parse arg inFileName . if inFileName = '' | inFileName = '.' then inFileName = './data/Brian.csv' csv = RREadFileLineByLine01.scanFile(inFileName)   header = htmlHeader() pre = htmlCsvText(csv, inFileName) table = htmlCsvTable(csv, inFil...
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...
#Ursa
Ursa
# # csv data manipulation #   # declare a string stream to hold lines decl string<> lines   # open the file specified on the command line, halting # execution if they didn't enter one. it will be created if # it doesn't exist yet decl file f if (< (size args) 2) out "error: please specify a csv file" endl conso...
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...
#VBA
VBA
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
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 ...
#zkl
zkl
var [const] D=Time.Date; foreach y in ([2008..2121]){ if (D.Sunday==D.weekDay(y,12,25)) println(y) }
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 ...
#zonnon
zonnon
  module Main; (*Access to Mono System package *) import System;   var now: System.DateTime; begin now := System.DateTime.Now; System.Console.Write(now.ToString("yyyy-MM-dd :")); System.Console.WriteLine(now.DayOfWeek); end Main.  
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 ...
#Python
Python
width = int(raw_input("Width of myarray: ")) height = int(raw_input("Height of Array: ")) myarray = [[0] * width for i in range(height)] myarray[0][0] = 3.5 print (myarray[0][0])
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Quackery
Quackery
[ witheach peek ] is {peek} ( { p --> x )   [ dip dup witheach [ peek dup ] drop ] is depack ( { p --> * )   [ reverse witheach [ dip swap poke ] ] is repack ( * p --> { )   [ dup dip [ rot dip [ depack drop ] ] ...
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...
#PL.2FI
PL/I
*process source attributes xref; stddev: proc options(main); declare a(10) float init(1,2,3,4,5,6,7,8,9,10); declare stdev float; declare i fixed binary;   stdev=std_dev(a); put skip list('Standard deviation', stdev);   std_dev: procedure(a) returns(float); declare a(*) float, n fixed bina...
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...
#Raku
Raku
# Recursive (cached) sub change-r($amount, @coins) { my @cache = [1 xx @coins], |([] xx $amount);   multi ways($n where $n >= 0, @now [$coin,*@later]) { @cache[$n;+@later] //= ways($n - $coin, @now) + ways($n, @later); } multi ways($,@) { 0 }   # more efficient to start with coins sorted in ...
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...
#NewLISP
NewLISP
; file: stringcount.lsp ; url: http://rosettacode.org/wiki/Count_occurrences_of_a_substring ; author: oofoe 2012-01-29   ; Obvious (and non-destructive...)   ; Note that NewLISP performs an /implicit/ slice on a string or list ; with this form "(start# end# stringorlist)". If the end# is omitted, ; the slice will ...
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...
#OCaml
OCaml
let () = for i = 0 to max_int do Printf.printf "%o\n" i done
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...
#PARI.2FGP
PARI/GP
oct(n)=n=binary(n);if(#n%3,n=concat([[0,0],[0]][#n%3],n));forstep(i=1,#n,3,print1(4*n[i]+2*n[i+1]+n[i+2]));print; n=0;while(1,oct(n);n++)
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_,...
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...
#Liberty_BASIC
Liberty BASIC
  nomainwin   quote$ =chr$( 34)   html$ ="<html><head></head><body>"   html$ =html$ +"<table border =" +quote$ +"6"+ quote$ +" solid rules =none ; cellspacing =" +quote$ +"10" +quote$ +"> <th> </th> <th> X </th> <th> Y </th> <th> Z </th>"   for i =1 to 4 d1$ =str$( i) d2$ =str$( int...
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.
#Objective-C
Objective-C
NSFileManager *fm = [NSFileManager defaultManager];   [fm createFileAtPath:@"output.txt" contents:[NSData data] attributes:nil]; // Pre-OS X 10.5 [fm createDirectoryAtPath:@"docs" attributes:nil]; // OS X 10.5+ [fm createDirectoryAtPath:@"docs" withIntermediateDirectories:NO attributes:nil error:NULL];
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.
#OCaml
OCaml
# let oc = open_out "output.txt" in close_out oc;; - : unit = ()   # Unix.mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *) - : unit = ()
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...
#Nim
Nim
import cgi, strutils   const csvtext = """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! 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...
#VBScript
VBScript
'Instatiate FSO. Set objFSO = CreateObject("Scripting.FileSystemObject") 'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv. Set objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",1,False) 'Set header status to account...
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...
#Vedit_macro_language
Vedit macro language
File_Open("input.csv") for (#1 = 0; #1 < 4; #1++) { Goto_Line(#1+2) // line (starting from line 2) if (#1) { Search(",", ADVANCE+COUNT, #1) // column } #2 = Num_Eval() // #2 = old value Del_Char(Chars_Matched) ...
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 ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 CLS 20 FOR y=2008 TO 2121 30 LET year=y: LET m=12: LET d=25: GO SUB 1000 40 IF wd=0 THEN PRINT d;" ";m;" ";y 50 NEXT y 60 STOP 1000 REM week day 1010 IF m=1 OR m=2 THEN LET m=m+12: LET year=year-1 1020 LET wd=FN m(year+INT (year/4)-INT (year/100)+INT (year/400)+d+INT ((153*m+8)/5),7) 1030 RETURN 1100 DEF FN m(a,b...
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#R
R
input <- readline("Enter two integers. Space delimited, please: ") dims <- as.numeric(strsplit(input, " ")[[1]]) arr <- array(dim=dims) ii <- ceiling(dims[1]/2) jj <- ceiling(dims[2]/2) arr[ii, jj] <- sum(dims) cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="")
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 ...
#Racket
Racket
  #lang racket   (printf "Enter XY dimensions: ") (define xy (cons (read) (read))) (define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0)))   (printf "Enter a number for the top-left: ") (vector-set! (vector-ref array 0) 0 (read)) (printf "Enter a number for the bottom-right: ") (vector-set! (vector-ref...
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...
#PowerShell
PowerShell
function Get-StandardDeviation { begin { $avg = 0 $nums = @() } process { $nums += $_ $avg = ($nums | Measure-Object -Average).Average $sum = 0; $nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) } [Math]::Sqrt($sum / $nums.Length) } }
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...
#REXX
REXX
/*REXX program counts the number of ways to make change with coins from an given amount.*/ numeric digits 20 /*be able to handle large amounts of $.*/ parse arg N $ /*obtain optional arguments from the CL*/ if N='' | N="," then N= 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...
#Nim
Nim
import strutils   proc count(s, sub: string): int = var i = 0 while true: i = s.find(sub, i) if i < 0: break i += sub.len # i += 1 for overlapping substrings inc result   echo count("the three truths","th")   echo count("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...
#Objective-C
Objective-C
@interface NSString (CountSubstrings) - (NSUInteger)occurrencesOfSubstring:(NSString *)subStr; @end   @implementation NSString (CountSubstrings) - (NSUInteger)occurrencesOfSubstring:(NSString *)subStr { return [[self componentsSeparatedByString:subStr] count] - 1; } @end   int main(int argc, const char *argv[]) { @...
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...
#Pascal
Pascal
program StrAdd; {$Mode Delphi} {$Optimization ON} uses sysutils;//IntToStr   const maxCntOct = (SizeOf(NativeUint)*8+(3-1)) DIV 3;   procedure IntToOctString(i: NativeUint;var res:Ansistring); var p : array[0..maxCntOct] of byte; c,cnt: LongInt; begin cnt := maxCntOct; repeat c := i AND 7; p[cnt] :=...
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...
#Nim
Nim
var primes = newSeq[int]()   proc getPrime(idx: int): int = if idx >= primes.len: if primes.len == 0: primes.add 2 primes.add 3   var last = primes[primes.high] while idx >= primes.len: last += 2 for i, p in primes: if p * p > last: primes.add last break...
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...
#Objeck
Objeck
  class CountingInFactors { function : Main(args : String[]) ~ Nil { for(i := 1; i <= 10; i += 1;){ count := CountInFactors(i); ("{$i} = {$count}")->PrintLine(); };   for(i := 9991; i <= 10000; i += 1;){ count := CountInFactors(i); ("{$i} = {$count}")->PrintLine(); }; }   function : Co...
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...
#Lingo
Lingo
on htmlTable (data) str = "<table>"   -- table head put "<thead><tr><th>&nbsp;</th>" after str repeat with cell in data[1] put "<th>"&cell&"</th>" after str end repeat put "</tr></thead>" after str   -- table body put "<tbody>" after str cnt = data.count repeat with i = 2 to cnt put "<tr><td...
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.
#Oz
Oz
for Dir in ["/" "./"] do File = {New Open.file init(name:Dir#"output.txt" flags:[create])} in {File close} {OS.mkDir Dir#"docs" ['S_IRUSR' 'S_IWUSR' 'S_IXUSR' 'S_IXGRP']} 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.
#PARI.2FGP
PARI/GP
write1("0.txt","") write1("/0.txt","")
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Oberon-2
Oberon-2
  MODULE CSV2HTML; IMPORT Object, IO, IO:FileChannel, IO:TextRider, SB := ADT:StringBuffer, NPCT:Tools, NPCT:CGI:Utils, Ex := Exception, Out; VAR fileChannel: FileChannel.Channel; rd: TextRider.Reader; line: ARRAY 1024 OF CHAR; table: SB.StringBuffer; parts: ARRAY 2 OF STRING;   PROCEDU...
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...
#Visual_FoxPro
Visual FoxPro
  CLOSE DATABASES ALL SET SAFETY OFF MODIFY FILE file1.csv NOEDIT *!* Create a cursor with integer columns CREATE CURSOR tmp1 (C1 I, C2 I, C3 I, C4 I, C5 I) APPEND FROM file1.csv TYPE CSV SELECT C1, C2, C3, C4, C5, C1+C2+C3+C4+C5 As sum ; FROM tmp1 INTO CURSOR tmp2 COPY TO file2.csv TYPE CSV MODIFY FILE file2.csv NOEDI...
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...
#Wren
Wren
import "io" for File   var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList   var file = File.create("rc.csv") // overwrite existing file file.writeBytes(lines[0] + ",SUM\n") for (line in lines.skip(1)) { if (line != "") { var nums = line.split(",").map { |s| Num.fromString(s) } ...
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 ...
#Raku
Raku
my ($major,$minor) = prompt("Dimensions? ").comb(/\d+/); my @array = [ '@' xx $minor ] xx $major; @array[ *.rand ][ *.rand ] = ' '; .say for @array;
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 ...
#Red
Red
Red ["Create two-dimensional array at runtime"]   width: to-integer ask "What is the width of the array? " height: to-integer ask "What is the height of the array? "   ; 2D arrays are just nested blocks in Red. matrix: copy [] ; Make an empty block to hold our...
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...
#PureBasic
PureBasic
;Define our Standard deviation function Declare.d Standard_deviation(x)   ; Main program If OpenConsole() Define i, x Restore MyList For i=1 To 8 Read.i x PrintN(StrD(Standard_deviation(x))) Next i Print(#CRLF$+"Press ENTER to exit"): Input() EndIf   ;Calculation procedure, with memory Procedure.d Sta...
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...
#Ring
Ring
  penny = 1 nickel = 1 dime = 1 quarter = 1 count = 0   for penny = 0 to 100 for nickel = 0 to 20 for dime = 0 to 10 for quarter = 0 to 4 if (penny + nickel * 5 + dime * 10 + quarter * 25) = 100 see "" + penny + " pennies " + nickel + " nickels " + dime + " di...
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...
#OCaml
OCaml
let count_substring str sub = let sub_len = String.length sub in let len_diff = (String.length str) - sub_len and reg = Str.regexp_string sub in let rec aux i n = if i > len_diff then n else try let pos = Str.search_forward reg str i in aux (pos + sub_len) (succ n) with Not_found...
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...
#Perl
Perl
use POSIX; printf "%o\n", $_ for (0 .. POSIX::UINT_MAX);
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...
#Phix
Phix
without javascript_semantics integer i = 0 constant ESC = #1B while not find(get_key(),{ESC,'q','Q'}) do printf(1,"%o\n",i) i += 1 end while
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...
#OCaml
OCaml
open Big_int   let prime_decomposition x = let rec inner c p = if lt_big_int p (square_big_int c) then [p] else if eq_big_int (mod_big_int p c) zero_big_int then c :: inner c (div_big_int p c) else inner (succ_big_int c) p in inner (succ_big_int (succ_big_int zero_big_int)) x   let (...
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...
#Lua
Lua
function htmlTable (data) local html = "<table>\n<tr>\n<th></th>\n" for _, heading in pairs(data[1]) do html = html .. "<th>" .. heading .. "</th>" .. "\n" end html = html .. "</tr>\n" for row = 2, #data do html = html .. "<tr>\n<th>" .. row - 1 .. "</th>\n" for _, field in p...
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.
#Pascal
Pascal
  program in out;   var   f : textfile;   begin   assignFile(f,'/output.txt'); rewrite(f); close(f); makedir('/docs'); assignFile(f,'/docs/output.txt'); rewrite(f); close(f);   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.
#Perl
Perl
use File::Spec::Functions qw(catfile rootdir); { # here open my $fh, '>', 'output.txt'; mkdir 'docs'; }; { # root dir open my $fh, '>', catfile rootdir, 'output.txt'; mkdir catfile rootdir, '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...
#Objeck
Objeck
use System.IO.File; use Data.CSV;   class CsvToHtml { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { table := CsvTable->New(FileReader->ReadFile(args[0])); if(table->IsParsed()) { buffer := "<html><body><table>"; Header(table->GetHeaders(), buffer); for(i := 1;...
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#XPL0
XPL0
string 0; \use zero-terminated strings def LF=$0A, EOF=$1A; int Val, Char; char Str(80);   proc InField; int I; [I:= 0; Val:= 0; loop [Char:= ChIn(1); if Char=^, or Char=LF or Char=EOF then quit; Str(I):= Char; I:= I+1; if Char>=^0 and Char<=^9 then ...
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...
#Yabasic
Yabasic
open #1, "manipy.csv", "r" //existing CSV file separated by spaces, not commas open #2, "manip2.csv", "w" //new CSV file for writing changed data   line input #1 header$ header$ = header$ + ",SUM" print #2 header$   while !eof(1) input #1 c1, c2, c3, c4, c5 sum = c1 + c2 + c3 + c4 + c5 print #2 c1, c2, c3,...
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 ...
#REXX
REXX
/*REXX program allocates/populates/displays a two-dimensional array. */ call bloat /*the BLOAT procedure does all allocations.*/ /*no more array named @ at this point. */ exit /*stick a fork in it, we're all done honey.*/ /*──────────────────...
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...
#Python
Python
>>> from math import sqrt >>> def sd(x): sd.sum += x sd.sum2 += x*x sd.n += 1.0 sum, sum2, n = sd.sum, sd.sum2, sd.n return sqrt(sum2/n - sum*sum/n/n)   >>> sd.sum = sd.sum2 = sd.n = 0 >>> for value in (2,4,4,4,5,5,7,9): print (value, sd(value))     (2, 0.0) (4, 1.0) (4, 0.94280904158206258)...
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...
#Ruby
Ruby
def make_change(amount, coins) @cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)} @coins = coins do_count(amount, @coins.length - 1) end   def do_count(n, m) if n < 0 || m < 0 0 elsif @cache[n][m] @cache[n][m] else @cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1...
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...
#Oforth
Oforth
  : countSubString(s, sub) 0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size + 1 under+ ] drop ;
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...
#ooRexx
ooRexx
  bag="the three truths" x="th" say left(bag,30) left(x,15) 'found' bag~countstr(x)   bag="ababababab" x="abab" say left(bag,30) left(x,15) 'found' bag~countstr(x)   -- can be done caselessly too bag="abABAbaBab" x="abab" say left(bag,30) left(x,15) 'found' bag~caselesscountstr(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...
#PHP
PHP
<?php for ($n = 0; is_int($n); $n++) { echo decoct($n), "\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...
#Picat
Picat
go => gen(N), println(to_oct_string(N)), fail.   gen(I) :- gen(0, I). gen(I, I). gen(I, J) :- I2 is I + 1, gen(I2, J).
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...
#PicoLisp
PicoLisp
(for (N 0 T (inc N)) (prinl (oct N)) )
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...
#Octave
Octave
for (n = 1:20) printf ("%i: ", n) printf ("%i ", factor (n)) printf ("\n") endfor
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...
#PARI.2FGP
PARI/GP
fnice(n)={ my(f,s="",s1); if (n < 2, return(n)); f = factor(n); s = Str(s, f[1,1]); if (f[1, 2] != 1, s=Str(s, "^", f[1,2])); for(i=2,#f[,1], s1 = Str(" * ", f[i, 1]); if (f[i, 2] != 1, s1 = Str(s1, "^", f[i, 2])); s = Str(s, s1) ); s }; n=0;while(n++, print(fnice(n)))
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...
#M2000_Interpreter
M2000 Interpreter
  MODULE HtmlTable { tag$=LAMBDA$ (a$)-> { =LAMBDA$ a$ -> { IF ISNUM THEN w$=STR$(NUMBER,0) ELSE w$=LETTER$ READ ? part$ ="<"+a$+IF$(LEN(part$)>0->" "+part$,"")+">"+w$+"</"+a$+">"+CHR$(13)+CHR$(10) } } INVENTORY Fun STACK NEW { DATA "html", "head", "body", "table", "tr", "th", "td" WHILE NOT EMPTY ...
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.
#Phix
Phix
integer fn   -- In the current working directory system("mkdir docs",2) fn = open("output.txt","w") close(fn)   -- In the filesystem root system("mkdir \\docs",2) fn = open("\\output.txt","w") if fn=-1 then puts(1,"unable to create \\output.txt\n") else close(fn) end if
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.
#PHP
PHP
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); 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...
#OCaml
OCaml
open Printf   let csv_data = "\ 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 mot...
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...
#zkl
zkl
csvFile:=File("test.csv"); header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") });   newFile:=File("test2.csv","w"); newFile.writeln(header + ",sum"); listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat...
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 ...
#Ring
Ring
  See 'Enter width : ' give width See 'Enter height : ' give height width=0+width height=0+height aList = list(height) for x in aList x = list(width) next aList[1][2] = 10 See aList[1][2] + nl  
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 ...
#Ruby
Ruby
puts 'Enter width and height: ' w=gets.to_i arr = Array.new(gets.to_i){Array.new(w)} arr[1][3] = 5 p arr[1][3]
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...
#R
R
cumsd <- function(x) { n <- seq_along(x) sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2) }   set.seed(12345L) x <- rnorm(10)   cumsd(x) # [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814   # Compare to the naive implementation, i.e. compute sd on each sublist: Vector...
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...
#Run_BASIC
Run BASIC
for penny = 0 to 100 for nickel = 0 to 20 for dime = 0 to 10 for quarter = 0 to 4 if penny + nickel * 5 + dime * 10 + quarter * 25 = 100 then print penny;" pennies ";nickel;" nickels "; dime;" dimes ";quarter;" quarters" count = count + 1 end if next qua...
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...
#Rust
Rust
fn make_change(coins: &[usize], cents: usize) -> usize { let size = cents + 1; let mut ways = vec![0; size]; ways[0] = 1; for &coin in coins { for amount in coin..size { ways[amount] += ways[amount - coin]; } } ways[cents] }   fn main() { println!("{}", make_chang...
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...
#PARI.2FGP
PARI/GP
subvec(v,u)={ my(i=1,s); while(i+#u<=#v, for(j=1,#u, if(v[i+j-1]!=u[j], i++; next(2)) ); s++; i+=#u ); s }; substr(s1,s2)=subvec(Vec(s1),Vec(s2)); substr("the three truths","th") substr("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...
#Pascal
Pascal
sub countSubstring { my $str = shift; my $sub = quotemeta(shift); my $count = () = $str =~ /$sub/g; return $count; # or return scalar( () = $str =~ /$sub/g ); }   print countSubstring("the three truths","th"), "\n"; # prints "3" print countSubstring("ababababab","abab"), "\n"; # prints "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...
#Pike
Pike
  int i=1; while(true) write("0%o\n", i++);  
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...
#PL.2FI
PL/I
/* Do the actual counting in octal. */ count: procedure options (main); declare v(5) fixed(1) static initial ((5)0); declare (i, k) fixed;   do k = 1 to 999; call inc; put skip edit ( (v(i) do i = 1 to 5) ) (f(1)); end;   inc: proc; declare (carry, i) fixed binary;   carry = 1; do i = 5...
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...
#Pascal
Pascal
program CountInFactors(output);   {$IFDEF FPC} {$MODE DELPHI} {$ENDIF}   type TdynArray = array of integer;   function factorize(number: integer): TdynArray; var k: integer; begin if number = 1 then begin setlength(Result, 1); Result[0] := 1 end else begin k := 2; while number > 1 do ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
x := RandomInteger[10]; Print["<table>", "\n","<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"] Scan[Print["<tr><td>", #, "</td><td>", x, "</td><td>", x, "</td><td>","</td></tr>"] & , Range[3]] Print["</table>"]
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.
#PicoLisp
PicoLisp
(out "output.txt") # Empty output (call 'mkdir "docs") # Call external (out "/output.txt") (call '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.
#Pike
Pike
import Stdio;   int main(){ write_file("input.txt","",0100); write_file("/input.txt","",0100); }
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...
#OpenEdge.2FProgress
OpenEdge/Progress
  FUNCTION csvToHtml RETURNS CHARACTER ( i_lhas_header AS LOGICAL, i_cinput AS CHARACTER ):   DEFINE VARIABLE coutput AS CHARACTER NO-UNDO.   DEFINE VARIABLE irow AS INTEGER NO-UNDO. DEFINE VARIABLE icolumn AS INTEGER NO-UNDO. DEFINE VARIABLE crow AS CHARACTER NO-UNDO. DEFI...
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 ...
#Rust
Rust
use std::env;   fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument");   assert_ne!(rows, 0, "rows were zero"); assert_ne!(...
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 ...
#Scala
Scala
object Array2D{ def main(args: Array[String]): Unit = { val x = Console.readInt val y = Console.readInt   val a=Array.fill(x, y)(0) a(0)(0)=42 println("The number at (0, 0) is "+a(0)(0)) } }
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Racket
Racket
  #lang racket (require math) (define running-stddev (let ([ns '()]) (λ(n) (set! ns (cons n ns)) (stddev ns)))) ;; run it on each number, return the last result (last (map running-stddev '(2 4 4 4 5 5 7 9)))  
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...
#SAS
SAS
/* call OPTMODEL procedure in SAS/OR */ proc optmodel; /* declare set and names of coins */ set COINS = {1,5,10,25}; str name {COINS} = ['penny','nickel','dime','quarter'];   /* declare variables and constraint */ var NumCoins {COINS} >= 0 integer; con Dollar: sum {i in COINS} i * NumCoins[i] = ...
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...
#Scala
Scala
def countChange(amount: Int, coins:List[Int]) = { val ways = Array.fill(amount + 1)(0) ways(0) = 1 coins.foreach (coin => for (j<-coin to amount) ways(j) = ways(j) + ways(j - coin) ) ways(amount) }   countChange (15, List(1, 5, 10, 25))