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_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... | #Elixir | Elixir | defmodule Table do
defp put_rows(n) do
Enum.map_join(1..n, fn i ->
"<tr align=right><th>#{i}</th>" <>
Enum.map_join(1..3, fn _ ->
"<td>#{:rand.uniform(2000)}</td>"
end) <> "</tr>\n"
end)
end
def create_table(n\\3) do
"<table border=1>\n" <>
"<th></th><th>X</th><th>Y</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
| #Python | Python | import datetime
today = datetime.date.today()
# The first requested format is a method of datetime objects:
today.isoformat()
# For full flexibility, use the strftime formatting codes from the link above:
today.strftime("%A, %B %d, %Y")
# This mechanism is integrated into the general string formatting system.
# You can... |
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
| #R | R | now <- Sys.time()
strftime(now, "%Y-%m-%d")
strftime(now, "%A, %B %d, %Y") |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Prolog | Prolog | removeElement([_|Tail], 0, Tail).
removeElement([Head|Tail], J, [Head|X]) :-
J_2 is J - 1,
removeElement(Tail, J_2, X).
removeColumn([], _, []).
removeColumn([Matrix_head|Matrix_tail], J, [X|Y]) :-
removeElement(Matrix_head, J, X),
removeColumn(Matrix_tail, J, Y).
removeRow([_|Matrix_tail], 0, Matri... |
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.
| #friendly_interactive_shell | friendly interactive shell | touch {/,}output.txt # create both /output.txt and output.txt
mkdir {/,}docs # create both /docs and 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.
| #FunL | FunL | import io.File
File( 'output.txt' ).createNewFile()
File( File.separator + 'output.txt' ).createNewFile()
File( 'docs' ).mkdir()
File( File.separator + 'docs' ).mkdir() |
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... | #Groovy | Groovy | def formatCell = { cell ->
"<td>${cell.replaceAll('&','&').replaceAll('<','<')}</td>"
}
def formatRow = { row ->
"""<tr>${row.split(',').collect { cell -> formatCell(cell) }.join('')}</tr>
"""
}
def formatTable = { csv, header=false ->
def rows = csv.split('\n').collect { row -> formatRow(row) }
... |
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... | #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use List::Util 'sum';
my @header = split /,/, <>;
# Remove the newline.
chomp $header[-1];
my %column_number;
for my $i (0 .. $#header) {
$column_number{$header[$i]} = $i;
}
my @rows = map [ split /,/ ], <>;
chomp $_->[-1] for @rows;
# Add 1 to the numbers in the ... |
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 ... | #REBOL | REBOL | rebol [
Title: "Yuletide Holiday"
URL: http://rosettacode.org/wiki/Yuletide_Holiday
]
for y 2008 2121 1 [
d: to-date reduce [y 12 25]
if 7 = d/weekday [prin [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 ... | #Red | Red | Red []
repeat yy 114 [
d: to-date reduce [25 12 (2007 + yy )]
if 7 = d/weekday [ print d ] ;; 7 = sunday
]
;; or
print "version 2"
d: to-date [25 12 2008]
while [d <= 25/12/2121 ] [
if 7 = d/weekday [
print rejoin [d/day '. d/month '. d/year ]
]
d/year: d/year + 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 ... | #Java | Java | import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("... |
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... | #Lobster | Lobster |
// Stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
class Stats:
M = 0.0
S = 0.0
n = 0
def incl(x):
n += 1
if n == 1:
M = x
else:
let mm = (x - M)
M += mm / n
S += mm * (x - M)
def ... |
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... | #Pike | Pike | string foo = "The quick brown fox jumps over the lazy dog";
write("0x%x\n", Gz.crc32(foo)); |
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... | #PL.2FI | PL/I | *process source attributes xref or(!) nest;
crct: Proc Options(main);
/*********************************************************************
* 19.08.2013 Walter Pachl derived from REXX
*********************************************************************/
Dcl (LEFT,LENGTH,RIGHT,SUBSTR,UNSPEC) Builtin;
Dcl SYSPRI... |
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... | #FutureBasic | FutureBasic | include "NSLog.incl"
void local fn Doit
long penny, nickel, dime, quarter, count = 0
NSLogSetTabInterval(30)
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
NSLog(@"%ld pennies\t... |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #Go | Go | package main
import "fmt"
func main() {
amount := 100
fmt.Println("amount, ways to make change:", amount, countChange(amount))
}
func countChange(amount int) int64 {
return cc(amount, 4)
}
func cc(amount, kindsOfCoins int) int64 {
switch {
case amount == 0:
return 1
case amount <... |
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... | #Elixir | Elixir | countSubstring = fn(_, "") -> 0
(str, sub) -> length(String.split(str, sub)) - 1 end
data = [ {"the three truths", "th"},
{"ababababab", "abab"},
{"abaabba*bbaba*bbab", "a*b"},
{"abaabba*bbaba*bbab", "a"},
{"abaabba*bbaba*bbab", " "},
{"abaabba*bbaba*bba... |
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... | #Erlang | Erlang |
%% Count non-overlapping substrings in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
-module(substrings).
-export([main/2]).
%% String and Sub exhausted, count a match and present result
match([], [], _OrigSub, Acc) ->
Acc+1;
%% String exhausted, present result
match([], _Sub, _OrigSub, Acc)... |
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... | #EDSAC_order_code | EDSAC order code |
[Count in octal, for Rosetta Code.
EDSAC program, Initial Orders 2.]
[Subroutine to print 17-bit non-negative integer in octal,
with suppression of leading zeros.
Input: 0F = number (not preserved)
Workspace: 0D, 4F, 5F]
T64K GK [load at location 64]
A3F T28@ [plant return link as usu... |
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... | #Elixir | Elixir | Stream.iterate(0,&(&1+1)) |> Enum.each(&IO.puts Integer.to_string(&1,8)) |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\di... | #DWScript | DWScript | function Factorize(n : Integer) : String;
begin
if n <= 1 then
Exit('1');
var k := 2;
while n >= k do begin
while (n mod k) = 0 do begin
Result += ' * '+IntToStr(k);
n := n div k;
end;
Inc(k);
end;
Result:=SubStr(Result, 4);
end;
var i : Integer;
for i := 1 to ... |
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... | #Erlang | Erlang |
-module( create_html_table ).
-export( [external_format/1, html_table/3, task/0] ).
external_format( XML ) -> remove_quoutes( lists:flatten(xmerl:export_simple_content([XML], xmerl_xml)) ).
html_table( Table_options, Headers, Contents ) ->
Header = html_table_header( Headers ),
Records = [html_table_record(X)... |
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
| #Racket | Racket | #lang racket
(require srfi/19)
;;; The first required format is an ISO-8601 year-month-day format, predefined
;;; as ~1 in date->string
(displayln (date->string (current-date) "~1"))
;;; You should be able to see how each of the components of the following format string
;;; work...
;;; ~d is zero padded day of mont... |
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
| #Raku | Raku | use DateTime::Format;
my $dt = DateTime.now;
say strftime('%Y-%m-%d', $dt);
say strftime('%A, %B %d, %Y', $dt); |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Python | Python |
def det(m,n):
if n==1: return m[0][0]
z=0
for r in range(n):
k=m[:]
del k[r]
z+=m[r][0]*(-1)**r*det([p[1:]for p in k],n-1)
return z
w=len(t)
d=det(h,w)
if d==0:r=[]
else:r=[det([r[0:i]+[s]+r[i+1:]for r,s in zip(h,t)],w)/d for i in range(w)]
print(r)
|
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.
| #Gambas | Gambas | Public Sub Main()
Dim byCount As Byte
Dim sToSave As String
For byCount = 0 To 50
sToSave &= Format(Str(byCount), "00") & " - Charlie was here!" & gb.NewLine
Next
File.Save(User.Home &/ "TestFile", sToSave)
Print File.Load(User.Home &/ "TestFile")
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.
| #Go | Go | package main
import (
"fmt"
"os"
)
func createFile(fn string) {
f, err := os.Create(fn)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("file", fn, "created!")
f.Close()
}
func createDir(dn string) {
err := os.Mkdir(dn, 0666)
if err != nil {
fmt.Pr... |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a st... | #Haskell | Haskell | --import Data.List.Split (splitOn) -- if the import is available
splitOn :: Char -> String -> [String] -- otherwise
splitOn delim = foldr (\x rest ->
if x == delim then "" : rest
else (x:head rest):tail rest) [""]
htmlEscape :: String -> String
htmlEscape = concatMa... |
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... | #Phix | Phix | with javascript_semantics
constant tcsv = """
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
"""
sequence lines = iff(platform()=JS?split(tcsv,"\n"):get_text("test.csv",GT_LF_STRIPPED))
for i=1 to length(lines) do
lines[i] = split(trim(lines[i]),',')
end for
lines[1] = join(lines[1],',')&",SUM"
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 ... | #REXX | REXX | do year=2008 to 2121
if date('w', year"1225", 's') == 'Sunday' then say year
end /*year*/ |
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 ... | #Ring | Ring |
for n = 2008 to 2121
if n < 2100 leap = n - 1900 else leap = n - 1904 ok
m = (((n-1900)%7) + floor(leap/4) + 27) % 7
if m = 4 see "25 Dec " + n + nl ok
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 ... | #JavaScript | JavaScript | var width = Number(prompt("Enter width: "));
var height = Number(prompt("Enter height: "));
//make 2D array
var arr = new Array(height);
for (var i = 0; i < h; i++) {
arr[i] = new Array(width);
}
//set value of element
a[0][0] = 'foo';
//print value of element
console.log('arr[0][0] = ' + arr[0][0]);
//cleanu... |
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... | #Lua | Lua | function stdev()
local sum, sumsq, k = 0,0,0
return function(n)
sum, sumsq, k = sum + n, sumsq + n^2, k+1
return math.sqrt((sumsq / k) - (sum/k)^2)
end
end
ldev = stdev()
for i, v in ipairs{2,4,4,4,5,5,7,9} do
print(ldev(v))
end |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #PowerBASIC | PowerBASIC | #COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
' ***********
FUNCTION CRC32(BYVAL p AS BYTE PTR, BYVAL NumBytes AS DWORD) AS DWORD
STATIC LUT() AS DWORD
LOCAL i, j, k, crc AS DWORD
IF ARRAYATTR(LUT(), 0) = 0 THEN
REDIM LUT(0 TO 255)
FOR i = 0 TO 255
k = i
FOR j = 0 TO 7
IF (k AND 1) THEN... |
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... | #PureBasic | PureBasic |
a$="The quick brown fox jumps over the lazy dog"
UseCRC32Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_CRC32)
OpenConsole()
PrintN("CRC32 Cecksum [hex] = "+UCase(b$))
PrintN("CRC32 Cecksum [dec] = "+Val("$"+b$))
Input()
End |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #Groovy | Groovy | def ccR
ccR = { BigInteger tot, List<BigInteger> coins ->
BigInteger n = coins.size()
switch ([tot:tot, coins:coins]) {
case { it.tot == 0 } :
return 1g
case { it.tot < 0 || coins == [] } :
return 0g
default:
return ccR(tot, coins[1..<n]) +
... |
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... | #Euphoria | Euphoria | function countSubstring(sequence s, sequence sub)
integer from,count
count = 0
from = 1
while 1 do
from = match_from(sub,s,from)
if not from then
exit
end if
from += length(sub)
count += 1
end while
return count
end function
? countSubstring(... |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer cou... | #F.23 | F# | open System
let countSubstring (where :string) (what : string) =
match what with
| "" -> 0 // just a definition; infinity is not an int
| _ -> (where.Length - where.Replace(what, @"").Length) / what.Length
[<EntryPoint>]
let main argv =
let show where what =
printfn @"countSubstring(""%s""... |
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... | #Emacs_Lisp | Emacs Lisp | (dotimes (i most-positive-fixnum) ;; starting from 0
(message "%o" 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... | #Erlang | Erlang |
F = fun(FF, I) -> io:fwrite("~.8B~n", [I]), FF(FF, I + 1) 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... | #EchoLisp | EchoLisp |
(define (task (nfrom 2) (range 20))
(for ((i (in-range nfrom (+ nfrom range))))
(writeln i "=" (string-join (prime-factors i) " x "))))
|
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... | #Eiffel | Eiffel |
class
COUNT_IN_FACTORS
feature
display_factor (p: INTEGER)
-- Factors of all integers up to 'p'.
require
p_positive: p > 0
local
factors: ARRAY [INTEGER]
do
across
1 |..| p as c
loop
io.new_line
io.put_string (c.item.out + "%T")
factors := factor (c.item)
across
f... |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The... | #Euphoria | Euphoria | puts(1,"<table>\n")
puts(1," <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>\n")
for i = 1 to 3 do
printf(1," <tr><td>%d</td>",i)
for j = 1 to 3 do
printf(1,"<td>%d</td>",rand(10000))
end for
puts(1,"</tr>\n")
end for
puts(1,"</table>") |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Raven | Raven | time int as today |
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
| #REBOL | REBOL | rebol [
Title: "Date Formatting"
URL: http://rosettacode.org/wiki/Date_format
]
; REBOL has no built-in pictured output.
zeropad: func [pad n][
n: to-string n
insert/dup n "0" (pad - length? n)
n
]
d02: func [n][zeropad 2 n]
print now ; Native formatting.
print rejoin [now/year "-" d02 now/mont... |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Racket | Racket | #lang typed/racket
(require math/matrix)
(define A (matrix [[2 -1 5 1]
[3 2 2 -6]
[1 3 3 -1]
[5 -2 -3 3]]))
(define B (col-matrix [ -3
-32
-47
49]))
(matrix->vector (matrix-solve A... |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Raku | Raku | sub det(@matrix) {
my @a = @matrix.map: { [|$_] };
my $sign = +1;
my $pivot = 1;
for ^@a -> $k {
my @r = ($k+1 .. @a.end);
my $previous-pivot = $pivot;
if 0 == ($pivot = @a[$k][$k]) {
(my $s = @r.first: { @a[$_][$k] != 0 }) // return 0;
(@a[$s],@a[$k]) = (@a[$k], @a[$s]... |
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.
| #Groovy | Groovy | new File("output.txt").createNewFile()
new File(File.separator + "output.txt").createNewFile()
new File("docs").mkdir()
new File(File.separator + "docs").mkdir() |
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.
| #Haskell | Haskell | import System.Directory
createFile name = writeFile name ""
main = do
createFile "output.txt"
createDirectory "docs"
createFile "/output.txt"
createDirectory "/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... | #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
pchar := &letters ++ &digits ++ '!?;. ' # printable chars
write("<TABLE>")
firstHead := (!arglist == "-heading")
tHead := write
while row := trim(read()) do {
if \firstHead then write(" <THEAD>") else tHead(" <TBODY>")
writes(" <TR><TD>")
whi... |
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... | #PHP | PHP |
<?php
// fputcsv() requires at least PHP 5.1.0
// file "data_in.csv" holds input data
// the result is saved in "data_out.csv"
// this version has no error-checking
$handle = fopen('data_in.csv','r');
$handle_output = fopen('data_out.csv','w');
$row = 0;
$arr = array();
while ($line = fgetcsv($handle))
{
$... |
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 ... | #Ruby | Ruby | require 'date'
(2008..2121).each {|year| puts "25 Dec #{year}" if Date.new(year, 12, 25).sunday? } |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of ... | #Run_BASIC | Run BASIC | for year = 2008 to 2121
if val(date$("12-25-";year)) mod 7 = 5 then print "For ";year;"xmas is Sunday"
next 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 ... | #jq | jq | M | setpath([i,j]; e)
|
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 ... | #Julia | Julia | function input(prompt::AbstractString)
print(prompt)
return readline()
end
n = input("Upper bound for dimension 1: ") |>
x -> parse(Int, x)
m = input("Upper bound for dimension 2: ") |>
x -> parse(Int, x)
x = rand(n, m)
display(x)
x[3, 3] # overloads `getindex` generic function
x[3, 3] = 5.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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];StandardDeviation[AppendTo[$Data, 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... | #Python | Python | >>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'
>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339' |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #QB64 | QB64 |
PRINT HEX$(crc32("The quick brown fox jumps over the lazy dog"))
FUNCTION crc32~& (buf AS STRING)
STATIC table(255) AS _UNSIGNED LONG
STATIC have_table AS _BYTE
DIM crc AS _UNSIGNED LONG, k AS _UNSIGNED LONG
DIM i AS LONG, j AS LONG
IF have_table = 0 THEN
FOR i = 0 TO 255
k... |
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... | #Haskell | Haskell | count :: (Integral t, Integral a) => t -> [t] -> a
count 0 _ = 1
count _ [] = 0
count x (c:coins) =
sum
[ count (x - (n * c)) coins
| n <- [0 .. (quot x c)] ]
main :: IO ()
main = print (count 100 [1, 5, 10, 25]) |
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... | #Factor | Factor | USING: math sequences splitting ;
: occurences ( seq subseq -- n ) split-subseq length 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... | #Forth | Forth | : str-count ( s1 len s2 len -- n )
2swap 0 >r
begin 2over search
while 2over nip /string
r> 1+ >r
repeat 2drop 2drop r> ;
s" the three truths" s" th" str-count . \ 3
s" ababababab" s" abab" str-count . \ 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... | #Euphoria | Euphoria | integer i
i = 0
while 1 do
printf(1,"%o\n",i)
i += 1
end while |
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... | #F.23 | F# | let rec countInOctal num : unit =
printfn "%o" num
countInOctal (num + 1)
countInOctal 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... | #Elixir | Elixir | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "#{n}: #{Enum.join(RC... |
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... | #Euphoria | Euphoria | function factorize(integer n)
sequence result
integer k
if n = 1 then
return {1}
else
k = 2
result = {}
while n > 1 do
while remainder(n, k) = 0 do
result &= k
n /= k
end while
k += 1
end while
... |
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... | #F.23 | F# | open System.Xml
type XmlDocument with
member this.Add element =
this.AppendChild element
member this.Element name =
this.CreateElement(name) :> XmlNode
member this.Element (name, (attr : (string * string) list)) =
let node = this.CreateElement(name)
for a in attr do
... |
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
| #RED | RED |
Red []
;; zeropad
f2n: func [d] [ if d > 9 [return d ] append copy "0" d ]
d: now/date
print rejoin [d/year "-" f2n d/month "-" f2n d/day]
print rejoin [system/locale/days/(d/weekday) ", " system/locale/months/(d/month) " " f2n d/day ", " d/year]
|
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
| #REXX | REXX | /*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/
x = date('S') /*get current date as yyyymmdd */
yyyy = left(x,4) /*pick off year (4 digs).*/
dd = right(x,2) /*pick off day-of-month (2 digs).*/
mm = substr(x,5,2)... |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #REXX | REXX | /* REXX Use Cramer's rule to compute solutions of given linear equations */
Numeric Digits 20
names='w x y z'
M=' 2 -1 5 1',
' 3 2 2 -6',
' 1 3 3 -1',
' 5 -2 -3 3'
v=' -3',
'-32',
'-47',
' 49'
Call mk_mat(m) /* M -> a.i.j */
Do j=1 To dim ... |
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.
| #HicEst | HicEst | SYSTEM(DIR="\docs") ! create argument if not existent, make it current
OPEN(FILE="output.txt", "NEW") ! in current directory
SYSTEM(DIR="C:\docs") ! create C:\docs if not existent, make it current
OPEN(FILE="output.txt", "NEW") ! in 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.
| #i | i | software {
create("output.txt")
create("docs/")
create("/output.txt")
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... | #J | J | require 'strings tables/csv'
encodeHTML=: ('&';'&';'<';'<';'>';'>')&stringreplace
tag=: adverb define
'starttag endtag'=.m
(,&.>/)"1 (starttag , ,&endtag) L:0 y
)
markupCells=: ('<td>';'</td>') tag
markupHdrCells=: ('<th>';'</th>') tag
markupRows=: ('<tr>';'</tr>',LF) tag
markupTable=: (('<t... |
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... | #PicoLisp | PicoLisp | (in "data.csv"
(prinl (line) "," "SUM")
(while (split (line) ",")
(prinl (glue "," @) "," (sum format @)) ) ) |
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... | #PL.2FI | PL/I | *process source xref attributes or(!);
csv: Proc Options(Main);
/*********************************************************************
* 19.10.2013 Walter Pachl
* 'erase d:\csv.out'
* 'set dd:in=d:\csv.in,recsize(300)'
* 'set dd:out=d:\csv.out,recsize(300)'
* Say 'Input:'
* 'type csv.in'
* 'csv'
* Say ' '
* ... |
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 ... | #Rust | Rust | extern crate chrono;
use chrono::prelude::*;
fn main() {
let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>();
println!("Years = {:?}", years);
} |
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 ... | #S-BASIC | S-BASIC |
$constant SUNDAY = 0
rem - compute p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)
comment
return day of week (Sun = 0, Mon = 1, etc.) for a
given Gregorian calendar date using Zeller's congruence
end
function dayofweek (mo, da, yr = integer) = integer
var y, c, z = integer
if m... |
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 ... | #Kotlin | Kotlin | fun main(args: Array<String>) {
// build
val dim = arrayOf(10, 15)
val array = Array(dim[0], { IntArray(dim[1]) } )
// fill
array.forEachIndexed { i, it ->
it.indices.forEach { j ->
it[j] = 1 + i + j
}
}
// print
array.forEach { println(it.asList()) }
} |
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 ... | #Logo | Logo | make "a2 mdarray [5 5]
mdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1
print mditem [1 1] :a2 ; 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... | #MATLAB_.2F_Octave | MATLAB / Octave | x = [2,4,4,4,5,5,7,9];
n = length (x);
m = mean (x);
x2 = mean (x .* x);
dev= sqrt (x2 - m * m)
dev = 2 |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Quackery | Quackery | [ table ] is crctable ( n --> n )
256 times
[ i^ 8 times
[ dup 1 >>
swap 1 & if
[ hex EDB88320 ^ ] ]
' crctable put ]
[ hex FFFFFFFF swap
witheach
[ over ^ hex FF &
crctable
swap 8 >> ^ ]
hex FFFFFFFF ^ ] is cr... |
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... | #R | R |
digest("The quick brown fox jumps over the lazy dog","crc32", serialize=F)
|
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
US_coins := [1, 5, 10, 25]
US_allcoins := [1,5,10,25,50,100]
EU_coins := [1, 2, 5, 10, 20, 50, 100, 200]
CDN_coins := [1,5,10,25,100,200]
CDN_allcoins := [1,5,10,25,50,100,200]
every trans := ![ [15,US_coins],
[100,US_coins],
... |
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... | #Fortran | Fortran | program Example
implicit none
integer :: n
n = countsubstring("the three truths", "th")
write(*,*) n
n = countsubstring("ababababab", "abab")
write(*,*) n
n = countsubstring("abaabba*bbaba*bbab", "a*b")
write(*,*) n
contains
function countsubstring(s1, s2) result(c)
character(*), intent(in) :: s... |
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... | #Factor | Factor | USING: kernel math prettyprint ;
0 [ dup .o 1 + t ] loop |
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... | #Forth | Forth | : octal ( -- ) 8 base ! ; \ where unavailable
octal ints |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\di... | #F.23 | F# | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (S... |
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... | #Factor | Factor | USING: html.streams literals prettyprint random xml.writer ;
: rnd ( -- n ) 10,000 random ;
{
{ "" "X" "Y" "Z" }
${ 1 rnd rnd rnd }
${ 2 rnd rnd rnd }
${ 3 rnd rnd rnd }
}
[ simple-table. ] with-html-writer pprint-xml |
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
| #Ring | Ring |
dateStr = date()
date1 = timelist()[19] + "-" + timelist()[10] + "-" + timelist()[6]
date2 = timelist()[2] + ", " + timelist()[4] + " " + timelist()[6] + ", " + timelist()[19] + nl
? dateStr
? date1
? date2
/*
timelist() ---> List contains the time and date information.
Index Value
-----------------------... |
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
| #Ruby | Ruby | puts Time.now
puts Time.now.strftime('%Y-%m-%d')
puts Time.now.strftime('%F') # same as %Y-%m-%d (ISO 8601 date formats)
puts Time.now.strftime('%A, %B %d, %Y') |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Ruby | Ruby | require 'matrix'
def cramers_rule(a, terms)
raise ArgumentError, " Matrix not square" unless a.square?
cols = a.to_a.transpose
cols.each_index.map do |i|
c = cols.dup
c[i] = terms
Matrix.columns(c).det / a.det
end
end
matrix = Matrix[
[2, -1, 5, 1],
[3, 2, 2, -6],
[1, 3, 3, -1... |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Rust | Rust | use std::ops::{Index, IndexMut};
fn main() {
let m = matrix(
vec![
2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,
],
4,
);
let mm = m.solve(&vec![-3., -32., -47., 49.]);
println!("{:?}", mm);
}
#[derive(Clone)]
struct Matrix {
elts: Vec<f... |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Icon_and_Unicon | Icon and Unicon | every dir := !["./","/"] do {
close(open(f := dir || "input.txt","w")) |stop("failure for open ",f)
mkdir(f := dir || "docs") |stop("failure for mkdir ",f)
} |
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... | #Java_2 | Java | String csv = "...";
// Use Collectors.joining(...) for streaming, otherwise StringJoiner
StringBuilder html = new StringBuilder("<table>\n");
Collector collector = Collectors.joining("</td><td>", " <tr><td>", "</td></tr>\n");
for (String row : csv.split("\n") ) {
html.append(Arrays.stream(row.split(",")).collect(c... |
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... | #PowerShell | PowerShell | ## Create a CSV file
@"
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
"@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force
## Import each line of the CSV file into an array of PowerShell objects
$records = Import-Csv -Path .\Temp.csv
## Sum the values of the properties of each object
$sums = ... |
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 ... | #SAS | SAS | data _null_;
do y=2008 to 2121;
a=mdy(12,25,y);
if weekday(a)=1 then put y;
end;
run;
/* 2011 2016 2022 2033 2039 2044 2050 2061 2067
2072 2078 2089 2095 2101 2107 2112 2118 */ |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of ... | #Scala | Scala | import java.util.{ Calendar, GregorianCalendar }
import Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }
object DayOfTheWeek extends App {
val years = 2008 to 2121
val yuletide =
years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY)
// If you want a test: (optional)
as... |
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 ... | #Lua | Lua | function multiply(n, a, b) if a <= b then return n, multiply(n, a + 1, b) end end
a, b = io.read() + 0, io.read() + 0
matrix = {multiply({multiply(1, 1, b)}, 1, a)}
matrix[a][b] = 5
print(matrix[a][b])
print(matrix[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... | #MiniScript | MiniScript | StdDeviator = {}
StdDeviator.count = 0
StdDeviator.sum = 0
StdDeviator.sumOfSquares = 0
StdDeviator.add = function(x)
self.count = self.count + 1
self.sum = self.sum + x
self.sumOfSquares = self.sumOfSquares + x*x
end function
StdDeviator.stddev = function()
m = self.sum / self.count
return sqrt... |
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... | #Racket | Racket | #lang racket
(define (bytes-crc32 data)
(bitwise-xor
(for/fold ([accum #xFFFFFFFF])
([byte (in-bytes data)])
(for/fold ([accum (bitwise-xor accum byte)])
([num (in-range 0 8)])
(bitwise-xor (quotient accum 2)
(* #xEDB88320 (bitwise-and accum 1)))))
#xFFFFFFFF))
(de... |
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... | #Raku | Raku | use NativeCall;
sub crc32(int32 $crc, Buf $buf, int32 $len --> int32) is native('z') { * }
my $buf = 'The quick brown fox jumps over the lazy dog'.encode;
say crc32(0, $buf, $buf.bytes).fmt('%08x'); |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.