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.
| #D | D | import std.stdio;
auto 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... |
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... | #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
-- Derive an NSDecimalNumber from an AppleScript number or numeric text.
-- NSDecimalNumbers also allow arithmetic and have a far greater range than AS numbers.
on decimalNumberFrom(n)
return current application's class "NS... |
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... | #D | D | void main() {
import std.stdio, std.functional;
int add(int a, int b) {
return a + b;
}
alias add2 = partial!(add, 2);
writeln("Add 2 to 3: ", add(2, 3));
writeln("Add 2 to 3 (curried): ", add2(3));
} |
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... | #Delphi | Delphi |
program Currying;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
Plus: TFunc<Integer, TFunc<Integer, Integer>>;
begin
Plus :=
function(x: Integer): TFunc<Integer, Integer>
begin
result :=
function(y: Integer): Integer
begin
result := x + y;
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 |... | #Ada | Ada |
type IO_Port is mod 2**8; -- One byte
Device_Port : type IO_Port;
for Device_Port'Address use 16#FFFF_F000#;
|
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 |... | #Aikido | Aikido |
var portaddr = 0x80
var v = peek (portaddr, 1) // 1 byte
v |= 0x40
poke (portaddr, v, 1) // 1 byte back again
var addr = malloc (16)
poke (addr, 1234, 4)
poke (addr+4, 0, 2)
poke (addr+6, 12, 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 |... | #Applesoft_BASIC | Applesoft BASIC | 0 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256
100 :
110 REM CREATE AN INTEGER OBJECT
120 :
130 I$ = CHR$ (42)
140 POKE 236, PEEK (131)
150 POKE 237, PEEK (132)
160 PRINT "HERE IS AN INTEGER : " ASC (I$)
200 :
210 REM PRINT THE MACHINE ADDRESS OF THE OBJECT
220 :
230 PRINT "ITS ADDRESS IS ... |
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... | #Maple | Maple | with(NumberTheory):
for n to 30 do lprint(Phi(n,x)) od:
x-1
x+1
x^2+x+1
x^2+1
x^4+x^3+x^2+x+1
x^2-x+1
x^6+x^5+x^4+x^3+x^2+x+1
x^4+1
x^6+x^3+1
x^4-x^3+x^2-x+1
x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^4-x^2+1
x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^6-x^5+x^4-x^3+x^2-x+1
x^8-x^7+x^5-x^4+x^3-x+1
x^8+1
x^16... |
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... | #Perl | Perl | use strict;
use warnings;
my @grid = 0;
my ($w, $h, $len);
my $cnt = 0;
my @next;
my @dir = ([0, -1], [-1, 0], [0, 1], [1, 0]);
sub walk {
my ($y, $x) = @_;
if (!$y || $y == $h || !$x || $x == $w) {
$cnt += 2;
return;
}
my $t = $y * ($w + 1) + $x;
$grid[$_]++ for $t, $len - $t;
for... |
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.
| #Go | Go | package main
import (
"fmt"
"time"
)
const taskDate = "March 7 2009 7:30pm EST"
const taskFormat = "January 2 2006 3:04pm MST"
func main() {
if etz, err := time.LoadLocation("US/Eastern"); err == nil {
time.Local = etz
}
fmt.Println("Input: ", taskDate)
t, err := time.P... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Ruby | Ruby | # games = ARGV converted to Integer
# No arguments? Pick any of first 32000 games.
begin
games = ARGV.map {|s| Integer(s)}
rescue => err
$stderr.puts err.inspect
$stderr.puts "Usage: #{__FILE__} number..."
abort
end
games.empty? and games = [rand(32000)]
# Create original deck of 52 cards, not yet shuffle... |
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 ... | #Draco | Draco | proc nonrec weekday(word y, m, d) byte:
word c;
if m<3 then
m := m+10;
y := y+1
else
m := m-2
fi;
c := y/100;
y := y%100;
((26 * m - 2)/10 + d + y + y/4 + c/4 - 2*c + 777) % 7
corp
proc nonrec main() void:
word year;
for year from 2008 upto 2121 do
i... |
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... | #Dyalect | Dyalect | func isCusip(s) {
if s.Length() != 9 { return false }
var sum = 0
for i in 0..7 {
var c = s[i]
var v =
match c {
'0'..'9' => c.Order() - 48,
'A'..'Z' => c.Order() - 55,
'*' => 36,
'@' => 37,
'#' => 38... |
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... | #Excel | Excel | =LAMBDA(s,
LET(
ns, VLOOKUP(
CHARS(s), CUSIPMAP, 2, FALSE
),
AND(
9 = COLUMNS(ns),
LET(
firstEight, INITCOLS(ns),
ixs, SEQUENCE(1, 8),
evensDoubled, IF(ISEVEN(ixs),
2 * INDEX(firstEi... |
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... | #ALGOL_68 | ALGOL 68 | MODE VALUE = STRUCT(CHAR value),
STDDEV = STRUCT(CHAR stddev),
MEAN = STRUCT(CHAR mean),
VAR = STRUCT(CHAR var),
COUNT = STRUCT(CHAR count),
RESET = STRUCT(CHAR reset);
MODE ACTION = UNION ( VALUE, STDDEV, MEAN, VAR, COUNT, RESET );
LONG REAL sum := 0;
LONG REAL sum2 := 0;
INT num := 0;
P... |
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
| #Clojure | Clojure | (let [now (.getTime (java.util.Calendar/getInstance))
f1 (java.text.SimpleDateFormat. "yyyy-MM-dd")
f2 (java.text.SimpleDateFormat. "EEEE, MMMM dd, yyyy")]
(println (.format f1 now))
(println (.format f2 now))) |
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Date-Format.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Days-Area.
03 Days-Data.
05 FILLER PIC X(9) VALUE "Monday".
05 FILLER PIC X(9) VALUE "Tuesday".
05 FILLER PIC X(9) VALUE "Wedne... |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Python | Python |
print("working...")
print("First 20 Cullen numbers:")
for n in range(1,20):
num = n*pow(2,n)+1
print(str(num),end= " ")
print()
print("First 20 Woodall numbers:")
for n in range(1,20):
num = n*pow(2,n)-1
print(str(num),end=" ")
print()
print("done...")
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Quackery | Quackery | [ dup << 1+ ] is cullen ( n --> n )
[ dup << 1 - ] is woodall ( n --> n )
say "First 20 Cullen numbers:" cr
20 times [ i^ 1+ cullen echo sp ] cr
cr
say "First 20 Woodall numbers:" cr
20 times [ i^ 1+ woodall echo sp ] cr |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Raku | Raku | my @cullen = ^∞ .map: { $_ × 1 +< $_ + 1 };
my @woodall = ^∞ .map: { $_ × 1 +< $_ - 1 };
put "First 20 Cullen numbers: ( n × 2**n + 1)\n", @cullen[1..20]; # A002064
put "\nFirst 20 Woodall numbers: ( n × 2**n - 1)\n", @woodall[1..20]; # A003261
put "\nFirst 5 Cullen primes: (in terms of n)\n", @cullen.grep( ... |
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.
| #Delphi | Delphi | let 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... |
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.
| #Dyalect | Dyalect | let 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... |
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... | #AWK | AWK |
# syntax: GAWK -M -f CURRENCY.AWK
# using GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2, GNU MP 5.1.2)
BEGIN {
PREC = 100
hamburger_p = 5.50
hamburger_q = 4000000000000000
hamburger_v = hamburger_p * hamburger_q
milkshake_p = 2.86
milkshake_q = 2
milkshake_v = milkshake_p * milkshake_q
subto... |
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... | #Bracmat | Bracmat | div$((4000000000000000*550+2*286)+1/2,1):?before-tax
& div$(!before-tax*765/10000+1/2,1):?tax
& !before-tax+!tax:?after-tax
& ( fix
= cents dollars
. mod$(!arg.100):?cents
& ( !cents:<10&0 !cents:?cents
|
)
& div$(!arg.100):?dollars
& str$(!dollars "." !cents)
)
& str
... |
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... | #EchoLisp | EchoLisp |
;;
;; curry functional definition
;; (define (curry proc . left-args) (lambda right-args (apply proc (append left-args right-args))))
;;
;; right-curry
;; (define (rcurry proc . right-args) (lambda left-args (apply proc (append left-args right-args))))
;;
(define add42 (curry + 42))
(add42 666) → 708
(map (curry... |
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... | #Eero | Eero | #import <stdio.h>
int main()
addN := (int n)
int adder(int x)
return x + n
return adder
add2 := addN(2)
printf( "Result = %d\n", add2(7) )
return 0
|
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 |... | #ARM_Assembly | ARM Assembly | mov r0,#0x00100000
ldr r1,testData
str r1,[r0] ;store 0x12345678 at address $100000
bx lr ;return from subroutine
testData:
.long 0x12345678 ;VASM uses .long for 32 bit and .word for 16 bit values, unlike most ARM assemblers. |
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 |... | #AutoHotkey | AutoHotkey | ; Create a variable with 4 bytes size and show it's machine address.
VarSetCapacity(var, 4, 0)
pAddress := &var
MsgBox Machine address: %pAddress%
; pAddress contains the memory address.
; Write a number and read it back.
NumPut(123456, pAddress+0, 0, "UInt")
MsgBox % "Contents of *pAdd... |
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 |... | #BBC_BASIC | BBC BASIC | REM Create an integer object:
anInteger% = 12345678
PRINT "Original value =", anInteger%
REM Print the machine address of the object:
address% = ^anInteger%
PRINT "Hexadecimal address = ";~address%
REM Take the address of the object and create
REM another integer ob... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Cyclotomic[#, x] & /@ Range[30] // Column
i = 1;
n = 10;
PrintTemporary[Dynamic[{magnitudes, i}]];
magnitudes = ConstantArray[True, n];
While[Or @@ magnitudes,
coeff = Abs[CoefficientList[Cyclotomic[i, x], x]];
coeff = Select[coeff, Between[{1, n}]];
coeff = DeleteDuplicates[coeff];
If[Or @@ magnitudes[[coeff]],
... |
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... | #Phix | Phix | with javascript_semantics
integer show = 2, -- max number to show
-- (nb mirrors are not shown)
chance = 1000 -- 1=always, 2=50%, 3=33%, etc
sequence grid
integer gh, -- = length(grid),
gw -- = length(grid[1])
integer ty1, ty2, tx1, tx2 -- target {y,x}s
procedur... |
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.
| #Groovy | Groovy | import org.joda.time.*
import java.text.*
def dateString = 'March 7 2009 7:30pm EST'
def sdf = new SimpleDateFormat('MMMM d yyyy h:mma zzz')
DateTime dt = new DateTime(sdf.parse(dateString))
println (dt)
println (dt.plusHours(12))
println (dt.plusHours(12).withZone(DateTimeZone.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.
| #Haskell | Haskell | import qualified Data.Time.Clock.POSIX as P
import qualified Data.Time.Format as F
-- UTC from EST
main :: IO ()
main = print t2
where
t1 =
F.parseTimeOrError
True
F.defaultTimeLocale
"%B %e %Y %l:%M%P %Z"
"March 7 2009 7:30pm EST"
t2 = P.posixSecondsToUTCTime $ 12 * 60... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Run_BASIC | Run BASIC | projectDir$ = "a_project" ' project directory
imageDir$ = DefaultDir$ + "\projects\" + projectDir$ + "\image\" ' directory of deck images
imagePath$ = "../";projectDir$;"/image/" ' path of deck images
suite$ = "C,D,H,S" ... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Rust | Rust | // Code available at https://rosettacode.org/wiki/Linear_congruential_generator#Rust
extern crate linear_congruential_generator;
use linear_congruential_generator::{MsLcg, Rng, SeedableRng};
// We can't use `rand::Rng::shuffle` because it uses the more uniform `rand::Rng::gen_range`
// (`% range` is subject to modu... |
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 ... | #ECL | ECL | //In what years between 2008 and 2121 will the 25th of December be a Sunday?
IMPORT STD;
BaseYear := 2008;
EndYear := 2121;
ChristmasDay := RECORD
UNSIGNED1 DayofWeek;
UNSIGNED2 Year;
END;
ChristmasDay FindDate(INTEGER Ctr) := TRANSFORM
SELF.DayofWeek := (STD.Date.FromGregorianYMD((BaseYear-1) + Ctr,12,2... |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of ... | #Elixir | Elixir | Enum.each(2008..2121, fn year ->
wday = Date.from_erl!({year, 12, 25}) |> Date.day_of_week
if wday==7, do: IO.puts "25 December #{year} is sunday"
end) |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #F.23 | F# |
// Validate CUSIP: Nigel Galloway. June 2nd., 2021
let fN=function n when n>47 && n<58->n-48 |n when n>64 && n<91->n-55 |42->36 |64->37 |_->38
let cD(n:string)=(10-(fst((n.[0..7])|>Seq.fold(fun(z,n)g->let g=(fN(int g))*(n+1) in (z+g/10+g%10,(n+1)%2))(0,0)))%10)%10=int(n.[8])-48
["037833100";"17275R102";"38259P508";"5... |
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... | #ALGOL_W | ALGOL W | begin
long real sum, sum2;
integer n;
long real procedure sd (long real value x) ;
begin
sum := sum + x;
sum2 := sum2 + (x*x);
n := n + 1;
if n = 0 then 0 else longsqrt(sum2/n - sum*sum/n/n)
end sd;
sum := sum2 := n := 0;
r_format := "A"; r_w... |
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
| #CoffeeScript | CoffeeScript |
date = new Date
console.log date.toLocaleDateString 'en-GB',
month: '2-digit'
day: '2-digit'
year: 'numeric'
.split('/').reverse().join '-'
console.log date.toLocaleDateString 'en-US',
weekday: 'long'
month: 'long'
day: 'numeric'
year: 'numeric'
|
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
| #ColdFusion | ColdFusion | <cfoutput>
#dateFormat(Now(), "YYYY-MM-DD")#<br />
#dateFormat(Now(), "DDDD, MMMM DD, YYYY")#
</cfoutput> |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
see "First 20 Cullen numbers:" + nl
for n = 1 to 20
num = n*pow(2,n)+1
see "" + num + " "
next
see nl + nl + "First 20 Woodall numbers:" + nl
for n = 1 to 20
num = n*pow(2,n)-1
see "" + num + " "
next
see nl + "done..." + nl
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Rust | Rust | // [dependencies]
// rug = "1.15.0"
use rug::integer::IsPrime;
use rug::Integer;
fn cullen_number(n: u32) -> Integer {
let num = Integer::from(n);
(num << n) + 1
}
fn woodall_number(n: u32) -> Integer {
let num = Integer::from(n);
(num << n) - 1
}
fn main() {
println!("First 20 Cullen number... |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Sidef | Sidef | func cullen(n) { n * (1 << n) + 1 }
func woodall(n) { n * (1 << n) - 1 }
say "First 20 Cullen numbers:"
say cullen.map(1..20).join(' ')
say "\nFirst 20 Woodall numbers:"
say woodall.map(1..20).join(' ')
say "\nFirst 5 Cullen primes: (in terms of n)"
say 5.by { cullen(_).is_prime }.join(' ')
say "\nFirst 12 Woo... |
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... | #11l | 11l | L(=line) File(‘data.csv’).read_lines()
I L.index == 0
line ‘’= ‘,SUM’
E
line ‘’= ‘,’sum(line.split(‘,’).map(Int))
print(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.
| #F.23 | F# | open System
let 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... |
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... | #C | C | Floating point number or Float for short, is an arbitrary precision mantissa with a limited precision exponent. The C data type for such objects is mpf_t. For example:
mpf_t 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... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace Currency
{
class Program
{
static void Main(string[] args)
{
MenuItem hamburger = new MenuItem() { Name = "Hamburger", Price = 5.5M };
MenuItem milkshake = new MenuItem() { Name = "Milkshake", Price = 2.86M };
... |
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... | #Eiffel | Eiffel | g (x: X): FUNCTION [ANY, TUPLE [Y], Z]
do
Result := agent (closed_x: X; y: Y): Z
do
Result := f (closed_x, y)
end (x, ?)
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... | #Erlang | Erlang |
-module(currying).
-compile(export_all).
% Function that curry the first or the second argument of a given function of arity 2
curry_first(F,X) ->
fun(Y) -> F(X,Y) end.
curry_second(F,Y) ->
fun(X) -> F(X,Y) end.
% Usual curry
curry(Fun,Arg) ->
case erlang:fun_info(Fun,arity) of
{arity,0} ->
... |
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 |... | #C | C | #include <stdio.h>
int main()
{
int intspace;
int *address;
address = &intspace; // address = 0x100;
*address = 65535;
printf("%p: %08x (=%08x)\n", address, *address, intspace);
// likely we must be worried about endianness, e.g.
*((char*)address) = 0x00;
*((char*)address+1) = 0x00;
*((char*)addre... |
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 |... | #C.2B.2B | C++ | #include <string>
#include <iostream>
int main()
{
// Allocate enough memory to hold an instance of std::string
char* data = new char[sizeof(std::string)];
// use placement new to construct a std::string in the memory we allocated previously
std::string* stringPtr = new (data) std::string("ABCD");
... |
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... | #Nim | Nim | import algorithm, math, sequtils, strformat, tables
type
Term = tuple[coeff: int; exp: Natural]
Polynomial = seq[Term]
# Table used to represent the list of factors of a number.
# If, for a number "n", "k" is present in the table "f" of its factors,
# "f[k]" contains the exponent of "k" in the prime fac... |
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... | #Python | Python | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or ... |
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.
| #HicEst | HicEst |
CHARACTER date="March 7 2009 7:30pm EST", am_pm, result*20
EDIT(Text=date, Parse=cMonth, GetPosition=next)
month = 1 + EDIT(Text='January,February,March,April,May,June,July,August,September,October,November,December', Right=cMonth, Count=',' )
READ(Text=date(next:)) day, year, hour, minute, am_pm
hou... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Scala | Scala | object Shuffler extends App {
private val suits = Array("C", "D", "H", "S")
private val values = Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K")
private val deck = values.flatMap(v => suits.map(s => s"$v$s"))
private var seed: Int = _
private def random() = {
seed = (214013 * ... |
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 ... | #Emacs_Lisp | Emacs Lisp | (require 'calendar)
(defun sunday-p (y)
"Is Dec 25th a Sunday in this year?"
(= (calendar-day-of-week (list 12 25 y)) 0))
(defun xmas-sunday (a b)
"In which years in the range a, b is Dec 25th a Sunday?"
(seq-filter #'sunday-p (number-sequence a b)))
(print (xmas-sunday 2008 2121)) |
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... | #Factor | Factor | USING: combinators.short-circuit formatting kernel math
math.parser qw regexp sequences unicode ;
IN: rosetta-code.cusip
: cusip-check-digit ( seq -- n )
but-last-slice [
[ dup alpha? [ digit> ] [ "*@#" index 36 + ] if ] dip
odd? [ 2 * ] when 10 /mod +
] map-index sum 10 mod 10 swap - 10 mod ;... |
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... | #Fortran | Fortran | CHARACTER*1 FUNCTION CUSIPCHECK(TEXT) !Determines the check sum character.
Committee on Uniform Security Identification Purposes, of the American (i.e. USA) Bankers' Association.
CHARACTER*8 TEXT !Specifically, an eight-symbol code.
CHARACTER*(*) VALID !These only are valid.
PARAMETER (VALID... |
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... | #AppleScript | AppleScript | -------------- CUMULATIVE STANDARD DEVIATION -------------
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
-- stdDevInc :: {sum:, squaresSum:, stages:} -> Real -> Integer
-- -> {sum:, squaresSum:, stages:}
on stdDevInc(a, n, i)
set sum to (sum of a) + n
set squaresSum to (squaresSum... |
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
| #Common_Lisp | Common Lisp | (defconstant *day-names*
#("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(defconstant *month-names*
#(nil "January" "February" "March" "April" "May" "June" "July"
"August" "September" "October" "November" "December"))
(multiple-value-bind (sec min hour date month year day day... |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Verilog | Verilog | module main;
integer n, num;
initial begin
$display("First 20 Cullen numbers:");
for(n = 1; n <= 20; n=n+1)
begin
num = n * (2 ** n) + 1;
$write(num, " ");
end
$display("");
$display("First 20 Woodall numbers:");
for(n = 1; n <= 20; n=n+1)
begin
... |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers o... | #Wren | Wren | import "./big" for BigInt
var cullen = Fn.new { |n| (BigInt.one << n) * n + 1 }
var woodall = Fn.new { |n| cullen.call(n) - 2 }
System.print("First 20 Cullen numbers (n * 2^n + 1):")
for (n in 1..20) System.write("%(cullen.call(n)) ")
System.print("\n\nFirst 20 Woodall numbers (n * 2^n - 1):")
for (n in 1..20) ... |
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... | #Ada | Ada | package CSV is
type Row(<>) is tagged private;
function Line(S: String; Separator: Character := ',') return Row;
function Next(R: in out Row) return Boolean;
-- if there is still an item in R, Next advances to it and returns True
function Item(R: Row) return String;
-- after calling R.Next i ... |
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.
| #Factor | Factor | USING: interpolate kernel math math.parser qw sequences ;
CONSTANT: 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 ... |
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.
| #Forth | Forth | : newdigit ( col row -- u ) 10 * + C" 0317598642709215486342068713591750983426612304597836742095815869720134894536201794386172052581436790" 1+ + c@ 48 - ;
: nextdigit ( addr -- addr+1 u ) dup c@ 48 - swap 1+ swap ;
: damm ( c u -- u )
0 rot rot
0 do
nextdigit
rot newdigit swap
loop drop
;
: isdamm? damm 0= if .... |
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... | #Clojure | Clojure | (require '[clojurewerkz.money.amounts :as ma])
(require '[clojurewerkz.money.currencies :as mc])
(require '[clojurewerkz.money.format :as mf])
(let [burgers (ma/multiply (ma/amount-of mc/USD 5.50) 4000000000000000)
milkshakes (ma/multiply (ma/amount-of mc/USD 2.86) 2)
pre-tax (ma/plus burgers milk... |
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... | #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. currency-example.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Burger-Price CONSTANT 5.50.
01 Milkshake-Price CONSTANT 2.86.
01 num-burgers PIC 9(18) VALUE 4000000000000000.
01 num-milkshakes... |
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... | #F.23 | F# | let addN n = (+) n |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific la... | #Factor | Factor | IN: scratchpad 2 [ 3 + ] curry
--- Data stack:
[ 2 3 + ]
IN: scratchpad call
--- Data stack:
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 |... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. object-address-test.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 int-space.
05 val PICTURE 9(5) VALUE 12345.
01 addr BASED.
05 val PICTURE 9(5) VALUE ZERO.
01 point USAGE POINTER.
PROCEDURE DIVISION.
D... |
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 |... | #Commodore_BASIC | Commodore BASIC | 10 POKE 50000,(3) REM EQUIVALENT OF LDA #$03 STA 50000
20 PEEK(50000) REM READ THE VALUE AT MEMORY ADDRESS 50000 |
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 |... | #D | D | import std.stdio ;
void main() {
int[] arr ;
foreach(i; [0,1,2,3])
arr ~= i*(1 << 24) + 0x417e7e7e ;
struct X {
char[16] msg ;
}
X* xPtr ;
int* iPtr ;
float* fPtr ;
int adrSpace = cast(int) arr.ptr ;
// get address of an existing object arr
xPtr = cast(X... |
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... | #PARI.2FGP | PARI/GP |
for(n=1,30,print(n," : ",polcyclo(n)))
contains_coeff(n, d) = p=polcyclo(n);for(k=0,poldegree(p),if(abs(polcoef(p,k))==d,return(1)));return(0)
for(d=1,10,i=1; while(contains_coeff(i,d)==0,i=i+1);print(d," : ",i))
|
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... | #Racket | Racket |
#lang racket
(define (cuts W H [count 0]) ; count = #f => visualize instead
(define W1 (add1 W)) (define H1 (add1 H))
(define B (make-vector (* W1 H1) #f))
(define (fD d) (cadr (assq d '([U D] [D U] [L R] [R L] [#f #f] [#t #t]))))
(define (fP p) (- (* W1 H1) p 1))
(define (Bset! p d) (vector-set! B p d) (... |
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.
| #Icon_and_Unicon | Icon and Unicon | link datetime
procedure main()
write("input = ",s := "March 7 2009 7:30pm EST" )
write("+12 hours = ",SecToTZDateLine(s := TZDateLineToSec(s) + 12*3600,"EST"))
write(" = ",SecToTZDateLine(s,"UTC"))
write(" = ",SecToTZDateLine(s,"NST"))
end
procedure SecToTZDateLine(s,tz) #: returns ... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "console.s7i";
const string: suits is "♣♦♥♠";
const string: nums is "A23456789TJQK";
var integer: randomSeed is 1;
const func integer: random is func
result
var integer: rand is 1;
begin
randomSeed := (randomSeed * 214013 + 2531011) mod 2 ** 31;
rand := randomSe... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Swift | Swift | enum Suit : String, CustomStringConvertible, CaseIterable {
case clubs = "C", diamonds = "D", hearts = "H", spades = "S"
var description: String {
return self.rawValue
}
}
enum Rank : Int, CustomStringConvertible, CaseIterable {
case ace=1, two, three, four, five, six, seven
case eight, nine... |
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 ... | #Erlang | Erlang | % Implemented by bengt kleberg
-module(yuletide).
-export([main/0, sunday_years/2]).
main() ->
[io:fwrite("25 December ~p is Sunday~n", [X]) || X <- sunday_years(2008, 2121)].
sunday_years( Start, Stop ) ->
[X || X <- lists:seq(Start, Stop), is_sunday(calendar:day_of_the_week({X, 12, 25}))].
is_sunday( 7 ) -> t... |
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... | #FreeBASIC | FreeBASIC | ' version 04-04-2017
' compile with: fbc -s console
sub cusip(input_str As String)
Print input_str;
If Len(input_str) <> 9 Then
Print " length is incorrect, invalid cusip"
Return
End If
Dim As Long i, v , sum
Dim As UByte x
For i = 1 To 8
x = input_str[i-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... | #Arturo | Arturo | arr: new []
loop [2 4 4 4 5 5 7 9] 'value [
'arr ++ value
print [value "->" deviation arr]
] |
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
| #Component_Pascal | Component Pascal |
MODULE DateFormat;
IMPORT StdLog, Dates;
PROCEDURE Do*;
VAR
d: Dates.Date;
resp: ARRAY 64 OF CHAR;
BEGIN
Dates.GetDate(d);
Dates.DateToString(d,Dates.short,resp);
StdLog.String(":> " + resp);StdLog.Ln;
Dates.DateToString(d,Dates.abbreviated,resp);
StdLog.String(":> " + resp);StdLog.Ln;
Dates.DateToString(d,... |
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... | #Aime | Aime | void
read_csv(list t, text path)
{
file f;
list l;
f_affix(f, path);
while (f_news(f, l, 0, 0, ",") ^ -1) {
l_append(t, l);
}
}
list
sum_columns(list t)
{
list c, l;
integer i;
l_append(c, "SUM");
for (i, l in t) {
if (i) {
integer j, sum;
... |
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... | #ALGOL_68 | ALGOL 68 | # count occurrances of a char in string #
PROC char count = (CHAR c, STRING str) INT:
BEGIN
INT count := 0;
FOR i TO UPB str DO
IF c = str[i] THEN count +:= 1
FI
OD;
count
END;
# split string on separator #
PROC char split = (STRING str, CHAR sep) FLEX[]STRING :
BEGIN
INT s... |
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.
| #Fortran | Fortran | LOGICAL FUNCTION DAMM(DIGIT) !Check that a sequence of digits checks out..
Calculates according to the method of H. Michael Damm, described in 2004.
CHARACTER*(*) DIGIT !A sequence of digits only.
INTEGER*1 OPTABLE(0:9,0:9) !The special "Operation table" of the method.
PARAMETER (OPTABLE = (... |
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... | #Delphi | Delphi |
program Currency;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigRationals,
Velthuis.BigDecimals,
Velthuis.BigIntegers;
var
one: BigInteger;
hundred: BigInteger;
half: BigRational;
type
TDc = record
value: BigInteger;
function ToString: string;
function Extend(n: BigInteger):... |
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... | #Forth | Forth | : curry ( x xt1 -- xt2 )
swap 2>r :noname r> postpone literal r> compile, postpone ; ;
5 ' + curry constant +5
5 +5 execute .
7 +5 execute . |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type CurriedAdd
As Integer i
Declare Function add(As Integer) As Integer
End Type
Function CurriedAdd.add(j As Integer) As Integer
Return i + j
End Function
Function add (i As Integer) as CurriedAdd
Return Type<CurriedAdd>(i)
End Function
Print "3 + 4 ="; add(3).add(4)
Print "2 + 6 =... |
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 |... | #Delphi | Delphi |
program Create_an_object_at_a_given_address;
{$APPTYPE CONSOLE}
var
origem: Integer;
copy: Integer absolute origem; // This is old the trick
begin
writeln('The "origem" adress is: ', cardinal(@origem));
writeln('The "copy" adress is: ', cardinal(@copy));
writeln;
origem := 10;
writeln('Assign ... |
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 |... | #Forth | Forth |
$3f8 constant LPT1:
LPT1: c@ .
$3f LPT1: 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 |... | #FreeBASIC | FreeBASIC | ' FB 1.05.0
Type Person
As String name
As Integer age
Declare Constructor(name As String, age As Integer)
End Type
Constructor Person(name As String, age As Integer)
This.name = name
This.age = age
End Constructor
Dim ap As Any Ptr = CAllocate(SizeOf(Person)) ' allocate memory to store a Person object
... |
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... | #Perl | Perl | use feature 'say';
use List::Util qw(first);
use Math::Polynomial::Cyclotomic qw(cyclo_poly_iterate);
say 'First 30 cyclotomic polynomials:';
my $it = cyclo_poly_iterate(1);
say "$_: " . $it->() for 1 .. 30;
say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:";
$it = cyclo_poly_iterate(1);
for (m... |
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... | #Raku | Raku | sub solve($hh, $ww, $recurse) {
my ($h, $w, $t, @grid) = $hh, $ww, 0;
state $cnt;
$cnt = 0 if $recurse;
($t, $w, $h) = ($w, $h, $w) if $h +& 1;
return 0 if $h == 1;
return 1 if $w == 1;
return $h if $w == 2;
return $w if $h == 2;
my ($cy, $cx) = ($h, $w) «div» 2;
my $len = ... |
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.
| #J | J | require'dates'
months=: <;._2 tolower 0 :0
January
February
March
April
May
June
July
August
September
October
November
December
)
numbers=: _".' '"_`(1 I.@:-e.&(":i.10)@])`]}~
words=: [:;:@tolower' '"_`(I.@(tolower = toupper)@])`]}~
getyear=: >./@numbers
getmonth=: 1 + months <./@i. words
getday=: {.@(numbers -. get... |
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.
| #Java | Java | import java.time.*;
import java.time.format.*;
class Main {
public static void main(String args[]) {
String dateStr = "March 7 2009 7:30pm EST";
DateTimeFormatter df = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM d yyyy h:mma zzz")
.toFormatter();
ZonedD... |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim H... | #Tcl | Tcl | proc rnd {{*r seed}} {
upvar 1 ${*r} r
expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16}
}
proc show cards {
set suits {\u2663 \u2666 \u2665 \u2660}
set values {A 2 3 4 5 6 7 8 9 T J Q K}
for {set i 0} {$i < 52} {incr i} {
set c [lindex $cards $i]
puts -nonewline [format " \033\[... |
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 ... | #ERRE | ERRE |
PROGRAM DAY_OF_THE_WEEK
PROCEDURE MODULO(X,Y->RES)
IF Y=0 THEN
RES=X
ELSE
RES=X-Y*INT(X/Y)
END IF
END PROCEDURE
PROCEDURE WD(M,D,Y->RES%)
IF M=1 OR M=2 THEN
M+=12
Y-=1
END IF
MODULO(365*Y+INT(Y/4)-INT(Y/100)+INT(Y/400)+D+INT((153*M+8)/5),7->RES)
RES%=RES+1.0
END PROCED... |
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 ... | #Euphoria | Euphoria |
--Day of the week task from Rosetta Code wiki
--User:Lnettnay
--In what years between 2008 and 2121 will the 25th of December be a Sunday
include std/datetime.e
datetime dt
for year = 2008 to 2121 do
dt = new(year, 12, 25)
if weeks_day(dt) = 1 then -- Sunday = 1
? 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... | #Go | Go | package main
import "fmt"
func isCusip(s string) bool {
if len(s) != 9 { return false }
sum := 0
for i := 0; i < 8; i++ {
c := s[i]
var v int
switch {
case c >= '0' && c <= '9':
v = int(c) - 48
case c >= 'A' && c <= 'Z':
v =... |
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... | #AutoHotkey | AutoHotkey | Data := [2,4,4,4,5,5,7,9]
for k, v in Data {
FileAppend, % "#" a_index " value = " v " stddev = " stddev(v) "`n", * ; send to stdout
}
return
stddev(x) {
static n, sum, sum2
n++
sum += x
sum2 += x*x
return sqrt((sum2/n) - (((sum*sum)/n)/n))
} |
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.