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/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
| #Crystal | Crystal | require "time"
time = Time.local
puts time.to_s("%Y-%m-%d")
puts time.to_s("%A, %B %d, %Y")
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #D | D | module datetimedemo ;
import tango.time.Time ;
import tango.text.locale.Locale ;
import tango.time.chrono.Gregorian ;
import tango.io.Stdout ;
void main() {
Gregorian g = new Gregorian ;
Stdout.layout = new Locale; // enable Stdout to handle date/time format
Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;
Stdout.format("{:yyy-MM-dd}", d).newline ;
Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;
Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
} |
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.
| #Arturo | Arturo | ; data.csv
;
; 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
table: read.csv "data.csv"
data: []
loop table 'row [
addable: ["SUM"]
if row <> first table ->
addable: @[to :string sum map row 'x [to :integer x]]
'data ++ @[row ++ addable]
]
loop data 'row [
loop row 'column ->
prints pad column 6
print ""
] |
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.
| #FreeBASIC | FreeBASIC | ' version 04-07-2018
' compile with: fbc -s console
Function Damm(digit_str As String) As UInteger
Dim As UInteger table(10,10) => { { 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 } , _
{ 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 } , { 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 } , _
{ 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 } , { 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 } , _
{ 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 } , { 5, 8, 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 } }
Dim As UInteger i, col_i, old_row_i, new_row_i
For i = 0 To Len(digit_str) -1
col_i = digit_str[i] - Asc("0")
new_row_i = table(old_row_i, col_i)
old_row_i = new_row_i
Next
Return new_row_i
End Function
' ------=< MAIN >=------
Data "5724", "5727", "112946", ""
Dim As UInteger checksum, t
Dim As String test_string
Do
Read test_string
If test_string = "" Then Exit Do
Print "Checksum test: ";test_string;
checksum = Damm(test_string)
If checksum = 0 Then
Print " is valid"
Else
Print " is invalid"
End If
Loop
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Action.21 | Action! | PROC Save(CHAR ARRAY text)
BYTE dev=[1]
Close(dev)
Open(dev,"C:",8,128)
PrintE("Saving started...")
PrintF("Saving text: ""%S""%E",text)
PrintD(dev,text)
Close(dev)
PrintE("Saving finished.")
RETURN
PROC Load()
CHAR ARRAY result(255)
BYTE dev=[1]
Close(dev)
Open(dev,"C:",4,128)
PrintE("Loading started...")
WHILE Eof(dev)=0
DO
InputSD(dev,result)
PrintF("Loading text: ""%S""%E",result)
OD
Close(dev)
PrintE("Loading finished.")
RETURN
PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
PrintE("Press any key to save a file on tape.")
Save("Atari Action!")
PutE()
PrintE("Rewind the tape and press any key to load previously saved file from tape.")
Load()
RETURN |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Applesoft_BASIC | Applesoft BASIC | SAVE |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Arturo | Arturo | write "TAPE.FILE" {
This code
should be able to write
a file
to magnetic tape
} |
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.
| #F.23 | F# | open System
let hamburgers = 4000000000000000M
let hamburgerPrice = 5.50M
let milkshakes = 2M
let milkshakePrice = 2.86M
let taxRate = 0.0765M
let total = hamburgers * hamburgerPrice + milkshakes * milkshakePrice
let tax = total * taxRate
let totalWithTax = total + tax
printfn "Total before tax:\t$%M" <| Math.Round (total, 2)
printfn " Tax:\t$%M" <| Math.Round (tax, 2)
printfn " Total:\t$%M" <| Math.Round (totalWithTax, 2) |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a 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.
| #Factor | Factor | USING: combinators.smart io kernel math math.functions money ;
10 15 ^ 4 * 5+50/100 * ! hamburger subtotal
2 2+86/100 * ! milkshake subtotal
+ ! subtotal
dup DECIMAL: 0.0765 * ! tax
[ + ] preserving ! total
"Total before tax: " write [ money. ] 2dip
"Tax: " write [ money. ] dip
"Total with tax: " write money. |
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.
| #FreeBASIC | FreeBASIC | Dim As Longint hamburger_p = 550
Dim As Longint hamburger_q = 4000000000000000
Dim As Longint hamburger_v = hamburger_p * hamburger_q
Dim As Longint milkshake_p = 286
Dim As Longint milkshake_q = 2
Dim As Longint milkshake_v = milkshake_p * milkshake_q
Dim As Longint subtotal = hamburger_v + milkshake_v
Dim As Longint tax = subtotal * .765
Print Using "\ \ \ \ \ \ \ \";"item";"price";"quantity";"value"
Print Using "hamburger ##.## ################ #####################.##";hamburger_p/100;hamburger_q;hamburger_v/100
Print Using "milkshake ##.## ################ #####################.##";milkshake_p/100;milkshake_q;milkshake_v/100
?
Print Using " subtotal #####################.##";subtotal/10
Print Using " tax #####################.##";tax/100
Print Using " total #####################.##";subtotal/10+tax/100
Sleep |
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.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math"
)
func PowN(b float64) func(float64) float64 {
return func(e float64) float64 { return math.Pow(b, e) }
}
func PowE(e float64) func(float64) float64 {
return func(b float64) float64 { return math.Pow(b, e) }
}
type Foo int
func (f Foo) Method(b int) int {
return int(f) + b
}
func main() {
pow2 := PowN(2)
cube := PowE(3)
fmt.Println("2^8 =", pow2(8))
fmt.Println("4³ =", cube(4))
var a Foo = 2
fn1 := a.Method // A "method value", like currying 'a'
fn2 := Foo.Method // A "method expression", like uncurrying
fmt.Println("2 + 2 =", a.Method(2)) // regular method call
fmt.Println("2 + 3 =", fn1(3))
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 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
| #Go | Go | package main
import(
"fmt"
"unsafe"
"reflect"
)
func pointer() {
fmt.Printf("Pointer:\n")
// Create a *int and store the address of 'i' in it. To create a pointer to
// an arbitrary memory location, use something like the following:
// p := (*int)(unsafe.Pointer(uintptr(0x100)))
// And replace '0x100' with the desired address.
var i int
p := &i
fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)
*p = 3
fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}
func slice() {
fmt.Printf("Slice:\n")
var a [10]byte
// reflect.SliceHeader is a runtime representation of the internal workings
// of a slice. To make it point to a specific address, use something like
// the following:
// h.Data = uintptr(0x100)
// And replace '0x100' with the desired address.
var h reflect.SliceHeader
h.Data = uintptr(unsafe.Pointer(&a)) // The address of the first element of the underlying array.
h.Len = len(a)
h.Cap = len(a)
// Create an actual slice from the SliceHeader.
s := *(*[]byte)(unsafe.Pointer(&h))
fmt.Printf("Before:\n\ts: %v\n\ta: %v\n", s, a)
// Copy a string into the slice. This fills the underlying array, which in
// this case has been manually set to 'a'.
copy(s, "A string.")
fmt.Printf("After:\n\ts: %v\n\ta: %v\n", s, a)
}
func main() {
pointer()
fmt.Println()
slice()
} |
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
| #J | J |
function unsafepointers()
intspace = [42]
address = pointer_from_objref(intspace)
println("The address of intspace is $address")
anotherint = unsafe_pointer_to_objref(address)
println("intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])")
intspace[1] = 123456
println("Now, intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])")
anotherint[1] = 7890
println("Now, intspace is $(intspace[1]), memory at $(pointer_from_objref(anotherint)), reference value $(anotherint[1])")
end
unsafepointers()
|
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
| #Julia | Julia |
function unsafepointers()
intspace = [42]
address = pointer_from_objref(intspace)
println("The address of intspace is $address")
anotherint = unsafe_pointer_to_objref(address)
println("intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])")
intspace[1] = 123456
println("Now, intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])")
anotherint[1] = 7890
println("Now, intspace is $(intspace[1]), memory at $(pointer_from_objref(anotherint)), reference value $(anotherint[1])")
end
unsafepointers()
|
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. | #Phix | Phix | -- demo\rosetta\Cyclotomic_Polynomial.exw
with javascript_semantics
function degree(sequence p)
for i=length(p) to 1 by -1 do
if p[i]!=0 then return i end if
end for
return -1
end function
function poly_div(sequence n, d)
while length(d)<length(n) do d &=0 end while
integer dn = degree(n),
dd = degree(d)
if dd<0 then throw("divide by zero") end if
sequence quot = repeat(0,dn)
while dn>=dd do
integer k = dn-dd
integer qk = n[dn]/d[dd]
quot[k+1] = qk
sequence d2 = d[1..length(d)-k]
for i=1 to length(d2) do
integer mi = -i
n[mi] -= d2[mi]*qk
end for
dn = degree(n)
end while
-- return {quot,n} -- (n is now the remainder)
if n!=repeat(0,length(n)) then ?9/0 end if
while quot[$]=0 do quot = quot[1..$-1] end while
return quot
end function
function poly(sequence si)
-- display helper
string r = ""
for t=length(si) to 1 by -1 do
integer sit = si[t]
if sit!=0 then
if sit=1 and t>1 then
r &= iff(r=""? "":" + ")
elsif sit=-1 and t>1 then
r &= iff(r=""?"-":" - ")
else
if r!="" then
r &= iff(sit<0?" - ":" + ")
sit = abs(sit)
end if
r &= sprintf("%d",sit)
end if
r &= iff(t>1?"x"&iff(t>2?sprintf("^%d",t-1):""):"")
end if
end for
if r="" then r="0" end if
return r
end function
--</Polynomial_long_division.exw>
--# memoize cache for recursive calls
constant cyclotomics = new_dict({{1,{-1,1}},{2,{1,1}}})
function cyclotomic(integer n)
--
-- Calculate the nth cyclotomic polynomial.
-- See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools
-- The algorithm is reliable but slow for large n > 1000.
--
sequence c
if getd_index(n,cyclotomics)!=NULL then
c = getd(n,cyclotomics)
else
if is_prime(n) then
c = repeat(1,n)
else -- recursive formula seen in wikipedia article
c = -1&repeat(0,n-1)&1
sequence f = factors(n,-1)
for i=1 to length(f) do
c = poly_div(c,deep_copy(cyclotomic(f[i])))
end for
end if
setd(n,c,cyclotomics)
end if
return c
end function
for i=1 to 30 do
sequence z = cyclotomic(i)
string s = poly(z)
printf(1,"cp(%2d) = %s\n",{i,s})
if i>1 and z!=reverse(z) then ?9/0 end if -- sanity check
end for
integer found = 0, n = 1, cheat = 0
sequence fn = repeat(false,10),
nxt = {105,385,1365,1785,2805,3135,6545,6545,10465,10465}
atom t1 = time()+1
puts(1,"\n")
while found<iff(platform()=JS?5:10) do
sequence z = cyclotomic(n)
for i=1 to length(z) do
atom azi = abs(z[i])
if azi>=1 and azi<=10 and fn[azi]=0 then
printf(1,"cp(%d) has a coefficient with magnitude %d\n",{n,azi})
cheat = azi -- (comment this out to prevent cheating!)
found += 1
fn[azi] = true
t1 = time()+1
end if
end for
if cheat then {n,cheat} = {nxt[cheat],0} else n += iff(n=1?4:10) end if
if time()>t1 and platform()!=JS then
printf(1,"working (%d) ...\r",n)
t1 = time()+1
end if
end while
|
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.
| #REXX | REXX | /*REXX program cuts rectangles into two symmetric pieces, the rectangles are cut along */
/*────────────────────────────────────────────────── unit dimensions and may be rotated.*/
numeric digits 20 /*be able to handle some big integers. */
parse arg N .; if N=='' | N=="," then N= 10 /*N not specified? Then use default.*/
dir.= 0; dir.0.1= -1; dir.1.0= -1; dir.2.1= 1; dir.3.0= 1 /*the four directions*/
do y=2 to N; say /*calculate rectangles up to size NxN.*/
do x=1 for y; if x//2 & y//2 then iterate /*Both X&Y odd? Skip.*/
z= solve(y,x,1); _= comma(z); _= right(_, max(14, length(_))) /*align output.*/
say right(y, 9) "x" right(x, 2) 'rectangle can be cut' _ "way"s(z).
end /*x*/
end /*y*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
comma: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _
s: if arg(1)=1 then return arg(3); return word( arg(2) 's', 1) /*pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
solve: procedure expose # @. dir. h len next. w; @.= 0 /*zero rectangle coördinates.*/
parse arg h,w,recur /*get values for some args. */
if h//2 then do; t= w; w= h; h= t; if h//2 then return 0
end
if w==1 then return 1
if w==2 then return h
if h==2 then return w /* [↓] % is REXX's integer ÷*/
cy= h % 2; cx= w % 2; wp= w + 1 /*cut the rectangle in half. */
len= (h+1) * wp - 1 /*extend area of rectangle. */
next.0= '-1'; next.1= -wp; next.2= 1; next.3= wp /*direction & distance*/
if recur then #= 0
cywp= cy * wp /*shortcut calculation*/
do x=cx+1 to w-1; t= cywp + x; @.t= 1
_= len - t; @._= 1; call walk cy - 1, x
end /*x*/
#= # + 1
if h==w then #= # + # /*double rectangle cut count.*/
else if w//2==0 & recur then call solve w, h, 0
return #
/*──────────────────────────────────────────────────────────────────────────────────────*/
walk: procedure expose # @. dir. h len next. w wp; parse arg y,x
if y==h | x==0 | x==w | y==0 then do; #= # + 2; return; end
t= y*wp + x; @.t= @.t + 1; _= len - t
@._= @._ + 1
do j=0 for 4; _= t + next.j /*try each of 4 directions.*/
if @._==0 then call walk y + dir.j.0, x + dir.j.1
end /*j*/
@.t= @.t - 1
_= len - t; @._= @._ - 1; return |
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.
| #JavaScript | JavaScript | function add12hours(dateString) {
// Get the parts of the date string
var parts = dateString.split(/\s+/),
date = parts[1],
month = parts[0],
year = parts[2],
time = parts[3];
var hr = Number(time.split(':')[0]),
min = Number(time.split(':')[1].replace(/\D/g,'')),
ampm = time && time.match(/[a-z]+$/i)[0],
zone = parts[4].toUpperCase();
var months = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
var zones = {'EST': 300, 'AEST': -600}; // Minutes to add to zone time to get UTC
// Convert month name to number, zero indexed. Return if invalid month
month = months.indexOf(month);
if (month === -1) { return; }
// Add 12 hours as specified. Add another 12 if pm for 24hr time
hr += (ampm.toLowerCase() === 'pm') ? 24 : 12
// Create a date object in local zone
var localTime = new Date(year, month, date);
localTime.setHours(hr, min, 0, 0);
// Adjust localTime minutes for the time zones so it is now a local date
// representing the same moment as the source date plus 12 hours
localTime.setMinutes(localTime.getMinutes() + zones[zone] - localTime.getTimezoneOffset() );
return localTime;
}
var inputDateString = 'March 7 2009 7:30pm EST';
console.log(
'Input: ' + inputDateString + '\n' +
'+12hrs in local time: ' + add12hours(inputDateString)
); |
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
| #UNIX_Shell | UNIX Shell | test $# -gt 0 || set -- $((RANDOM % 32000))
for seed; do
print Game $seed:
# Shuffle deck.
deck=({A,{2..9},T,J,Q,K}{C,D,H,S})
for i in {52..1}; do
((seed = (214013 * seed + 2531011) & 0x7fffffff))
((j = (seed >> 16) % i + 1))
t=$deck[$i]
deck[$i]=$deck[$j]
deck[$j]=$t
done
# Deal cards.
print -n ' '
for i in {52..1}; do
print -n ' '$deck[$i]
((i % 8 == 5)) && print -n $'\n '
done
print
done |
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.
| #F.23 | F# | open System
[ 2008 .. 2121 ]
|> List.choose (fun y -> if DateTime(y,12,25).DayOfWeek = DayOfWeek.Sunday then Some(y) else None)
|> printfn "%A" |
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.
| #Factor | Factor | USING: calendar math.ranges prettyprint sequences ;
2008 2121 [a,b] [ 12 25 <date> sunday? ] filter . |
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
| #Groovy | Groovy | class Cusip {
private static Boolean isCusip(String s) {
if (s.length() != 9) return false
int sum = 0
for (int i = 0; i <= 7; i++) {
char c = s.charAt(i)
int v
if (c >= ('0' as char) && c <= ('9' as char)) {
v = c - 48
} else if (c >= ('A' as char) && c <= ('Z' as char)) {
v = c - 55 // lower case letters apparently invalid
} else if (c == '*' as char) {
v = 36
} else if (c == '@' as char) {
v = 37
} else if (c == '#' as char) {
v = 38
} else {
return false
}
if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing
sum += v / 10 + v % 10
}
return s.charAt(8) - 48 == (10 - (sum % 10)) % 10
}
static void main(String[] args) {
List<String> candidates=new ArrayList<>()
candidates.add("037833100")
candidates.add("17275R102")
candidates.add("38259P508")
candidates.add("594918104")
candidates.add("68389X106")
candidates.add("68389X105")
for (String candidate : candidates) {
System.out.printf("%s -> %s%n", candidate, isCusip(candidate) ? "correct" : "incorrect")
}
}
} |
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
| #AWK | AWK |
# syntax: GAWK -f STANDARD_DEVIATION.AWK
BEGIN {
n = split("2,4,4,4,5,5,7,9",arr,",")
for (i=1; i<=n; i++) {
temp[i] = arr[i]
printf("%g %g\n",arr[i],stdev(temp))
}
exit(0)
}
function stdev(arr, i,n,s1,s2,variance,x) {
for (i in arr) {
n++
x = arr[i]
s1 += x ^ 2
s2 += x
}
variance = ((n * s1) - (s2 ^ 2)) / (n ^ 2)
return(sqrt(variance))
}
|
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
| #Delphi | Delphi | ShowMessage(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', 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
| #Diego | Diego | me_lang(en)_cal(gregorian);
me_msg()_now()_format(yyyy-mm-dd);
me_msg()_now()_format(eeee, mmmm dd, yyyy); |
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.
| #AutoHotkey | AutoHotkey | Loop, Read, Data.csv
{
i := A_Index
Loop, Parse, A_LoopReadLine, CSV
Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",")
}
FileAppend, %Output%, NewData.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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
var table = [10][10]byte{
{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(input string) bool {
var interim byte
for _, c := range []byte(input) {
interim = table[interim][c-'0']
}
return interim == 0
}
func main() {
for _, s := range []string{"5724", "5727", "112946", "112949"} {
fmt.Printf("%6s %t\n", s, damm(s))
}
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #C | C |
#include<stdio.h>
int main()
{
FILE* fp = fopen("TAPE.FILE","w");
fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
fprintf(fp,"EOF");
fclose(fp);
return 0;
}
|
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #C.2B.2B | C++ | #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return 0;
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Clojure | Clojure | (spit "/dev/tape" "Hello, World!") |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a 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.
| #Frink | Frink |
st = 4000000000000000 * 5.50 dollars + 2 * 2.86 dollars
tax = round[st * 7.65 percent, cent]
total = st + tax
println["Subtotal: " + format[st, "dollars", 2]]
println["Tax: " + format[tax, "dollars", 2]]
println["Total: " + format[total, "dollars", 2]]
|
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a 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.
| #Go | Go | package main
import (
"fmt"
"log"
"math/big"
)
// DC for dollars and cents. Value is an integer number of cents.
type DC int64
func (dc DC) String() string {
d := dc / 100
if dc < 0 {
dc = -dc
}
return fmt.Sprintf("%d.%02d", d, dc%100)
}
// Extend returns extended price of a unit price.
func (dc DC) Extend(n int) DC {
return dc * DC(n)
}
var one = big.NewInt(1)
var hundred = big.NewRat(100, 1)
// ParseDC parses dollars and cents as a string into a DC.
func ParseDC(s string) (DC, bool) {
r, ok := new(big.Rat).SetString(s)
if !ok {
return 0, false
}
r.Mul(r, hundred)
if r.Denom().Cmp(one) != 0 {
return 0, false
}
return DC(r.Num().Int64()), true
}
// TR for tax rate. Value is an an exact rational.
type TR struct {
*big.Rat
}
func NewTR() TR {
return TR{new(big.Rat)}
}
// SetString overrides Rat.SetString to return the TR type.
func (tr TR) SetString(s string) (TR, bool) {
if _, ok := tr.Rat.SetString(s); !ok {
return TR{}, false
}
return tr, true
}
var half = big.NewRat(1, 2)
// Tax computes a tax amount, rounding to the nearest cent.
func (tr TR) Tax(dc DC) DC {
r := big.NewRat(int64(dc), 1)
r.Add(r.Mul(r, tr.Rat), half)
return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())
}
func main() {
hamburgerPrice, ok := ParseDC("5.50")
if !ok {
log.Fatal("Invalid hamburger price")
}
milkshakePrice, ok := ParseDC("2.86")
if !ok {
log.Fatal("Invalid milkshake price")
}
taxRate, ok := NewTR().SetString("0.0765")
if !ok {
log.Fatal("Invalid tax rate")
}
totalBeforeTax := hamburgerPrice.Extend(4000000000000000) +
milkshakePrice.Extend(2)
tax := taxRate.Tax(totalBeforeTax)
total := totalBeforeTax + tax
fmt.Printf("Total before tax: %22s\n", totalBeforeTax)
fmt.Printf(" Tax: %22s\n", tax)
fmt.Printf(" Total: %22s\n", total)
} |
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.
| #Go | Go | package main
import (
"fmt"
"math"
)
func PowN(b float64) func(float64) float64 {
return func(e float64) float64 { return math.Pow(b, e) }
}
func PowE(e float64) func(float64) float64 {
return func(b float64) float64 { return math.Pow(b, e) }
}
type Foo int
func (f Foo) Method(b int) int {
return int(f) + b
}
func main() {
pow2 := PowN(2)
cube := PowE(3)
fmt.Println("2^8 =", pow2(8))
fmt.Println("4³ =", cube(4))
var a Foo = 2
fn1 := a.Method // A "method value", like currying 'a'
fn2 := Foo.Method // A "method expression", like uncurrying
fmt.Println("2 + 2 =", a.Method(2)) // regular method call
fmt.Println("2 + 3 =", fn1(3))
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 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
| #Kotlin | Kotlin | // Kotlin/Native Technology Preview
import kotlinx.cinterop.*
fun main(args: Array<String>) {
val intVar = nativeHeap.alloc<IntVar>().apply { value = 42 }
with(intVar) { println("Value is $value, address is $rawPtr") }
intVar.value = 52 // create new value at this address
with(intVar) { println("Value is $value, address is $rawPtr") }
nativeHeap.free(intVar)
} |
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
| #Lua | Lua | local a = {10}
local b = a
print ("address a:"..tostring(a), "value a:"..a[1])
print ("address b:"..tostring(b), "value b:"..b[1])
b[1] = 42
print ("address a:"..tostring(a), "value a:"..a[1])
print ("address b:"..tostring(b), "value b:"..b[1]) |
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
structure alfa {
val as long
}
Buffer Clear Beta as alfa*2
Print Beta(0) ' return address
Return Beta, 0!val:=500 ' unsigned integer 32 bit
Print Eval(Beta, 0!val)=500
Return Beta, 0!val:=0xFFFFFFFF
Print Eval(Beta, 0!val)=4294967295
Buffer Code ExecMem as byte*1024
Offset=0
EmbLong(0xb8, 5000) ' mov eax,5100
EmbByteLong(0x3,0x5, Beta(0)) ' add eax, [Beta(0)]
EmbLong(0xa3, Beta(1)) ' mov [Beta(1)], eax
EmbByte(0x31, 0xC0) ' xor eax, eax
Ret() ' Return
Execute Code ExecMem, 0
Print eval(Beta, 1!val)=4999
Sub Ret()
Return ExecMem, Offset:=0xC3
Offset++
End Sub
Sub EmbByte()
Return ExecMem, Offset:=Number, Offset+1:=Number
Offset+=2
End Sub
Sub EmbLong()
Return ExecMem, Offset:=Number, Offset+1:=Number as Long
Offset+=5
End Sub
Sub EmbByteLong()
Return ExecMem, Offset:=Number, Offset+1:=Number, Offset+2:=Number as Long
Offset+=6
End Sub
}
Checkit
|
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. | #Python | Python | from itertools import count, chain
from collections import deque
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n):
for p in primes():
if n%p == 0:
return False
if p*p > n:
return True
def factors(n):
for p in primes():
# prime factoring is such a non-issue for small numbers that, for
# this example, we might even just say
# for p in count(2):
if p*p > n:
if n > 1:
yield(n, 1, 1)
break
if n%p == 0:
cnt = 0
while True:
n, cnt = n//p, cnt+1
if n%p != 0: break
yield p, cnt, n
# ^^ not the most sophisticated prime number routines, because no need
# Returns (list1, list2) representing the division between
# two polinomials. A list p of integers means the product
# (x^p[0] - 1) * (x^p[1] - 1) * ...
def cyclotomic(n):
def poly_div(num, den):
return (num[0] + den[1], num[1] + den[0])
def elevate(poly, n): # replace poly p(x) with p(x**n)
powerup = lambda p, n: [a*n for a in p]
return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n))
if n == 0:
return ([], [])
if n == 1:
return ([1], [])
p, m, r = next(factors(n))
poly = cyclotomic(r)
return elevate(poly_div(elevate(poly, p), poly), p**(m-1))
def to_text(poly):
def getx(c, e):
if e == 0:
return '1'
elif e == 1:
return 'x'
return 'x' + (''.join('⁰¹²³⁴⁵⁶⁷⁸⁹'[i] for i in map(int, str(e))))
parts = []
for (c,e) in (poly):
if c < 0:
coef = ' - ' if c == -1 else f' - {-c} '
else:
coef = (parts and ' + ' or '') if c == 1 else f' + {c}'
parts.append(coef + getx(c,e))
return ''.join(parts)
def terms(poly):
# convert above representation of division to (coef, power) pairs
def merge(a, b):
# a, b should be deques. They may change during the course.
while a or b:
l = a[0] if a else (0, -1) # sentinel value
r = b[0] if b else (0, -1)
if l[1] > r[1]:
a.popleft()
elif l[1] < r[1]:
b.popleft()
l = r
else:
a.popleft()
b.popleft()
l = (l[0] + r[0], l[1])
yield l
def mul(poly, p): # p means polynomial x^p - 1
poly = list(poly)
return merge(deque((c, e+p) for c,e in poly),
deque((-c, e) for c,e in poly))
def div(poly, p): # p means polynomial x^p - 1
q = deque()
for c,e in merge(deque(poly), q):
if c:
q.append((c, e - p))
yield (c, e - p)
if e == p: break
p = [(1, 0)] # 1*x^0, i.e. 1
for x in poly[0]: # numerator
p = mul(p, x)
for x in sorted(poly[1], reverse=True): # denominator
p = div(p, x)
return p
for n in chain(range(11), [2]):
print(f'{n}: {to_text(terms(cyclotomic(n)))}')
want = 1
for n in count():
c = [c for c,_ in terms(cyclotomic(n))]
while want in c or -want in c:
print(f'C[{want}]: {n}')
want += 1 |
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.
| #Ruby | Ruby | def cut_it(h, w)
if h.odd?
return 0 if w.odd?
h, w = w, h
end
return 1 if w == 1
nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] # [next,dy,dx]
blen = (h + 1) * (w + 1) - 1
grid = [false] * (blen + 1)
walk = lambda do |y, x, count=0|
return count+1 if y==0 or y==h or x==0 or x==w
t = y * (w + 1) + x
grid[t] = grid[blen - t] = true
nxt.each do |nt, dy, dx|
count += walk[y + dy, x + dx] unless grid[t + nt]
end
grid[t] = grid[blen - t] = false
count
end
t = h / 2 * (w + 1) + w / 2
if w.odd?
grid[t] = grid[t + 1] = true
count = walk[h / 2, w / 2 - 1]
count + walk[h / 2 - 1, w / 2] * 2
else
grid[t] = true
count = walk[h / 2, w / 2 - 1]
return count * 2 if h == w
count + walk[h / 2 - 1, w / 2]
end
end
for w in 1..9
for h in 1..w
puts "%d x %d: %d" % [w, h, cut_it(w, h)] if (w * h).even?
end
end |
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.
| #jq | jq | "March 7 2009 7:30pm EST"
| strptime("%B %d %Y %I:%M%p %Z")
| .[3] += 12
| mktime | strftime("%B %d %Y %I:%M%p %Z") |
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.
| #Julia | Julia | using Dates
function main()
dtstr = "March 7 2009 7:30pm" # Base.Dates doesn't handle "EST"
cleandtstr = replace(dtstr, r"(am|pm)"i, "")
dtformat = dateformat"U dd yyyy HH:MM"
dtime = parse(DateTime, cleandtstr, dtformat) +
Hour(12 * contains(dtstr, r"pm"i)) # add 12h for the pm
println(Dates.format(dtime + Hour(12), dtformat))
end
main()
|
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
| #Wren | Wren | class Lcg {
construct new(a, c, m, d, s) {
_a = a
_c = c
_m = m
_d = d
_s = s
}
nextInt() {
_s = (_a * _s + _c) % _m
return _s / _d
}
}
var CARDS = "A23456789TJQK"
var SUITS = "♣♦♥♠".toList
var deal = Fn.new {
var cards = List.filled(52, null)
for (i in 0...52) {
var card = CARDS[(i/4).floor]
var suit = SUITS[i%4]
cards[i] = card + suit
}
return cards
}
var game = Fn.new { |n|
if (n.type != Num || !n.isInteger || n <= 0) {
Fiber.abort("Game number must be a positive integer.")
}
System.print("Game #%(n):")
var msc = Lcg.new(214013, 2531011, 1<<31, 1<<16, n)
var cards = deal.call()
for (m in 52..1) {
var index = (msc.nextInt() % m).floor
var temp = cards[index]
cards[index] = cards[m - 1]
System.write("%(temp) ")
if ((53 - m) % 8 == 0) System.print()
}
System.print("\n")
}
game.call(1)
game.call(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.
| #FBSL | FBSL | #APPTYPE CONSOLE
'In what years between 2008 and 2121 will the 25th of December be a Sunday?
DIM date AS INTEGER, dayname AS STRING
FOR DIM year = 2008 TO 2121
date = year * 10000 + 1225
dayname = dateconv(date,"dddd")
IF dayname = "Sunday" THEN
PRINT "Christmas Day is on a Sunday in ", year
END IF
NEXT
PAUSE
|
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
| #Haskell | Haskell | import Data.List(elemIndex)
data Result = Valid | BadCheck | TooLong | TooShort | InvalidContent deriving Show
-- convert a list of Maybe to a Maybe list.
-- result is Nothing if any of values from the original list are Nothing
allMaybe :: [Maybe a] -> Maybe [a]
allMaybe = sequence
toValue :: Char -> Maybe Int
toValue c = elemIndex c $ ['0'..'9'] ++ ['A'..'Z'] ++ "*@#"
-- check a list of ints to see if they represent a valid CUSIP
valid :: [Int] -> Bool
valid ns0 =
let -- multiply values with even index by 2
ns1 = zipWith (\i n -> (if odd i then n else 2*n)) [1..] $ take 8 ns0
-- apply div/mod formula from site and sum up results
sm = sum $ fmap (\s -> ( s `div` 10 ) + s `mod` 10) ns1
in -- apply mod/mod formula from site and compare to last value in list
ns0!!8 == (10 - (sm `mod` 10)) `mod` 10
-- check a String to see if it represents a valid CUSIP
checkCUSIP :: String -> Result
checkCUSIP cs
| l < 9 = TooShort
| l > 9 = TooLong
| otherwise = case allMaybe (fmap toValue cs) of
Nothing -> InvalidContent
Just ns -> if valid ns then Valid else BadCheck
where l = length cs
testData =
[ "037833100"
, "17275R102"
, "38259P508"
, "594918104"
, "68389X106"
, "68389X105"
]
main = mapM_ putStrLn (fmap (\s -> s ++ ": " ++ show (checkCUSIP s)) testData) |
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
| #Axiom | Axiom | )abbrev package TESTD TestDomain
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where
R ==> Record(n : Integer, sum : T, ssq : T)
Exports == AbelianMonoid with
_+ : (%,T) -> %
_+ : (T,%) -> %
sd : % -> T
Implementation == R add
Rep := R -- similar representation and implementation
obj : %
0 == [0,0,0]
obj + (obj2:%) == [obj.n + obj2.n, obj.sum + obj2.sum, obj.ssq + obj2.ssq]
obj + (x:T) == obj + [1, x, x*x]
(x:T) + obj == obj + x
sd obj ==
mean : T := obj.sum / (obj.n::T)
sqrt(obj.ssq / (obj.n::T) - mean*mean) |
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
| #EGL | EGL |
// 2012-09-26
SysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), "yyyy-MM-dd"));
// Wednesday, September 26, 2012
SysLib.setLocale("en", "US");
SysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), "EEEE, MMMM dd, yyyy"));
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Elixir | Elixir | defmodule Date_format do
def iso_date, do: Date.utc_today |> Date.to_iso8601
def iso_date(year, month, day), do: Date.from_erl!({year, month, day}) |> Date.to_iso8601
def long_date, do: Date.utc_today |> long_date
def long_date(year, month, day), do: Date.from_erl!({year, month, day}) |> long_date
@months Enum.zip(1..12, ~w[January February March April May June July August September October November December])
|> Map.new
@weekdays Enum.zip(1..7, ~w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday])
|> Map.new
def long_date(date) do
weekday = Date.day_of_week(date)
"#{@weekdays[weekday]}, #{@months[date.month]} #{date.day}, #{date.year}"
end
end
IO.puts Date_format.iso_date
IO.puts Date_format.long_date
IO.puts Date_format.iso_date(2007,11,10)
IO.puts Date_format.long_date(2007,11,10) |
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.
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN { FS = OFS = "," }
NR==1 {
print $0, "SUM"
next
}
{
sum = 0
for (i=1; i<=NF; i++) {
sum += $i
}
print $0, sum
} |
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.
| #Go | Go | package main
import "fmt"
var table = [10][10]byte{
{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(input string) bool {
var interim byte
for _, c := range []byte(input) {
interim = table[interim][c-'0']
}
return interim == 0
}
func main() {
for _, s := range []string{"5724", "5727", "112946", "112949"} {
fmt.Printf("%6s %t\n", s, damm(s))
}
} |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #ALGOL_68 | ALGOL 68 | BEGIN
# find some cuban primes (using the definition: a prime p is a cuban prime if #
# p = n^3 - ( n - 1 )^3 #
# for some n > 0) #
# returns a string representation of n with commas #
PROC commatise = ( LONG INT n )STRING:
BEGIN
STRING result := "";
STRING unformatted = whole( n, 0 );
INT ch count := 0;
FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
IF ch count <= 2 THEN ch count +:= 1
ELSE ch count := 1; "," +=: result
FI;
unformatted[ c ] +=: result
OD;
result
END # commatise # ;
# sieve the primes #
INT sieve max = 2 000 000;
[ sieve max ]BOOL sieve; FOR i TO UPB sieve DO sieve[ i ] := TRUE OD;
sieve[ 1 ] := FALSE;
FOR s FROM 2 TO ENTIER sqrt( sieve max ) DO
IF sieve[ s ] THEN
FOR p FROM s * s BY s TO sieve max DO sieve[ p ] := FALSE OD
FI
OD;
# count the primes, we can ignore 2, as we know it isn't a cuban prime #
sieve[ 2 ] := FALSE;
INT prime count := 0;
FOR s TO UPB sieve DO IF sieve[ s ] THEN prime count +:= 1 FI OD;
# construct a list of the primes #
[ 1 : prime count ]INT primes;
INT prime pos := LWB primes;
FOR s FROM LWB sieve TO UPB sieve DO
IF sieve[ s ] THEN primes[ prime pos ] := s; prime pos +:= 1 FI
OD;
# find the cuban primes #
INT cuban count := 0;
LONG INT final cuban := 0;
INT max cuban = 100 000; # mximum number of cubans to find #
INT print limit = 200; # show all cubans up to this one #
print( ( "First ", commatise( print limit ), " cuban primes: ", newline ) );
LONG INT prev cube := 1;
FOR n FROM 2 WHILE
LONG INT this cube = ( LENG n * n ) * n;
LONG INT p = this cube - prev cube;
prev cube := this cube;
IF ODD p THEN
# 2 is not a cuban prime so we only test odd numbers #
BOOL is prime := TRUE;
INT max factor = SHORTEN ENTIER long sqrt( p );
FOR f FROM LWB primes WHILE is prime AND primes[ f ] <= max factor DO
is prime := p MOD primes[ f ] /= 0
OD;
IF is prime THEN
# have a cuban prime #
cuban count +:= 1;
IF cuban count <= print limit THEN
# must show this cuban #
STRING p formatted = commatise( p );
print( ( " "[ UPB p formatted : ], p formatted ) );
IF cuban count MOD 10 = 0 THEN print( ( newline ) ) FI
FI;
final cuban := p
FI
FI;
cuban count < max cuban
DO SKIP OD;
IF cuban count MOD 10 /= 0 THEN print( ( newline ) ) FI;
print( ( "The ", commatise( max cuban ), " cuban prime is: ", commatise( final cuban ), newline ) )
END |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #COBOL | COBOL | >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. MAKE-TAPE-FILE.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT TAPE-FILE
ASSIGN "./TAPE.FILE"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD TAPE-FILE.
01 TAPE-FILE-RECORD PIC X(51).
PROCEDURE DIVISION.
OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE
WRITE TAPE-FILE-RECORD
FROM "COBOL treats tape files and text files identically."
END-WRITE
STOP RUN. |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Crystal | Crystal | filename = {% if flag?(:win32) %}
"TAPE.FILE"
{% else %}
"/dev/tape"
{% end %}
File.write filename, "howdy, planet!" |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #D | D | import std.stdio;
void main() {
version(Windows) {
File f = File("TAPE.FILE", "w");
} else {
File f = File("/dev/tape", "w");
}
f.writeln("Hello World!");
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Delphi | Delphi |
program Create_a_file_on_magnetic_tape;
{$APPTYPE CONSOLE}
const
{$IFDEF WIN32}
FileName = 'tape.file';
{$ELSE}
FileName = '/dev/tape';
{$ENDIF}
var
f: TextFile;
begin
Assign(f, FileName);
Rewrite(f);
Writeln(f, 'Hello World');
close(f);
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.
| #Haskell | Haskell | import Data.Fixed
import Text.Printf
type Percent = Centi
type Dollars = Centi
tax :: Percent -> Dollars -> Dollars
tax rate = MkFixed . round . (rate *)
printAmount :: String -> Dollars -> IO ()
printAmount name = printf "%-10s %20s\n" name . showFixed False
main :: IO ()
main = do
let subtotal = 4000000000000000 * 5.50 + 2 * 2.86
tx = tax 7.65 subtotal
total = subtotal + tx
printAmount "Subtotal" subtotal
printAmount "Tax" tx
printAmount "Total" total |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a 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.
| #J | J | require 'format/printf'
Items=: ;: 'Hamburger Milkshake'
Quantities=: 4000000000000000 2
Prices=: x: 5.50 2.86
Tax_rate=: x: 0.0765
makeBill=: verb define
'items prices quantities'=. y
values=. prices * quantities
subtotal=. +/ values
tax=. Tax_rate * subtotal
total=. subtotal + tax
'%9s %8s %20s %22s' printf ;:'Item Price Quantity Value'
'%9s %8.2f %20d %22.2f' printf"1 items ,. <"0 prices ,. quantities ,. values
'%62s' printf <'-------------------------------'
'%40s %21.2f' printf"1 (;:'Subtotal: Tax: Total:') ,. subtotal;tax;total
)
makeBill Items;Prices;Quantities |
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.
| #Groovy | Groovy | def divide = { Number x, Number y ->
x / y
}
def partsOf120 = divide.curry(120)
println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}" |
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.
| #Haskell | Haskell | \ -> |
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
| #Nim | Nim | type
MyObject = object
x: int
y: float
var
mem = alloc(sizeof(MyObject))
objPtr = cast[ptr MyObject](mem)
echo "object at ", cast[int](mem), ": ", objPtr[]
objPtr[] = MyObject(x: 42, y: 3.1415)
echo "object at ", cast[int](mem), ": ", objPtr[]
|
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
| #Pascal | Pascal | program test;
type
t8Byte = array[0..7] of byte;
var
I : integer;
A : integer absolute I;
K : t8Byte;
L : Int64 absolute K;
begin
I := 0;
A := 255; writeln(I);
I := 4711;writeln(A);
For i in t8Byte do
Begin
K[i]:=i;
write(i:3,' ');
end;
writeln(#8#32);
writeln(L);
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
| #Perl | Perl | # 20210218 Perl programming solution
use strict;
use warnings;
# create an integer object
print "Here is an integer : ", my $target = 42, "\n";
# print the machine address of the object
print "And its reference is : ", my $targetref = \$target, "\n";
# take the address of the object and create another integer object at this address
print "Now assigns a new value to it : ", $$targetref = 69, "\n";
# print the value of this object to verify that it is same as one of the origin
print "Then compare with the referent : ", $target, "\n"; |
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. | #Raku | Raku | use Math::Polynomial::Cyclotomic:from<Perl5> <cyclo_poly_iterate cyclo_poly>;
say 'First 30 cyclotomic polynomials:';
my $iterator = cyclo_poly_iterate(1);
say "Φ($_) = " ~ super $iterator().Str for 1..30;
say "\nSmallest cyclotomic polynomial with |n| as a coefficient:";
say "Φ(1) has a coefficient magnitude: 1";
my $index = 0;
for 2..9 -> $coefficient {
loop {
$index += 5;
my \Φ = cyclo_poly($index);
next unless Φ ~~ / $coefficient\* /;
say "Φ($index) has a coefficient magnitude: $coefficient";
$index -= 5;
last;
}
}
sub super ($str) {
$str.subst( / '^' (\d+) /, { $0.trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]) }, :g)
} |
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.
| #Rust | Rust |
fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) {
if x == 0 || y == 0 || x == w || y == h {
*count += 1;
return;
}
vis[y][x] = true;
vis[h - y][w - x] = true;
if x != 0 && ! vis[y][x - 1] {
cwalk(&mut vis, count, w, h, y, x - 1, d | 1);
}
if d & 1 != 0 && x < w && ! vis[y][x+1] {
cwalk(&mut vis, count, w, h, y, x + 1, d | 1);
}
if y != 0 && ! vis[y - 1][x] {
cwalk(&mut vis, count, w, h, y - 1, x, d | 2);
}
if d & 2 != 0 && y < h && ! vis[y + 1][x] {
cwalk(&mut vis, count, w, h, y + 1, x, d | 2);
}
vis[y][x] = false;
vis[h - y][w - x] = false;
}
fn count_only(x: usize, y: usize) -> isize {
let mut count = 0;
let mut w = x;
let mut h = y;
if (h * w) & 1 != 0 {
return count;
}
if h & 1 != 0 {
std::mem::swap(&mut w, &mut h);
}
let mut vis = vec![vec![false; w + 1]; h + 1];
vis[h / 2][w / 2] = true;
if w & 1 != 0 {
vis[h / 2][w / 2 + 1] = true;
}
let mut res;
if w > 1 {
cwalk(&mut vis, &mut count, w, h, h / 2, w / 2 - 1, 1);
res = 2 * count - 1;
count = 0;
if w != h {
cwalk(&mut vis, &mut count, w, h, h / 2 + 1, w / 2, if w & 1 != 0 { 3 } else { 2 });
}
res += 2 * count - if w & 1 == 0 { 1 } else { 0 };
}
else {
res = 1;
}
if w == h {
res = 2 * res + 2;
}
res
}
fn main() {
for y in 1..10 {
for x in 1..y + 1 {
if x & 1 == 0 || y & 1 == 0 {
println!("{} x {}: {}", y, x, count_only(x, y));
}
}
}
}
|
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.
| #Kotlin | Kotlin | // version 1.0.6
import java.text.SimpleDateFormat
import java.util.*
fun main(args: Array<String>) {
val dts = "March 7 2009 7:30pm EST"
val sdf = SimpleDateFormat("MMMM d yyyy h:mma z")
val dt = sdf.parse(dts)
val cal = GregorianCalendar(TimeZone.getTimeZone("EST")) // stay with EST
cal.time = dt
cal.add(Calendar.HOUR_OF_DAY, 12) // add 12 hours
val fmt = "%tB %1\$td %1\$tY %1\$tl:%1\$tM%1\$tp %1\$tZ"
println(fmt.format(cal)) // display new time
// display time now in Mountain Standard Time which is 2 hours earlier than EST
cal.timeZone = TimeZone.getTimeZone("MST")
println(fmt.format(cal))
} |
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.
| #langur | langur | val .input = "March 7 2009 7:30pm -05:00"
val .iformat = "January 2 2006 3:04pm -07:00" # input format
val .format = "January 2 2006 3:04pm MST" # output format
val .d1 = toDateTime .input, .iformat
val .d2 = .d1 + dt/PT12H/
val .d3 = toDateTime .d2, "US/Arizona"
val .d4 = toDateTime .d2, ZLS
val .d5 = toDateTime .d2, "Z"
val .d6 = toDateTime .d2, "+02:30"
val .d7 = toDateTime .d2, "EST"
writeln "input string: ", .input
writeln "input format string: ", .iformat
writeln "output format string: ", .format
writeln()
writeln $"original: \.d1; (\.d1:dt.format;)"
writeln $"+12 hours: \.d2; (\.d2:dt.format;)"
writeln $"in Arizona: \.d3; (\.d3:dt.format;)"
writeln $"in local time zone: \.d4; (\.d4:dt.format;)"
writeln $"in UTC: \.d5; (\.d5:dt.format;)"
writeln $"+02:30 time zone: \.d6; (\.d6:dt.format;)"
writeln $"in EST: \.d7; (\.d7:dt.format;)" |
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
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
int RandState;
func Rand; \Random number in range 0 to 32767
[RandState:= (214013*RandState + 2531011) & $7FFF_FFFF;
return RandState >> 16;
];
int Card, Deck(52), Size;
char Suit, Rank;
[RandState:= IntIn(8); \seed RNG with number from command line
for Card:= 0 to 52-1 do Deck(Card):= Card; \create array of 52 cards
Rank:= "A23456789TJQK";
Suit:= "CDHS";
Size:= 52;
repeat Card:= rem(Rand/Size); \choose a random card
ChOut(0, Rank(Deck(Card)/4)); \deal it by showing it
ChOut(0, Suit(rem(0)));
if rem(Size/8)=5 then CrLf(0) else ChOut(0, ^ );
Size:= Size-1; \one less card in deck
Deck(Card):= Deck(Size); \replace dealt card with last card
until Size = 0; \all cards have been dealt
] |
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
| #zkl | zkl | var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡
var seed=1; const RMAX32=(1).shiftLeft(31) - 1;
fcn rnd{ (seed=((seed*214013 + 2531011).bitAnd(RMAX32))).shiftRight(16) }
fcn game(n){
seed=n;
deck:=(0).pump(52,List,'wrap(n){ if(n>=44) n+=4; // I want JQK, not JCQ
(suits[n%4] + n/4).toString(8) }).copy(); // int-->UTF-8
[52..1,-1].pump(Void,'wrap(len){ deck.swap(len-1,rnd()%len); });
deck.reverse();
println("Game #",n);
foreach n in ([0..51,8]){ deck[n,8].concat(" ").println(); }
}
game(1);
game(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.
| #Forth | Forth |
\ Zeller's Congruence
: weekday ( d m y -- wd) \ 1 mon..7 sun
over 3 < if 1- swap 12 + swap then
100 /mod
dup 4 / swap 2* -
swap dup 4 / + +
swap 1+ 13 5 */ + +
( in zeller 0=sat, so -2 to 0= mon, then mod, then 1+ for 1=mon)
2- 7 mod 1+ ;
: yuletide
." December 25 is Sunday in "
2122 2008 do
25 12 i weekday
7 = if i . then
loop cr ;
|
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.
| #Fortran | Fortran | PROGRAM YULETIDE
IMPLICIT NONE
INTEGER :: day, year
WRITE(*, "(A)", ADVANCE="NO") "25th of December is a Sunday in"
DO year = 2008, 2121
day = Day_of_week(25, 12, year)
IF (day == 1) WRITE(*, "(I5)", ADVANCE="NO") year
END DO
CONTAINS
FUNCTION Day_of_week(d, m, y)
INTEGER :: Day_of_week, j, k, mm, yy
INTEGER, INTENT(IN) :: d, m, y
mm=m
yy=y
IF(mm.le.2) THEN
mm=mm+12
yy=yy-1
END IF
j = yy / 100
k = MOD(yy, 100)
Day_of_week = MOD(d + ((mm+1)*26)/10 + k + k/4 + j/4 + 5*j, 7)
END FUNCTION Day_of_week
END PROGRAM YULETIDE |
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
| #Icon_and_Unicon | Icon and Unicon | # cusip.icn -- Committee on Uniform Security Identification Procedures
procedure main()
local code, codes
codes := ["037833100", "17275R102", "38259P508",
"594918104", "68389X106", "68389X105"]
while code := pop(codes) do {
writes(code, " : ")
if check_code(code) then
write("valid.")
else write("not valid.")
}
end
procedure check_code(c)
local p, sum, value
static codetable
initial codetable := buildtable()
sum := 0
value := 0
every p := 1 to 8 do {
if p % 2 = 1 then # odd position
value := codetable[c[p]]
else # even position
value := 2 * codetable[c[p]]
sum +:= (value / 10) + (value % 10)
}
sum := (10 - (sum % 10)) % 10
if sum = c[9] then return else fail
end
procedure buildtable()
local chars, n, t
t := table()
chars := &digits || &ucase || "*@#"
every n := 1 to *chars do
t[chars[n]] := (n - 1)
return t
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
| #BBC_BASIC | BBC BASIC | MAXITEMS = 100
FOR i% = 1 TO 8
READ n
PRINT "Value = "; n ", running SD = " FNrunningsd(n)
NEXT
END
DATA 2,4,4,4,5,5,7,9
DEF FNrunningsd(n)
PRIVATE list(), i%
DIM list(MAXITEMS)
i% += 1
list(i%) = n
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2) |
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
| #Emacs_Lisp | Emacs Lisp | (format-time-string "%Y-%m-%d")
(format-time-string "%F") ;; new in Emacs 24
;; => "2015-11-08"
(format-time-string "%A, %B %e, %Y")
;; => "Sunday, November 8, 2015" |
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
| #Erlang | Erlang | -module(format_date).
-export([iso_date/0, iso_date/1, iso_date/3, long_date/0, long_date/1, long_date/3]).
-import(calendar,[day_of_the_week/1]).
-import(io,[format/2]).
-import(lists,[append/1]).
iso_date() -> iso_date(date()).
iso_date(Year, Month, Day) -> iso_date({Year, Month, Day}).
iso_date(Date) ->
format("~4B-~2..0B-~2..0B~n", tuple_to_list(Date)).
long_date() -> long_date(date()).
long_date(Year, Month, Day) -> long_date({Year, Month, Day}).
long_date(Date = {Year, Month, Day}) ->
Months = { "January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December" },
Weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" },
Weekday = day_of_the_week(Date),
WeekdayName = element(Weekday, Weekdays),
MonthName = element(Month, Months),
append([WeekdayName, ", ", MonthName, " ", integer_to_list(Day), ", ",
integer_to_list(Year)]). |
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.
| #BaCon | BaCon | OPTION COLLAPSE TRUE
OPTION DELIM ","
csv$ = LOAD$("data.csv")
DOTIMES AMOUNT(csv$, NL$)
line$ = TOKEN$(csv$, _, NL$)
IF _ = 1 THEN
total$ = APPEND$(line$, 0, "SUM")
ELSE
line$ = CHANGE$(line$, _, STR$(_*10) )
total$ = APPEND$(total$, 0, line$, NL$)
total$ = APPEND$(total$, 0, STR$(LOOP(i, AMOUNT(line$), VAL(TOKEN$(line$, i)))) )
FI
DONE
SAVE total$ TO "data.csv"
PRINT total$
|
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.
| #BASIC | BASIC | OPEN "manip.csv" FOR INPUT AS #1
OPEN "manip2.csv" FOR OUTPUT AS #2
LINE INPUT #1, header$
PRINT #2, header$ + ",SUM"
WHILE NOT EOF(1)
INPUT #1, c1, c2, c3, c4, c5
sum = c1 + c2 + c3 + c4 + c5
WRITE #2, c1, c2, c3, c4, c5, sum
WEND
CLOSE #1, #2
END |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Groovy | Groovy | class DammAlgorithm {
private static final int[][] TABLE = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[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],
]
private static boolean damm(String s) {
int interim = 0
for (char c : s.toCharArray()) interim = TABLE[interim][c - ('0' as Character)]
return interim == 0
}
static void main(String[] args) {
int[] numbers = [5724, 5727, 112946, 112949]
for (Integer number : numbers) {
boolean isValid = damm(number.toString())
if (isValid) {
System.out.printf("%6d is valid\n", number)
} else {
System.out.printf("%6d is invalid\n", number)
}
}
}
} |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Bracmat | Bracmat | ( ( cubanprimes
=
. !arg:(?N.?bigN)
& :?cubans
& (0.1.1):(?cube100k.?cube1.?count)
& 0:?i
& whl
' ( 1+!i:?i
& !i+1:?j
& !j^3:?cube2
& !cube2+-1*!cube1:?diff
& ( !diff^1/2:~(!diff^?)
| ( !count:~>!N
& !diff !cubans:?cubans
|
)
& ( !count:<!bigN
| !diff:?cube100k&~
)
& 1+!count:?count
)
& !cube2:?cube1
)
& ( columnwidth
= cols
. !arg:(%@:@(?:? [?cols)) ?
& div$(-1+!cols.3)*4+1
)
& columnwidth$!cubans:?colwidth
& \n:?table
& 0:?col
& ( format
= n col cif R
. !arg:(?n.?col)
& -1:?cif
& vap
$ ( (
=
. ( mod$(1+!cif:?cif.3):0
& -2+!col:?col
& ","
| -1+!col:?col&
)
!arg
)
. rev$!n
)
: "," ?R
& rev$(str$!R):?R
& whl
' ( !col+-1:?col:>-2
& " " !R:?R
)
& str$!R
)
& whl
' ( !cubans:%?cuban ?cubans
& mod$(1+!col:?col.10):?col
& (!col:0&\n|" ")
format$(!cuban.!colwidth)
!table
: ?table
)
& out$(str$("The first " !N " cuban primes are: " !table))
& out
$ ( str
$ ( "The 100,000th cuban prime is "
format$(!cube100k.columnwidth$!cube100k)
)
)
)
& cubanprimes$(200.100000)
) |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #C | C | #include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef long long llong_t;
struct PrimeArray {
llong_t *ptr;
size_t size;
size_t capacity;
};
struct PrimeArray allocate() {
struct PrimeArray primes;
primes.size = 0;
primes.capacity = 10;
primes.ptr = malloc(primes.capacity * sizeof(llong_t));
return primes;
}
void deallocate(struct PrimeArray *primes) {
free(primes->ptr);
primes->ptr = NULL;
}
void push_back(struct PrimeArray *primes, llong_t p) {
if (primes->size >= primes->capacity) {
size_t new_capacity = (3 * primes->capacity) / 2 + 1;
llong_t *temp = realloc(primes->ptr, new_capacity * sizeof(llong_t));
if (NULL == temp) {
fprintf(stderr, "Failed to reallocate the prime array.");
exit(1);
} else {
primes->ptr = temp;
primes->capacity = new_capacity;
}
}
primes->ptr[primes->size++] = p;
}
int main() {
const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks;
struct PrimeArray primes = allocate();
int c = 0;
bool showEach = true;
llong_t u = 0, v = 1, i;
push_back(&primes, 3);
push_back(&primes, 5);
printf("The first %d cuban primes:\n", cutOff);
for (i = 1; i < LLONG_MAX; ++i) {
bool found = false;
llong_t mx = ceil(sqrt(v += (u += 6)));
llong_t j;
for (j = 0; j < primes.size; ++j) {
if (primes.ptr[j] > mx) {
break;
}
if (v % primes.ptr[j] == 0) {
found = true;
break;
}
}
if (!found) {
c += 1;
if (showEach) {
llong_t z;
for (z = primes.ptr[primes.size - 1] + 2; z <= v - 2; z += 2) {
bool fnd = false;
for (j = 0; j < primes.size; ++j) {
if (primes.ptr[j] > mx) {
break;
}
if (z % primes.ptr[j] == 0) {
fnd = true;
break;
}
}
if (!fnd) {
push_back(&primes, z);
}
}
push_back(&primes, v);
printf("%11lld", v);
if (c % 10 == 0) {
printf("\n");
}
if (c == cutOff) {
showEach = false;
printf("\nProgress to the %dth cuban prime: ", bigUn);
}
}
if (c % little == 0) {
printf(".");
if (c == bigUn) {
break;
}
}
}
}
printf("\nThe %dth cuban prime is %lld\n", c, v);
deallocate(&primes);
return 0;
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #F.23 | F# |
open System
open System.IO
let env = Environment.OSVersion.Platform
let msg = "Hello Rosetta!"
match env with
| PlatformID.Win32NT | PlatformID.Win32S | PlatformID.Win32Windows | PlatformID.WinCE -> File.WriteAllText("TAPE.FILE", msg)
| _ -> File.WriteAllText("/dev/tape", msg)
|
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Factor | Factor | USING: io.encodings.ascii io.files kernel system ;
"Hello from Rosetta Code!"
os windows? "tape.file" "/dev/tape" ?
ascii set-file-contents |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Fortran | Fortran | Dim As Integer numarch = Freefile
Open "tape.file" For Output As #numarch
Print #numarch, "Soy un archivo de cinta ahora, o espero serlo pronto."
Close #numarch |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #FreeBASIC | FreeBASIC | Dim As Integer numarch = Freefile
Open "tape.file" For Output As #numarch
Print #numarch, "Soy un archivo de cinta ahora, o espero serlo pronto."
Close #numarch |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Go | Go | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
} |
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.
| #Java | Java | import java.math.*;
import java.util.*;
public class Currency {
final static String taxrate = "7.65";
enum MenuItem {
Hamburger("5.50"), Milkshake("2.86");
private MenuItem(String p) {
price = new BigDecimal(p);
}
public final BigDecimal price;
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
MathContext mc = MathContext.DECIMAL128;
Map<MenuItem, BigDecimal> order = new HashMap<>();
order.put(MenuItem.Hamburger, new BigDecimal("4000000000000000"));
order.put(MenuItem.Milkshake, new BigDecimal("2"));
BigDecimal subtotal = BigDecimal.ZERO;
for (MenuItem it : order.keySet())
subtotal = subtotal.add(it.price.multiply(order.get(it), mc));
BigDecimal tax = new BigDecimal(taxrate, mc);
tax = tax.divide(new BigDecimal("100"), mc);
tax = subtotal.multiply(tax, mc);
System.out.printf("Subtotal: %20.2f%n", subtotal);
System.out.printf(" Tax: %20.2f%n", tax);
System.out.printf(" Total: %20.2f%n", subtotal.add(tax));
}
} |
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.
| #Hy | Hy | (defn addN [n]
(fn [x]
(+ x 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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
add2 := addN(2)
write("add2(7) = ",add2(7))
write("add2(1) = ",add2(1))
end
procedure addN(n)
return makeProc{ repeat { (x := (x@&source)[1], x +:= n) } }
end
procedure makeProc(A)
return (@A[1], A[1])
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
| #Phix | Phix | poke(0x80,or_bits(peek(0x80),0x40))
#ilASM{ mov al,[0x80]
or al,0x40
mov [0x80],al}
|
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
| #PicoLisp | PicoLisp | : (setq IntSpace 12345) # Integer
-> 12345
: (setq Address (adr 'IntSpace)) # Encoded machine address
-> -2969166782547
: (set (adr Address) 65535) # Set this address to a new value
-> 65535
: IntSpace # Show the new value
-> 65535 |
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
| #PureBasic | PureBasic | ; Allocate a 1Mb memory area work within to avoid conflicts,
; this address could be any number but it may then fail on some systems.
*a=AllocateMemory(1024*1024)
; Write a int wit value "31415" at address +312,
; using pointer '*a' with a displacement.
PokeI(*a+312, 31415)
; Write a float with value Pi at address +316,
; by creating a new pointer '*b' for this address
*b=*a+316
PokeF(*b, #PI)
;Now test it
For i=0 To 1024000 Step 4
n=PeekI(*a+i)
If n
Debug "Int at +"+Str(i)+" = "+Str(n)
Debug "Float at +"+Str(i)+"= "+StrF(PeekF(*a+i))
EndIf
Next
|
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
| #Racket | Racket |
#lang racket
(require ffi/unsafe)
(define x #"Foo")
;; Get the address of the `x' object
(printf "The address of `x' is: ~s\n" (cast x _scheme _long))
(define address (cast x _bytes _long))
(printf "The address of the bytestring it holds: ~s\n" address)
(define y (cast address _long _bytes))
(printf "Converting this back to a bytestring: ~s\n" y)
(bytes-set! y 0 71)
(printf "Changed the converted bytestring: ~s\n" y)
(printf "The original one is now: ~s\n" x)
;; But (bytes-set! x 0 71) will throw an error since `x' is immutable,
;; showing that we've really modifed the memory directly in a way that
;; the runtime doesn't like.
;; Also, the above can fail at any moment if a GC happens, since
;; Racket's GC moves objects. So a proper way to do this is not to
;; start from an existing object, but allocate one outside of the GC's
;; reach, using raw malloc():
(define buf (malloc 4 'raw))
(make-sized-byte-string buf 4)
;; or start with a given address of something like a memory-mapped IO
;; object
|
http://rosettacode.org/wiki/Cyclotomic_polynomial | Cyclotomic polynomial | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.
Task
Find and print the first 30 cyclotomic polynomials.
Find and print the order of the first 10 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. | #Sidef | Sidef | var Poly = require('Math::Polynomial')
Poly.string_config(Hash(fold_sign => true, prefix => "", suffix => ""))
func poly_interpolation(v) {
v.len.of {|n| v.len.of {|k| n**k } }.msolve(v)
}
say "First 30 cyclotomic polynomials:"
for k in (1..30) {
var a = (k+1).of { cyclotomic(k, _) }
var Φ = poly_interpolation(a)
say ("Φ(#{k}) = ", Poly.new(Φ...))
}
say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"
for n in (1..10) { # very slow
var k = (1..Inf -> first {|k|
poly_interpolation((k+1).of { cyclotomic(k, _) }).first { .abs == n }
})
say "Φ(#{k}) has coefficient with magnitude #{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.
| #Tcl | Tcl | package require Tcl 8.5
proc walk {y x} {
global w ww h cnt grid len
if {!$y || $y==$h || !$x || $x==$w} {
incr cnt 2
return
}
set t [expr {$y*$ww + $x}]
set m [expr {$len - $t}]
lset grid $t [expr {[lindex $grid $t] + 1}]
lset grid $m [expr {[lindex $grid $m] + 1}]
if {![lindex $grid [expr {$y*$ww + $x-1}]]} {
walk $y [expr {$x-1}]
}
if {![lindex $grid [expr {($y-1)*$ww + $x}]]} {
walk [expr {$y-1}] $x
}
if {![lindex $grid [expr {$y*$ww + $x+1}]]} {
walk $y [expr {$x+1}]
}
if {![lindex $grid [expr {($y+1)*$ww + $x}]]} {
walk [expr {$y+1}] $x
}
lset grid $t [expr {[lindex $grid $t] - 1}]
lset grid $m [expr {[lindex $grid $m] - 1}]
}
# Factored out core of [solve]
proc SolveCore {} {
global w ww h cnt grid len
set ww [expr {$w+1}]
set cy [expr {$h / 2}]
set cx [expr {$w / 2}]
set len [expr {($h+1) * $ww}]
set grid [lrepeat $len 0]
incr len -1
for {set x $cx;incr x} {$x < $w} {incr x} {
set t [expr {$cy*$ww+$x}]
lset grid $t 1
lset grid [expr {$len - $t}] 1
walk [expr {$cy - 1}] $x
}
incr cnt
}
proc solve {H W} {
global w h cnt
set h $H
set w $W
if {$h & 1} {
set h $W
set w $H
}
if {$h & 1} {
return 0
}
if {$w==1} {return 1}
if {$w==2} {return $h}
if {$h==2} {return $w}
set cnt 0
SolveCore
if {$h==$w} {
incr cnt $cnt
} elseif {!($w & 1)} {
lassign [list $w $h] h w
SolveCore
}
return $cnt
}
apply {{limit} {
for {set yy 1} {$yy <= $limit} {incr yy} {
for {set xx 1} {$xx <= $yy} {incr xx} {
if {!($xx&1 && $yy&1)} {
puts [format "%d x %d: %ld" $yy $xx [solve $yy $xx]]
}
}
}
}} 10 |
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.
| #Lasso | Lasso | local(date) = date('March 7 2009 7:30PM EST',-format='MMMM d yyyy h:mma z')
#date->add(-hour = 24)
#date->timezone = 'GMT' |
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.
| #Lingo | Lingo | ----------------------------------------
-- Returns string representation of given date object in YYYY-MM-DD hh:mm:ii format
-- @param {date} dateObj
-- @returns {string}
----------------------------------------
on dateToDateTimeString (dateObj)
str = ""
s = string(dateObj.year)
if s.length<4 then put "0000".char[1..4-s.length] before s
put s after str
s = string(dateObj.month)
if s.length<2 then s = "0"&s
put s after str
s = string(dateObj.day)
if s.length<2 then put "0" before s
put s after str
sec = dateObj.seconds
s = string(sec / 3600)
sec = sec mod 3600
if s.length<2 then put "0" before s
put s after str
s = string(sec / 60)
sec = sec mod 60
if s.length<2 then put "0" before s
put s after str
s = string(sec)
if s.length<2 then put "0" before s
put s after str
put ":" after char 12 of str
put ":" after char 10 of str
put " " after char 8 of str
put "-" after char 6 of str
put "-" after char 4 of str
return str
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | for y = 2008 to 2121
if (parseDate["$y-12-25"] -> ### u ###) == "7"
println[y] |
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.
| #Frink | Frink | for y = 2008 to 2121
if (parseDate["$y-12-25"] -> ### u ###) == "7"
println[y] |
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
| #J | J | ccd =. 10 | 10 - 10 | [: +/ [: , 10 (#.^:_1) (8 $ 1 2) * '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#' i. ]
ccd '68389X10'
5 |
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
| #Java | Java | import java.util.List;
public class Cusip {
private static Boolean isCusip(String s) {
if (s.length() != 9) return false;
int sum = 0;
for (int i = 0; i <= 7; i++) {
char c = s.charAt(i);
int v;
if (c >= '0' && c <= '9') {
v = c - 48;
} else if (c >= 'A' && c <= 'Z') {
v = c - 55; // lower case letters apparently invalid
} else if (c == '*') {
v = 36;
} else if (c == '@') {
v = 37;
} else if (c == '#') {
v = 38;
} else {
return false;
}
if (i % 2 == 1) v *= 2; // check if odd as using 0-based indexing
sum += v / 10 + v % 10;
}
return s.charAt(8) - 48 == (10 - (sum % 10)) % 10;
}
public static void main(String[] args) {
List<String> candidates = List.of(
"037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105", "EXTRACRD8",
"EXTRACRD9", "BADCUSIP!", "683&9X106", "68389x105", "683$9X106", "68389}105", "87264ABE4"
);
for (String candidate : candidates) {
System.out.printf("%s -> %s%n", candidate, isCusip(candidate) ? "correct" : "incorrect");
}
}
} |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action;
typedef struct stat_obj_struct {
double sum, sum2;
size_t num;
Action action;
} sStatObject, *StatObject;
StatObject NewStatObject( Action action )
{
StatObject so;
so = malloc(sizeof(sStatObject));
so->sum = 0.0;
so->sum2 = 0.0;
so->num = 0;
so->action = action;
return so;
}
#define FREE_STAT_OBJECT(so) \
free(so); so = NULL
double stat_obj_value(StatObject so, Action action)
{
double num, mean, var, stddev;
if (so->num == 0.0) return 0.0;
num = so->num;
if (action==COUNT) return num;
mean = so->sum/num;
if (action==MEAN) return mean;
var = so->sum2/num - mean*mean;
if (action==VAR) return var;
stddev = sqrt(var);
if (action==STDDEV) return stddev;
return 0;
}
double stat_object_add(StatObject so, double v)
{
so->num++;
so->sum += v;
so->sum2 += v*v;
return stat_obj_value(so, so->action);
} |
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
| #Euphoria | Euphoria | constant days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
constant months = {"January","February","March","April","May","June",
"July","August","September","October","November","December"}
sequence now
now = date()
now[1] += 1900
printf(1,"%d-%02d-%02d\n",now[1..3])
printf(1,"%s, %s %d, %d\n",{days[now[7]],months[now[2]],now[3],now[1]}) |
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.
| #BQN | BQN |
csvstr ← ⟨"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"⟩
Split ← (⊢-˜¬×+`)∘=⟜','⊸⊔
strdata ← >Split¨csvstr
intdata ← •BQN¨⌾(1⊸↓) strdata
sums ← ⟨"SUMS"⟩ ∾+´˘ 1↓ intdata
done ← sums ∾˜˘ intdata
|
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.
| #C | C |
#define TITLE "CSV data manipulation"
#define URL "http://rosettacode.org/wiki/CSV_data_manipulation"
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h> /* malloc...*/
#include <string.h> /* strtok...*/
#include <ctype.h>
#include <errno.h>
/**
* How to read a CSV file ?
*/
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
/**
* Utility function to trim whitespaces from left & right of a string
*/
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
/* from right */
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
/* from left */
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
/**
* De-allocate csv structure
*/
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
/**
* Allocate memory for a CSV structure
*/
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
/**
* Get value in CSV table at COL, ROW
*/
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
/**
* Set value in CSV table at COL, ROW
*/
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
/**
* Resize CSV table
*/
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
/* Build a new (fake) csv */
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
/* re-link data */
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
/* destroy data */
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { /* skip */ }
}
}
/* on rows */
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
/**
* Open CSV file and load its content into provided CSV structure
**/
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
/**
* Open CSV file and save CSV structure content into it
**/
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
/**
* Test
*/
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.