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/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.
| #Haskell | Haskell | import Data.Char (digitToInt)
import Text.Printf (printf)
damm :: String -> Bool
damm = (==0) . foldl (\r -> (table !! r !!) . digitToInt) 0
where
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]... |
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 - ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static List<long> primes = new List<long>() { 3, 5 };
static void Main(string[] args)
{
const int cutOff = 200;
const int bigUn = 100000;
const int chunks = 50;
const int little = b... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Groovy | Groovy | import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class CreateFile {
static void main(String[] args) throws IOException {
String os = System.getProperty("os.name")
if (os.contains("Windows")) {
Path path = Paths.get("tape.file")
Files.write(pat... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Haskell | Haskell | module Main (main) where
main :: IO ()
main = writeFile "/dev/tape" "Hello from Rosetta Code!" |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write(open("/dev/tape","w"),"Hi")
end |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #IS-BASIC | IS-BASIC | 100 OPEN #1:"Tape1:README.TXT" ACCESS OUTPUT
110 PRINT #1:"I am a tape file now, or hope to be soon."
120 CLOSE #1 |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Java | Java | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
public class CreateFile {
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) ... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #JavaScript | JavaScript | const money = require('money-math')
let hamburgers = 4000000000000000
let hamburgerPrice = 5.50
let shakes = 2 ... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #jq | jq | def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# print as dollars and cents
def dollars:
(. % 100) as $c
| "$\((. - $c) /100).\($c)";
def dollars($width):
dollars | lpad($width);
def innerproduct($y):
. as $x
| reduce range(0;$x|length) as $i (0; . + ($x[$i]*$y[$i]));
def plus... |
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... | #Io | Io | curry := method(fn,
a := call evalArgs slice(1)
block(
b := a clone appendSeq(call evalArgs)
performWithArgList("fn", b)
)
)
// example:
increment := curry( method(a,b,a+b), 1 )
increment call(5)
// result => 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... | #J | J | threePlus=: 3&+
threePlus 7
10
halve =: %&2 NB. % means divide
halve 20
10
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2 |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Raku | Raku | use NativeCall;
use NativeCall::Types;
# bind to basic libc memory management
sub malloc(size_t) returns Pointer[uint8] is native {*};
sub memset(Pointer, uint32, size_t) is native {*};
sub free(Pointer[uint8]) is native {*};
my Pointer[uint8] $base-p = malloc(100);
memset($base-p, 0, 100);
# define object as a C... |
http://rosettacode.org/wiki/Cyclotomic_polynomial | Cyclotomic polynomial | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.
Task
Find and print the first 30 cyclotomic polynomials.
Find and print the order of the first 10... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Private ReadOnly MAX_ALL_FACTORS As Integer = 100_000
#Const ALGORITHM = 2
Class Term
Implements IComparable(Of Term)
Public ReadOnly Property Coefficient As Long
Public ReadOnly Property Exponent As Long
Public Sub New(c As Long, Option... |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles... | #Wren | Wren | import "/fmt" for Fmt
var grid = []
var w = 0
var h = 0
var len = 0
var cnt = 0
var next = [0] * 4
var dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]
var walk // recursive
walk = Fn.new { |y, x|
if (y == 0 || y == h || x == 0 || x == w) {
cnt = cnt + 2
return
}
var t = y * (w + 1) + x
gri... |
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.
| #Lua | Lua |
str = string.lower( "March 7 2009 7:30pm EST" )
month = string.match( str, "%a+" )
if month == "january" then month = 1
elseif month == "february" then month = 2
elseif month == "march" then month = 3
elseif month == "april" then month = 4
elseif month == "may" then month = 5
elseif month == "... |
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 ... | #FutureBasic | FutureBasic | window 1
long y
CFDateRef dt
NSInteger day
CFCalendarRef cal
DateComponentsRef comps
cal = fn CalendarCurrent
comps = fn DateComponentsInit
DateComponentsSetMonth( comps, 12 )
DateComponentsSetDay( comps, 25 )
for y = 2008 to 2121
DateComponentsSetYear( comps, y )
dt = fn Ca... |
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 ... | #Gambas | Gambas | Public Sub Main()
Dim siCount As Short
For siCount = 2008 To 2121
If WeekDay(Date(siCount, 12, 25)) = 0 Then Print Format(Date(siCount, 12, 25), "dddd dd mmmm yyyy") & " falls on a Sunday"
Next
End |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #JavaScript | JavaScript | (() => {
'use strict';
// cusipValid = Dict Char Int -> String -> Bool
const cusipValid = charMap => s => {
const
ns = fromMaybe([])(
traverse(flip(lookupDict)(charMap))(
chars(s)
)
);
return 9 === ns.length && (
... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace standardDeviation
{
class Program
{
static void Main(string[] args)
{
List<double> nums = new List<double> { 2, 4, 4, 4, 5, 5, 7, 9 };
for (int i = 1; i <= nums.Count; 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
| #F.23 | F# | > open System;;
> Console.WriteLine( DateTime.Now.ToString("yyyy-MM-dd") );;
2010-08-13
> Console.WriteLine( "{0:D}", DateTime.Now );;
Friday, August 13, 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
| #Factor | Factor | USING: formatting calendar io ;
now "%Y-%m-%d" strftime print
now "%A, %B %d, %Y" strftime print |
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... | #C.23 | C# | using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",... |
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.
| #J | J | OpTbl=: _99 ". ];._2 noun define
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
)
getdigits=: 10&#.inv
getDamm=: verb define
row=. 0
for_digit. getdigits y do.... |
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 - ... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <chrono>
#include <climits>
#include <cmath>
using namespace std;
vector <long long> primes{ 3, 5 };
int main()
{
cout.imbue(locale(""));
const int cutOff = 200, bigUn = 100000,
chunks = 50, little = bigUn / chunks;
const char tn[] = " cuban prime"... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #JCL | JCL | // EXEC PGM=IEBGENER
//* Create a file named "TAPE.FILE" on magnetic tape; "UNIT=TAPE"
//* may vary depending on site-specific esoteric name assignment
//SYSPRINT DD SYSOUT=*
//SYSIN DD DUMMY
//SYSUT2 DD UNIT=TAPE,DSN=TAPE.FILE,DISP=(,CATLG)
//SYSUT1 DD *
DATA TO BE WRITTEN TO TAPE
/* |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Julia | Julia |
open("/dev/tape", "w") do f
write(f, "Hello tape!")
end
|
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Kotlin | Kotlin | // version 1.1.0 (Linux)
import java.io.FileWriter
fun main(args: Array<String>) {
val lp0 = FileWriter("/dev/tape")
lp0.write("Hello, world!")
lp0.close()
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Lua | Lua | require "lfs"
local out
if lfs.attributes('/dev/tape') then
out = '/dev/tape'
else
out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file) |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Nim | Nim | var t = open("/dev/tape", fmWrite)
t.writeln "Hi Tape!"
t.close |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Phix | Phix | include builtins/write_file.e
constant filepath = iff(platform()=WINDOWS?"tape.file":"/dev/tape"),
write_file(file_path,"Hello world!") |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Julia | Julia | using Printf
p = [big"5.50", big"2.86"]
q = [4000000000000000, 2]
tr = big"0.0765"
beftax = p' * q
tax = beftax * tr
afttax = beftax + tax
@printf " - tot. before tax: %20.2f \$\n" beftax
@printf " - tax: %20.2f \$\n" tax
@printf " - tot. after tax: %20.2f \$\n" afttax |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Kotlin | Kotlin | // version 1.1.2
import java.math.BigDecimal
import java.math.MathContext
fun main(args: Array<String>) {
val mc = MathContext.DECIMAL128
val nHamburger = BigDecimal("4000000000000000", mc)
val pHamburger = BigDecimal("5.50")
val nMilkshakes = BigDecimal("2", mc)
val pMilkshakes = BigDecimal("... |
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... | #Java | Java | public class Currier<ARG1, ARG2, RET> {
public interface CurriableFunctor<ARG1, ARG2, RET> {
RET evaluate(ARG1 arg1, ARG2 arg2);
}
public interface CurriedFunctor<ARG2, RET> {
RET evaluate(ARG2 arg);
}
final CurriableFunctor<ARG1, ARG2, RET> functo... |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Rust | Rust | use std::{mem,ptr};
fn main() {
let mut data: i32;
// Rust does not allow us to use uninitialized memory but the STL provides an `unsafe`
// function to override this protection.
unsafe {data = mem::uninitialized()}
// Construct a raw pointer (perfectly safe)
let address = &mut data as *mu... |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #S-BASIC | S-BASIC |
var first, addr = integer
based second = integer
first = 12345
location var addr = first
base second at addr
print "Value of first variable ="; first
print "Address of first variable = "; hex$(addr)
print "Value of second variable ="; second
end
|
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Scala | Scala | package require critcl
# A command to 'make an integer object' and couple it to a Tcl variable
critcl::cproc linkvar {Tcl_Interp* interp char* var1} int {
int *intPtr = (int *) ckalloc(sizeof(int));
*intPtr = 0;
Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT);
return (int) intPtr;
}
# A c... |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Tcl | Tcl | package require critcl
# A command to 'make an integer object' and couple it to a Tcl variable
critcl::cproc linkvar {Tcl_Interp* interp char* var1} int {
int *intPtr = (int *) ckalloc(sizeof(int));
*intPtr = 0;
Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT);
return (int) intPtr;
}
# A c... |
http://rosettacode.org/wiki/Cyclotomic_polynomial | Cyclotomic polynomial | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.
Task
Find and print the first 30 cyclotomic polynomials.
Find and print the order of the first 10... | #Wren | Wren | import "/trait" for Stepped
import "/sort" for Sort
import "/math" for Int, Nums
import "/fmt" for Fmt
var algo = 2
var maxAllFactors = 1e5
class Term {
construct new(coef, exp) {
_coef = coef
_exp = exp
}
coef { _coef }
exp { _exp }
*(t) { Term.new(_coef * t.coef, _exp + t.... |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles... | #zkl | zkl | fcn cut_it(h,w){
if(h.isOdd){
if(w.isOdd) return(0);
t,h,w=h,w,t; // swap w,h: a,b=c,d --> a=c; b=d; so need a tmp
}
if(w==1) return(1);
nxt :=T(T(w+1, 1,0), T(-w-1, -1,0), T(-1, 0,-1), T(1, 0,1)); #[next, dy,dx]
blen:=(h + 1)*(w + 1) - 1;
grid:=(blen + 1).pump(List(),False); //-->L(Fal... |
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.
| #Maple | Maple | twelve_hours := proc(str)
local dt, zone;
local months := ["January","February","March","April","May","June","July","August","September","October","November","December"];
dt := StringTools:-ParseTime("%B %d %Y %l:%M%p", str);
zone := StringTools:-RegSplit(" ", str)[-1];
dt := Date(dt:-year, dt:-month, dt:-monthDay... |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | dstr = "March 7 2009 7:30pm EST";
DateString[DatePlus[dstr, {12, "Hour"}], {"DayName", " ", "MonthName", " ", "Day", " ", "Year", " ", "Hour24", ":", "Minute", "AMPM"}] |
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 ... | #GAP | GAP | Filtered([2008 .. 2121], y -> WeekDay([25, 12, y]) = "Sun");
# [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ]
# A possible implementation of WeekDayAlt
days := ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];;
WeekDayAlt := function(args)
local d, m, ... |
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 ... | #Go | Go | package main
import "fmt"
import "time"
func main() {
for year := 2008; year <= 2121; year++ {
if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==
time.Sunday {
fmt.Printf("25 December %d is Sunday\n", year)
}
}
} |
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... | #Julia | Julia | module CUSIP
function _lastdigitcusip(input::AbstractString)
input = uppercase(input)
s = 0
for (i, c) in enumerate(input)
if isdigit(c)
v = Int(c) - 48
elseif isalpha(c)
v = Int(c) - 64 + 9
elseif c == '*'
v = 36
elseif 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... | #Kotlin | Kotlin | // version 1.1.0
fun isCusip(s: String): Boolean {
if (s.length != 9) return false
var sum = 0
for (i in 0..7) {
val c = s[i]
var v = when (c) {
in '0'..'9' -> c.toInt() - 48
in 'A'..'Z' -> c.toInt() - 55 // lower case letters apparently invalid
'*' ... |
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... | #C.2B.2B | C++ |
#include <assert.h>
#include <cmath>
#include <vector>
#include <iostream>
template<int N> struct MomentsAccumulator_
{
std::vector<double> m_;
MomentsAccumulator_() : m_(N + 1, 0.0) {}
void operator()(double v)
{
double inc = 1.0;
for (auto& mi : m_)
{
mi += inc;
inc *= v;
}
}
};
double Stdev(... |
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
| #Fantom | Fantom |
fansh> Date.today.toLocale("YYYY-MM-DD")
2011-02-24
fansh> Date.today.toLocale("WWWW, MMMM DD, YYYY")
Thursday, February 24, 2011
|
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
| #Forth | Forth | : .-0 ( n -- n )
[char] - emit
dup 10 < if [char] 0 emit then ;
: .short-date
time&date ( s m h D M Y )
1 u.r .-0 1 u.r .-0 1 u.r
drop drop drop ;
: str-table
create ( n -- ) 0 do , loop
does> ( n -- str len ) swap cells + @ count ;
here ," December"
here ," November"
here ," October"
here ," ... |
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... | #C.2B.2B | C++ | #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Java | Java | public class DammAlgorithm {
private static final int[][] table = {
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
... |
http://rosettacode.org/wiki/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 - ... | #Common_Lisp | Common Lisp | ;;; Show the first 200 and the 100,000th cuban prime.
;;; Cuban primes are the difference of 2 consecutive cubes.
(defun primep (n)
(cond ((< n 4) t)
((evenp n) nil)
((zerop (mod n 3)) nil)
(t (loop for i from 5 upto (isqrt n) by 6
when (or
(zerop (mod n i)... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #PicoLisp | PicoLisp | (out "/dev/tape"
(prin "Hello World!") ) |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Python | Python | >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>> |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Racket | Racket |
#lang racket
(with-output-to-file "/dev/tape" #:exists 'append
(λ() (displayln "I am a cheap imitation of the Perl code for a boring problem")))
|
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Raku | Raku | my $tape = open "/dev/tape", :w or die "Can't open tape: $!";
$tape.say: "I am a tape file now, or hope to be soon.";
$tape.close; |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #REXX | REXX | /*REXX pgm demonstrates writing records to an attached magnetic tape.*/
dsName = 'TAPE.FILE' /*dsName of "file" being written.*/
do j=1 for 100 /*write 100 records to mag tape. */
call lineout dsName, 'this is record' j || "."
end /*j*/
... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Ring | Ring |
# Project : Create a file on magnetic tape
fn = "Tape.file"
fp = fopen(fn,"w")
str = "I am a tape file now, or hope to be soon."
fwrite(fp, str)
fclose(fp)
|
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Lua | Lua | C = setmetatable(require("bc"), {__call=function(t,...) return t.new(...) end})
C.digits(6) -- enough for .nn * .nnnn ==> .nnnnnn, follow with trunc(2) to trim trailing zeroes
subtot = (C"4000000000000000" * C"5.50" + C"2" * C"2.86"):trunc(2) -- cosmetic trunc
tax = (subtot * C"0.0765" + C"0.005"):trunc(2) -- roundin... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #M2000_Interpreter | M2000 Interpreter |
Module Currency_Task {
Locale 1033
Font "Courier New"
Form 80,32
\\Decimal type
hamburgers=4000000000000000@
\\ Currency type
hamburger_price=5.5#
milkshakes=2#
milkshake_price=2.86#
tax_rate=0.0765#
\\ Using Columns with variable width in console
... |
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... | #JavaScript | JavaScript | function addN(n) {
var curry = function(x) {
return x + n;
};
return curry;
}
add2 = addN(2);
alert(add2);
alert(add2(7)); |
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... | #jq | jq |
def plus(x): . + x;
def plus5: plus(5);
|
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Wren | Wren | /* create_object_at_given_address.wren */
import "./fmt" for Fmt
foreign class Integer {
construct new(i) {}
foreign value
foreign value=(i)
foreign address
}
var i = Integer.new(42)
Fmt.print("Integer object with value of: $d allocated at address $#x.", i.value, i.address)
i.value = 42
F... |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Z80_Assembly | Z80 Assembly | LD HL,&FFFF
LD (&C000),HL |
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.
| #mIRC_Scripting_Language | mIRC Scripting Language | echo -ag $asctime($calc($ctime(March 7 2009 7:30pm EST)+43200)) |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.text.SimpleDateFormat
import java.text.ParseException
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method manipulateDate(sampleDate, dateFmt, dHours = 0) private static
... |
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 ... | #Groovy | Groovy | def yuletide = { start, stop -> (start..stop).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } } |
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 ... | #Haskell | Haskell | import Data.Time (fromGregorian)
import Data.Time.Calendar.WeekDate (toWeekDate)
--------------------- DAY OF THE WEEK --------------------
isXmasSunday :: Integer -> Bool
isXmasSunday year = 7 == weekDay
where
(_, _, weekDay) = toWeekDate $ fromGregorian year 12 25
--------------------------- TEST ------... |
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... | #langur | langur | val .isCusip = f(.s) {
if not isString(.s) or len(.s) != 9 {
return false
}
val .basechars = cp2s('0'..'9') ~ cp2s('A'..'Z') ~ "*@#"
val .sum = for[=0] .i of 8 {
var .v = index(s2s(.s, .i), .basechars)
if not .v: return false
.v = .v[1]-1
if .i div 2: .v x= 2
... |
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... | #Lua | Lua | function checkDigit (cusip)
if #cusip ~= 8 then return false end
local sum, c, v, p = 0
for i = 1, 8 do
c = cusip:sub(i, i)
if c:match("%d") then
v = tonumber(c)
elseif c:match("%a") then
p = string.byte(c) - 55
v = p + 9
elseif c == "*" then
v = 36
elseif c == "@" th... |
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 ... | #11l | 11l | V width = 3
V height = 5
V myarray = [[0] * width] * height
print(myarray[height-1][width-1]) |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #Clojure | Clojure |
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
(let [v (deref (find-var (symbol (str *ns* "/v"))))]
(swap! v conj x)
(let [m (/ (reduce + @v) (count @v))]
(Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))]
(when (nil? (resolve 'v)... |
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... | #11l | 11l | V crc_table = [0] * 256
L(i) 256
UInt32 rem = i
L 8
I rem [&] 1 != 0
rem >>= 1
rem (+)= EDB8'8320
E
rem >>= 1
crc_table[i] = rem
F crc32(buf, =crc = UInt32(0))
crc = (-)crc
L(k) buf
crc = (crc >> 8) (+) :crc_table[(crc [&] F'F) (+) k.code]
R (-)crc
prin... |
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
| #Fortran | Fortran | PROGRAM DATE
IMPLICIT NONE
INTEGER :: dateinfo(8), day
CHARACTER(9) :: month, dayname
CALL DATE_AND_TIME(VALUES=dateinfo)
SELECT CASE(dateinfo(2))
CASE(1)
month = "January"
CASE(2)
month = "February"
CASE(3)
month = "March"
CASE(4)
month = "April"
CASE(5)
... |
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... | #Clojure | Clojure |
(require '[clojure.data.csv :as csv]
'[clojure.java.io :as io])
(defn add-sum-column [coll]
(let [titles (first coll)
values (rest coll)]
(cons (conj titles "SUM")
(map #(conj % (reduce + (map read-string %))) values))))
(with-open [in-file (io/reader "test_in.csv")]
(doall
(l... |
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.
| #JavaScript | JavaScript | const table = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 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 - ... | #D | D | import std.math;
import std.stdio;
void main() {
long[] primes = [3, 5];
immutable cutOff = 200;
immutable bigUn = 100_000;
immutable chunks = 50;
immutable little = bigUn / chunks;
immutable tn = " cuban prime";
writefln("The first %s%ss:", cutOff, tn);
int c;
bool showEach = tr... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Ruby | Ruby | File.open("tape.file", "w") do |fh|
fh.syswrite("This code should be able to write a file to magnetic tape.\n")
end |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Rust | Rust | use std::io::Write;
use std::fs::File;
fn main() -> std::io::Result<()> {
File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!")
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Scala | Scala | object LinePrinter extends App {
import java.io.{ FileWriter, IOException }
{
val lp0 = new FileWriter("/dev/tape")
lp0.write("Hello, world!")
lp0.close()
}
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var file: tapeFile is STD_NULL;
begin
tapeFile := open("/dev/tape", "w");
if tapeFile = STD_NULL then
tapeFile := open("tape.file", "w");
end if;
if tapeFile <> STD_NULL then
writeln(tapeFile, "Hello, world!");
close(ta... |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Tcl | Tcl | cd /tmp
# Create the file
set f [open hello.jnk w]
puts $f "Hello World!"
close $f
# Archive to tape
set fin [open "|tar cf - hello.jnk" rb]
set fout [open /dev/tape wb]
fcopy $fin $fout
close $fin
close $fout |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
STATUS = CREATE ("tape.file",tape-o,-std-)
PRINT STATUS |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Maple | Maple |
Digits := 50;
tax := .0765;
burgersquantity := 4000000000000000;
burgersprice := 5.50;
burgerscost := burgersquantity * burgersprice;
milkshakesquantity := 2;
milkshakesprice := 2.86;
milkshakescost := milkshakesquantity * milkshakesprice;
total := burgerscost + milkshakescost;
printf("%.2f\n",total);
total... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | total = 4000000000000000 Rationalize[5.50] + 2 Rationalize[2.86];
AccountingForm[N[total, 20], {\[Infinity], 2}]
tax = total Rationalize[0.0765];
AccountingForm[N[tax, 20], {\[Infinity], 2}]
AccountingForm[N[total + tax, 20], {\[Infinity], 2}] |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Nim | Nim | import strutils
import bignum
type Currency = Int
#---------------------------------------------------------------------------------------------------
func currency(units, subunits: int): Currency =
## Build a currency from units and subunits.
## Units may be negative. Subunits must be in range 0..99.
if su... |
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... | #Julia | Julia |
function addN(n::Number)::Function
adder(x::Number) = n + x
return adder
end
|
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... | #Kotlin | Kotlin | // version 1.1.2
fun curriedAdd(x: Int) = { y: Int -> x + y }
fun main(args: Array<String>) {
val a = 2
val b = 3
val sum = curriedAdd(a)(b)
println("$a + $b = $sum")
} |
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.
| #Nim | Nim | import times
const Date = "March 7 2009 7:30pm EST"
echo "Original date is: ", Date
var dt = Date.replace("EST", "-05:00").parse("MMMM d yyyy h:mmtt zzz")
echo "Original date in UTC is: ", dt.utc().format("MMMM d yyyy h:mmtt zzz")
dt = dt + initDuration(hours = 12)
echo "Date 12 hours later is: ", dt.utc(... |
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.
| #ooRexx | ooRexx |
sampleDate = 'March 7 2009 7:30pm EST'
Parse var sampleDate month day year time zone
basedate = .DateTime~fromNormalDate(day month~left(3) year)
basetime = .DateTime~fromCivilTime(time)
-- this will give us this in a merged format...now we can add in the
-- timezone informat
mergedTime = (basedate + b... |
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 ... | #HicEst | HicEst | DO year = 1, 1000000
TIME(Year=year, MOnth=12, Day=25, TO, WeekDay=weekday)
IF( weekday == 7) WRITE(StatusBar) year
ENDDO
END |
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 ... | #Icon_and_Unicon | Icon and Unicon | link datetime
procedure main()
writes("December 25th is a Sunday in: ")
every writes((dayoweek(25,12,y := 2008 to 2122)=="Sunday",y)," ")
end |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Cusip]
rules = Thread[(ToString /@ Range[0, 9]) -> Range[0, 9]]~Join~
Thread[CharacterRange["A", "Z"] -> Range[26] + 9]~Join~
Thread[Characters["*@#"] -> {36, 37, 38}];
Cusip[cusip_String] := Module[{s = cusip, sum = 0, c, value, check},
If[StringLength[s] != 9,
Print["Cusip must be 9 characters!"];... |
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... | #Modula-2 | Modula-2 | MODULE CUSIP;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..10] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE cusipCheckDigit(cusip : ARRAY OF CHAR) : INTEGER;
VAR
i,v,su... |
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 ... | #68000_Assembly | 68000 Assembly | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Array setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Create_2D_Array:
ARRAY_2D equ $100000
ARRAY_POINTER_VARIABLE equ $... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. run-stddev.
environment division.
input-output section.
file-control.
select input-file assign to "input.txt"
organization is line sequential.
data division.
file section.
fd input-file.
01 inp-record.
03 inp-fld pic 9(03).
working-storage section.
01 filler pic 9(01... |
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... | #6502_Assembly | 6502 Assembly | PRHEX EQU $FDDA ; <= REPLACE THIS WITH THE PRHEX ROUTINE FOR YOUR MACHINE
string EQU $EC
length EQU $EE
crc0 EQU $FA
crc1 EQU $FB
crc2 EQU $FC
crc3 EQU $FD
table0 EQU $9200
table1 EQU $9300
table2 EQU $9400
table3 EQU $9500
ORG $9114
LDA #<text
STA string
LDA #>text
STA string+1
LDA #$2b ; length ... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with GNAT.CRC32; use GNAT.CRC32;
with Interfaces; use Interfaces;
procedure TestCRC is
package IIO is new Ada.Text_IO.Modular_IO (Unsigned_32);
crc : CRC32;
num : Unsigned_32;
str : String := "The quick brown fox jumps over the lazy dog";
begin
Initialize (crc);
Upda... |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "vbcompat.bi"
Dim d As Long = Now
Print "This example was created on : "; Format(d, "yyyy-mm-dd")
Print "In other words on : "; Format(d, "dddd, mmmm d, yyyy")
Print
Print "Press any key to quit the program"
Sleep |
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
| #Free_Pascal | Free Pascal | program Format_Date_Time;
uses
SysUtils;
begin
WriteLn(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));
end.
|
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... | #11l | 11l | V input_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!’
print(... |
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.