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/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... | #FreeBASIC | FreeBASIC |
Function determinant(matrix() As Double) As Double
Dim As long n=Ubound(matrix,1),sign=1
Dim As Double det=1,s=1
Dim As Double b(1 To n,1 To n)
For c As long=1 To n
For d As long=1 To n
b(c,d)=matrix(c,d)
Next d
Next c
#macro pivot(num)
... |
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.
| #ChucK | ChucK |
FileIO text;
text.open("output.txt", FileIO.WRITE);
|
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.
| #Clojure | Clojure | (import '(java.io File))
(.createNewFile (new File "output.txt"))
(.mkdir (new File "docs"))
(.createNewFile (File. (str (File/separator) "output.txt")))
(.mkdir (File. (str (File/separator) "docs"))) |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a st... | #CoffeeScript | CoffeeScript | String::__defineGetter__ 'escaped', () ->
this.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"') // rosettacode doesn't like "
text = '''
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the ... |
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... | #Icon_and_Unicon | Icon and Unicon | import Utils # To get CSV procedures
procedure main(A)
f := open(A[1]) | &input
i := 1
write(!f) # header line(?)
every csv := parseCSV(!f) do {
csv[i+:=1] *:= 100
write(encodeCSV(csv))
}
end |
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.
| #REXX | REXX | /* REXX */
Call init
Call test 5724
Call test 5727
Call test 112946
Call test 112940
Exit
test:
Parse Arg number
int_digit=0
Do p=1 To length(number)
d=substr(number,p,1)
int_digit=grid.int_digit.d
If p<length(number) Then cd=int_digit
End
If int_digit=0 Then
Say number 'is ok'
Else
Say number 'is not ok,... |
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 - ... | #REXX | REXX | /*REXX program finds and displays a number of cuban primes or the Nth cuban prime. */
numeric digits 20 /*ensure enough decimal digits for #s. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 200 ... |
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.
| #UNIX_Shell | UNIX Shell | epoch=$(date -d 'March 7 2009 7:30pm EST +12 hours' +%s)
date -d @$epoch
TZ=Asia/Shanghai date -d @$epoch |
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.
| #Wren | Wren | import "/date" for Date
var fmt = "mmmm| |d| |yyyy| |H|:|MM|am| |zz|"
var d = Date.parse("March 7 2009 7:30pm EST", fmt)
Date.default = fmt
System.print("Original date/time : %(d)")
d = d.addHours(12)
System.print("12 hours later : %(d)")
// Adjust to MST say
d = d.adjustTime("MST")
System.print("Adjusted to MST ... |
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 ... | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main()
{
@autoreleasepool {
for(NSUInteger i=2008; i<2121; i++)
{
NSCalendarDate *d = [[NSCalendarDate alloc]
initWithYear: i
month: 12
day: 25
... |
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... | #XPL0 | XPL0 | string 0; \use zero-terminated strings
func Valid(Cusip); \Return 'true' if valid CUSIP code
char Cusip;
int Sum, I, C, V;
[Sum:= 0;
for I:= 0 to 8-1 do
[C:= Cusip(I);
ChOut(0, C);
case of
C>=^0 & C<=^9: V:= C-^0;
C>=^A & C<=^Z: V:= C-^A+10;
... |
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... | #Yabasic | Yabasic | sub cusip(inputStr$)
local i, v, sum, x$
Print inputStr$;
If Len(inputStr$) <> 9 Print " length is incorrect, invalid cusip" : return
For i = 1 To 8
x$ = mid$(inputStr$, i, 1)
switch x$
Case "*": v = 36 : break
Case "@": v = 37 : break
Case "#": v ... |
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 ... | #D | D | void main() {
import std.stdio, std.conv, std.string;
int nRow, nCol;
write("Give me the numer of rows: ");
try {
nRow = readln.strip.to!int;
} catch (StdioException) {
nRow = 3;
writeln;
}
write("Give me the numer of columns: ");
try {
nCol = readln.s... |
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... | #Groovy | Groovy | List samples = []
def stdDev = { def sample ->
samples << sample
def sum = samples.sum()
def sumSq = samples.sum { it * it }
def count = samples.size()
(sumSq/count - (sum/count)**2)**0.5
}
[2,4,4,4,5,5,7,9].each {
println "${stdDev(it)}"
} |
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... | #J | J | ((i.32) e. 32 26 23 22 16 12 11 10 8 7 5 4 2 1 0) 128!:3 'The quick brown fox jumps over the lazy dog'
_3199229127 |
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... | #Java | Java | import java.util.zip.* ;
public class CRCMaker {
public static void main( String[ ] args ) {
String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
CRC32 myCRC = new CRC32( ) ;
myCRC.update( toBeEncoded.getBytes( ) ) ;
System.out.println( "The CRC-32 value is : "... |
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.2B.2B | C++ |
#include <iostream>
#include <stack>
#include <vector>
struct DataFrame {
int sum;
std::vector<int> coins;
std::vector<int> avail_coins;
};
int main() {
std::stack<DataFrame> s;
s.push({ 100, {}, { 25, 10, 5, 1 } });
int ways = 0;
while (!s.empty()) {
DataFrame top = s.top();
s.pop();
if... |
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... | #Arturo | Arturo | countOccurrences: function [str, substr]-> size match str substr
loop [["the three truths" "th"] ["ababababab" "abab"]] 'pair ->
print [
~"occurrences of '|last pair|' in '|first pair|':"
countOccurrences first pair last pair
] |
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... | #AutoHotkey | AutoHotkey | MsgBox % countSubstring("the three truths","th") ; 3
MsgBox % countSubstring("ababababab","abab") ; 2
CountSubstring(fullstring, substring){
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
} |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program countoctal.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************... |
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... | #Arturo | Arturo | loop 1..30 'x [
fs: [1]
if x<>1 -> fs: factors.prime x
print [pad to :string x 3 "=" join.with:" x " to [:string] fs]
] |
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... | #BQN | BQN | Tag ← {∾"<"‿𝕨‿">"‿𝕩‿"</"‿𝕨‿">"}
•Show "table" Tag ∾∾⟜(@+10)¨("tr"Tag∾)¨⟨"th"⊸Tag¨ ""<⊸∾⥊¨"XYZ"⟩∾("td" Tag •Fmt)¨¨ 0‿0‿1‿2 + 1‿3‿3‿3 × 4/⟨↕4⟩ |
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
| #Nanoquery | Nanoquery | import Nanoquery.Util
d = new(Date)
println d.getYear() + "-" + d.getMonth() + "-" + d.getDay()
println d.getDayOfWeek() + ", " + d.getMonthName() + " " + d.getDay() + ", " + d.getYear() |
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
| #Neko | Neko | /**
<doc>
<h2>Date format</h2>
<p>Neko uses Int32 to store system date/time values.
And lib C strftime style formatting for converting to string form</p>
</doc>
*/
var date_now = $loader.loadprim("std@date_now", 0)
var date_format = $loader.loadprim("std@date_format", 2)
var now = date_now()
$print(date_format... |
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... | #Go | Go | package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
var m = mat.NewDense(4, 4, []float64{
2, -1, 5, 1,
3, 2, 2, -6,
1, 3, 3, -1,
5, -2, -3, 3,
})
var v = []float64{-3, -32, -47, 49}
func main() {
x := make([]float64, len(v))
b := make([]float64, len(v))
d := mat.Det(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.
| #COBOL | COBOL | identification division.
program-id. create-a-file.
data division.
working-storage section.
01 skip pic 9 value 2.
01 file-name.
05 value "/output.txt".
01 dir-name.
05 value "/docs".
01 file-handle usage binary-long.... |
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... | #Common_Lisp | Common Lisp | (defvar *csv* "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!")
(defu... |
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... | #J | J | data=: (','&splitstring);.2 freads 'rc_csv.csv' NB. read and parse data
data=: (<'"spam"') (<2 3)} data NB. amend cell in 3rd row, 4th column (0-indexing)
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data NB. format and write out amended data |
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... | #Java | Java | import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
... |
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.
| #Ring | Ring | # Project : Damm algorithm
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],
[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.
| #Ruby | Ruby | 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,8,1,4,3,6,7,9,0]
]
def damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| ... |
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 - ... | #Ring | Ring |
load "stdlib.ring"
sum = 0
limit = 1000
see "First 200 cuban primes:" + nl
for n = 1 to limit
pr = pow(n+1,3) - pow(n,3)
if isprime(pr)
sum = sum + 1
if sum < 201
see "" + pr + " "
else
exit
ok
ok
next
see "done..." + nl
|
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 - ... | #Ruby | Ruby | require "openssl"
RE = /(\d)(?=(\d\d\d)+(?!\d))/ # Activesupport uses this for commatizing
cuban_primes = Enumerator.new do |y|
(1..).each do |n|
cand = 3*n*(n+1) + 1
y << cand if OpenSSL::BN.new(cand).prime?
end
end
def commatize(num)
num.to_s.gsub(RE, "\\1,")
end
cbs = cuban_primes.take(200)
form... |
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.
| #zkl | zkl | var Date=Time.Date;
fcn add12h(dt){
re:=RegExp(0'|(\w+)\s+(\d+)\s+(\d+)\ +(.+)\s|);
re.search(dt);
_,M,D,Y,hms:=re.matched; //"March","7","2009","7:30pm"
M=Date.monthNames.index(M); //3
h,m,s:=Date.parseTime(hms); //19,30,0
dti:=T(Y,M,D, h,m,s).apply("toInt");
Y,M,D, h,m,s=Date.addHMS(dti,12);
... |
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 ... | #OCaml | OCaml | #load "unix.cma"
open Unix
try
for i = 2008 to 2121 do
(* I'm lazy so we'll just borrow the current time
instead of having to set all the fields explicitly *)
let mytime = { (localtime (time ())) with
tm_year = i - 1900;
tm_mon = 11;
tm_mday... |
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 ... | #Oforth | Oforth | import: date
seqFrom(2008, 2121) filter(#[ 12 25 Date newDate dayOfWeek Date.SUNDAY == ]) . |
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... | #Zig | Zig | const std = @import("std");
const print = std.debug.print;
pub fn CusipCheckDigit(cusip: *const [9:0]u8) bool {
var i: usize = 0;
var sum: i32 = 0;
while (i < 8) {
const c = cusip[i];
var v: i32 = undefined;
if (c <= '9' and c >= '0') {
v = c - 48;
}
els... |
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... | #zkl | zkl | fcn cusipCheckDigit(cusip){
var [const] vs=[0..9].chain(["A".."Z"],T("*","@","#")).pump(String);
try{
sum:=Walker.cycle(1,2).zipWith(fcn(n,c){ v:=vs.index(c)*n; v/10 + v%10 },
cusip[0,8]).reduce('+);
((10 - sum%10)%10 == cusip[8].toInt()) and cusip.len()==9
}catch{ False }
} |
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 ... | #Delphi | Delphi | program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
matrix:array of array of Byte;
i,j:Integer;
begin
Randomize;
//Finalization is not required in this case, but you have to do
//so when reusing the variable in scope
Finalize(matrix);
//Init first dimension with random size from 1..10
//Rememb... |
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... | #Haskell | Haskell | {-# LANGUAGE BangPatterns #-}
import Data.List (foldl') -- '
import Data.STRef
import Control.Monad.ST
data Pair a b = Pair !a !b
sumLen :: [Double] -> Pair Double Double
sumLen = fiof2 . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) --'
where fiof2 (Pair s l) = Pair s (fromIntegral l)
divl :: Pair ... |
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... | #JavaScript | JavaScript | (() => {
'use strict';
// --------------------- CRC-32 ----------------------
// crc32 :: String -> Int
const crc32 = str => {
// table :: [Int]
const table = enumFromTo(0)(255).map(
n => take(9)(
iterate(
x => (
... |
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... | #Clojure | Clojure | (def denomination-kind [1 5 10 25])
(defn- cc [amount denominations]
(cond (= amount 0) 1
(or (< amount 0) (empty? denominations)) 0
:else (+ (cc amount (rest denominations))
(cc (- amount (first denominations)) denominations))))
(defn count-change
"Calculates the number of time... |
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... | #AWK | AWK | #
# countsubstring(string, pattern)
# Returns number of occurrences of pattern in string
# Pattern treated as a literal string (regex characters not expanded)
#
function countsubstring(str, pat, len, i, c) {
c = 0
if( ! (len = length(pat) ) )
return 0
while(i = index(str, pat)) {
str = substr(str,... |
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... | #BaCon | BaCon | FUNCTION Uniq_Tally(text$, part$)
LOCAL x
WHILE TALLY(text$, part$)
INCR x
text$ = MID$(text$, INSTR(text$, part$)+LEN(part$))
WEND
RETURN x
END FUNCTION
PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th")
PRINT "ababababab - abab: ", Uniq_Tally("ababababab", "abab") |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #Arturo | Arturo | loop 1..40 'i ->
print ["number in base 10:" pad to :string i 2
"number in octal:" pad as.octal i 2] |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #AutoHotkey | AutoHotkey | DllCall("AllocConsole")
Octal(int){
While int
out := Mod(int, 8) . out, int := int//8
return out
}
Loop
{
FileAppend, % Octal(A_Index) "`n", CONOUT$
Sleep 200
} |
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... | #AutoHotkey | AutoHotkey | factorize(n){
if n = 1
return 1
if n < 1
return false
result := 0, m := n, k := 2
While n >= k{
while !Mod(m, k){
result .= " * " . k, m /= k
}
k++
}
return SubStr(result, 5)
}
Loop 22
out .= A_Index ": " factorize(A_index) "`n"
MsgBox % out |
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... | #Bracmat | Bracmat | ( ( makeTable
= headTexts
minRowNr
maxRowNr
headCells
cells
rows
Generator
Table
. get$"xmlio.bra" { A library that converts from Bracmat format to XML or HTML }
& !arg:(?headTexts.?minRowNr.?maxRowNr.?Generator)
& ( headCells
... |
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
| #NetRexx | NetRexx |
import java.text.SimpleDateFormat
say SimpleDateFormat("yyyy-MM-dd").format(Date())
say SimpleDateFormat("EEEE, MMMM dd, yyyy").format(Date())
|
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
| #NewLISP | NewLISP | ; file: date-format.lsp
; url: http://rosettacode.org/wiki/Date_format
; author: oofoe 2012-02-01
; The "now" function returns the current time as a list. A time zone
; offset in minutes can be supplied. The example below is for Eastern
; Standard Time. NewLISP's implicit list indexing is used to extract
; the f... |
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... | #Groovy | Groovy | class CramersRule {
static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),
Arrays.asList(3d, 2d, 2d, -6d),
Arrays.asList(1d, 3d, 3d, -1d),
Arrays.asList(5d, -2d, -3d, 3d))
List<Double> b = Arrays.asList(-3d, -32d, -47... |
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.
| #Common_Lisp | Common Lisp | (let ((stream (open "output.txt" :direction :output)))
(close stream)) |
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.
| #Component_Pascal | Component Pascal |
MODULE CreateFile;
IMPORT Files, StdLog;
PROCEDURE Do*;
VAR
f: Files.File;
res: INTEGER;
BEGIN
f := Files.dir.New(Files.dir.This("docs"),Files.dontAsk);
f.Register("output","txt",TRUE,res);
f.Close();
f := Files.dir.New(Files.dir.This("C:\AEAT\docs"),Files.dontAsk);
f.Register("output","txt",TRUE,res);
f.... |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a st... | #D | D | void main() {
import std.stdio;
immutable input =
"Character,Speech\n" ~
"The multitude,The messiah! Show us the messiah!\n" ~
"Brians mother,<angry>Now you listen here! He's not the messiah; " ~
"he's a very naughty boy! Now go away!</angry>\n" ~
"The multitude,Who... |
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... | #JavaScript | JavaScript | (function () {
'use strict';
// splitRegex :: Regex -> String -> [String]
function splitRegex(rgx, s) {
return s.split(rgx);
}
// lines :: String -> [String]
function lines(s) {
return s.split(/[\r\n]/);
}
// unlines :: [String] -> String
function unlines(xs) {
... |
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.
| #Rust | Rust | fn damm(number: &str) -> u8 {
static TABLE: [[u8; 10]; 10] = [
[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/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.
| #Scala | Scala | import scala.annotation.tailrec
object DammAlgorithm extends App {
private val numbers = Seq(5724, 5727, 112946, 112949)
@tailrec
private def damm(s: String, interim: Int): String = {
def table =
Vector(
Vector(0, 3, 1, 7, 5, 9, 8, 6, 4, 2),
Vector(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
... |
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 - ... | #Rust | Rust | use std::time::Instant;
use separator::Separatable;
const NUMBER_OF_CUBAN_PRIMES: usize = 200;
const COLUMNS: usize = 10;
const LAST_CUBAN_PRIME: usize = 100_000;
fn main() {
println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME);
let start = ... |
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 - ... | #Scala | Scala | import spire.math.SafeLong
import spire.implicits._
import scala.annotation.tailrec
import scala.collection.parallel.immutable.ParVector
object CubanPrimes {
def main(args: Array[String]): Unit = {
println(formatTable(cubanPrimes.take(200).toVector, 10))
println(f"The 100,000th cuban prime is: ${getNthCub... |
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 ... | #ooRexx | ooRexx | date = .datetime~new(2008, 12, 25)
lastdate = .datetime~new(2121, 12, 25)
resultList = .array~new -- our collector of years
-- date objects are directly comparable
loop while date <= lastdate
if date~weekday == 7 then resultList~append(date~year)
-- step to the next year
date = date~addYears(1)
end
say "Chr... |
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 ... | #Elena | Elena | import extensions;
public program()
{
var n := new Integer();
var m := new Integer();
console.write:"Enter two space delimited integers:";
console.loadLine(n,m);
var myArray := class Matrix<int>.allocate(n,m);
myArray.setAt(0,0,2);
console.printLine(myArray.at(0, 0))
} |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #Elixir | Elixir |
defmodule TwoDimArray do
def create(w, h) do
List.duplicate(0, w)
|> List.duplicate(h)
end
def set(arr, x, y, value) do
List.replace_at(arr, x,
List.replace_at(Enum.at(arr, x), y, value)
)
end
def get(arr, x, y) do
arr |> Enum.at(x) |> Enum.at(y)
end
end
width = IO.g... |
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... | #Haxe | Haxe | using Lambda;
class Main {
static function main():Void {
var nums = [2, 4, 4, 4, 5, 5, 7, 9];
for (i in 1...nums.length+1)
Sys.println(sdev(nums.slice(0, i)));
}
static function average<T:Float>(nums:Array<T>):Float {
return nums.fold(function(n, t) return n + t, 0) / nums.length;
}
static functi... |
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... | #Jsish | Jsish | # Util.crc32('The quick brown fox jumps over the lazy dog').toString(16); |
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... | #Julia | Julia | using Libz
println(string(Libz.crc32(UInt8.(b"The quick brown fox jumps over the lazy dog")), base=16))
|
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... | #COBOL | COBOL |
identification division.
program-id. CountCoins.
data division.
working-storage section.
77 i pic 9(3).
77 j pic 9(3).
77 m pic 9(3) value 4.
77 n pic 9(3) value 100.
... |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer cou... | #BASIC | BASIC | DECLARE FUNCTION countSubstring& (where AS STRING, what AS STRING)
PRINT "the three truths, th:", countSubstring&("the three truths", "th")
PRINT "ababababab, abab:", countSubstring&("ababababab", "abab")
FUNCTION countSubstring& (where AS STRING, what AS STRING)
DIM c AS LONG, s AS LONG
s = 1 - LEN(what)
... |
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... | #AWK | AWK | BEGIN {
for (l = 0; l <= 2147483647; l++) {
printf("%o\n", 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... | #BASIC | BASIC | DIM n AS LONG
FOR n = 0 TO &h7FFFFFFF
PRINT OCT$(n)
NEXT |
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... | #AWK | AWK |
# syntax: GAWK -f COUNT_IN_FACTORS.AWK
BEGIN {
fmt = "%d=%s\n"
for (i=1; i<=16; i++) {
printf(fmt,i,factors(i))
}
i = 2144; printf(fmt,i,factors(i))
i = 6358; printf(fmt,i,factors(i))
exit(0)
}
function factors(n, f,p) {
if (n == 1) {
return(1)
}
p = 2
while (p <= ... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
printf("<table style=\"text-align:center; border: 1px solid\"><th></th>"
"<th>X</th><th>Y</th><th>Z</th>");
for (i = 0; i < 4; i++) {
printf("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>", i,
rand() % 10000, rand() % 10000, rand() % 10000);... |
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
| #Nim | Nim | import times
var t = now()
echo(t.format("yyyy-MM-dd"))
echo(t.format("dddd',' MMMM d',' yyyy")) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Objeck | Objeck |
use IO;
use Time;
bundle Default {
class CurrentDate {
function : Main(args : String[]) ~ Nil {
t := Date->New();
Console->Print(t->GetYear())->Print("-")->Print(t->GetMonth())->Print("-")
->PrintLine(t->GetDay());
Console->Print(t->GetDayName())->Print(", ")->Print(t->GetMonthName()... |
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... | #Haskell | Haskell | import Data.Matrix
solveCramer :: (Ord a, Fractional a) => Matrix a -> Matrix a -> Maybe [a]
solveCramer a y
| da == 0 = Nothing
| otherwise = Just $ map (\i -> d i / da) [1..n]
where da = detLU a
d i = detLU $ submatrix 1 n 1 n $ switchCols i (n+1) ay
ay = a <|> y
n = ncols a
task = s... |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Crystal | Crystal | File.write "output.txt", ""
Dir.mkdir "docs"
File.write "/output.txt", ""
Dir.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.
| #D | D | module fileio ;
import std.stdio ;
import std.path ;
import std.file ;
import std.stream ;
string[] genName(string name){
string cwd = curdir ~ sep ; // on current directory
string root = sep ; // on root
name = std.path.getBaseName(name) ;
return [cwd ~ name, root ~ name] ;
}
void Remove(string ... |
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... | #Delphi | Delphi | program csv2html;
{$APPTYPE CONSOLE}
uses
SysUtils,
Classes;
const
// Carriage Return/Line Feed
CRLF = #13#10;
// The CSV data
csvData =
'Character,Speech'+CRLF+
'The multitude,The messiah! Show us the messiah!'+CRLF+
'Brians mother,<angry>Now you listen here! He''s not the messiah; he''s a... |
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... | #jq | jq | # Omit empty lines
def read_csv:
split("\n")
| map(if length>0 then split(",") else empty end) ;
# add_column(label) adds a summation column (with the given label) to
# the matrix representation of the CSV table, and assumes that all the
# entries in the body of the CSV file are, or can be converted to,
# numbers... |
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... | #Julia | Julia | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
|
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.
| #Sidef | Sidef | func damm(digits) {
static 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 - ... | #Sidef | Sidef | func cuban_primes(n) {
1..Inf -> lazy.map {|k| 3*k*(k+1) + 1 }\
.grep{ .is_prime }\
.first(n)
}
cuban_primes(200).slices(10).each {
say .map { "%9s" % .commify }.join(' ')
}
say ("\n100,000th cuban prime is: ", cuban_primes(1e5).last.commify) |
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 - ... | #Transd | Transd |
#lang transd
MainModule: {
primes: Vector<ULong>([3, 5]),
lim: 200,
bigUn: 100000,
chunks: 50,
little: 0,
c: 0,
showEach: true,
u: ULong(0),
v: ULong(1),
_start: (λ found Bool() fnd Bool() mx Int() z ULong()
(= little (/ bigUn chunks))
(for i in Range(1 (pow... |
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 ... | #PARI.2FGP | PARI/GP |
njd(D) =
{
my (m, y);
if (D[2] > 2, y = D[1]; m = D[2]+1, y = D[1]-1; m = D[2]+13);
(1461*y)\4 + (306001*m)\10000 + D[3] - 694024 + if (100*(100*D[1]+D[2])+D[3] > 15821004, 2 - y\100 + y\400)
}
for (y = 2008, 2121, if (njd([y,12,25]) % 7 == 1, print(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 ... | #Erlang | Erlang |
-module( two_dimensional_array ).
-export( [create/2, get/3, set/4, task/0] ).
create( X, Y ) -> array:new( [{size, X}, {default, array:new( [{size, Y}] )}] ).
get( X, Y, Array ) -> array:get( Y, array:get(X, Array) ).
set( X, Y, Value, Array ) ->
Y_array = array:get( X, Array ),
New_y_array = array:set( Y,... |
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... | #HicEst | HicEst | REAL :: n=8, set(n), sum=0, sum2=0
set = (2,4,4,4,5,5,7,9)
DO k = 1, n
WRITE() 'Adding ' // set(k) // 'stdev = ' // stdev(set(k))
ENDDO
END ! end of "main"
FUNCTION stdev(x)
USE : sum, sum2, k
sum = sum + x
sum2 = sum2 + x*x
stdev = ( sum2/k - (sum/k)^2) ^ 0.5
END |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Kotlin | Kotlin | // version 1.0.6
import java.util.zip.CRC32
fun main(args: Array<String>) {
val text = "The quick brown fox jumps over the lazy dog"
val crc = CRC32()
with (crc) {
update(text.toByteArray())
println("The CRC-32 checksum of '$text' = ${"%x".format(value)}")
}
} |
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... | #Lingo | Lingo | crcObj = script("CRC").new()
crc32 = crcObj.crc32("The quick brown fox jumps over the lazy dog")
put crc32
-- <ByteArrayObject length = 4 ByteArray = 0x41, 0x4f, 0xa3, 0x39 >
put crc32.toHexString(1, crc32.length)
-- "41 4f a3 39" |
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... | #Coco | Coco | changes = (amount, coins) ->
ways = [1].concat [0] * amount
for coin of coins
for j from coin to amount
ways[j] += ways[j - coin]
ways[amount]
console.log changes 100, [1 5 10 25] |
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... | #Commodore_BASIC | Commodore BASIC | 5 m=100:rem money = $1.00 or 100 pennies.
10 print chr$(147);chr$(14);"This program will calculate the number"
11 print "of combinations of 'change' that can be"
12 print "given for a $1 bill."
13 print:print "The coin values are:"
14 print "0.01 = Penny":print "0.05 = Nickle"
15 print "0.10 = Dime":print "0.25 = Quart... |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
::Main
call :countString "the three truths","th"
call :countString "ababababab","abab"
pause>nul
exit /b
::/Main
::Procedure
:countString
set input=%~1
set cnt=0
:count_loop
set trimmed=!input:*%~2=!
if "!trimmed!"=="!input!" (echo.!cnt!&goto :EOF)
set input=!trimm... |
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... | #BBC_BASIC | BBC BASIC | tst$ = "the three truths"
sub$ = "th"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
tst$ = "ababababab"
sub$ = "abab"
PRINT ; FNcountSubstring(tst$, sub$) " """ sub$ """ in """ tst$ """"
END
DEF FNcountSubstring(A$, B$)
LOCAL I%, N%
I%... |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #Batch_File | Batch File |
@echo off
:: {CTRL + C} to exit the batch file
:: Send incrementing decimal values to the :to_Oct function
set loop=0
:loop1
call:to_Oct %loop%
set /a loop+=1
goto loop1
:: Convert the decimal values parsed [%1] to octal and output them on a new line
:to_Oct
set todivide=%1
set "fulloct="
:loop2
set tomod=%todivi... |
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... | #BBC_BASIC | BBC BASIC | N% = 0
REPEAT
PRINT FN_tobase(N%, 8, 0)
N% += 1
UNTIL FALSE
END
REM Convert N% to string in base B% with minimum M% digits:
DEF FN_tobase(N%, B%, M%)
LOCAL D%, A$
REPEAT
D% = N% MOD B%
N% DIV= B%
IF D%<0 D% += B% : N% -= 1
... |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\di... | #BASIC | BASIC | 100 FOR I = 1 TO 20
110 GOSUB 200"FACTORIAL
120 PRINT I" = "FA$
130 NEXT I
140 END
200 FA$ = "1"
210 LET NUM = I
220 LET O = 5 - (I = 1) * 4
230 FOR F = 2 TO I
240 LET M = INT (NUM / F) * F
250 IF NUM - M GOTO 300
260 LET NUM = NUM / F
270 LET F$ = STR $(F)
... |
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... | #BBC_BASIC | BBC BASIC | FOR i% = 1 TO 20
PRINT i% " = " FNfactors(i%)
NEXT
END
DEF FNfactors(N%)
LOCAL P%, f$
IF N% = 1 THEN = "1"
P% = 2
WHILE P% <= N%
IF (N% MOD P%) = 0 THEN
f$ += STR$(P%) + " x "
N% DIV= P%
ELSE
P% += 1
ENDIF
... |
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... | #C.23 | C# | using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
StringBuilder s = new StringBuilder();
Random rnd = new Random();
s.AppendLine("<table>");
s.AppendLine("<thead align = \"right\">");
s.Append("<tr><th></th>");
for(int i=0; i<3; i... |
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
| #Objective-C | Objective-C | NSLog(@"%@", [NSDate date]);
NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil]);
NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%A, %B %d, %Y" timeZone:nil locale:nil]); |
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
| #OCaml | OCaml | # #load "unix.cma";;
# open Unix;;
# let t = time() ;;
val t : float = 1219997516.
# let gmt = gmtime t ;;
val gmt : Unix.tm =
{tm_sec = 56; tm_min = 11; tm_hour = 8; tm_mday = 29; tm_mon = 7;
tm_year = 108; tm_wday = 5; tm_yday = 241; tm_isdst = false}
# Printf.sprintf "%d-%02d-%02d" (1900 + gmt.tm_year) (1... |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #J | J | cramer=:4 :0
A=. x [ b=. y
det=. -/ .*
A %~&det (i.#A) b"_`[`]}&.|:"0 2 A
) |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Java | Java |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CramersRule {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d),
Arrays.asList(3d, 2d, 2d, -6d),
Arra... |
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.