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 ... | #AppleScript | AppleScript | set R to text returned of (display dialog "Enter number of rows:" default answer 2) as integer
set c to text returned of (display dialog "Enter number of columns:" default answer 2) as integer
set array to {}
repeat with i from 1 to R
set temp to {}
repeat with j from 1 to c
set temp's end to 0
end repeat
set arr... |
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... | #D | D | import std.stdio, std.math;
struct StdDev {
real sum = 0.0, sqSum = 0.0;
long nvalues;
void addNumber(in real input) pure nothrow {
nvalues++;
sum += input;
sqSum += input ^^ 2;
}
real getStdDev() const pure nothrow {
if (nvalues == 0)
return 0.0;
... |
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... | #Clojure | Clojure | (let [crc (new java.util.zip.CRC32)
str "The quick brown fox jumps over the lazy dog"]
(. crc update (. str getBytes))
(printf "CRC-32('%s') = %s\n" str (Long/toHexString (. crc getValue)))) |
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... | #COBOL | COBOL | *> tectonics: cobc -xj crc32-zlib.cob -lz
identification division.
program-id. rosetta-crc32.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 crc32-initial usag... |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write(map(&date,"/","-"))
write(&dateline ? tab(find(&date[1:5])+4))
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.
| #Action.21 | Action! | PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
PROC CreateFile(CHAR ARRAY fname)
BYTE dev=[1]
Close(dev)
Open(dev,fname,8)
Close(dev)
RETURN
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.
| #Ada | Ada | with Ada.Streams.Stream_IO, Ada.Directories;
use Ada.Streams.Stream_IO, Ada.Directories;
procedure File_Creation is
File_Handle : File_Type;
begin
Create (File_Handle, Out_File, "output.txt");
Close (File_Handle);
Create_Directory("docs");
Create (File_Handle, Out_File, "/output.txt");
Close ... |
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... | #AutoHotkey | AutoHotkey | CSVData =
(
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
)
TableData... |
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... | #ECL | ECL | // Assumes a CSV file exists and has been sprayed to a Thor cluster
MyFileLayout := RECORD
STRING Field1;
STRING Field2;
STRING Field3;
STRING Field4;
STRING Field5;
END;
MyDataset := DATASET ('~Rosetta::myCSVFile', MyFileLayout,CSV(SEPARATOR(',')));
MyFileLayout Appended(MyFileLayout pInput):= TRANSFORM
... |
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... | #Elixir | Elixir |
defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row,... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Nim | Nim |
from algorithm import reverse
const Table = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Objeck | Objeck | class DammAlgorithm {
@table : static : Int[,];
function : Main(args : String[]) ~ Nil {
@table := [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2]
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3]
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9]
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6]
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8]
[3, 6, 7, 4, 2, 0... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Haskell | Haskell | import Data.Numbers.Primes (isPrime)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
cubans :: [Int]
cubans = filter isPrime . map (\x -> (succ x ^ 3) - (x ^ 3)) $ [1 ..]
main :: IO ()
main = do
mapM_ (\row -> mapM_ (printf "%10s" . thousands) row >> printf "\n") $ row... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #J | J |
isPrime =: 1&p:
assert 1 0 -: isPrime 3 9
NB. difference, but first cube, of incremented y with y
dcc =: -&(^&3)~ >:
assert ((8 9 13^3)-7 8 12^3) -: dcc 7 8 12
Filter =: (#~`)(`:6)
assert 2 3 5 7 11 13 -: isPrime Filter i. 16
cubanPrime =: [: isPrime Filter dcc
assert 7 19 37 61 127 271 331 397 547 631 919... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Ring | Ring |
# Project : Currency
nhamburger = "4000000000"
phamburger = "5.50"
nmilkshakes = "2"
pmilkshakes = "2.86"
taxrate = "0.0765"
price = nhamburger * phamburger + nmilkshakes * pmilkshakes
tax = price * taxrate
see "total price before tax : " + price + nl
see "tax thereon @ 7.65 : " + tax + nl
see "total price after... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Ruby | Ruby | require 'bigdecimal/util'
before_tax = 4000000000000000 * 5.50.to_d + 2 * 2.86.to_d
tax = (before_tax * 0.0765.to_d).round(2)
total = before_tax + tax
puts "Before tax: $#{before_tax.to_s('F')}
Tax: $#{tax.to_s('F')}
Total: $#{total.to_s('F')}"
|
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Rust | Rust | extern crate num_bigint; // 0.3.0
extern crate num_rational; // 0.3.0
use num_bigint::BigInt;
use num_rational::BigRational;
use std::ops::{Add, Mul};
use std::fmt;
fn main() {
let hamburger = Currency::new(5.50);
let milkshake = Currency::new(2.86);
let pre_tax = hamburger * 4_000_000_000_000_000 +... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #PARI.2FGP | PARI/GP | curriedPlus(x)=y->x+y;
curriedPlus(1)(2) |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Perl | Perl | sub curry{
my ($func, @args) = @_;
sub {
#This @_ is later
&$func(@args, @_);
}
}
sub plusXY{
$_[0] + $_[1];
}
my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n"; |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Python | Python | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3] # format can't handle "EST" for some reason
tdelta = datetime.timedelta(hours=12) # twelve hours..
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftim... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #R | R | time <- strptime("March 7 2009 7:30pm EST", "%B %d %Y %I:%M%p %Z") # "2009-03-07 19:30:00"
isotime <- ISOdatetime(1900 + time$year, time$mon, time$mday,
time$hour, time$min, time$sec, "EST") # "2009-02-07 19:30:00 EST"
twelvehourslater <- isotime + 12 * 60 * 60 # "2... |
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 ... | #Lasso | Lasso | loop(-From=2008, -to=2121) => {^
local(tDate = date('12/25/' + loop_count))
#tDate->dayOfWeek == 1 ? '\r' + #tDate->format('%D') + ' is a 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 ... | #Liberty_BASIC | Liberty BASIC | count = 0
for year = 2008 to 2121
dateString$="12/25/";year
dayNumber=date$(dateString$)
if dayNumber mod 7 = 5 then
count = count + 1
print dateString$
end if
next year
print count; " years when Christmas Day falls on a Sunday"
end |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #PicoLisp | PicoLisp | (de cusip (Str)
(let (Str (mapcar char (chop Str)) S 0)
(for (I . C) (head 8 Str)
(let V
(cond
((<= 48 C 57) (- C 48))
((<= 65 C 90) (+ 10 (- C 65)))
((= C 42) 36)
((= C 64) 37)
((= C 35) 38) )
(or
... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #PowerShell | PowerShell |
function Get-CheckDigitCUSIP {
[CmdletBinding()]
[OutputType([int])]
Param ( # Validate input
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )] # @#*
[ValidateScript({$_.Length -eq 9})]
[string]
$cusip
)
$sum = 0
0..7 | ... |
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 ... | #Arturo | Arturo | width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]] |
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 ... | #AutoHotkey | AutoHotkey | Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2] |
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... | #Delphi | Delphi | def makeRunningStdDev() {
var sum := 0.0
var sumSquares := 0.0
var count := 0.0
def insert(v) {
sum += v
sumSquares += v ** 2
count += 1
}
/** Returns the standard deviation of the inputs so far, or null if there
have been no inputs. */
def stddev() {
... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #CoffeeScript | CoffeeScript |
crc32 = do ->
table =
for n in [0..255]
for [0..7]
if n & 1
n = 0xEDB88320 ^ n >>> 1
else
n >>>= 1
n
(str, crc = -1) ->
for c in str
crc = crc >>> 8 ^ table[(crc ^ c.charCodeAt 0) & 255]
(crc ^ -1) >>> 0
|
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... | #Common_Lisp | Common Lisp | (ql:quickload :ironclad)
(defun string-to-digest (str digest)
"Return the specified digest for the ASCII string as a hex string."
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence digest
(ironclad:ascii-string-to-byte-array str))))
(string-to-digest "The quick brown ... |
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... | #11l | 11l | UInt32 seed = 0
F nonrandom(n)
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) % n
F rand9999()
R nonrandom(9000) + 1000
F tag(tag, txt, attr = ‘’)
R ‘<’tag‘’attr‘>’txt‘</’tag‘>’
V header = tag(‘tr’, ‘,X,Y,Z’.split(‘,’).map(txt -> tag(‘th’, txt)).join(‘’))"\n"
V rows = (1..5).map(i -> tag(‘tr’... |
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
| #J | J | 6!:0 'YYYY-MM-DD'
2010-08-19 |
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
| #Java | Java |
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import java.text.DateFormat;
public class Dates{
public static void main(String[] args){
Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed
DateFormatSymbols symbols = new DateForma... |
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... | #11l | 11l | F det(mm)
V m = copy(mm)
V result = 1.0
L(j) 0 .< m.len
V imax = j
L(i) j + 1 .< m.len
I m[i][j] > m[imax][j]
imax = i
I imax != j
swap(&m[imax], &m[j])
result = -result
I abs(m[j][j]) < 1e-12
R Float.infinity
L(i) j + 1 .< m... |
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.
| #Aikido | Aikido |
var sout = openout ("output.txt") // in current dir
sout.close()
var sout1 = openout ("/output.txt") // in root dir
sout1.close()
mkdir ("docs")
mkdir ("/docs")
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Aime | Aime | # Make a directory using the -mkdir- program
void
mkdir(text p)
{
sshell ss;
b_cast(ss_path(ss), "mkdir");
l_append(ss_argv(ss), "mkdir");
l_append(ss_argv(ss), p);
ss_link(ss);
}
void
create_file(text p)
{
file f;
f_open(f, p, OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644);
... |
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... | #AutoIt | AutoIt |
Local $ascarray[4] = [34,38,60,62]
$String = "Character,Speech" & @CRLF
$String &= "The multitude,The messiah! Show us the messiah!" & @CRLF
$String &= "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" & @CRLF
$String &= "The multitude,Who are you?" &... |
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... | #Erlang | Erlang |
-module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Pascal | Pascal | program DammAlgorithm;
uses
sysutils;
TYPE TA = ARRAY[0..9,0..9] OF UInt8;
CONST table : TA =
((0,3,1,7,5,9,8,6,4,2),
(7,0,9,2,1,5,4,8,6,3),
(4,2,0,6,8,7,1,3,5,9),
(1,7,5,0,9,8,3,4,2,6),
(6,1,2,3,0,4,5,9,7,8),
(3,6,... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Java | Java |
public class CubanPrimes {
private static int MAX = 1_400_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
preCompute();
cubanPrime(200, true);
for ( int i = 1 ; i <= 5 ; i++ ) {
int max = (int) Math.pow(10, i);
... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Scala | Scala | import java.text.NumberFormat
import java.util.Locale
object SizeMeUp extends App {
val menu: Map[String, (String, Double)] = Map("burg" ->("Hamburger XL", 5.50), "milk" ->("Milkshake", 2.86))
val order = List((4000000000000000L, "burg"), (2L, "milk"))
Locale.setDefault(new Locale("ru", "RU"))
val (curr... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Phix | Phix | with javascript_semantics
sequence curries = {}
function create_curried(integer rid, sequence partial_args)
curries = append(curries,{rid,partial_args})
return length(curries) -- (return an integer id)
end function
function call_curried(integer id, sequence args)
{integer rid, sequence partial_args} = cur... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #PHP | PHP | <?php
function curry($callable)
{
if (_number_of_required_params($callable) === 0) {
return _make_function($callable);
}
if (_number_of_required_params($callable) === 1) {
return _curry_array_args($callable, _rest(func_get_args()));
}
return _curry_array_args($callable, _rest(func_... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Racket | Racket |
#lang racket
(require srfi/19)
(define 12hours (make-time time-duration 0 (* 12 60 60)))
(define (string->time s)
(define t (date->time-utc (string->date s "~B~e~Y~H~M")))
(if (regexp-match "pm" s)
(add-duration t 12hours)
t))
(date->string
(time-utc->date
(add-duration
(string->time "Marc... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Raku | Raku | my @month = <January February March April May June July August September October November December>;
my %month = flat (@month Z=> ^12), (@month».substr(0,3) Z=> ^12), 'Sept' => 8;
grammar US-DateTime {
rule TOP { <month> <day>','? <year>','? <time> <tz> }
token month {
(\w+)'.'? { make %month{$0} // die "... |
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 ... | #Lingo | Lingo | put "December 25 is a Sunday in:"
refDateObj = date(1905,1,2)
repeat with year = 2008 to 2121
dateObj = date(year, 12, 25)
dayOfWeek = ((dateObj - refDateObj) mod 7)+1 -- 1=Monday..7=Sunday
if dayOfWeek=7 then put year
end repeat |
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 ... | #LiveCode | LiveCode | function xmasSunday startDate endDate
convert the long date to dateitems
put it into xmasDay
put 12 into item 2 of xmasDay
put 25 into item 3 of xmasDay
repeat with i = startDate to endDate
put i into item 1 of xmasDay
convert xmasDay to dateItems
if item 7 of xmasDay is 1 th... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Python | Python | #!/usr/bin/env python3
import math
def cusip_check(cusip):
if len(cusip) != 9:
raise ValueError('CUSIP must be 9 characters')
cusip = cusip.upper()
total = 0
for i in range(8):
c = cusip[i]
if c.isdigit():
v = int(c)
elif c.isalpha():
p = ord... |
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 ... | #AutoIt | AutoIt | ; == get dimensions from user input
$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. "5,3"')
$aDimension = StringSplit($sInput, ',', 2)
; == create array
Dim $a2D[ $aDimension[0] ][ $aDimension[1] ]
; == write value to last row/last column
$a2D[ UBound($a2D) -1 ][ UBoun... |
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... | #E | E | def makeRunningStdDev() {
var sum := 0.0
var sumSquares := 0.0
var count := 0.0
def insert(v) {
sum += v
sumSquares += v ** 2
count += 1
}
/** Returns the standard deviation of the inputs so far, or null if there
have been no inputs. */
def stddev() {
... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Component_Pascal | Component Pascal |
MODULE BbtComputeCRC32;
IMPORT ZlibCrc32,StdLog;
PROCEDURE Do*;
VAR
s: ARRAY 128 OF SHORTCHAR;
BEGIN
s := "The quick brown fox jumps over the lazy dog";
StdLog.IntForm(ZlibCrc32.CRC32(0,s,0,LEN(s$)),16,12,'0',TRUE);
StdLog.Ln;
END Do;
END BbtComputeCRC32.
|
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... | #Crystal | Crystal |
require "digest/crc32";
p Digest::CRC32.checksum("The quick brown fox jumps over the lazy dog").to_s(16)
|
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... | #360_Assembly | 360 Assembly | * Create an HTML table 19/02/2017
CREHTML CSECT
USING CREHTML,R13
B 72(R15)
DC 17F'0'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 end of prolog
LA R8,RND
XPRNT PGBODY,64 ... |
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
| #JavaScript | JavaScript | var now = new Date(),
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' ... |
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... | #Ada | Ada | with Ada.Text_IO;
with Ada.Numerics.Generic_Real_Arrays;
procedure Cramers_Rules is
type Real is new Float;
-- This is the type we want to use in the matrix and vector
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real);
use Real_Arrays;
function Solve_Cramer (M : in Real_... |
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.
| #ALGOL_68 | ALGOL 68 | main:(
INT errno;
PROC touch = (STRING file name)INT:
BEGIN
FILE actual file;
INT errno := open(actual file, file name, stand out channel);
IF errno NE 0 THEN GO TO stop touch FI;
close(actual file); # detach the book and keep it #
errno
EXIT
stop touch:
errno
END;
errno :=... |
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... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
FS=","
print "<table>"
}
{
gsub(/</, "\\<")
gsub(/>/, "\\>")
gsub(/&/, "\\>")
print "\t<tr>"
for(f = 1; f <= NF; f++) {
if(NR == 1 && header) {
printf "\t\t<th>%s</th>\n", $f
... |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #Euphoria | Euphoria | --- Read CSV file and add columns headed with 'SUM'
--- with trace
-- trace(0)
include get.e
include std/text.e
function split(sequence s, integer c)
sequence removables = " \t\n\r\x05\u0234\" "
sequence out
integer first, delim
out = {}
first = 1
while first <= length(s) do
delim = ... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Perl | Perl | sub damm {
my(@digits) = split '', @_[0];
my @tbl =([< 0 3 1 7 5 9 8 6 4 2 >],
[< 7 0 9 2 1 5 4 8 6 3 >],
[< 4 2 0 6 8 7 1 3 5 9 >],
[< 1 7 5 0 9 8 3 4 2 6 >],
[< 6 1 2 3 0 4 5 9 7 8 >],
[< 3 6 7 4 2 0 9 5 8 1 >],
[< 5 8 6 9 7 2... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #jq | jq | # input should be a non-negative integer
def commatize:
def digits: tostring | explode | reverse;
[foreach digits[] as $d (-1; .+1;
(select(. > 0 and . % 3 == 0)|44), $d)] # "," is 44
| reverse | implode ;
def count(stream): reduce stream as $i (0; .+1);
def lpad($len): tostring | ($len - length) ... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Julia | Julia | using Primes
function cubanprimes(N)
cubans = zeros(Int, N)
cube100k, cube1, count = 0, 1, 1
for i in Iterators.countfrom(1)
j = BigInt(i + 1)
cube2 = j^3
diff = cube2 - cube1
if isprime(diff)
count ≤ N && (cubans[count] = diff)
if count == 100000
... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Sidef | Sidef | struct Item {
name, price, quant
}
var check = %q{
Hamburger 5.50 4000000000000000
Milkshake 2.86 2
}.lines.grep(/\S/).map { Item(.words...) }
var tax_rate = 0.0765
var fmt = "%-10s %8s %18s %22s\n"
printf(fmt, %w(Item Price Quantity Extension)...)
var subtotal = check.map { |item|
var... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Smalltalk | Smalltalk | check := #(
" amount name price "
(4000000000000000 'hamburger' 5.50s2 )
(2 'milkshakes' 2.86s2 )
).
tax := 7.65s2.
fmt := '%-10s %10P %22P %26P\n'.
totalSum := 0.
totalTax := 0.
Transcript clear.
Transcript printf:fmt withAll:#('Item' 'Price' 'Qty' 'Extension').
T... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #PicoLisp | PicoLisp | : (de multiplier (@X)
(curry (@X) (N) (* @X N)) )
-> multiplier
: (multiplier 7)
-> ((N) (* 7 N))
: ((multiplier 7) 3)
-> 21 |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #PowerShell | PowerShell |
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }
|
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Prolog | Prolog | ?- [library('lambda.pl')].
% library(lambda.pl) compiled into lambda 0,00 sec, 28 clauses
true.
?- N = 5, F = \X^Y^(Y is X+N), maplist(F, [1,2,3], L).
N = 5,
F = \X^Y^ (Y is X+5),
L = [6,7,8].
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #REBOL | REBOL | rebol [
Title: "Date Manipulation"
URL: http://rosettacode.org/wiki/Date_Manipulation
]
; Only North American zones here -- feel free to extend for your area.
zones: [
NST -3:30 NDT -2:30 AST -4:00 ADT -3:00 EST -5:00 EDT -4:00
CST -6:00 CDT -5:00 MST -7:00 MDT -6:00 PST -8:00 PDT -7:00 AKST -9:00
AKDT -8:00 H... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Red | Red |
d: 07-Mar-2009/19:30 + 12:00
print d
8-Mar-2009/7:30:00
d/timezone: 1
print d
8-Mar-2009/8:30:00+01:00 |
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 ... | #Logo | Logo | ; Determine if a Gregorian calendar year is leap
to leap? :year
output (and
equal? 0 modulo :year 4
not member? modulo :year 400 [100 200 300]
)
end
; Convert Gregorian calendar date to a simple day count from
; day 1 = January 1, 1 CE
to day_number :year :month :day
local "elapsed make "elapsed dif... |
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 ... | #Lua | Lua | require("date")
for year=2008,2121 do
if date(year, 12, 25):getweekday() == 1 then
print(year)
end
end |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Quackery | Quackery | [ -1 split 0 peek char 0 -
swap 0 swap
witheach
[ [ dup char 0 char 9 1+ within iff
[ char 0 - ] done
dup char A char Z 1+ within iff
[ char A - 10 + ] done
dup char * = iff
[ drop 36 ] done
dup char @ = iff
[ drop 37 ] done
... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Racket | Racket | #lang racket
(require srfi/14)
(define 0-char (char->integer #\0))
(define A-char (char->integer #\A))
(define (cusip-value c)
(cond
[(char-set-contains? char-set:digit c)
(- (char->integer c) 0-char)]
[(char-set-contains? char-set:upper-case c)
(+ 10 (- (char->integer c) A-char))]
[(char=... |
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 ... | #AWK | AWK | /[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
# how to scan "multidim" array as explained in the GNU AWK manual
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
} |
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... | #Elixir | Elixir | defmodule Standard_deviation do
def add_sample( pid, n ), do: send( pid, {:add, n} )
def create, do: spawn_link( fn -> loop( [] ) end )
def destroy( pid ), do: send( pid, :stop )
def get( pid ) do
send( pid, {:get, self()} )
receive do
{ :get, value, _pid } -> value
end
end
def tas... |
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... | #D | D | void main() {
import std.stdio, std.digest.crc;
"The quick brown fox jumps over the lazy dog"
.crc32Of.crcHexString.writeln;
} |
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... | #Delphi | Delphi | program CalcCRC32;
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.ZLib;
var
Data: AnsiString = 'The quick brown fox jumps over the lazy dog';
CRC: UInt32;
begin
CRC := crc32(0, @Data[1], Length(Data));
WriteLn(Format('CRC32 = %8.8X', [CRC]));
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... | #11l | 11l | F changes(amount, coins)
V ways = [Int64(0)] * (amount + 1)
ways[0] = 1
L(coin) coins
L(j) coin .. amount
ways[j] += ways[j - coin]
R ways[amount]
print(changes(100, [1, 5, 10, 25]))
print(changes(100000, [1, 5, 10, 25, 50, 100])) |
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... | #Action.21 | Action! | DEFINE ROW_COUNT="4"
DEFINE COL_COUNT="3"
PROC Main()
CHAR ARRAY headers=[0 'X 'Y 'Z]
BYTE row,col
INT v
PrintE("<html>")
PrintE("<head></head>")
PrintE("<body>")
PrintE("<table border=1>")
PrintE("<thead align=""center"">")
Print("<tr><th></th>")
FOR col=1 TO COL_COUNT
DO
PrintF("<th>%C... |
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
| #Joy | Joy |
DEFINE weekdays == [ "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday" ];
months == [ "January" "February" "March" "April" "May" "June" "July" "August"
"September" "October" "November" "December" ].
time localtime [ [0 at 'd 4 4 format] ["-"] [1 at 'd 2 2 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
| #jq | jq | $ jq -n 'now | (strftime("%Y-%m-%d"), strftime("%A, %B %d, %Y"))'
"2015-07-02"
"Thursday, July 02, 2015" |
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... | #ALGOL_68 | ALGOL 68 | # returns the solution of a.x = b via Cramer's rule #
# this is for REAL arrays, could define additional operators #
# for INT, COMPL, etc. #
PRIO CRAMER = 1;
OP CRAMER = ( [,]REAL a, []REAL b )[]REAL:
IF 1 UPB a /= 2 UPB a
OR 1 LW... |
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.
| #APL | APL | 'output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
'\output.txt' ⎕ncreate ¯1+⌊/0,⎕nnums
⎕mkdir 'Docs'
⎕mkdir '\Docs' |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #AppleScript | AppleScript | close (open for access "output.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... | #Batch_File | Batch File | ::Batch Files are terrifying when it comes to string processing.
::But well, a decent implementation!
@echo off
REM Below is the CSV data to be converted.
REM Exactly three colons must be put before the actual line.
:::Character,Speech
:::The multitude,The messiah! Show us the messiah!
:::Brians mother,<angry>Now you... |
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... | #F.23 | F# | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line su... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Phix | Phix | constant tbl = sq_add(1,{{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, ... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Kotlin | Kotlin | import kotlin.math.ceil
import kotlin.math.sqrt
fun main() {
val primes = mutableListOf(3L, 5L)
val cutOff = 200
val bigUn = 100_000
val chunks = 50
val little = bigUn / chunks
println("The first $cutOff cuban primes:")
var showEach = true
var c = 0
var u = 0L
var v = 1L
... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Swift | Swift | import Foundation
extension Decimal {
func rounded(_ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
var result = Decimal()
var localCopy = self
NSDecimalRound(&result, &localCopy, scale, roundingMode)
return result
}
}
let costHamburgers = Decimal(4000000000000000) * Deci... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Tcl | Tcl | package require math::decimal
namespace import math::decimal::*
set hamburgerPrice [fromstr 5.50]
set milkshakePrice [fromstr 2.86]
set taxRate [/ [fromstr 7.65] [fromstr 100]]
set burgers 4000000000000000
set shakes 2
set net [+ [* [fromstr $burgers] $hamburgerPrice] [* [fromstr $shakes] $milkshakePrice]]
set tax ... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #VBA | VBA | Public Sub currency_task()
'4000000000000000 hamburgers at $5.50 each
Dim number_of_hamburgers As Variant
number_of_hamburgers = CDec(4E+15)
Dim price_of_hamburgers As Currency
price_of_hamburgers = 5.5
'2 milkshakes at $2.86 each, and
Dim number_of_milkshakes As Integer
number_of_milksh... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Python | Python | def addN(n):
def adder(x):
return x + n
return adder |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Quackery | Quackery | [ ' [ ' ] swap nested join
]'[ nested join ] is curried ( x --> [ ) |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Racket | Racket |
#lang racket
(((curry +) 3) 2) ; =>5
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #REXX | REXX | /*REXX program adds 12 hours to a given date and time, displaying the before and after.*/
aDate = 'March 7 2009 7:30pm EST' /*the original or base date to be used.*/
parse var aDate mon dd yyyy hhmm tz . /*obtain the various parts and pieces. */
mins = time('M', hhmm, "C") ... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Ring | Ring |
# Project : Date manipulation
load "stdlib.ring"
dateorigin = "March 7 2009 7:30pm EST"
monthname = "January February March April May June July August September October November December"
for i = 1 to 12
if dateorigin[1] = monthname[i]
monthnum = i
ok
next
thedate = str2list(substr(dateorigin, ... |
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 ... | #M2000_Interpreter | M2000 Interpreter |
Print "December 25 is a Sunday in:"
For Year=2008 to 2121 {
if Str$(Date("25/12/"+str$(Year,"")),"w")="1" Then {
Print Year
}
}
\\ is the same with this:
Print "December 25 is a Sunday in:"
For Year=2008 to 2121 {
if Str$(Date(str$(Year,"")+"-12-25"),"w")="1" Then {
Print... |
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 ... | #M4 | M4 | divert(-1)
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
dnl julian day number corresponding to December 25th of given year
define(`julianxmas',
`define(`yrssince0',eval($1+4712))`'define(`noOfLpYrs',
eval((yrssince0+3)... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Raku | Raku | sub divmod ($v, $r) { $v div $r, $v mod $r }
my %chr = (flat 0..9, 'A'..'Z', <* @ #>) Z=> 0..*;
sub cuisp-check ($cuisp where *.chars == 9) {
my ($code, $chk) = $cuisp.comb(8);
my $sum = [+] $code.comb.kv.map: { [+] (($^k % 2 + 1) * %chr{$^v}).&divmod(10) };
so (10 - $sum mod 10) mod 10 eq $chk;
}
# TES... |
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 ... | #BASIC | BASIC | 10 INPUT "ENTER TWO INTEGERS:"; X%, Y%
20 DIM A%(X% - 1, Y% - 1)
30 X% = RND(1) * X%
40 Y% = RND(1) * Y%
50 A%(X%, Y%) = -32767
60 PRINT A%(X%, Y%)
70 CLEAR |
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 ... | #BQN | BQN | #!/usr/bin/env bqn
# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# (BQNcrate phrase).
Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢
# Natural number from base-10 digits (BQNcrate phrase).
Base10 ← 10⊸×⊸+˜´∘⌽
# Parse any number of space-separated numbers from string 𝕩.
ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}... |
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.