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],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
];
bool damm(string s) {
int interim = 0;
foreach (c; s) {
interim = table[interim][c - '0'];
}
return interim == 0;
}
void main() {
import std.conv : to;
auto numbers = [5724, 5727, 112946, 112949];
foreach (number; numbers) {
bool isValid = damm(number.to!string());
writef("%6d is ", number);
if (isValid) {
writeln("valid");
} else {
writeln("invalid");
}
}
} |
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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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 "NSDecimalNumber"'s decimalNumberWithString:(n as text)
end decimalNumberFrom
-- Multiply two NSDecimalNumbers.
on multiply(dn1, dn2)
return dn1's decimalNumberByMultiplyingBy:(dn2)
end multiply
-- Add two NSDecimalNumbers.
on add(dn1, dn2)
return dn1's decimalNumberByAdding:(dn2)
end add
on billTotal(quantitiesAndPrices, taxRate, currencySymbol)
-- Set up an NSNumberFormatter for converting between currency strings and NSDecimalNumbers.
set currencyFormatter to current application's class "NSNumberFormatter"'s new()
tell currencyFormatter to setNumberStyle:(current application's NSNumberFormatterCurrencyStyle)
tell currencyFormatter to setCurrencySymbol:(currencySymbol)
tell currencyFormatter to setGeneratesDecimalNumbers:(true)
-- Tot up the bill from the list of quantities (numbers or numeric strings) and unit prices (currency strings with symbols).
set subtotal to decimalNumberFrom(0) -- or: current application's class "NSDecimalNumber"'s zero()
repeat with thisEntry in quantitiesAndPrices
set {quantity:quantity, unitPrice:unitPrice} to thisEntry
set entryTotal to multiply(decimalNumberFrom(quantity), currencyFormatter's numberFromString:(unitPrice))
set subtotal to add(subtotal, entryTotal)
end repeat
-- Work out the tax and add it to the subtotal.
set tax to multiply(subtotal, decimalNumberFrom(taxRate / 100))
set total to add(subtotal, tax)
-- Format and return the results.
return (current application's class "NSString"'s stringWithFormat_("Subtotal: %@
Tax: %@
Total: %@", ¬
currencyFormatter's stringFromNumber:(subtotal), ¬
currencyFormatter's stringFromNumber:(tax), ¬
currencyFormatter's stringFromNumber:(total))) ¬
as text
end billTotal
-- Demo code:
set currencySymbol to "$"
set quantitiesAndPrices to {{quantity:"4000000000000000", unitPrice:currencySymbol & "5.50"}, ¬
{quantity:2, unitPrice:currencySymbol & 2.86}}
set taxRate to 7.65
return billTotal(quantitiesAndPrices, taxRate, currencySymbol) |
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 language.
Add any historic details as to how the feature made its way into the language.
| #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 language.
Add any historic details as to how the feature made its way into the language.
| #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;
end;
Writeln(Plus(3)(4));
Writeln(Plus(2)(Plus(3)(4)));
readln;
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 : " FN P( FN P(236) + 1)
300 :
310 REM TAKE THE ADDRESS OF THE OBJECT AND CREATE ANOTHER INTEGER OBJECT AT THIS ADDRESS
320 :
330 O$ = CHR$ (0)
340 POKE 250, PEEK (131)
350 POKE 251, PEEK (132)
360 POKE FN P(250) + 1, PEEK ( FN P(236) + 1)
370 POKE FN P(250) + 2, PEEK ( FN P(236) + 2)
400 :
410 REM PRINT THE VALUE OF THIS OBJECT TO VERIFY THAT IT IS SAME AS ONE OF THE ORIGIN
420 :
430 PRINT "COMPARE OTHER INTEGER : " ASC (O$)
500 :
510 REM CHANGE THE VALUE OF THE ORIGIN AND VERIFY IT AGAIN
520 :
530 POKE FN P( FN P(236) + 1),69
540 PRINT "NEW INTEGER VALUE : " ASC (I$)
550 PRINT "COMPARE OTHER INTEGER : " ASC (O$) |
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 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #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+x^15+x^14+x^13+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^3+1
x^18+x^17+x^16+x^15+x^14+x^13+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^8-x^6+x^4-x^2+1
x^12-x^11+x^9-x^8+x^6-x^4+x^3-x+1
x^10-x^9+x^8-x^7+x^6-x^5+x^4-x^3+x^2-x+1
x^22+x^21+x^20+x^19+x^18+x^17+x^16+x^15+x^14+x^13+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^8-x^4+1
x^20+x^15+x^10+x^5+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^18+x^9+1
x^12-x^10+x^8-x^6+x^4-x^2+1
x^28+x^27+x^26+x^25+x^24+x^23+x^22+x^21+x^20+x^19+x^18+x^17+x^16+x^15+x^14+x^13+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^8+x^7-x^5-x^4-x^3+x+1
PhiSet:=[seq(map(abs,{coeffs(Phi(k,x),x)}),k=1..15000)]:
[seq(ListTools:-SelectFirst(s->member(n,s),PhiSet,output=indices),n=1..20)];
#[1, 105, 385, 1365, 1785, 2805, 3135, 6545, 6545, 10465, 10465,
# 10465, 10465, 10465, 11305, 11305, 11305, 11305, 11305, 11305] |
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 are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #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 my $i (0 .. 3) {
if (!$grid[$t + $next[$i]]) {
walk($y + $dir[$i]->[0], $x + $dir[$i]->[1]);
}
}
$grid[$_]-- for $t, $len - $t;
}
sub solve {
my ($hh, $ww, $recur) = @_;
my ($t, $cx, $cy, $x);
($h, $w) = ($hh, $ww);
if ($h & 1) { ($t, $w, $h) = ($w, $h, $w); }
if ($h & 1) { return 0; }
if ($w == 1) { return 1; }
if ($w == 2) { return $h; }
if ($h == 2) { return $w; }
{
use integer;
($cy, $cx) = ($h / 2, $w / 2);
}
$len = ($h + 1) * ($w + 1);
@grid = ();
$grid[$len--] = 0;
@next = (-1, -$w - 1, 1, $w + 1);
if ($recur) { $cnt = 0; }
for ($x = $cx + 1; $x < $w; $x++) {
$t = $cy * ($w + 1) + $x;
@grid[$t, $len - $t] = (1, 1);
walk($cy - 1, $x);
}
$cnt++;
if ($h == $w) {
$cnt *= 2;
} elsif (!($w & 1) && $recur) {
solve($w, $h);
}
return $cnt;
}
sub MAIN {
print "ok\n";
my ($y, $x);
for my $y (1 .. 10) {
for my $x (1 .. $y) {
if (!($x & 1) || !($y & 1)) {
printf("%d x %d: %d\n", $y, $x, solve($y, $x, 1));
}
}
}
}
MAIN(); |
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.Parse(taskFormat, taskDate)
if err != nil {
fmt.Println(err)
return
}
t = t.Add(12 * time.Hour)
fmt.Println("+12 hrs: ", t)
if _, offset := t.Zone(); offset == 0 {
fmt.Println("No time zone info.")
return
}
atz, err := time.LoadLocation("US/Arizona")
if err == nil {
fmt.Println("+12 hrs in Arizona:", t.In(atz))
}
} |
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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 shuffled.
orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join)
games.each do |seed|
deck = orig_deck.dup
# Shuffle deck with random index from linear congruential
# generator like Microsoft.
state = seed
52.downto(2) do |len|
state = ((214013 * state) + 2531011) & 0x7fff_ffff
index = (state >> 16) % len
last = len - 1
deck[index], deck[last] = deck[last], deck[index]
end
deck.reverse! # Shuffle did reverse deck. Do reverse again.
# Deal cards.
puts "Game ##{seed}"
deck.each_slice(8) {|row| puts " " + row.join(" ")}
puts
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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
if weekday(year, 12, 25)=0 then
writeln(year)
fi
od
corp |
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 American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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,
_ => false
}
if i % 2 == 1 { v *= 2 }
sum += v / 10 + v % 10
}
s[8].Order() - 48 == (10 - (sum % 10)) % 10
}
var candidates = [
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
]
for candidate in candidates {
var b =
if isCusip(candidate) {
"correct"
} else {
"incorrect"
}
print("\(candidate) -> \(b)")
} |
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 American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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(firstEight, 1, ixs),
INDEX(firstEight, 1, ixs)
),
LASTCOL(ns) = MOD(
10 - MOD(
SUM(
QUOTIENT(evensDoubled, 10),
MOD(evensDoubled, 10)
),
10
),
10
)
)
)
)
)
CUSIPMAP
={"0",0;"1",1;"2",2;"3",3;"4",4;"5",5;"6",6;"7",7;"8",8;"9",9;"A",
10;"B",11;"C",12;"D",13;"E",14;"F",15;"G",16;"H",17;"I",18;"J",19;"K",
20;"L",21;"M",22;"N",23;"O",24;"P",25;"Q",26;"R",27;"S",28;"T",29;"U",
30;"V",31;"W",32;"X",33;"Y",34;"Z",35;"*",36;"@",37;"#",38} |
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 language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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;
PROC stat object = (LONG REAL v, ACTION action)LONG REAL:
(
LONG REAL m;
CASE action IN
(VALUE):(
num +:= 1;
sum +:= v;
sum2 +:= v*v;
stat object(0, LOC STDDEV)
),
(STDDEV):
long sqrt(stat object(0, LOC VAR)),
(MEAN):
IF num>0 THEN sum/LONG REAL(num) ELSE 0 FI,
(VAR):(
m := stat object(0, LOC MEAN);
IF num>0 THEN sum2/LONG REAL(num)-m*m ELSE 0 FI
),
(COUNT):
num,
(RESET):
sum := sum2 := num := 0
ESAC
);
[]LONG REAL v = ( 2,4,4,4,5,5,7,9 );
main:
(
LONG REAL sd;
FOR i FROM LWB v TO UPB v DO
sd := stat object(v[i], LOC VALUE);
printf(($"value: "g(0,6)," standard dev := "g(0,6)l$, v[i], sd))
OD
) |
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 "Wednesday".
05 FILLER PIC X(9) VALUE "Thursday".
05 FILLER PIC X(9) VALUE "Friday".
05 FILLER PIC X(9) VALUE "Saturday".
05 FILLER PIC X(9) VALUE "Sunday".
03 Days-Values REDEFINES Days-Data.
05 Days-Table PIC X(9) OCCURS 7 TIMES.
01 Months-Area.
03 Months-Data.
05 FILLER PIC X(9) VALUE "January".
05 FILLER PIC X(9) VALUE "February".
05 FILLER PIC X(9) VALUE "March".
05 FILLER PIC X(9) VALUE "April".
05 FILLER PIC X(9) VALUE "May".
05 FILLER PIC X(9) VALUE "June".
05 FILLER PIC X(9) VALUE "July".
05 FILLER PIC X(9) VALUE "August".
05 FILLER PIC X(9) VALUE "September".
05 FILLER PIC X(9) VALUE "October".
05 FILLER PIC X(9) VALUE "November".
05 FILLER PIC X(9) VALUE "December".
03 Months-Values REDEFINES Months-Data.
05 Months-Table PIC X(9) OCCURS 12 TIMES.
01 Current-Date-Str.
03 Current-Year PIC X(4).
03 Current-Month PIC X(2).
03 Current-Day PIC X(2).
01 Current-Day-Of-Week PIC 9.
PROCEDURE DIVISION.
MOVE FUNCTION CURRENT-DATE (1:8) TO Current-Date-Str
DISPLAY Current-Year "-" Current-Month "-" Current-Day
ACCEPT Current-Day-Of-Week FROM DAY-OF-WEEK
DISPLAY
FUNCTION TRIM(
Days-Table (FUNCTION NUMVAL(Current-Day-Of-Week)))
", "
FUNCTION TRIM(
Months-Table (FUNCTION NUMVAL(Current-Month)))
" "
Current-Day
", "
Current-Year
END-DISPLAY
GOBACK
. |
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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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( &is-prime, :k )[^5]; # A005849
put "\nFirst 12 Woodall primes: (in terms of n)\n", @woodall.grep( &is-prime, :k )[^12]; # A002234 |
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, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0]
]
func damm(s) {
var interim = 0
for c in s {
interim = table[interim][Integer(c)]
}
return interim == 0;
}
let numbers = [5724, 5727, 112946, 112949]
for number in numbers {
let isValid = damm(number.ToString())
if isValid {
print("\(number) is valid")
} else {
print("\(number) is invalid")
}
} |
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, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0]
]
func damm(s) {
var interim = 0
for c in s {
interim = table[interim][Integer(c)]
}
return interim == 0;
}
let numbers = [5724, 5727, 112946, 112949]
for number in numbers {
let isValid = damm(number.ToString())
if isValid {
print("\(number) is valid")
} else {
print("\(number) is invalid")
}
} |
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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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
subtotal = hamburger_v + milkshake_v
tax = subtotal * .0765
printf("%-9s %8s %18s %22s\n","item","price","quantity","value")
printf("hamburger %8.2f %18d %22.2f\n",hamburger_p,hamburger_q,hamburger_v)
printf("milkshake %8.2f %18d %22.2f\n\n",milkshake_p,milkshake_q,milkshake_v)
printf("%37s %22.2f\n","subtotal",subtotal)
printf("%37s %22.2f\n","tax",tax)
printf("%37s %22.2f\n","total",subtotal+tax)
exit(0)
}
|
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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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
$ ( "before-tax "
fix$!before-tax
"\ntax "
fix$!tax
\n
"after-tax "
fix$!after-tax
\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 language.
Add any historic details as to how the feature made its way into the language.
| #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 cons 'simon) '( gallubert garfunkel et-merveilles))
→ ((simon . gallubert) (simon . garfunkel) (simon . et-merveilles))
(map (rcurry cons 'simon) '( gallubert garfunkel et-merveilles))
→ ((gallubert . simon) (garfunkel . simon) (et-merveilles . simon))
;Implementation : result of currying :
(curry * 2 3 (+ 2 2))
→ (λ _#:g1004 (#apply-curry #* (2 3 4) _#:g1004))
|
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 language.
Add any historic details as to how the feature made its way into the language.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 *pAddress: " . NumGet(pAddress+0, 0, "UInt") |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 object at this address:
!address% = 87654321
REM Print the value of this object to verify
REM that it is same as one of the origin:
PRINT "New value =", anInteger%
REM Change the value and verify it again:
anInteger% = 55555555
PRINT "Final value =", !address%
|
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 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #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]],
Do[
If[magnitudes[[c]] == True,
Print["CyclotomicPolynomial(", i,
") has coefficient with magnitude ", c]
]
,
{c, coeff}
];
magnitudes[[coeff]] = False;
];
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 are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #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
procedure mirror(integer y, x, ch)
-- plant/reset ch and the symmetric copy
grid[y,x] = ch
grid[gh-y+1,gw-x+1] = ch
end procedure
enum RIGHT, UP, DOWN, LEFT
constant dyx = {{0,+1},{-1,0},{+1,0},{0,-1}},
chx = "-||-"
function search(integer y, x, d, level)
integer count = 0
if level=0 or grid[y,x]!='x' then
mirror(y,x,'x')
integer {dy,dx} = dyx[d],
{ny,nx} = {y+dy,x+dx},
{yy,xx} = {y+dy*2,x+dx*3}
if grid[ny,nx]=' ' then
integer c = chx[d]
mirror(ny,nx,c)
if c='-' then
mirror(ny,nx+dx,c)
end if
integer meet = (yy=ty1 or yy=ty2) and (xx=tx1 or xx=tx2)
if meet then
count = 1
if show and rand(chance)=chance then
show -= 1
sequence g = deep_copy(grid) -- (make copy/avoid reset)
-- fill in(/overwrite) the last cut, if any
if ty1!=ty2 then g[ty1+1,tx1] = '|'
elsif tx1!=tx2 then g[ty1][tx1+1..tx1+2] = "--"
end if
puts(1,join(g,'\n')&"\n\n")
end if
else
if grid[yy,xx]='+' then -- (minor gain)
for d=RIGHT to LEFT do -- (kinda true!)
count += search(yy,xx,d,level+1)
end for
end if
end if
mirror(ny,nx,' ')
if c='-' then
mirror(ny,nx+dx,' ')
end if
end if
if level!=0 then
-- ((level=0)==leave outer edges 'x' for next iteration)
mirror(y,x,'+')
end if
end if
return count
end function
procedure make_grid(integer w,h)
-- The outer edges are 'x'; the inner '+' become 'x' when visited.
-- Likewise edges are cuts but the inner ones get filled in later.
sequence tb = join(repeat("x",w+1),"--"),
hz = join('x'&repeat("+",w-1)&'x'," ")&"\n",
vt = "|"&repeat(' ',w*3-1)&"|\n"
grid = split(tb&"\n"&join(repeat(vt,h),hz)&tb,'\n')
-- set size (for mirroring) and target info:
gh = length(grid) gw = length(grid[1])
ty1 = h+even(h) ty2 = ty1+odd(h)*2
tx1 = floor(w/2)*3+1 tx2 = tx1+odd(w)*3
end procedure
function side(integer w, h)
make_grid(w,h)
-- search top to mid-point
integer count = 0, last = 0
for r=3 to h+1 by 2 do
last = search(r,1,RIGHT,0) -- left to right
count += 2*last
end for
if even(h) then
count -= last -- (un-double the centre line)
end if
return count
end function
--atom t0 = time()
-- nb sub-optimal: obviously "grid" was designed for easy display, rather than speed.
for y=1 to iff(platform()=JS?7:9) do -- 24s
--for y=1 to 10 do -- (gave up on >10x8)
for x=1 to y do
-- for x=1 to min(y,8) do -- 4 mins 16s (with y to 10)
if even(x*y) then
integer count = side(x,y)
if x=y then
count *= 2
else
count += side(y,x)
end if
printf(1,"%d x %d: %d\n", {y, x, count})
end if
end for
end for
--?elapsed(time()-t0)
|
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 * 60 + P.utcTimeToPOSIXSeconds t1 |
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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" ' Club,Diamond,Heart,Spades
card$ = "A,2,3,4,5,6,7,8,9,T,J,Q,K" ' Cards Ace to King
dim n(55) ' make ordered deck
for i = 1 to 52 ' of 52 cards
n(i) = i
next i
for i = 1 to 52 * 3 ' shuffle deck 3 times
i1 = int(rnd(1)*52) + 1
i2 = int(rnd(1)*52) + 1
h2 = n(i1)
n(i1) = n(i2)
n(i2) = h2
next i
for yy = 1 to 8 ' display 7 across and 8 down
for xx = 1 to 7
card = card + 1
s = (n(card) mod 4) + 1 ' determine suite
c = (n(card) mod 13) + 1 ' determine card
cardId$ = word$(card$,c,",");word$(suite$,s,",");".gif"
html "<div style='position: relative; left:";(xx -1) * 80;"px; top:";(yy -1) * 20;"px; height:0px; width:0px;>"
html "<div style='width:100px; height:100px; border:solid 0px #000;'>"
html "<img src=";imagePath$;cardId$;" width=70px >"
html "</div></div>"
if card = 52 then end ' out of cards
next xx
next yy |
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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 modulo bias). If an exact match of the old dealer is not needed,
// `rand::Rng::shuffle` should be used.
fn shuffle<T>(rng: &mut MsLcg, deck: &mut [T]) {
let len = deck.len() as u32;
for i in (1..len).rev() {
let j = rng.next_u32() % (i + 1);
deck.swap(i as usize, j as usize);
}
}
fn gen_deck() -> Vec<String> {
const RANKS: [char; 13] = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'];
const SUITS: [char; 4] = ['C', 'D', 'H', 'S'];
let render_card = |card: usize| {
let (suit, rank) = (card % 4, card / 4);
format!("{}{}", RANKS[rank], SUITS[suit])
};
(0..52).map(render_card).collect()
}
fn deal_ms_fc_board(seed: u32) -> Vec<String> {
let mut rng = MsLcg::from_seed(seed);
let mut deck = gen_deck();
shuffle(&mut rng, &mut deck);
deck.reverse();
deck.chunks(8).map(|row| row.join(" ")).collect::<Vec<_>>()
}
fn main() {
let seed = std::env::args()
.nth(1)
.and_then(|n| n.parse().ok())
.expect("A 32-bit seed is required");
for row in deal_ms_fc_board(seed) {
println!(": {}", row);
}
}
|
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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,25)) % 7; //0=Sunday
SELF.Year := (BaseYear-1) + Ctr;
END;
YearDS := DATASET(EndYear-BaseYear,FindDate(COUNTER));
OUTPUT(YearDS(DayofWeek=0),{Year});
/* Outputs:
2011
2016
2022
2033
2039
2044
2050
2061
2067
2072
2078
2089
2095
2101
2107
2112
2118
*/
|
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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 American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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";"594918104";"68389X103";"68389X105"]|>List.iter(fun n->printfn "CUSIP %s is %s" n (if cD n then "valid" else "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 language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 := 14; r_d := 6; % set output to fixed point format %
for i := 2,4,4,4,5,5,7,9
do begin
long real val;
val := i;
write(val, sd(val))
end for_i
end. |
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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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 numbers:");
let cullen: Vec<String> = (1..21).map(|x| cullen_number(x).to_string()).collect();
println!("{}", cullen.join(" "));
println!("\nFirst 20 Woodall numbers:");
let woodall: Vec<String> = (1..21).map(|x| woodall_number(x).to_string()).collect();
println!("{}", woodall.join(" "));
println!("\nFirst 5 Cullen primes in terms of n:");
let cullen_primes: Vec<String> = (1..)
.filter_map(|x| match cullen_number(x).is_probably_prime(25) {
IsPrime::No => None,
_ => Some(x.to_string()),
})
.take(5)
.collect();
println!("{}", cullen_primes.join(" "));
println!("\nFirst 12 Woodall primes in terms of n:");
let woodall_primes: Vec<String> = (1..)
.filter_map(|x| match woodall_number(x).is_probably_prime(25) {
IsPrime::No => None,
_ => Some(x.to_string()),
})
.take(12)
.collect();
println!("{}", woodall_primes.join(" "));
} |
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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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 Woodall primes: (in terms of n)"
say 12.by { woodall(_).is_prime }.join(' ') |
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 changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #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; 0; 1; 7|];
[|9; 4; 3; 8; 6; 1; 7; 2; 0; 5|];
[|2; 5; 8; 1; 4; 3; 6; 7; 9; 0|];
|]
let damm str =
let rec helper (v:string) interim =
if v.Length = 0 then 0 = interim
else helper (v.Substring(1)) (TABLE.[interim].[(int (v.[0])) - (int '0')])
helper str 0
[<EntryPoint>]
let main _ =
let numbers = [|5724; 5727; 112946; 112949|]
for number in numbers do
let isValid = damm (number.ToString())
if isValid then
printfn "%6d is valid" number
else
printfn "%6d is invalid" number
0 // return an integer exit code
|
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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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 };
IList<CartItem> cart = new List<CartItem>();
cart.Add(new CartItem() { item = hamburger, quantity = 4000000000000000 });
cart.Add(new CartItem() { item = milkshake, quantity = 2 });
decimal total = CalculateTotal(cart);
Console.WriteLine(string.Format("Total before tax: {0:C}", total));
// Add Tax
decimal tax = total * 0.0765M;
Console.WriteLine(string.Format("Tax: {0:C}", tax));
total += tax;
Console.WriteLine(string.Format("Total with tax: {0:C}", total));
}
private static decimal CalculateTotal(IList<CartItem> cart)
{
decimal total = 0M;
foreach (CartItem item in cart)
{
total += item.quantity * item.item.Price;
}
return total;
}
private struct MenuItem
{
public string Name { get; set; }
public decimal Price { get; set; }
}
private struct CartItem
{
public MenuItem item { get; set; }
public decimal quantity { get; set; }
}
}
} |
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 language.
Add any historic details as to how the feature made its way into the language.
| #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 language.
Add any historic details as to how the feature made its way into the language.
| #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} ->
erlang:error(badarg);
{arity,ArityFun} ->
create_ano_fun(ArityFun,Fun,Arg);
_ ->
erlang:error(badarg)
end.
create_ano_fun(Arity,Fun,Arg) ->
Pars =
[{var,1,list_to_atom(lists:flatten(io_lib:format("X~p", [N])))}
|| N <- lists:seq(2,Arity)],
Ano =
{'fun',1,
{clauses,[{clause,1,Pars,[],
[{call,1,{var,1,'Fun'},[{var,1,'Arg'}] ++ Pars}]}]}},
{_,Result,_} = erl_eval:expr(Ano, [{'Arg',Arg},{'Fun',Fun}]),
Result.
% Generalization of the currying
curry_gen(Fun,GivenArgs,PosGivenArgs,PosParArgs) ->
Pos = PosGivenArgs ++ PosParArgs,
case erlang:fun_info(Fun,arity) of
{arity,ArityFun} ->
case ((length(GivenArgs) + length(PosParArgs)) == ArityFun) and
(length(GivenArgs) == length(PosGivenArgs)) and
(length(Pos) == sets:size(sets:from_list(Pos))) of
true ->
fun(ParArgs) ->
case length(ParArgs) == length(PosParArgs) of
true ->
Given = lists:zip(PosGivenArgs,GivenArgs),
Pars = lists:zip(PosParArgs,ParArgs),
{_,Args} = lists:unzip(lists:sort(Given ++ Pars)),
erlang:apply(Fun,Args);
false ->
erlang:error(badarg)
end
end;
false ->
erlang:error(badarg)
end;
_ ->
erlang:error(badarg)
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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*)address+2) = 0xff;
*((char*)address+3) = 0xff; // if sizeof(int) == 4!
// which maybe is not the best way of writing 32 bit values...
printf("%p: %08x (=%08x)\n", address, *address, intspace);
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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");
std::cout << *stringPtr << " 0x" << stringPtr << std::endl;
// use placement new to construct a new string object in the same memory location
// remember to manually call destructor
stringPtr->~basic_string();
stringPtr = new (data) std::string("123456");
std::cout << *stringPtr << " 0x" << stringPtr << std::endl;
// clean up
stringPtr->~basic_string();
delete[] data;
} |
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 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #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 factor decomposition.
Factors = Table[int, int]
####################################################################################################
# Miscellaneous.
## Parity tests.
template isOdd(n: int): bool = (n and 1) != 0
template isEven(n: int): bool = (n and 1) == 0
#---------------------------------------------------------------------------------------------------
proc sort(poly: var Polynomial) {.inline.} =
## Sort procedure for the terms of a polynomial (high degree first).
algorithm.sort(poly, proc(x, y: Term): int = cmp(x.exp, y.exp), Descending)
####################################################################################################
# Superscripts.
const Superscripts: array['0'..'9', string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]
func superscript(n: Natural): string =
## Return the Unicode string to use to represent an exponent.
if n == 1:
return ""
for d in $n:
result.add(Superscripts[d])
####################################################################################################
# Term operations.
func term(coeff, exp: int): Term =
## Create a term.
if exp < 0:
raise newException(ValueError, "term exponent cannot be negative")
(coeff, Natural exp)
#---------------------------------------------------------------------------------------------------
func `*`(a, b: Term): Term =
## Multiply two terms.
(a.coeff * b.coeff, Natural a.exp + b.exp)
#---------------------------------------------------------------------------------------------------
func `+`(a, b: Term): Term =
## Add two terms.
if a.exp != b.exp:
raise newException(ValueError, "addition of terms with unequal exponents")
(a.coeff + b.coeff, a.exp)
#---------------------------------------------------------------------------------------------------
func `-`(a: Term): Term =
## Return the opposite of a term.
(-a.coeff, a.exp)
#---------------------------------------------------------------------------------------------------
func `$`(a: Term): string =
## Return the string representation of a term.
if a.coeff == 0: "0"
elif a.exp == 0: $a.coeff
elif a.coeff == 1: 'x' & superscript(a.exp)
elif a.coeff == -1: "-x" & superscript(a.exp)
else: $a.coeff & 'x' & superscript(a.exp)
####################################################################################################
# Polynomial.
func polynomial(terms: varargs[Term]): Polynomial =
## Create a polynomial described by its terms.
for t in terms:
if t.coeff != 0:
result.add(t)
if result.len == 0:
return @[term(0, 0)]
sort(result)
#---------------------------------------------------------------------------------------------------
func hasCoeffAbs(poly: Polynomial; coeff: int): bool =
## Return true if the polynomial contains a given coefficient.
for t in poly:
if abs(t.coeff) == coeff:
return true
#---------------------------------------------------------------------------------------------------
func leadingCoeff(poly: Polynomial): int {.inline.} =
## Return the coefficient of the term with the highest degree.
poly[0].coeff
#---------------------------------------------------------------------------------------------------
func degree(poly: Polynomial): int {.inline.} =
## Return the degree of the polynomial.
if poly.len == 0: -1
else: poly[0].exp
#---------------------------------------------------------------------------------------------------
func `+`(poly: Polynomial; someTerm: Term): Polynomial =
## Add a term to a polynomial.
var added = false
for currTerm in poly:
if currterm.exp == someTerm.exp:
added = true
if currTerm.coeff + someTerm.coeff != 0:
result.add(currTerm + someTerm)
else:
result.add(currTerm)
if not added:
result.add(someTerm)
#---------------------------------------------------------------------------------------------------
func `+`(a, b: Polynomial): Polynomial =
## Add two polynomials.
var aIndex = a.high
var bIndex = b.high
while aIndex >= 0 or bIndex >= 0:
if aIndex < 0:
result &= b[bIndex]
dec bIndex
elif bIndex < 0:
result &= a[aIndex]
dec aIndex
else:
let t1 = a[aIndex]
let t2 = b[bIndex]
if t1.exp == t2.exp:
let t3 = t1 + t2
if t3.coeff != 0:
result.add(t3)
dec aIndex
dec bIndex
elif t1.exp < t2.exp:
result.add(t1)
dec aIndex
else:
result.add(t2)
dec bIndex
sort(result)
#---------------------------------------------------------------------------------------------------
func `*`(poly: Polynomial; someTerm: Term): Polynomial =
## Multiply a polynomial by a term.
for currTerm in poly:
result.add(currTerm * someTerm)
#---------------------------------------------------------------------------------------------------
func `/`(a, b: Polynomial): Polynomial =
## Divide a polynomial by another polynomial.
var a = a
let lcb = b.leadingCoeff
let db = b.degree
while a.degree >= b.degree:
let lca = a.leadingCoeff
let s = lca div lcb
let t = term(s, a.degree - db)
result = result + t
a = a + b * -t
#---------------------------------------------------------------------------------------------------
func `$`(poly: Polynomial): string =
## Return the string representation of a polynomial.
for t in poly:
if result.len == 0:
result.add($t)
else:
if t.coeff > 0:
result.add('+')
result.add($t)
else:
result.add('-')
result.add($(-t))
####################################################################################################
# Cyclotomic polynomial.
var
# Cache of list of factors.
factorCache: Table[int, Factors] = {2: {2: 1}.toTable}.toTable
# Cache of cyclotomic polynomials. Initialized with 1 -> x - 1.
polyCache: Table[int, Polynomial] = {1: polynomial(term(1, 1), term(-1, 0))}.toTable
#---------------------------------------------------------------------------------------------------
proc getFactors(n: int): Factors =
## Return the list of factors of a number.
if n in factorCache:
return factorCache[n]
if n.isEven:
result = getFactors(n div 2)
result[2] = result.getOrDefault(2) + 1
factorCache[n] = result
return
var i = 3
while i * i <= n:
if n mod i == 0:
result = getFactors( n div i)
result[i] = result.getOrDefault(i) + 1
factorCache[n] = result
return
inc i, 2
result[n] = 1
factorCache[n] = result
#---------------------------------------------------------------------------------------------------
proc cycloPoly(n: int): Polynomial =
## Find the nth cyclotomic polynomial.
if n in polyCache:
return polyCache[n]
let factors = getFactors(n)
if n in factors:
# n is prime.
for i in countdown(n - 1, 0): # Add the terms by decreasing degrees.
result.add(term(1, i))
elif factors.len == 2 and factors.getOrDefault(2) == 1 and factors.getOrDefault(n div 2) == 1:
# n = 2 x prime.
let prime = n div 2
var coeff = -1
for i in countdown(prime - 1, 0): # Add the terms by decreasing degrees.
coeff *= -1
result.add(term(coeff, i))
elif factors.len == 1 and 2 in factors:
# n = 2 ^ h.
let h = factors[2]
result.add([term(1, 1 shl (h - 1)), term(1, 0)])
elif factors.len == 1 and n notin factors:
# n = prime ^ k.
var p, k = 0
for prime, v in factors.pairs:
if prime > p:
p = prime
k = v
for i in countdown(p - 1, 0): # Add the terms by decreasing degrees.
result.add(term(1, i * p^(k-1)))
elif factors.len == 2 and 2 in factors:
# n = 2 ^ h x prime ^ k.
var p, k = 0
for prime, v in factors.pairs:
if prime != 2 and prime > p:
p = prime
k = v
var coeff = -1
let twoExp = 1 shl (factors[2] - 1)
for i in countdown(p - 1, 0): # Add the terms by decreasing degrees.
coeff *= -1
result.add(term(coeff, i * twoExp * p^(k-1)))
elif 2 in factors and isOdd(n div 2) and n div 2 > 1:
# CP(2m)[x] = CP(-m)[x], n odd integer > 1.
let cycloDiv2 = cycloPoly(n div 2)
for t in cycloDiv2:
result.add(if t.exp.isEven: t else: -t)
else:
# Let p, q be primes such that p does not divide n, and q divides n.
# Then CP(np)[x] = CP(n)[x^p] / CP(n)[x].
var m = 1
var cyclo = cycloPoly(m)
let primes = sorted(toSeq(factors.keys))
for prime in primes:
# Compute CP(m)[x^p].
var terms: Polynomial
for t in cyclo:
terms.add(term(t.coeff, t.exp * prime))
cyclo = terms / cyclo
m *= prime
# Now, m is the largest square free divisor of n.
let s = n div m
# Compute CP(n)[x] = CP(m)[x^s].
for t in cyclo:
result.add(term(t.coeff, t.exp * s))
polyCache[n] = result
#———————————————————————————————————————————————————————————————————————————————————————————————————
echo "Cyclotomic polynomials for n ⩽ 30:"
for i in 1..30:
echo &"Φ{'(' & $i & ')':4} = {cycloPoly(i)}"
echo ""
echo "Smallest cyclotomic polynomial with n or -n as a coefficient:"
var n = 0
for i in 1..10:
while true:
inc n
if cycloPoly(n).hasCoeffAbs(i):
echo &"Φ{'(' & $n & ')':7} has coefficient with magnitude = {i}"
dec n
break |
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 are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #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 x == w:
return count + 1
t = y * (w + 1) + x
grid[t] = grid[blen - t] = True
if not grid[t + next[0]]:
count = walk(y + dirs[0][0], x + dirs[0][1], count)
if not grid[t + next[1]]:
count = walk(y + dirs[1][0], x + dirs[1][1], count)
if not grid[t + next[2]]:
count = walk(y + dirs[2][0], x + dirs[2][1], count)
if not grid[t + next[3]]:
count = walk(y + dirs[3][0], x + dirs[3][1], count)
grid[t] = grid[blen - t] = False
return count
t = h // 2 * (w + 1) + w // 2
if w % 2:
grid[t] = grid[t + 1] = True
count = walk(h // 2, w // 2 - 1, count)
res = count
count = 0
count = walk(h // 2 - 1, w // 2, count)
return res + count * 2
else:
grid[t] = True
count = walk(h // 2, w // 2 - 1, count)
if h == w:
return count * 2
count = walk(h // 2 - 1, w // 2, count)
return count
def main():
for w in xrange(1, 10):
for h in xrange(1, w + 1):
if not((w * h) % 2):
print "%d x %d: %d" % (w, h, cut_it(w, h))
main() |
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
hour = hour + 12*(am_pm == 'p')
TIME(MOnth=month, Day=day, Year=year, Hour=hour, MInute=minute, TO, Excel=xls_day)
WRITE(Text=result, Format="UWWW CCYY-MM-DD HH:mm") xls_day + 0.5
! result = "Sun 2009-03-08 07:30"
END
|
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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 * seed + 2531011) & Integer.MAX_VALUE
seed >> 16
}
private def getShuffledDeck = {
val d = deck.map(c => c)
for(i <- deck.length - 1 until 0 by -1) {
val r = random() % (i + 1)
val card = d(r)
d(r) = d(i)
d(i) = card
}
d.reverse
}
def deal(seed: Int): Unit = {
this.seed = seed
getShuffledDeck.grouped(8).foreach(e => println(e.mkString(" ")))
}
deal(1)
println
deal(617)
} |
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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 American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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 ;
: cusip? ( seq -- ? )
{
[ R/ [0-9A-Z*@#]+/ matches? ]
[ [ last digit> ] [ cusip-check-digit ] bi = ]
} 1&& ;
qw{ 037833100 17275R102 38259P508 594918104 68389X106 68389X105 }
[ dup cusip? "correct" "incorrect" ? "%s -> %s\n" printf ] each |
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 American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#")
INTEGER I,V,S !Assistants.
S = 0 !Start the checksum.
DO I = 1,LEN(TEXT) !Step through the text.
V = INDEX(VALID,TEXT(I:I)) - 1 !Since counting starts with one.
IF (MOD(I,2).EQ.0) V = V*2 !V = V*(2 - MOD(I,2))?
S = S + V/10 + MOD(V,10) !Specified calculation.
END DO !On to the next character.
I = MOD(10 - MOD(S,10),10) + 1 !Again, counting starts with one.
CUSIPCHECK = VALID(I:I) !Thanks to the MOD 10, surely a digit.
END FUNCTION CUSIPCHECK !No checking for invalid input...
PROGRAM POKE !Just to try it out.
INTEGER I,N !Assistants.
PARAMETER (N = 6) !A whole lot of blather
CHARACTER*9 CUSIP(N) !Just to have an array of test codes.
DATA CUSIP/ !Here they are, as specified.
1 "037833100",
2 "17275R102",
3 "38259P508",
4 "594918104",
5 "68389X106",
6 "68389X105"/
CHARACTER*1 CUSIPCHECK !Needed as no use of the MODULE protocol.
DO I = 1,N !"More than two? Use a DO..."
WRITE (6,*) CUSIP(I),CUSIPCHECK(CUSIP(I)(1:8)).EQ.CUSIP(I)(9:9)
END DO
END |
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 language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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 of a) + (n ^ 2)
set stages to (stages of a) & ¬
((squaresSum / i) - ((sum / i) ^ 2)) ^ 0.5
{sum:(sum of a) + n, squaresSum:squaresSum, stages:stages}
end stdDevInc
--------------------------- TEST -------------------------
on run
set xs to [2, 4, 4, 4, 5, 5, 7, 9]
stages of foldl(stdDevInc, ¬
{sum:0, squaresSum:0, stages:[]}, xs)
--> {0.0, 1.0, 0.942809041582, 0.866025403784, 0.979795897113, 1.0, 1.399708424448, 2.0}
end run
-------------------- GENERIC FUNCTIONS -------------------
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn |
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 daylight-p zone) (get-decoded-time)
(format t "~4d-~2,'0d-~2,'0d~%" year month date)
(format t "~a, ~a ~d, ~4d~%"
(aref *day-names* day) (aref *month-names* month) date year)) |
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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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
num = n * (2 ** n) - 1;
$write(num, " ");
end
$finish ;
end
endmodule |
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 or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #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) System.write("%(woodall.call(n)) ")
System.print("\n\nFirst 2 Cullen primes (in terms of n):")
var count = 0
var n = 1
while (count < 2) {
var cn = cullen.call(n)
if (cn.isProbablePrime(5)){
System.write("%(n) ")
count = count + 1
}
n = n + 1
}
System.print("\n\nFirst 12 Woodall primes (in terms of n):")
count = 0
n = 1
while (count < 12) {
var wn = woodall.call(n)
if (wn.isProbablePrime(5)){
System.write("%(n) ")
count = count + 1
}
n = n + 1
}
System.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 changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #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 times, this returns the i'th item (if any)
private
type Row(Length: Natural) is tagged record
Str: String(1 .. Length);
Fst: Positive;
Lst: Natural;
Nxt: Positive;
Sep: Character;
end record;
end CSV; |
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 7 2 0 5 }
{ 2 5 8 1 4 3 6 7 9 0 }
}
: damm? ( str -- ? )
0 [ digit> swap table nth nth ] reduce zero? ;
qw{ 5724 5727 112946 112949 }
[ dup damm? "" "in" ? [I ${} is ${}validI] nl ] each |
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 ." yes" else ." no" then ;
: .damm
2dup damm
rot rot type 48 + emit
; |
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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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 milkshakes)
tax (ma/multiply pre-tax 0.0765 :up)]
(println "Total before tax: " (mf/format pre-tax))
(println " Tax: " (mf/format tax))
(println " Total with tax: " (mf/format (ma/plus pre-tax tax)))) |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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 PIC 9(18) VALUE 2.
01 tax PIC 9(18)V99.
01 tax-edited PIC $(17)9.99.
01 Tax-Rate CONSTANT 7.65.
01 total PIC 9(18)V99.
01 total-edited PIC $(17)9.99.
PROCEDURE DIVISION.
COMPUTE total rounded, total-edited rounded =
num-burgers * Burger-Price + num-milkshakes * Milkshake-Price
DISPLAY "Total before tax: " total-edited
COMPUTE tax rounded, tax-edited rounded = total * (Tax-Rate / 100)
DISPLAY " Tax: " tax-edited
ADD tax TO total GIVING total-edited rounded
DISPLAY " Total with tax: " total-edited
.
END PROGRAM currency-example. |
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 language.
Add any historic details as to how the feature made its way into the language.
| #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 language.
Add any historic details as to how the feature made its way into the language.
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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.
DISPLAY val OF int-space END-DISPLAY
SET point TO ADDRESS OF int-space
DISPLAY point END-DISPLAY
SET ADDRESS OF addr TO point
DISPLAY val OF addr END-DISPLAY
MOVE 65535 TO val OF addr
DISPLAY val OF addr END-DISPLAY
DISPLAY val OF int-space END-DISPLAY
STOP RUN.
END PROGRAM object-address-test.
|
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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*) adrSpace ;
// xPtr now point to arr, as a struct X
writefln("arr(as X)'s msg = '%s' (len %d) @ 0x%08x",
xPtr.msg, xPtr.msg.length, xPtr) ;
iPtr = cast(int*) (adrSpace + 1 * 4 /*bytes*/) ;
fPtr = cast(float*) iPtr ;
// pointers now point to arr[1]
writefln("arr[1] = 0x%8x (%9.4f) @ 0x%08X", *iPtr, *fPtr, iPtr) ;
iPtr = cast(int*) (adrSpace + 3 * 4 /*bytes*/) ;
fPtr = cast(float*) iPtr ;
// pointers now point to arr[3]
writefln("arr[3] = 0x%8x (%9.4f) @ 0x%08X", *iPtr, *fPtr, iPtr) ;
*fPtr = 0.5f ; // change value
writefln("arr[3] = 0x%8x (%9.4f) @ 0x%08X", *iPtr, *fPtr, iPtr) ;
} |
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 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #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 are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #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) (vector-set! B (fP p) (fD d)))
(define center (/ (fP 0) 2))
(when (integer? center) (Bset! center #t))
(define (run c* d)
(define p (- center c*))
(Bset! p d)
(let loop ([p p])
(define-values [q r] (quotient/remainder p W1))
(if (and (< 0 r W) (< 0 q H))
(for ([d '(U D L R)])
(define n (+ p (case d [(U) (- W1)] [(D) W1] [(L) -1] [(R) 1])))
(unless (vector-ref B n) (Bset! n (fD d)) (loop n) (Bset! n #f)))
(if count (set! count (add1 count)) (visualize B W H))))
(Bset! p #f))
(when (even? W) (run (if (odd? H) (/ W1 2) W1) 'D))
(when (even? H) (run (if (odd? W) 1/2 1) 'R))
(or count (void)))
(define (visualize B W H)
(define W2 (+ 2 (* W 2))) (define H2 (+ 1 (* H 2)))
(define str (make-string (* H2 W2) #\space))
(define (Sset! i c) (string-set! str i c))
(for ([i (in-range (- W2 1) (* W2 H2) W2)]) (Sset! i #\newline))
(for ([i (in-range 0 (- W2 1))]) (Sset! i #\#) (Sset! (+ i (* W2 H 2)) #\#))
(for ([i (in-range 0 (* W2 H2) W2)]) (Sset! i #\#) (Sset! (+ i W2 -2) #\#))
(for* ([i (add1 W)] [j (add1 H)])
(define p (* 2 (+ i (* j W2))))
(define b (vector-ref B (+ i (* j (+ W 1)))))
(cond [b (Sset! p #\#)
(define d (case b [(U) (- W2)] [(D) W2] [(R) 1] [(L) -1]))
(when (integer? d) (Sset! (+ p d) #\#))]
[(equal? #\space (string-ref str p)) (Sset! p #\.)]))
(display str) (newline))
(printf "Counts:\n")
(for* ([W (in-range 1 10)] [H (in-range 1 (add1 W))]
#:unless (and (odd? W) (odd? H)))
(printf "~s x ~s: ~s\n" W H (cuts W H)))
(newline)
(cuts 4 3 #f)
|
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 dateline + time zone given seconds
return NormalizedDate(SecToDateLine(s+\(_TZdata("table")[\tz|"UTC"]))||" "|| tz)
end
procedure TZDateLineToSec(s) #: returns seconds given dateline (and time zone)
return (
NormalizedDate(s) ? (
d := tab(find("am"|"pm")+2),tab(many('\t ,')),
tz := \_TZdata("table")[tab(0)]
),
DateLineToSec(d) - tz)
end
procedure NormalizedDate(s) #: returns a consistent dateline
static D,M
initial {
D := ["Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"]
M := ["January","February","March","April","May","June",
"July","August","September","October","November","December"]
}
map(s) ? { # parse and build consistent dateline
ds := 1(x := !D, =map(x)) | "" # Weekday
ds ||:= 1(", ", tab(many('\t ,')|&pos))
ds ||:= 1(x := !M, =map(x)) | fail # Month
ds ||:= 1(" ", tab(many('\t ,')|&pos))
ds ||:= tab(many(&digits)) | fail # day
ds ||:= 1(", ", tab(many('\t ,'))) | fail
ds ||:= tab(many(&digits)) | fail # year
ds ||:= 1(" ", tab(many('\t ,'))) | fail
ds ||:= tab(many(&digits))||(=":"||tab(many(&digits))|&null) | fail # time
ds ||:= 1(" ", tab(many('\t ,')|&pos))
ds ||:= =("am"|"pm") | fail # halfday
ds ||:= 1(" ", tab(many('\t ,')|&pos))
tz := map(=!_TZdata("list"),&lcase,&ucase)
}
if ds[1] == "," then
ds := SecToDateLine(DateLineToSec("Sunday"||ds)) # get IPL to fix weekday
return ds ||:= " " || \tz|"UTC"
end
procedure _TZdata(x) #: internal return TZ data (demo version incomplete)
static TZ,AZ
initial {
TZ := table()
AZ := []
"UTC/0;ACDT/+10.5;CET/1;EST/-5;NPT/+5.75;NST/-3.5;PST/-8;" ?
while ( a := tab(find("/")), move(1), o := tab(find(";")), move(1) ) do {
TZ[map(a)] := TZ[a] := integer(3600*o)
put(AZ,a,map(a))
}
every TZ[&null|""] := TZ["UTC"]
}
return case x of { "list" : AZ ; "table" : TZ }
end |
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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 := randomSeed >> 16;
end func;
const proc: show (in array integer: cards) is func
local
var integer: index is 0;
begin
for index range 1 to 52 do
write(" " <& suits[succ(cards[index] rem 4)] <& nums[succ(cards[index] div 4)]);
if index rem 8 = 0 or index = 52 then
writeln;
end if;
end for;
end func;
const func array integer: deal (in integer: gameNum) is func
result
var array integer: cards is 52 times 0;
local
var integer: i is 0;
var integer: j is 0;
var integer: s is 0;
begin
randomSeed := gameNum;
for i range 1 to 52 do
cards[i] := 52 - i;
end for;
for i range 1 to 51 do
j := 52 - random mod (53 - i);
s := cards[i];
cards[i] := cards[j];
cards[j] := s;
end for;
end func;
const proc: main is func
local
var integer: gameNum is 11982;
var array integer: cards is 0 times 0;
begin
OUT := STD_CONSOLE;
if length(argv(PROGRAM)) >= 1 then
block
gameNum := integer parse (argv(PROGRAM)[1]);
exception
catch RANGE_ERROR: noop;
end block;
end if;
cards := deal(gameNum);
writeln("Hand " <& gameNum);
show(cards);
end func; |
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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, ten, jack, queen, king
var description: String {
let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"]
return d[self] ?? String(self.rawValue)
}
}
struct Card : CustomStringConvertible {
let rank : Rank, suit : Suit
var description : String {
return String(describing:self.rank) + String(describing:self.suit)
}
init(rank:Rank, suit:Suit) {
self.rank = rank; self.suit = suit
}
init(sequence n:Int) {
self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4])
}
}
struct Deck : CustomStringConvertible {
var cards = [Card]()
init(seed:Int) {
for i in (0..<52).reversed() {
self.cards.append(Card(sequence:i))
}
struct MicrosoftLinearCongruentialGenerator {
var seed : Int
mutating func next() -> Int {
self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1)
return self.seed >> 16
}
}
var r = MicrosoftLinearCongruentialGenerator(seed: seed)
for i in 0..<51 {
self.cards.swapAt(i, 51-r.next()%(52-i))
}
}
var description : String {
var s = ""
for (ix,c) in self.cards.enumerated() {
s.write(String(describing:c))
s.write(ix % 8 == 7 ? "\n" : " ")
}
return s
}
}
let d1 = Deck(seed: 1)
print(d1)
let d617 = Deck(seed: 617)
print(d617)
|
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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 ) -> true;
is_sunday( _ ) -> false. |
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 American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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]
Select Case x
Case Asc("0") To Asc("9")
v = x - Asc("0")
Case Asc("A") To Asc("Z")
v = x - Asc("A") + 1 + 9
Case Asc("*")
v= 36
Case Asc("@")
v = 37
Case Asc("#")
v = 38
Case Else
Print " found a invalid character, invalid cusip"
return
End Select
If (i And 1) = 0 Then v = v * 2
sum = sum + v \ 10 + v Mod 10
Next
sum = (10 - (sum Mod 10)) Mod 10
If sum = (input_str[8] - Asc("0")) Then
Print " is valid"
Else
Print " is invalid"
End If
End Sub
' ------=< MAIN >=------
Data "037833100", "17275R102", "38259P508"
Data "594918104", "68389X106", "68389X105"
Dim As String input_str
Print
For i As Integer = 1 To 6
Read input_str
cusip(input_str)
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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 language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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,Dates.long,resp);
StdLog.String(":> " + resp);StdLog.Ln;
Dates.DateToString(d,Dates.plainAbbreviated,resp);
StdLog.String(":> " + resp);StdLog.Ln;
Dates.DateToString(d,Dates.plainLong,resp);
StdLog.String(":> " + resp);StdLog.Ln;
END Do;
END DateFormat.
|
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 changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #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;
text s;
sum = 0;
for (j, s in l) {
sum += atoi(s);
}
l_append(c, sum);
}
}
return c;
}
void
add_column(list t, list c)
{
integer i;
list l;
for (i, l in t) {
l_append(l, c[i]);
}
}
void
write_csv(list t, text path)
{
integer i;
file f;
list l;
f_create(f, path, 00644);
for (i, l in t) {
f_(f, l[0]);
l_ocall(l, f_, 2, 1, -1, f, ",");
f_newline(f);
}
}
integer
main(void)
{
list t;
read_csv(t, "tmp/CSV_data_manipulation.csv");
add_column(t, sum_columns(t));
write_csv(t, "tmp/CSV_data_manipulated.csv");
return 0;
} |
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 changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #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 strlen := UPB str, cnt := 0;
INT len, p;
INT start := 1;
[char count (sep, str) + 1] STRING list;
WHILE start <= strlen ANDF char in string (sep, p, str[start:]) DO
p +:= start - 1;
list[cnt +:= 1] := str[start:p-1];
start := p + 1
OD;
IF cnt = 0 THEN list[cnt +:= 1] := str
ELIF start <= UPB str + 1 THEN list[cnt +:= 1] := str[start:]
FI;
list
END;
PROC join = ([]STRING words, STRING sep) STRING:
IF UPB words > 0 THEN
STRING str := words [1];
FOR i FROM 2 TO UPB words DO
str +:= sep + words[i]
OD;
str
ELSE
""
FI;
# read a line from file #
PROC readline = (REF FILE f) STRING:
BEGIN
STRING line;
get (f, line); new line (f);
line
END;
# Add one item to tuple #
OP +:= = (REF FLEX[]STRING tuple, STRING item) VOID:
BEGIN
[UPB tuple+1]STRING new;
new[:UPB tuple] := tuple;
new[UPB new] := item;
tuple := new
END;
# convert signed number TO INT #
OP TOINT = (STRING str) INT:
BEGIN
INT n := 0, sign := 1;
FOR i TO UPB str WHILE sign /= 0 DO
IF is digit (str[i]) THEN n := n * 10 + ABS str[i] - ABS "0"
ELIF i = 1 AND str[i] = "-" THEN sign := -1
ELIF i /= 1 OR str[i] /= "+" THEN sign := 0
FI
OD;
n * sign
END;
OP STR = (INT i) STRING: whole (i,0);
# The main program #
FILE foo;
open (foo, "CSV_data_manipulation.data", stand in channel);
FLEX[0]STRING header := char split (readline (foo), ",");
header +:= "SUM";
print ((join (header, ","), new line));
WHILE NOT end of file (foo) DO
FLEX[0]STRING fields := char split (readline (foo), ",");
INT sum := 0;
FOR i TO UPB fields DO
sum +:= TOINT fields[i]
OD;
fields +:= STR sum;
print ((join (fields, ","), new line))
OD;
close (foo) |
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 = (/ !A set of constants...
o 0, 3, 1, 7, 5, 9, 8, 6, 4, 2, ! CAREFUL!
1 7, 0, 9, 2, 1, 5, 4, 8, 6, 3, !Fortran stores arrays in column-major order.
2 4, 2, 0, 6, 8, 7, 1, 3, 5, 9, !Despite the manifest row and column layout apparent here
3 1, 7, 5, 0, 9, 8, 3, 4, 2, 6, !This sequence of consecutive items will go into storage order.
4 6, 1, 2, 3, 0, 4, 5, 9, 7, 8, !The table resulting from this sequence of constants
5 3, 6, 7, 4, 2, 0, 9, 5, 8, 1, !Will appear to be transposed if referenced as (row,column)
6 5, 8, 6, 9, 7, 2, 0, 1, 3, 4, !What appears to be row=6 column=1 (counting from zero)
7 8, 9, 4, 5, 3, 6, 2, 0, 1, 7, !is to be accessed as OPTABLE(1,6) = 8, not OPTABLE(6,1)
8 9, 4, 3, 8, 6, 1, 7, 2, 0, 5, !Storage order is (0,0), (1,0), (2,0), ... (9,0)
9 2, 5, 8, 1, 4, 3, 6, 7, 9, 0/)) !Followed by (0,1), (1,1), (2,1), ... (9,1)
INTEGER I,D,ID !Assistants.
ID = 0 !Here we go.
DO I = 1,LEN(DIGIT) !Step through the text.
D = ICHAR(DIGIT(I:I)) - ICHAR("0") !Convert to an integer. (ASCII or EBCDIC)
IF (D.LT.0 .OR. D.GT.9) STOP "DAMM! Not a digit!" !This shouldn't happen!
ID = OPTABLE(D,ID) !Transposed: D is the column index and ID the row.
END DO !On to the next.
DAMM = ID .EQ. 0 !Somewhere, a check digit should ensure this.
END FUNCTION DAMM !Simple, fast, and alas, rarely used.
LOGICAL DAMM !Not a default type.
WRITE (6,*) DAMM("5724"),"5724"
WRITE (6,*) DAMM("5727"),"5727"
WRITE (6,*) DAMM("112946"),"112946"
END |
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 quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #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): TDc;
class operator Add(a, b: TDc): TDc;
end;
TTR = record
value: BigRational;
function SetString(const s: string; var TR: TTR): boolean;
function Tax(dc: TDc): TDc;
end;
{ TDc }
// Extend returns extended price of a unit price.
class operator TDc.Add(a, b: TDc): TDc;
begin
Result.value := a.value + b.value;
end;
function TDc.Extend(n: BigInteger): TDc;
begin
Result.value := n * value;
end;
function TDc.ToString: string;
var
d: BigInteger;
begin
d := value.Divide(value, 100);
if value < 0 then
value := -value;
Result := Format('%s.%2s', [d.ToString, (value mod 100).ToString]);
end;
// ParseDC parses dollars and cents as a string into a DC.
function ParseDC(s: string; var Dc: TDc): Boolean;
var
r: BigRational;
d: BigDecimal;
begin
Result := d.TryParse(s, d);
if not Result then
begin
Dc.value := 0;
exit(false);
end;
r := r.Create(d);
r := r.Multiply(r, 100);
if BigInteger.Compare(r.Denominator, 1) <> 0 then
begin
Dc.value := 0;
exit(false);
end;
Result := true;
Dc.value := r.Numerator;
end;
{ TTR }
function TTR.SetString(const s: string; var TR: TTR): boolean;
var
d: BigDecimal;
begin
Result := d.TryParse(s, d);
if Result then
TR.value := BigRational.Create(d);
end;
function TTR.Tax(dc: TDc): TDc;
var
r: BigRational;
i: BigInteger;
begin
r := BigRational.Create(dc.value, 1);
r := r.Multiply(r, self.value);
r := r.add(r, half);
i := i.Divide(r.Numerator, r.Denominator);
Result.value := i;
end;
var
hamburgerPrice, milkshakePrice, totalBeforeTax, tax, total: TDc;
taxRate: TTR;
begin
one := 1;
hundred := 100;
half := BigRational.Create(1, 2);
if not ParseDC('5.50', hamburgerPrice) then
begin
Writeln('Invalid hamburger price');
halt(1);
end;
if not ParseDC('2.86', milkshakePrice) then
begin
Writeln('Invalid milkshake price');
halt(2);
end;
if not taxRate.SetString('0.0765', taxRate) then
begin
Writeln('Invalid tax rat');
halt(3);
end;
totalBeforeTax := hamburgerPrice.Extend(4000000000000000) + milkshakePrice.Extend(2);
tax := taxRate.Tax(totalBeforeTax);
total := totalBeforeTax + tax;
Writeln('Total before tax: ', totalBeforeTax.ToString: 22);
Writeln(' Tax: ', tax.ToString: 22);
Writeln(' Total: ', total.ToString: 22);
readln;
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 language.
Add any historic details as to how the feature made its way into the language.
| #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 language.
Add any historic details as to how the feature made its way into the language.
| #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 ="; add(2).add(6)
Sleep |
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 10 to "origem" ');
writeln('The value of "origem" é ', origem);
writeln('The value of "copy" é ', copy);
writeln;
copy := 2;
writeln('Assign 2 to "copy" ');
writeln('The value of "origem" é ', origem);
writeln('The value of "copy" é ', copy);
Readln;
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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #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
'create a Person object at the address of the memory we've just allocated
Dim p As Person Ptr = New(ap) Person("Teresa", 60)
'check addresses are same
Print ap, p
'check data is not corrupt
Print p -> name, p -> age
'call implicit destructor
p -> Destructor
'free memory
Deallocate(ap)
Print
Print "Press any key to quit"
Sleep |
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 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #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 (my ($n, $k) = (1, 1) ; $n <= 10 ; ++$k) {
my $poly = $it->();
while (my $c = first { abs($_) == $n } $poly->coeff) {
say "CP $k has coefficient with magnitude = $n";
$n++;
}
} |
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 are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #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 = ($h + 1) × ($w + 1);
@grid[$len--] = 0;
my @next = -1, -$w-1, 1, $w+1;
for $cx+1 ..^ $w -> $x {
$t = $cy × ($w + 1) + $x;
@grid[$_] = 1 for $t, $len-$t;
walk($cy - 1, $x);
}
sub walk($y, $x) {
constant @dir = <0 -1 0 1> Z <-1 0 1 0>;
$cnt += 2 and return if not $y or $y == $h or not $x or $x == $w;
my $t = $y × ($w+1) + $x;
@grid[$_]++ for $t, $len-$t;
walk($y + @dir[$_;0], $x + @dir[$_;1]) if not @grid[$t + @next[$_]] for 0..3;
@grid[$_]-- for $t, $len-$t;
}
$cnt++;
if $h == $w { $cnt ×= 2 }
elsif $recurse and not $w +& 1 { solve($w, $h, False) }
$cnt
}
((1..9 X 1..9).grep:{ .[0] ≥ .[1] }).flat.map: -> $y, $x {
say "$y × $x: " ~ solve $y, $x, True unless $x +& 1 and $y +& 1;
} |
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 -. getyear)
gethour=: (2 { numbers) + 12 * (<'pm') e. words
getminsec=: 2 {. 3}. numbers
getts=: getyear, getmonth, getday, gethour, getminsec
timeadd=: 1&tsrep@+&tsrep
deltaT=: (1 tsrep 0)&([ + -@#@[ {. ]) |
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();
ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);
System.out.println("Date: " + dateStr);
System.out.println("+12h: " + after12Hours.format(df));
ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET"));
System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df));
}
}
|
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 Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #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\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \
[lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]]
if {($i&7)==7 || $i==51} {puts ""}
}
}
proc deal {seed} {
for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]}
for {set i 0} {$i < 51} {incr i} {
set j [expr {51 - [rnd]%(52-$i)}]
set tmp [lindex $cards $i]
lset cards $i [lindex $cards $j]
lset cards $j $tmp
}
return $cards
}
if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} {
set s 11982
}
set cards [deal $s]
puts "Hand $s"
show $cards |
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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 PROCEDURE
BEGIN
PRINT(CHR$(12);) ! CLS
FOR YR=2008 TO 2121 DO
WD(12,25,YR->RES%)
IF RES%=1 THEN ! day 1 is Sunday......
PRINT("Dec";25;",";YR)
END IF
END FOR
GET(K$)
END PROGRAM
|
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 December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #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
end if
end for
|
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #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 = int(c) - 55
case c == '*':
v = 36
case c == '@':
v = 37
case c == '#':
v = 38
default:
return false
}
if i % 2 == 1 { v *= 2 } // check if odd as using 0-based indexing
sum += v/10 + v%10
}
return int(s[8]) - 48 == (10 - (sum%10)) % 10
}
func main() {
candidates := []string {
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105",
}
for _, candidate := range candidates {
var b string
if isCusip(candidate) {
b = "correct"
} else {
b = "incorrect"
}
fmt.Printf("%s -> %s\n", candidate, b)
}
}
|
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 language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #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
No community queries yet
The top public SQL queries from the community will appear here once available.