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 ... | #Clean | Clean | import StdEnv
Start :: *World -> { {Real} }
Start world
# (console, world) = stdio world
(_, dim1, console) = freadi console
(_, dim2, console) = freadi console
= createArray dim1 (createArray dim2 1.0) |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #Clojure | Clojure | (let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0))) |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #Forth | Forth | : f+! ( x addr -- ) dup f@ f+ f! ;
: st-count ( stats -- n ) f@ ;
: st-sum ( stats -- sum ) float+ f@ ;
: st-sumsq ( stats -- sum*sum ) 2 floats + f@ ;
: st-mean ( stats -- mean )
dup st-sum st-count f/ ;
: st-variance ( stats -- var )
dup st-sumsq
dup st-mean fdup f* dup st-count... |
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... | #FreeBASIC | FreeBASIC | ' version 18-03-2017
' compile with: fbc -s console
Function crc32(buf As String) As UInteger<32>
Static As UInteger<32> table(256)
Static As UInteger<32> have_table
Dim As UInteger<32> crc, k
Dim As ULong i, j
If have_table = 0 Then
For i = 0 To 255
k = i
For j... |
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... | #AutoHotkey | AutoHotkey | countChange(amount){
return cc(amount, 4)
}
cc(amount, kindsOfCoins){
if ( amount == 0 )
return 1
if ( amount < 0 ) || ( kindsOfCoins == 0 )
return 0
return cc(amount, kindsOfCoins-1)
+ cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)
}
firstDenomination(kindsOfCoins){
return [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... | #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
jmp demo
;;; Count non-overlapping substrings [ES:DI] in [DS:SI]
;;; Return count in AX
subcnt: xor ax,ax ; Set count to 0
xor dl,dl ; Zero to compare to
mov bp,di ; Keep copy of substring pointer
.scan: cmp dl,[si] ; End of string?
je .out ; Then we're done
mov bx,si ; Ke... |
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... | #8080_Assembly | 8080 Assembly |
;-------------------------------------------------------
; useful equates
;-------------------------------------------------------
bdos equ 5 ; CP/M BDOS entry
conout equ 2 ; BDOS console output function
cr equ 13 ; ASCII carriage return
lf equ 10 ; ASCII line feed
;-----------------------------------------------... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program countOctal64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesA... |
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... | #360_Assembly | 360 Assembly | * Count in factors 24/03/2017
COUNTFAC CSECT assist plig\COUNTFAC
USING COUNTFAC,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13... |
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... | #Action.21 | Action! | PROC PrintFactors(CARD a)
BYTE notFirst
CARD p
IF a=1 THEN
PrintC(a) RETURN
FI
p=2 notFirst=0
WHILE p<=a
DO
IF a MOD p=0 THEN
IF notFirst THEN
Put('x)
FI
notFirst=1
PrintC(p)
a==/p
ELSE
p==+1
FI
OD
RETURN
PROC Main()
CARD i
FOR i=1 ... |
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... | #AutoHotkey | AutoHotkey | out = <table style="text-align:center; border: 1px solid"><th></th><th>X</th><th>Y</th><th>Z</th><tr>
Loop 4
out .= "`r`n<tr><th>" A_Index "</th><td>" Rand() "</td><td>" Rand() "</td><td>" Rand() "</tr>"
out .= "`r`n</table>"
MsgBox % clipboard := out
Rand(u=1000){
Random, n, 1, % u
return n
} |
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
| #Lua | Lua | print( os.date( "%Y-%m-%d" ) )
print( os.date( "%A, %B %d, %Y" ) ) |
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
| #M2000_Interpreter | M2000 Interpreter |
Print str$(today, "yyyy-mm-dd")
Print str$(today, "dddd, mmm, dd, yyyy")
|
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... | #D | D | import std.array : array, uninitializedArray;
import std.range : iota;
import std.stdio : writeln;
import std.typecons : tuple;
alias vector = double[4];
alias matrix = vector[4];
auto johnsonTrotter(int n) {
auto p = iota(n).array;
auto q = iota(n).array;
auto d = uninitializedArray!(int[])(n);
d[]... |
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.
| #BBC_BASIC | BBC BASIC | CLOSE #OPENOUT("output.txt")
CLOSE #OPENOUT("\output.txt")
*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.
| #Blue | Blue | global _start
: syscall ( num:eax -- result:eax ) syscall ;
: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;
: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;
: open ( pathname:edi flags:esi mode:edx -- fd:e... |
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... | #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
class Program
{
private static string ConvertCsvToHtmlTable(string csvText)
{
//split the CSV, assume no commas or line breaks in text
List<List<string>> splitString = new List<List<s... |
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... | #Go | Go | package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log... |
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.
| #Python | Python | def damm(num: int) -> bool:
row = 0
for digit in str(num):
row = _matrix[row][int(digit)]
return row == 0
_matrix = (
(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),... |
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 - ... | #Phix | Phix | with javascript_semantics
include mpfr.e
integer np = 0,
i = 2
mpz p3 = mpz_init(1*1*1),
i3 = mpz_init(),
p = mpz_init(),
pn = mpz_init()
printf(1,"The first 200 cuban primes are:\n")
sequence first200 = {}
atom t0 = time()
constant lim = iff(platform()=JS?10000:100000)
while np<lim do
mpz_... |
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... | #TXR | TXR | (op - 10 @1 @2 5) |
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... | #Vala | Vala | delegate double Dbl_Op(double d);
Dbl_Op curried_add(double a) {
return (b) => a + b;
}
void main() {
print(@"$(curried_add(3.0)(4.0))\n");
double sum2 = curried_add(2.0) (curried_add(3.0)(4.0)); //sum2 = 9
print(@"$sum2\n");
} |
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... | #Visual_Basic_.NET | Visual Basic .NET | Option Explicit On
Option Infer On
Option Strict On
Module Currying
' The trivial curry.
Function Curry(Of T1, TResult)(func As Func(Of T1, TResult)) As Func(Of T1, TResult)
' At least satisfy the implicit contract that the result isn't reference-equal to the original function.
Return Function... |
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.
| #Smalltalk | Smalltalk | DateTime extend [
setYear: aNum [ year := aNum ]
].
Object subclass: DateTimeTZ [
|dateAndTime timeZoneDST timeZoneName timeZoneVar|
DateTimeTZ class >> new [ ^(super basicNew) ]
DateTimeTZ class >> readFromWithMeridian: aStream andTimeZone: aDict [
|me|
me := self new.
^ me initWithMeridian: ... |
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 ... | #MUMPS | MUMPS |
DOWHOLIDAY
;In what years between 2008 and 2121 will December 25 be a Sunday?
;Uses the VA's public domain routine %DTC (Part of the Kernel) named here DIDTC
NEW BDT,EDT,CHECK,CHKFOR,LIST,I,X,Y
;BDT - the beginning year to check
;EDT - the end year to check
;BDT and EDT are year offsets from the epoch date 1/1/... |
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 ... | #Nanoquery | Nanoquery | import Nanoquery.Util
// loop through the years 2008 through 2121
for year in range(2008, 2121)
if (new(Date,"12/25/" + str(year)).getDayOfWeek() = "Sunday")
println "In " + year + ", December 25th is a Sunday."
end if
end for |
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... | #Tcl | Tcl | proc ordinal-of-alpha {c} { ;# returns ordinal position of c in the alphabet (A=1, B=2...)
lsearch {_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z} [string toupper $c]
}
proc Cusip-Check-Digit {cusip} { ;# algorithm Cusip-Check-Digit(cusip) is
if {[string length $cus... |
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 ... | #CLU | CLU | prompt = proc (s: string) returns (int)
stream$puts(stream$primary_output(), s)
return(int$parse(stream$getl(stream$primary_input())))
end prompt
start_up = proc ()
po: stream := stream$primary_output()
% Ask for width and height
width: int := prompt("Width? ")
height: int := prompt("Height?... |
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 ... | #Common_Lisp | Common Lisp | (let ((d1 (read))
(d2 (read)))
(assert (and (typep d1 '(integer 1))
(typep d2 '(integer 1)))
(d1 d2))
(let ((array (make-array (list d1 d2) :initial-element nil))
(p1 0)
(p2 (floor d2 2)))
(setf (aref array p1 p2) t)
(print (aref array p1 p2)))) |
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... | #Fortran | Fortran |
program standard_deviation
implicit none
integer(kind=4), parameter :: dp = kind(0.0d0)
real(kind=dp), dimension(:), allocatable :: vals
integer(kind=4) :: i
real(kind=dp), dimension(8) :: sample_data = (/ 2, 4, 4, 4, 5, 5, 7, 9 /)
do i = lbound(sample_data, 1), ubound(sample_data, 1)
call sampl... |
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... | #Go | Go | package main
import (
"fmt"
"hash/crc32"
)
func main() {
s := []byte("The quick brown fox jumps over the lazy dog")
result := crc32.ChecksumIEEE(s)
fmt.Printf("%X\n", result)
} |
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... | #Groovy | Groovy | def crc32(byte[] bytes) {
new java.util.zip.CRC32().with { update bytes; value }
} |
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... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
print cc(100)
exit
}
function cc(amount, coins, numPennies, numNickles, numQuarters, p, n, d, q, s, count) {
numPennies = amount
numNickles = int(amount / 5)
numDimes = int(amount / 10)
numQuarters = int(amount / 25)
count = 0
for (p = 0; p <= numPennie... |
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... | #Action.21 | Action! | BYTE FUNC CountSubstring(CHAR ARRAY s,sub)
BYTE i,j,res,found
i=1 res=0
WHILE i-1+sub(0)<=s(0)
DO
found=1
FOR j=1 TO sub(0)
DO
IF s(j+i-1)#sub(j) THEN
found=0
EXIT
FI
OD
IF found=1 THEN
i==+sub(0)
res==+1
ELSE
i==+1
FI
OD
RETURN (re... |
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... | #Ada | Ada | with Ada.Strings.Fixed, Ada.Integer_Text_IO;
procedure Substrings is
begin
Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "the three truths",
Pattern => "th"));
Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => "ababababab",
... |
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... | #Action.21 | Action! | PROC PrintOctal(CARD v)
CHAR ARRAY a(6)
BYTE i=[0]
DO
a(i)=(v&7)+'0
i==+1
v=v RSH 3
UNTIL v=0
OD
DO
i==-1
Put(a(i))
UNTIL i=0
OD
RETURN
PROC Main()
CARD i=[0]
DO
PrintF("decimal=%U octal=",i)
PrintOctal(i) PutE()
i==+1
UNTIL i=0
OD
RETURN |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Octal is
package IIO is new Ada.Text_IO.Integer_IO(Integer);
begin
for I in 0 .. Integer'Last loop
IIO.Put(I, Base => 8);
Ada.Text_IO.New_Line;
end loop;
end Octal; |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\di... | #Ada | Ada | with Ada.Command_Line, Ada.Text_IO, Prime_Numbers;
procedure Count is
package Prime_Nums is new Prime_Numbers
(Number => Natural, Zero => 0, One => 1, Two => 2); use Prime_Nums;
procedure Put (List : Number_List) is
begin
for Index in List'Range loop
Ada.Text_IO.Put (Integer'Image (List... |
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... | #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
print "<table>\n <thead align = \"right\">"
printf " <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = \"right\">\n"
for (i=1; i<=10; i++) {
printf " <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n",i, 10*i, 100*i, 1000*i-1
}
... |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Maple | Maple |
with(StringTools);
FormatTime("%Y-%m-%d")
FormatTime("%A,%B %d, %y")
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DateString[{"Year", "-", "Month", "-", "Day"}]
DateString[{"DayName", ", ", "MonthName", " ", "Day", ", ", "Year"}] |
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... | #EchoLisp | EchoLisp |
(lib 'matrix)
(string-delimiter "")
(define (cramer A B (X)) ;; --> vector X
(define ∆ (determinant A))
(for/vector [(i (matrix-col-num A))]
(set! X (matrix-set-col! (array-copy A) i B))
(// (determinant X) ∆)))
(define (task)
(define A (list->array
'( 2 -1 5 1 3 2 2 -6 1 3 3 -1 5 -2 -3 3) 4 4))
(define... |
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.
| #Bracmat | Bracmat | put$(,"output.txt",NEW) |
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.
| #C | C | #include <stdio.h>
int main() {
FILE *fh = fopen("output.txt", "w");
fclose(fh);
return 0;
} |
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... | #C.2B.2B | C++ | #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the me... |
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... | #Groovy | Groovy | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt'... |
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.
| #Quackery | Quackery | [ 0 swap witheach
[ char 0 - dip
[ 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 ]
[ 5 8 6 9 7 2 0 1 3 4 ]
... |
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.
| #R | R | Damm_algo <- function(number){
row_i = 0
iterable = strsplit(toString(number), "")[[1]]
validation_matrix =
matrix(
c(
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,... |
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 - ... | #Python | Python |
import datetime
import math
primes = [ 3, 5 ]
cutOff = 200
bigUn = 100_000
chunks = 50
little = bigUn / chunks
tn = " cuban prime"
print ("The first {:,}{}s:".format(cutOff, tn))
c = 0
showEach = True
u = 0
v = 1
st = datetime.datetime.now()
for i in range(1, int(math.pow(2,20))):
found = False
u += 6
... |
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... | #Wortel | Wortel | @let {
addOne \+ 1
subtractFrom1 \- 1
subtract1 \~- 1
subtract1_2 &\- [. 1]
add ^+
; partial apply to named functions
addOne_2 \add 1
; testing
[[
!addOne 5 ; returns 6
!subtractFrom1 5 ; returns -4
!subtract1 5 ; returns 4
!subtract1_2 5 ; returns 4
!addOne_2 5 ; returns 6
... |
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... | #Wren | Wren | var addN = Fn.new { |n| Fn.new { |x| n + x } }
var adder = addN.call(40)
System.print("The answer to life is %(adder.call(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... | #Z80_Assembly | Z80 Assembly | macro ResetCursors
ld hl,&0101
call &BB75
endm |
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.
| #SQL | SQL |
-- March 7 2009 7:30pm EST
SELECT
TO_TIMESTAMP_TZ(
'March 7 2009 7:30pm EST',
'MONTH DD YYYY HH:MIAM TZR'
)
at TIME zone 'US/Eastern' orig_dt_time
FROM dual;
-- 12 hours later DST change
SELECT
(TO_TIMESTAMP_TZ(
'March 7 2009 7:30pm EST',
'MONTH DD YYYY HH:MIAM TZR'
)+
INTERVAL '12' HOUR)
at TIME zone 'US/Eas... |
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.
| #Standard_ML | Standard ML |
val smltime= fn input => (* parse given format *)
let
val mth::day::year::itime::t = String.fields Char.isSpace input ;
val tmp = String.fields (fn x=> x= #":") itime;
val h = (valOf(Int.fromString (hd tmp) )) + (if String.isSuffix "pm" (hd(tl tm... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
yearRanges = [int 2008, 2121]
searchday = ''
cal = Calendar
loop year = yearRanges[0] to yearRanges[1]
cal = GregorianCalendar(year, Calendar.DECEMBER, 25)
dayIndex = cal.get(Calendar.DAY_OF_WEEK)
if dayIndex = Calendar.SUNDA... |
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 ... | #Nim | Nim | import times
for year in 2008..2121:
if getDayOfWeek(25, mDec, year) == dSun:
stdout.write year, ' '
echo "" |
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... | #VBA | VBA | Private Function Cusip_Check_Digit(s As Variant) As Integer
Dim Sum As Integer, c As String, v As Integer
For i = 1 To 8
c = Mid(s, i, 1)
If IsNumeric(c) Then
v = Val(c)
Else
Select Case c
Case "a" To "z"
v = Asc(c) - Asc("a") +... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function IsCUSIP(s As String) As Boolean
If s.Length <> 9 Then
Return False
End If
Dim sum = 0
For i = 0 To 7
Dim c = s(i)
Dim v As Integer
If "0" <= c AndAlso c <= "9" Then
v = Asc(c) - 48
... |
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 ... | #Component_Pascal | Component Pascal |
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
IMPORT Out;
(* Open array *)
PROCEDURE DoTwoDim*;
VAR d: POINTER TO ARRAY OF ARRAY OF INTEGER;
BEGIN
NEW(d, 5, 4); (* allocating array in memory *)
d[1, 2] := 100; (* second row, third column element *)
d[4, 3] := -100; (* fifth row, ... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function calcStandardDeviation(number As Double) As Double
Static a() As Double
Redim Preserve a(0 To UBound(a) + 1)
Dim ub As UInteger = UBound(a)
a(ub) = number
Dim sum As Double = 0.0
For i As UInteger = 0 To ub
sum += a(i)
Next
Dim mean As Double = sum / (ub + 1)
Dim dif... |
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... | #Haskell | Haskell | import Data.Bits ((.&.), complement, shiftR, xor)
import Data.Word (Word32)
import Numeric (showHex)
crcTable :: Word32 -> Word32
crcTable = (table !!) . fromIntegral
where
table = ((!! 8) . iterate xf) <$> [0 .. 255]
shifted x = shiftR x 1
xf r
| r .&. 1 == 1 = xor (shifted r) 0xedb88320
| ... |
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... | #BBC_BASIC | BBC BASIC | DIM uscoins%(3)
uscoins%() = 1, 5, 10, 25
PRINT FNchange(100, uscoins%()) " ways of making $1"
PRINT FNchange(1000, uscoins%()) " ways of making $10"
DIM ukcoins%(7)
ukcoins%() = 1, 2, 5, 10, 20, 50, 100, 200
PRINT FNchange(100, ukcoins%()) " ways of making £1"
PRINT FN... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// ad hoc 128 bit integer type; faster than using GMP because of low
// overhead
typedef struct { uint64_t x[2]; } i128;
// display in decimal
void show(i128 v) {
uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32};
int i, j = 0, len = 4;
char b... |
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... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
PROC count string in string = (STRING needle, haystack)INT: (
INT start:=LWB haystack, next, out:=0;
FOR count WHILE string in string(needle, next, haystack[start:]) DO
start+:=next+UPB needle-LWB needle;
out:=count
OD;
out
);
printf(($d" "$,
count string in string... |
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... | #Apex | Apex |
String substr = 'ABC';
String str = 'ABCZZZABCYABCABCXXABC';
Integer substrLen = substr.length();
Integer count = 0;
Integer index = str.indexOf(substr);
while (index >= 0) {
count++;
str = str.substring(index+substrLen);
index = str.indexOf(substr);
}
System.debug('Count String : '+count);
|
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... | #Aime | Aime | integer o;
o = 0;
do {
o_xinteger(8, o);
o_byte('\n');
o += 1;
} while (0 < o); |
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... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
INT oct width = (bits width-1) OVER 3 + 1;
main:
(
FOR i TO 17 # max int # DO
printf(($"8r"8r n(oct width)dl$, BIN i))
OD
) |
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... | #ALGOL_68 | ALGOL 68 | OP +:= = (REF FLEX []INT a, INT b) VOID:
BEGIN
[⌈a + 1] INT c;
c[:⌈a] := a;
c[⌈a+1:] := b;
a := c
END;
PROC factorize = (INT nn) []INT:
BEGIN
IF nn = 1 THEN (1)
ELSE
INT k := 2, n := nn;
FLEX[0]INT result;
WHILE n > 1 DO
WHILE n MOD k = 0 DO
result +:... |
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... | #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
:: It's easier and neater to create the variables holding the random 4 digit numbers ahead of time
for /l %%i in (1,1,12) do set /a rand%%i=!random! %% 9999
:: The command output of everything within the brackets is sent to the file "table.html", overwriting anything alread... |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | >> datestr(now,'yyyy-mm-dd')
ans =
2010-06-18
>> datestr(now,'dddd, mmmm dd, yyyy')
ans =
Friday, June 18, 2010 |
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
| #min | min | ("YYYY-MM-dd" "dddd, MMMM dd, YYYY") ('timestamp dip tformat puts!) foreach |
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... | #Factor | Factor | USING: kernel math math.matrices.laplace prettyprint sequences ;
IN: rosetta-code.cramers-rule
: replace-col ( elt n seq -- seq' ) flip [ set-nth ] keep flip ;
: solve ( m v -- seq )
dup length <iota> [
rot [ replace-col ] keep [ determinant ] bi@ /
] 2with map ;
: cramers-rule-demo ( -- )
{
... |
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... | #Fortran | Fortran | DATA A/2, -1, 5, 1
1 3, 2, 2, -6
2 1, 3, 3, -1
3 5, -2, -3, 3/ |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #C.23 | C# | using System;
using System.IO;
class Program {
static void Main(string[] args) {
File.Create("output.txt");
File.Create(@"\output.txt");
Directory.CreateDirectory("docs");
Directory.CreateDirectory(@"\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.
| #C.2B.2B | C++ | #include <direct.h>
#include <fstream>
int main() {
std::fstream f("output.txt", std::ios::out);
f.close();
f.open("/output.txt", std::ios::out);
f.close();
_mkdir("docs");
_mkdir("/docs");
return 0;
} |
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... | #Clojure | Clojure |
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!
|
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... | #Haskell | Haskell | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = brea... |
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.
| #Racket | Racket | #lang racket/base
(require racket/match)
(define operation-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)
#(5 8 6 9 7 2 0 1 3 4)
#(8 9 4 5 3 6 2 0 1 7)
#(9 4 3 8 6 1 7 2 0 5)
#(2 5 ... |
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.
| #Raku | Raku | sub damm ( *@digits ) {
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,... |
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 - ... | #Racket | Racket | #lang racket
(require math/number-theory
racket/generator)
(define (make-cuban-prime-generator)
(generator ()
(let loop ((y 1) (y3 1))
(let* ((x (+ y 1))
(x3 (expt x 3))
(p (quotient (- x3 y3) (- x y))))
(when (prime... |
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 - ... | #Raku | Raku | use Lingua::EN::Numbers;
use ntheory:from<Perl5> <:all>;
my @cubans = lazy (1..Inf).map({ ($_+1)³ - .³ }).grep: *.&is_prime;
put @cubans[^200]».&comma».fmt("%9s").rotor(10).join: "\n";
put '';
put @cubans[99_999]., # zero indexed |
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... | #zkl | zkl | addOne:= Op("+").fp(1); addOne(5) //-->6
minusOne:=Op("-").fp1(1); minusOne(5) //-->4, note that this fixed 1 as the second parameter
// fix first and third parameters:
foo:=String.fpM("101","<foo>","</foo>"); foo("zkl"); //-->"<foo>zkl</foo>"
fcn g(x){x+1} f:=fcn(f,x){f(x)+x}.fp(g); f(5); //-->11
f:=fcn(f,x){f(x)+x... |
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.
| #Swift | Swift | import Foundation
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd yyyy hh:mma zzz"
guard let date = formatter.date(from: "March 7 2009 7:30pm EST") else {
fatalError()
}
print(formatter.string(from: date))
print(formatter.string(from: date + 60 * 60 * 12)) |
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.
| #Tcl | Tcl | set date "March 7 2009 7:30pm EST"
set epoch [clock scan $date -format "%B %d %Y %I:%M%p %z"]
set later [clock add $epoch 12 hours]
puts [clock format $later] ;# Sun Mar 08 08:30:00 EDT 2009
puts [clock format $later -timezone :Asia/Shanghai] ;# Sun Mar 08 20:30:00 CST 2009 |
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 ... | #Oberon-2 | Oberon-2 |
MODULE DayOfWeek;
IMPORT NPCT:Dates, Out;
VAR
year: INTEGER;
date: Dates.Date;
BEGIN
FOR year := 2008 TO 2121 DO
date := Dates.NewDate(25,12,year);
IF date.DayOfWeek() = Dates.sunday THEN
Out.Int(date.year,4);Out.Ln
END
END
END DayOfWeek.
|
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... | #Vlang | Vlang | fn is_cusip(s string) bool {
if s.len != 9 { return false }
mut sum := 0
for i in 0..8 {
c := s[i]
mut v :=0
match true {
c >= '0'[0] && c <= '9'[0] {
v = c - 48
}
c >= 'A'[0] && c <= 'Z'[0] {
v = c - 55
}
c ==... |
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... | #Wren | Wren | var isCusip = Fn.new { |s|
if (s.count != 9) return false
var sum = 0
for (i in 0..7) {
var c = s[i].bytes[0]
var v
if (c >= 48 && c <= 57) { // '0' to '9'
v = c - 48
} else if (c >= 65 && c <= 90) { // 'A' to 'Z'
v = c - 55
} else if (s[i] == ... |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #Crystal | Crystal | require "random"
first = gets.not_nil!.to_i32
second = gets.not_nil!.to_i32
arr = Array(Array(Int32)).new(first, Array(Int32).new second, 0)
random = Random.new
first = random.rand 0..(first - 1)
second = random.rand 0..(second - 1)
arr[first][second] = random.next_int
puts arr[first][second] |
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... | #Go | Go | package main
import (
"fmt"
"math"
)
func newRsdv() func(float64) float64 {
var n, a, q float64
return func(x float64) float64 {
n++
a1 := a+(x-a)/n
q, a = q+(x-a)*(x-a1), a1
return math.Sqrt(q/n)
}
}
func main() {
r := newRsdv()
for _, x := range []flo... |
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... | #Haxe | Haxe | using StringTools;
class Main {
static function main() {
var data = haxe.io.Bytes.ofString("The quick brown fox jumps over the lazy dog");
var crc = haxe.crypto.Crc32.make(data);
Sys.println(crc.hex());
}
} |
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... | #Icon_and_Unicon | Icon and Unicon | link hexcvt,printf
procedure main()
s := "The quick brown fox jumps over the lazy dog"
a := "414FA339"
printf("crc(%i)=%s - implementation is %s\n",
s,r := crc32(s),if r == a then "correct" else "in error")
end
procedure crc32(s) #: return crc-32 (ISO 3309, ITU-T V.42, Gzip, PNG) of s
static... |
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... | #C.23 | C# |
// Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
class Program
{
static long Count(int[] C, int m, int n)
{
var table = new long[n + 1];
table[0] = 1;
for (int i = 0; i < m; i++)
for (int j = C[i]; j <= ... |
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... | #APL | APL | csubs←{0=x←⊃⍸⍺⍷⍵:0 ⋄ 1+⍺∇(¯1+x+⍴⍺)↓⍵} |
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... | #AppleScript | AppleScript | use framework "OSAKit"
on run
{countSubstring("the three truths", "th"), ¬
countSubstring("ababababab", "abab")}
end run
on countSubstring(str, subStr)
return evalOSA("JavaScript", "var matches = '" & str & "'" & ¬
".match(new RegExp('" & subStr & "', 'g'));" & ¬
"matches ? matches.l... |
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... | #ALGOL_W | ALGOL W | begin
string(12) r;
string(8) octDigits;
integer number;
octDigits := "01234567";
number := -1;
while number < MAXINTEGER do begin
integer v, cPos;
number := number + 1;
v := number;
% build a string of octal digits in r, representing number %
... |
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... | #APL | APL | 10⊥¨8∘⊥⍣¯1¨⍳100000 |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program countFactors.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a ... |
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... | #BBC_BASIC | BBC BASIC | ncols% = 3
nrows% = 4
*spool temp.htm
PRINT "<html><head></head><body>"
PRINT "<table border=1 cellpadding=10 cellspacing=0>"
FOR row% = 0 TO nrows%
IF row% = 0 THEN
PRINT "<tr><th></th>" ;
ELSE
PRINT "<tr><th>" ; row% "</th>" ;
ENDIF... |
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
| #mIRC_Scripting_Language | mIRC Scripting Language | echo -ag $time(yyyy-mm-dd)
echo -ag $time(dddd $+ $chr(44) mmmm dd $+ $chr(44) yyyy) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #MUMPS | MUMPS | DTZ
WRITE !,"Date format 3: ",$ZDATE($H,3)
WRITE !,"Or ",$ZDATE($H,12),", ",$ZDATE($H,9)
QUIT |
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.