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/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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | next[last_] := Mod[214013 last + 2531011, 2^31];
deal[n_] :=
Module[{last = n, idx,
deck = StringJoin /@
Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J",
"Q", "K"}, {"C", "D", "H", "S"}}], res = {}},
While[deck != {}, last = next[last];
idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1;
deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}];
AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res];
format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]];
Print[format[deal[1]]];
Print[format[deal[617]]]; |
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
| #Nim | Nim | import sequtils, strutils, os
proc randomGenerator(seed: int): iterator: int =
var state = seed
return iterator: int =
while true:
state = (state * 214013 + 2531011) and int32.high
yield state shr 16
proc deal(seed: int): seq[int] =
const nc = 52
result = toSeq countdown(nc - 1, 0)
var rnd = randomGenerator seed
for i in 0 ..< nc:
let r = rnd()
let j = (nc - 1) - r mod (nc - i)
swap result[i], result[j]
proc show(cards: seq[int]) =
var l = newSeq[string]()
for c in cards:
l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4]
for i in countup(0, cards.high, 8):
echo " ", l[i..min(i+7, l.high)].join(" ")
let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982
echo "Hand ", seed
let deck = deal seed
show deck |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Racket | Racket |
#lang racket
(provide (contract-out [x 1-to-10/c]))
(define 1-to-10/c (between/c 1 10))
(define x 5)
|
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Raku | Raku | subset OneToTen of Int where 1..10;
my OneToTen $n = 5;
$n += 6; |
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.
| #BCPL | BCPL | get "libhdr"
let weekday(y, m, d) =
m<3 -> wd((y-1)/100, (y-1) rem 100, m + 10, d),
wd(y/100, y rem 100, m - 2, d)
and wd(c, y, m, d) =
((26*m-2)/10 + d + y + y/4 + c/4 - 2 * c + 777) rem 7
let start() be
for year = 2008 to 2121
if weekday(year, 12, 25) = 0
do writef("%N*N", year) |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North 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
| #360_Assembly | 360 Assembly | * CUSIP 07/06/2018
CUSIP CSECT
USING CUSIP,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=F'6') do i=1 to 6
LR R1,R6 i
MH R1,=H'9' *9
LA R4,T-9(R1) @t(i)
MVC X,0(R4) x=t(i)
SR R10,R10 w=0
LA R7,1 j=1
DO WHILE=(C,R7,LE,=F'8') do j=1 to 8
LA R14,X-1 x
AR R14,R7 j
MVC Y(1),0(R14) y=substr(x,j,1)
LA R9,L'XX z=length(xx)
LA R8,1 k=1
DO WHILE=(C,R8,LE,=A(L'XX)) do k=1 to length(xx)
LA R4,XX-1 xx
AR R4,R8 k
MVC C(1),0(R4) c=substr(xx,k,1)
IF CLC,Y(1),EQ,C THEN if y=c then
LR R9,R8 k
BCTR R9,0 z=k-1
ENDIF , endif
LA R8,1(R8) k++
ENDDO , enddo k
LR R4,R7 j
LA R1,2 2
SRDA R4,32 ~
DR R4,R1 j/2=0
IF LTR,R4,Z,R4 THEN if j//2=0 then
AR R9,R9 z=z+z
ENDIF , endif
LR R4,R9 z
LA R1,10 10
SRDA R4,32 ~
DR R4,R1 r4=z//10 ; r5=z/10
AR R10,R5 w+z/10
AR R10,R4 w=w+z/10+z//10
LA R7,1(R7) j++
ENDDO , enddo j
LR R4,R10 w
LA R1,10 10
SRDA R4,32 ~
DR R4,R1 w/10
LA R2,10 10
SR R2,R4 10-w//10
SRDA R2,32 ~
DR R2,R1 /10
STC R2,U u=(10-w//10)//10
OI U,X'F0' bin to char
IF CLC,U,EQ,X+8 THEN if u=substr(x,9,1) then
MVC OK,=CL3' ' ok=' '
ELSE , else
MVC OK,=C'n''t' ok='n''t'
ENDIF , endif
MVC PG+6(9),X output x
MVC PG+18(3),OK output ok
XPRNT PG,L'PG print
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
XX DC CL39'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#'
U DS CL1
Y DS CL1
C DS CL1
T DC CL9'037833100',CL9'17275R102',CL9'38259P508'
DC CL9'594918104',CL9'68389X106',CL9'68389X105'
X DS CL9
OK DS CL3
PG DC CL80'CUSIP ......... is... valid'
YREGS
END CUSIP |
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
| #Action.21 | Action! | INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit
BYTE FUNC Verify(CHAR ARRAY code)
BYTE i,c,v
CARD sum
IF code(0)#9 THEN
RETURN (0)
ELSEIF IsDigit(code(1))=0 THEN
RETURN (0)
FI
sum=0
FOR i=2 TO code(0)
DO
c=code(i)
IF IsDigit(c) THEN
v=c-'0
ELSEIF IsAlpha(c) THEN
v=ToUpper(c)-'A+10
ELSEIF c='* THEN
v=36
ELSEIF c='@ THEN
v=37
ELSEIF c='# THEN
v=38
ELSE
RETURN (0)
FI
IF (i&1)=0 THEN
v==*2
FI
sum==+v/10+v MOD 10
OD
v=(10-(sum MOD 10)) MOD 10
IF v#code(1)-'0 THEN
RETURN (0)
FI
RETURN (1)
PROC Test(CHAR ARRAY code)
Print(code)
IF Verify(code) THEN
PrintE(" is valid")
ELSE
PrintE(" is invalid")
FI
RETURN
PROC Main()
Put(125) PutE() ;clear the screen
Test("037833100")
Test("17275R102")
Test("38259P508")
Test("594918104")
Test("68389X106")
Test("68389X105")
RETURN |
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
| #ABAP | ABAP |
report zdate.
data: lv_month type string,
lv_weekday type string,
lv_date type string,
lv_day type c.
call function 'DATE_COMPUTE_DAY'
exporting date = sy-datum
importing day = lv_day.
select single ltx from t247 into lv_month
where spras = sy-langu and
mnr = sy-datum+4(2).
select single langt from t246 into lv_weekday
where sprsl = sy-langu and
wotnr = lv_day.
concatenate lv_weekday ', ' lv_month ' ' sy-datum+6(2) ', ' sy-datum(4) into lv_date respecting blanks.
write lv_date.
concatenate sy-datum(4) '-' sy-datum+4(2) '-' sy-datum+6(2) into lv_date.
write / lv_date.
|
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.
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns TRUE if the check digit of s is correct according to the Damm algorithm, #
# FALSE otherwise #
PROC has valid damm check digit = ( STRING s )BOOL:
BEGIN
# operation table - as per wikipedia example #
[,]INT operation table =
( [,]INT( ( 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 )
)
) [ AT 0, AT 0 ]
;
INT interim digit := 0;
FOR s pos FROM LWB s TO UPB s DO
INT next digit = ABS s[ s pos ] - ABS "0";
IF next digit < 0 OR next digit > 9 THEN
# invalid digit #
print( ( "Invalid damm digit: ", s[ s pos ], newline ) );
stop
ELSE
# have a valid digit #
interim digit := operation table[ interim digit, next digit ]
FI
OD;
interim digit = 0
END # has valid damm check digit # ;
# test the damm algorithm #
PROC test damm algorithm = ( STRING s, BOOL expected )VOID:
BEGIN
BOOL valid = has valid damm check digit( s );
print( ( "check digit of ", s, " is "
, IF valid THEN "valid" ELSE "invalid" FI
, IF valid = expected THEN "" ELSE " *** NOT AS EXPECTED" FI
, newline
)
)
END # test damm algorithm # ;
# test cases - as per other language samples #
test damm algorithm( "5724", TRUE );
test damm algorithm( "5727", FALSE );
test damm algorithm( "112946", TRUE )
END |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# gojq does not currently define _nwise
def _nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def printRows($m): _nwise($m) | map(lpad(5)) | join(""); |
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.
| #Delphi | Delphi |
program Cut_a_rectangle;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
grid: array of byte;
w, h, len: Integer;
cnt: UInt64;
next: array of Integer;
dir: array of array of Integer = [[0, -1], [-1, 0], [0, 1], [1, 0]];
procedure walk(y, x: Integer);
var
i, t: Integer;
begin
if (y = 0) or (y = h) or (x = 0) or (x = w) then
begin
inc(cnt);
Exit;
end;
t := y * (w + 1) + x;
inc(grid[t]);
inc(grid[len - t]);
for i := 0 to 3 do
if grid[t + next[i]] = 0 then
walk(y + dir[i][0], x + dir[i][1]);
dec(grid[t]);
dec(grid[len - t]);
end;
function solve(hh, ww: Integer; recur: Boolean): UInt64;
var
t, cx, cy, x, i: Integer;
begin
h := hh;
w := ww;
if Odd(h) then
begin
t := w;
w := h;
h := t;
end;
if Odd(h) then
Exit(0);
if w = 1 then
Exit(1);
if w = 2 then
Exit(h);
if h = 2 then
Exit(w);
cy := h div 2;
cx := w div 2;
len := (h + 1) * (w + 1);
setlength(grid, len);
for i := 0 to High(grid) do
grid[i] := 0;
dec(len);
next := [-1, -w - 1, 1, w + 1];
if recur then
cnt := 0;
for x := cx + 1 to w - 1 do
begin
t := cy * (w + 1) + x;
grid[t] := 1;
grid[len - t] := 1;
walk(cy - 1, x);
end;
Inc(cnt);
if h = w then
inc(cnt, 2)
else if not odd(w) and recur then
solve(w, h, False);
Result := cnt;
end;
var
y, x: Integer;
begin
for y := 1 to 10 do
for x := 1 to y do
if not Odd(x) or not Odd(y) then
writeln(format('%d x %d: %d', [y, x, solve(y, x, True)]));
Readln;
end. |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory 'is_prime';
use List::AllUtils 'firstidx';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
my @cyclops = 0;
for my $exp (0..3) {
my @oom = grep { ! /0/ } 10**$exp .. 10**($exp+1)-1;
for my $l (@oom) {
for my $r (@oom) {
push @cyclops, $l . '0' . $r;
}
}
}
my @prime_cyclops = grep { is_prime $_ } @cyclops;
my @prime_blind = grep { is_prime $_ =~ s/0//r } @prime_cyclops;
my @prime_palindr = grep { $_ eq reverse $_ } @prime_cyclops;
my $upto = 50;
my $over = 10_000_000;
for (
['', @cyclops],
['prime', @prime_cyclops],
['blind prime', @prime_blind],
['palindromic prime', @prime_palindr]) {
my($text,@values) = @$_;
my $i = firstidx { $_ > $over } @values;
say "First $upto $text cyclops numbers:\n" .
(sprintf "@{['%8d' x $upto]}", @values[0..$upto-1]) =~ s/(.{80})/$1\n/gr;
printf "First $text number > %s: %s at (zero based) index: %s\n\n", map { comma($_) } $over, $values[$i], $i;
} |
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.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"DATELIB"
date$ = "March 7 2009 7:30pm EST"
mjd% = FN_readdate(date$, "mdy", 0)
colon% = INSTR(date$, ":")
hours% = VAL(MID$(date$, colon%-2))
IF INSTR(date$, "am") IF hours%=12 hours% -= 12
IF INSTR(date$, "pm") IF hours%<>12 hours% += 12
mins% = VAL(MID$(date$, colon%+1))
now% = mjd% * 1440 + hours% * 60 + mins%
new% = now% + 12 * 60 : REM 12 hours later
PRINT FNformat(new%, "EST")
PRINT FNformat(new% + 5 * 60, "GMT")
PRINT FNformat(new% - 3 * 60, "PST")
END
DEF FNformat(datetime%, zone$)
LOCAL mjd%, hours%, mins%, ampm$
mjd% = datetime% DIV 1440
hours% = (datetime% DIV 60) MOD 24
mins% = datetime% MOD 60
IF hours% < 12 THEN ampm$ = "am" ELSE ampm$ = "pm"
IF hours% = 0 hours% += 12
IF hours% > 12 hours% -= 12
= FN_date$(mjd%, "MMMM d yyyy") + " " + STR$(hours%) + \
\ ":" + RIGHT$("0"+STR$(mins%), 2) + ampm$ + " " + zone$
ENDPROC
|
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
/* ts.tm_hour += 12; instead of t += 12*60*60
works too. */
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));
return EXIT_SUCCESS;
} |
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
| #Objeck | Objeck | class FreeCell {
function : Main(args : String[]) ~ Nil {
Deal(1)->PrintLine();
Deal(617)->PrintLine();
}
function : Deal(seed : Int) ~ String {
deck := Deck->New(seed)->ToString();
return "Game #{$seed}:\n{$deck}\n";
}
}
class Deck {
@cards : Card[];
New(seed : Int) {
r := Random->New(seed);
@cards := Card->New[52];
for(i := 0; i < 52; i+= 1;) {
@cards[i] := Card->New(51 - i);
};
for(i := 0; i < 51; i += 1;) {
j := 51 - r->Next() % (52 - i);
tmp := @cards[i]; @cards[i] := @cards[j]; @cards[j] := tmp;
};
}
method : public : ToString() ~ String {
buffer := "";
each(i : @cards) {
buffer += @cards[i]->ToString();
buffer += (i % 8 = 7 ? "\n" : " ");
};
return buffer;
}
}
class Random {
@seed : Int;
New(seed : Int) {
@seed := seed;
}
method : public : Next() ~ Int {
@seed := (@seed * 214013 + 2531011) and Int->MaxSize();
return @seed >> 16;
}
}
class Card {
@value : Int;
@suit : Int;
New(value : Int) {
@value := value / 4; @suit := value % 4;
}
method : public : ToString() ~ String {
suits := "♣♦♥♠"; values := "A23456789TJQK";
value := values->Get(@value); suit := suits->Get(@suit);
return "{$value}{$suit}";
}
} |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Retro | Retro | {{
variable update
---reveal---
: .limited @update &! &@ if update off ;
: to dup 1 10 within [ update on ] [ drop "Out of bounds\n" puts ] if ;
: limited: create 1 , &.limited reclass ;
}} |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Ruby | Ruby | Some object-oriented languages won't let you subclass the "basic" data types
like integers. Other languages implement those data types as classes, so you
can subclass them, no questions asked. Ruby implements numbers as classes
(Integer, with its concrete subclasses Fixnum and Bignum), and you can subclass
those classes. If you try, though, you'll quickly discover that your subclasses
are useless: they don't have constructors.
Ruby jealously guards the creation of new Integer objects. This way it ensures
that, for instance, there can be only one Fixnum instance for a given number
The easiest way to delegate all methods is to create a class that's nearly empty
and define a method_missing method.
|
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.
| #Befunge | Befunge | 8 >:"2("*+::::4/+\"d"/-\45v
@_^#`"y": +1$<_v#%7+1+/*:*<
>:#,_>$:.55+,^ >0" ,52 ceD" |
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.
| #Bracmat | Bracmat | { Calculate day of week in proleptic Gregorian calendar. Sunday == 0. }
( wday
= year month day adjustment mm yy
. !arg:(?year,?month,?day)
& div$(14+-1*!month,12):?adjustment
& !month+12*!adjustment+-2:?mm
& !year+-1*!adjustment:?yy
& mod
$ ( !day
+ div$(13*!mm+-1,5)
+ !yy
+ div$(!yy,4)
+ -1*div$(!yy,100)
+ div$(!yy,400)
, 7
)
)
& 2008:?y
& whl
' ( !y:~>2121
& ( wday$(!y,12,25):0
& put$(str$(!y "-12-25\n"))
|
)
& 1+!y:?y
)
& done; |
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
| #Ada | Ada | with Ada.Text_IO;
procedure Cusip_Test is
use Ada.Text_IO;
subtype Cusip is String (1 .. 9);
function Check_Cusip (Code : Cusip) return Boolean is
Sum : Integer := 0;
V : Integer;
begin
for I in Code'First .. Code'Last - 1 loop
case Code (I) is
when '0' .. '9' =>
V := Character'Pos (Code (I)) - Character'Pos ('0');
when 'A' .. 'Z' =>
V := Character'Pos (Code (I)) - Character'Pos ('A') + 10;
when '*' => V := 36;
when '@' => V := 37;
when '#' => V := 38;
when others => return False;
end case;
if I mod 2 = 0 then
V := V * 2;
end if;
Sum := Sum + V / 10 + (V mod 10);
end loop;
return (10 - (Sum mod 10)) mod 10 =
Character'Pos (Code (Code'Last)) - Character'Pos ('0');
end Check_Cusip;
type Cusip_Array is array (Natural range <>) of Cusip;
Test_Array : Cusip_Array :=
("037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105");
begin
for I in Test_Array'Range loop
Put (Test_Array (I) & ": ");
if Check_Cusip (Test_Array (I)) then
Put_Line ("valid");
else
Put_Line ("not valid");
end if;
end loop;
end Cusip_Test; |
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
| #Action.21 | Action! | DEFINE PTR="CARD"
TYPE Date=[
INT year
BYTE month
BYTE day]
PTR ARRAY DayOfWeeks(7)
PTR ARRAY Months(12)
PROC Init()
DayOfWeeks(0)="Sunday" DayOfWeeks(1)="Monday"
DayOfWeeks(2)="Tuesday" DayOfWeeks(3)="Wednesday"
DayOfWeeks(4)="Thursday" DayOfWeeks(5)="Friday"
DayOfWeeks(6)="Saturday"
Months(0)="January" Months(1)="February"
Months(2)="March" Months(3)="April"
Months(4)="May" Months(5)="June"
Months(6)="July" Months(7)="August"
Months(8)="September" Months(9)="October"
Months(10)="November" Months(11)="December"
RETURN
;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
BYTE FUNC DayOfWeek(Date POINTER d) ;1<=m<=12, y>1752
BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
BYTE res
INT y
y=d.year
IF d.month<3 THEN
y==-1
FI
res=(y+y/4-y/100+y/400+t(d.month-1)+d.day) MOD 7
RETURN (res)
PROC PrintB2(BYTE x)
IF x<10 THEN
Put('0)
FI
PrintB(x)
RETURN
PROC PrintDateShort(Date POINTER d)
PrintI(d.year) Put('-)
PrintB2(d.month) Put('-)
PrintB2(d.day)
RETURN
PROC PrintDateLong(Date POINTER d)
BYTE wd
wd=DayOfWeek(d)
Print(DayOfWeeks(wd)) Print(", ")
Print(Months(d.month-1)) Put(' )
PrintB(d.day) Print(", ")
PrintI(d.year)
RETURN
PROC Main()
Date d
Init()
;There is no function to get the current date
;on Atari 8-bit computer
d.year=2021 d.month=9 d.day=1
PrintDateShort(d) PutE()
PrintDateLong(d) PutE()
RETURN |
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
| #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
with Ada.Text_IO; use Ada.Text_IO;
procedure Date_Format is
function Image (Month : Month_Number) return String is
begin
case Month is
when 1 => return "January";
when 2 => return "February";
when 3 => return "March";
when 4 => return "April";
when 5 => return "May";
when 6 => return "June";
when 7 => return "July";
when 8 => return "August";
when 9 => return "September";
when 10 => return "October";
when 11 => return "November";
when 12 => return "December";
end case;
end Image;
function Image (Day : Day_Name) return String is
begin
case Day is
when Monday => return "Monday";
when Tuesday => return "Tuesday";
when Wednesday => return "Wednesday";
when Thursday => return "Thursday";
when Friday => return "Friday";
when Saturday => return "Saturday";
when Sunday => return "Sunday";
end case;
end Image;
Today : Time := Clock;
begin
Put_Line (Image (Today) (1..10));
Put_Line
( Image (Day_Of_Week (Today)) & ", "
& Image (Ada.Calendar.Month (Today))
& Day_Number'Image (Ada.Calendar.Day (Today)) & ","
& Year_Number'Image (Ada.Calendar.Year (Today))
);
end Date_Format; |
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.
| #APL | APL | damm←{⎕IO←0
tbl←⍉⍪0 3 1 7 5 9 8 6 4 2
tbl⍪← 7 0 9 2 1 5 4 8 6 3
tbl⍪← 4 2 0 6 8 7 1 3 5 9
tbl⍪← 1 7 5 0 9 8 3 7 2 6
tbl⍪← 6 1 2 3 0 4 5 9 7 8
tbl⍪← 3 6 7 4 2 0 9 5 8 1
tbl⍪← 5 8 6 9 7 2 0 1 3 4
tbl⍪← 8 9 4 5 3 6 2 0 1 7
tbl⍪← 9 4 3 8 6 1 7 2 0 5
tbl⍪← 2 5 8 1 4 3 6 7 9 0
0={tbl[⍵;⍺]}/⌽0,⍵
} |
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.
| #AppleScript | AppleScript | -- Return a check digit value for the given integer value or numeric string.
-- The result is 0 if the input's last digit is already a valid check digit for it.
on damm(n)
set digits to {n mod 10}
set n to n div 10
repeat until (n is 0)
set beginning of digits to n mod 10
set n to n div 10
end repeat
script o
property 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}
end script
set interim to 0
repeat with d in digits
set interim to item (interim * 10 + d + 1) of o's table -- AppleScript indices are 1-based.
end repeat
return interim
end damm
-- Task code:
local testNumbers, possibilities, output, n
set testNumbers to {5724, 57240, 572400, 87591, 100}
-- Include a number with a check digit actually generated by the handler.
tell (random number 1000000) to set end of testNumbers to it * 10 + (my damm(it))
set possibilities to {" is invalid", " is valid"}
set output to {}
repeat with n in testNumbers
set end of output to (n as text) & item (((damm(n) is 0) as integer) + 1) of possibilities
end repeat
return output |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Julia | Julia | isCurzon(n, k) = (BigInt(k)^n + 1) % (k * n + 1) == 0
function printcurzons(klow, khigh)
for k in filter(iseven, klow:khigh)
n, curzons = 0, Int[]
while length(curzons) < 1000
isCurzon(n, k) && push!(curzons, n)
n += 1
end
println("Curzon numbers with k = $k:")
foreach(p -> print(lpad(p[2], 5), p[1] % 25 == 0 ? "\n" : ""), enumerate(curzons[1:50]))
println(" Thousandth Curzon with k = $k: ", curzons[1000])
end
end
printcurzons(2, 10)
|
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Pascal | Pascal |
program CurzonNumbers;
uses SysUtils;
const
MAX_CURZON_MEG = 100;
RC_LINE_LENGTH = 66;
procedure ListCurzonNumbers( base : integer);
var
k, n, m, x, testBit, maxCurzon : uint64;
nrHits : integer;
lineOut : string;
begin
maxCurzon := 1000000*MAX_CURZON_MEG;
k := uint64( base);
nrHits := 0;
n := 0;
WriteLn;
if Odd( base) then WriteLn( SysUtils.Format(
'Curzon numbers with base %d up to %d million', [base, MAX_CURZON_MEG]))
else WriteLn( SysUtils.Format(
'First 50 Curzon numbers with base %d', [base]));
lineOut := '';
repeat
inc(n); // possible (generalized) Curzon number
m := k*n + 1; // modulus
testBit := 1;
repeat testBit := testBit shl 1 until testBit > n;
testBit := testBit shr 2;
// Calculate k^n modulo m
x := k;
while testBit > 0 do begin
x := (x*x) mod m;
if (testBit and n) <> 0 then x := (x*k) mod m;
testBit := testBit shr 1;
end;
// n is a Curzon number to base k iff k^n + 1 is divisible by m
if (x + 1) mod m = 0 then begin
inc( nrHits);
if Odd( base) then
lineOut := lineOut + ' ' + SysUtils.IntToStr( n)
else if (nrHits <= 50) then
lineOut := lineOut + SysUtils.Format( '%5d', [n]);
if Length( lineOut) >= RC_LINE_LENGTH then begin
WriteLn( lineOut); lineOut := '';
end
else if (nrHits = 1000) then begin
if lineOut <> '' then begin
WriteLn( lineOut); lineOut := '';
end;
WriteLn( SysUtils.Format( '1000th = %d', [n]));
end;
end;
until (n = maxCurzon) or (nrHits = 1000);
if lineOut <> '' then WriteLn( lineOut);
end;
begin
ListCurzonNumbers( 2);
ListCurzonNumbers( 4);
ListCurzonNumbers( 6);
ListCurzonNumbers( 8);
ListCurzonNumbers(10);
ListCurzonNumbers( 3);
ListCurzonNumbers( 5);
ListCurzonNumbers( 7);
ListCurzonNumbers( 9);
ListCurzonNumbers(11);
end.
|
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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Finds solution for cut a rectangle up to 10 x 10.
local
i, j, n: Integer
r: GRID
do
n := 10
from
i := 1
until
i > n
loop
from
j := 1
until
j > i
loop
if i.bit_and (1) /= 1 or j.bit_and (1) /= 1 then
create r.make (i, j)
r.print_solution
end
j := j + 1
end
i := i + 1
end
end
end
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Phix | Phix | with javascript_semantics
atom t0 = time()
function bump(sequence half)
-- add a digit to valid halves
-- eg {0} --> {1..9} (no zeroes)
-- --> {11..99} ("")
-- --> {111..999}, etc
sequence res = {}
for i=1 to length(half) do
integer hi = half[i]*10
for digit=1 to 9 do
res &= hi+digit
end for
end for
return res
end function
procedure cyclops(string s="")
sequence res = {},
half = {0} -- valid digits, see bump()
integer left = 1, -- half[] before the 0
right = 0, -- half[] after the 0
hlen = 1, -- length(half)
cpow = 10, -- cyclops power (of 10)
bcpow = 1, -- blind cyclops power
cn = 0 -- cyclops number (scratch)
bool valid = false,
bPrime = match("prime",s),
bBlind = match("blind",s),
bPalin = match("palindromic",s)
while length(res)<50 or cn<=1e7 or not valid do
right += 1
if right>hlen then
right = 1
left += 1
if left>hlen then
half = bump(half)
hlen = length(half)
cpow *= 10
bcpow *= 10
left = 1
end if
end if
integer lh = half[left],
rh = half[right]
cn = lh*cpow+rh -- cyclops number
valid = not bPrime or is_prime(cn)
if valid and bBlind then
valid = is_prime(lh*bcpow+rh)
end if
if valid and bPalin then
valid = sprintf("%d",lh) == reverse(sprintf("%d",rh))
end if
if valid then
res = append(res,sprintf("%7d",cn))
end if
end while
printf(1,"First 50 %scyclops numbers:\n%s\n",{s,join_by(res[1..50],1,10)})
printf(1,"First %scyclops number > 10,000,000: %s at (one based) index: %d\n\n",
{s,res[$],length(res)})
end procedure
cyclops()
cyclops("prime ")
cyclops("blind prime ")
cyclops("palindromic prime ")
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #C.23 | C# | class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST")); //probably not the best way to do this
Console.ReadLine();
}
} |
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
| #Objective-C | Objective-C | #define RMAX32 ((1U << 31) - 1)
//--------------------------------------------------------------------
@interface Rand : NSObject
-(instancetype) initWithSeed: (int)seed;
-(int) next;
@property (nonatomic) long seed;
@end
@implementation Rand
-(instancetype) initWithSeed: (int)seed {
if ((self = [super init])) {
self.seed = seed;
}
return self;
}
-(int) next {
return (int) ((_seed = (_seed * 214013 + 2531011) & RMAX32) >> 16);
}
@end
//--------------------------------------------------------------------
@interface Card : NSObject
-(instancetype) initWithSequence: (int)n;
-(instancetype) initWithValue: (int)v suit: (int)s;
@property (nonatomic) int value;
@property (nonatomic) int suit;
@end
@implementation Card
-(instancetype) initWithSequence: (int)n {
return [self initWithValue:n/4 suit:n%4];
}
-(instancetype) initWithValue: (int)v suit: (int)s {
if ((self = [super init])) {
_value = v; _suit = s;
}
return self;
}
-(NSString *) description {
static NSString * const kSuits = @"♣♦♥♠";
static NSString * const kValues = @"A23456789TJQK";
return [NSString stringWithFormat:@"%C%C",
[kValues characterAtIndex:_value],
[kSuits characterAtIndex:_suit]];
}
@end
//--------------------------------------------------------------------
@interface Deck : NSObject
-(instancetype) initWithSeed: (int)seed;
@property (nonatomic, strong) NSMutableArray *cards;
@end
@implementation Deck
-(instancetype) initWithSeed: (int)seed {
if ((self = [super init])) {
Rand *r = [[Rand alloc] initWithSeed:seed];
_cards = [NSMutableArray array];
for (int i = 0; i < 52; i++)
[_cards addObject:[[Card alloc] initWithSequence:51 - i]];
for (int i = 0; i < 51; i++)
[_cards exchangeObjectAtIndex:i withObjectAtIndex:51 - [r next] % (52 - i)];
}
return self;
}
-(NSString *) description {
NSMutableString *s = [NSMutableString string];
for (int i = 0; i < [_cards count]; i++) {
[s appendString:[_cards[i] description]];
[s appendString:i%8==7 ? @"\n" : @" "];
}
return s;
}
@end
//--------------------------------------------------------------------
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Deck 1\n%@\n", [[Deck alloc] initWithSeed:1]);
NSLog(@"Deck 617\n%@\n", [[Deck alloc] initWithSeed:617]);
}
return 0;
} |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Rust | Rust | use std::convert::TryFrom;
mod test_mod {
use std::convert::TryFrom;
use std::fmt;
// Because the `i8` is not `pub` this cannot be directly constructed
// by code outside this module
#[derive(Copy, Clone, Debug)]
pub struct TwoDigit(i8);
impl TryFrom<i8> for TwoDigit {
type Error = &'static str;
fn try_from(value: i8) -> Result<Self, Self::Error> {
if value < -99 || value > 99 {
Err("Number cannot fit into two decimal digits")
} else {
Ok(TwoDigit(value))
}
}
}
impl Into<i8> for TwoDigit {
fn into(self) -> i8 { self.0 }
}
// This powers `println!`'s `{}` token.
impl fmt::Display for TwoDigit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
}
pub fn main() {
let foo = test_mod::TwoDigit::try_from(50).unwrap();
let bar: i8 = foo.into();
println!("{} == {}", foo, bar);
} |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Scala | Scala | class TinyInt(val int: Byte) {
import TinyInt._
require(int >= lower && int <= upper, "TinyInt out of bounds.")
override def toString = int.toString
}
object TinyInt {
val (lower, upper) = (1, 10)
def apply(i: Byte) = new TinyInt(i)
}
val test = (TinyInt.lower to TinyInt.upper).map(n => TinyInt(n.toByte)) |
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.
| #C | C | #include <stdio.h>
/* Calculate day of week in proleptic Gregorian calendar. Sunday == 0. */
int wday(int year, int month, int day)
{
int adjustment, mm, yy;
adjustment = (14 - month) / 12;
mm = month + 12 * adjustment - 2;
yy = year - adjustment;
return (day + (13 * mm - 1) / 5 +
yy + yy / 4 - yy / 100 + yy / 400) % 7;
}
int main()
{
int y;
for (y = 2008; y <= 2121; y++) {
if (wday(y, 12, 25) == 0) printf("%04d-12-25\n", y);
}
return 0;
} |
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
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns TRUE if cusip is a valid CUSIP code #
OP ISCUSIP = ( STRING cusip )BOOL:
IF ( UPB cusip - LWB cusip ) /= 8
THEN
# code is wrong length #
FALSE
ELSE
# string is 9 characters long - check it is valid #
STRING cusip digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"[ AT 0 ];
INT check digit := 0;
IF NOT char in string( cusip[ UPB cusip ], check digit, cusip digits )
THEN
# invalid check digit #
FALSE
ELSE
# OK so far compare the calculated check sum to the supplied one #
INT sum := 0;
INT c pos := LWB cusip - 1;
FOR i TO 8 DO
INT digit := 0;
IF NOT char in string( cusip[ i + c pos ], digit, cusip digits )
THEN
# invalid digit #
digit := -999
FI;
IF NOT ODD i
THEN
# even digit #
digit *:= 2
FI;
sum +:= ( digit OVER 10 ) + ( digit MOD 10 )
OD;
( 10 - ( sum MOD 10 ) ) MOD 10 = check digit
FI
FI ; # ISCUSIP #
# task test cases #
PROC test cusip = ( STRING cusip )VOID:
print( ( cusip, IF ISCUSIP cusip THEN " valid" ELSE " invalid" FI, newline ) );
test cusip( "037833100" );
test cusip( "17275R102" );
test cusip( "38259P508" );
test cusip( "594918104" );
test cusip( "68389X106" );
test cusip( "68389X105" )
END |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #ALGOL_68 | ALGOL 68 | # define the layout of the date/time as provided by the call to local time #
STRUCT ( INT sec, min, hour, mday, mon, year, wday, yday, isdst) tm = (6,5,4,3,2,1,7,~,8);
FORMAT # some useful format declarations #
ymd repr = $4d,"-"2d,"-"2d$,
month repr = $c("January","February","March","April","May","June","July",
"August","September","October","November","December")$,
week day repr = $c("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")$,
dmdy repr = $f(week day repr)", "f(month repr)" "g(-0)", "g(-4)$,
mon = $c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")$,
wday = $c("Sun","Mon","Tue","Wed","Thu","Fri","Sat")$,
tz = $c("MSK","MSD")$,
unix time repr = $f(wday)" "f(mon)z-d," "dd,":"dd,":"dd," "f(tz)" "dddd$;
[]INT now = local time;
printf((ymd repr, now[year OF tm:mday OF tm], $l$));
printf((dmdy repr, now[wday OF tm], now[mon OF tm], now[mday OF tm], now[year OF tm], $l$));
printf((unix time repr, now[wday OF tm], now[mon OF tm], now[mday OF tm],
now[hour OF tm:sec OF tm], now[isdst OF tm]+1, now[year OF tm], $l$)) |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #ARM_Assembly | ARM Assembly | .text
.global _start
@@@ Check if the zero-terminated ASCII string in [r0],
@@@ which should contain a decimal number, has a
@@@ matching check digit. Zero flag set if true,
@@@ check digit returned in r0.
damm: mov r1,#0 @ R1 = interim digit
ldr r2,=3f @ R2 = table base address
1: ldrb r3,[r0],#1 @ Load byte
tst r3,r3 @ Zero yet?
beq 2f @ If so, stop
sub r3,r3,#'0 @ Subtract ASCII 0
lsl r1,r1,#1 @ Table lookup
add r1,r1,r1,lsl#2 @ R3 = R1*10 + R3
add r3,r1,r3
ldrb r1,[r2,r3] @ R1 = new interim digit
b 1b @ Next value
2: movs r0,r1 @ Set flag according to r0.
bx lr
3: .byte 0,3,1,7,5,9,8,6,4,2 @ Since the table is constant,
.byte 7,0,9,2,1,5,4,8,6,3 @ it can be stored as part of
.byte 4,2,0,6,8,7,1,3,5,9 @ the subroutine.
.byte 1,7,5,0,9,8,3,4,2,6 @ This way the OS will even mark
.byte 6,1,2,3,0,4,5,9,7,8 @ it as read-only, so we can
.byte 3,6,7,4,2,0,9,5,8,1 @ be sure nothing changes it.
.byte 5,8,6,9,7,2,0,1,3,4
.byte 8,9,4,5,3,6,2,0,1,7
.byte 9,4,3,8,6,1,7,2,0,5
.byte 2,5,8,1,4,3,6,7,9,0
.align 4 @ Instructions must be word-aligned
@@@ Grab the argument from the command line, and see
@@@ if it matches.
_start: pop {r0} @ Is there even an argument?
cmp r0,#2
movne r7,#1 @ If not, exit immediately
swine #0
add sp,sp,#4 @ Discard program name
pop {r0} @ Grab argument
bl damm @ Check if it matches
ldreq r1,=pass @ If yes, say 'pass'
ldrne r1,=fail @ If not, say 'fail'
mov r0,#1 @ Print string to stdout
mov r2,#5 @ Both are 5 characters
mov r7,#4 @ Write syscall = 4
swi #0
mov r0,#0 @ Exit
mov r7,#1
swi #0
pass: .ascii "Pass\n"
fail: .ascii "Fail\n" |
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.
| #Arturo | Arturo | 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]
]
digits: function [x][map split x => [to :integer]]
damm?: function [z][zero? fold digits z .seed: 0 => [get get table]]
test: function [str][
result: switch damm? str -> "valid"
-> "invalid"
print [str "is" result]
]
loop ["5724" "5727" "112946" "112949"] => test |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[CurzonNumberQ]
CurzonNumberQ[b_Integer][n_Integer]:=PowerMod[b,n,b n+1]==b n
val=Select[Range[100000],CurzonNumberQ[2]];
Take[val,50]
val[[1000]]
val=Select[Range[100000],CurzonNumberQ[4]];
Take[val,50]
val[[1000]]
val=Select[Range[100000],CurzonNumberQ[6]];
Take[val,50]
val[[1000]]
val=Select[Range[100000],CurzonNumberQ[8]];
Take[val,50]
val[[1000]]
val=Select[Range[100000],CurzonNumberQ[10]];
Take[val,50]
val[[1000]] |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Perl | Perl | use strict;
use warnings;
use Math::AnyNum 'ipow';
sub curzon {
my($base,$cnt) = @_;
my($n,@C) = 0;
while (++$n) {
push @C, $n if 0 == (ipow($base,$n) + 1) % ($base * $n + 1);
return @C if $cnt == @C;
}
}
my $upto = 50;
for my $k (<2 4 6 8 10>) {
my @C = curzon($k,1000);
print "First $upto Curzon numbers using a base of $k:\n" .
(sprintf "@{['%5d' x $upto]}", @C[0..$upto-1]) =~ s/(.{125})/$1\n/gr;
print "Thousandth: $C[-1]\n\n";
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Phix | Phix | with javascript_semantics
include mpfr.e
mpz {pow,z} = mpz_inits(2)
for base=2 to 10 by 2 do
printf(1,"The first 50 Curzon numbers using a base of %d:\n",base)
integer count = 0, n = 1
mpz_set_si(pow,base)
while true do
mpz_add_ui(z,pow,1)
integer d = base*n + 1
if mpz_divisible_ui_p(z,d) then
count = count + 1
if count<=50 then
printf(1,"%5d%s",{n,iff(remainder(count,25)=0?"\n":"")})
elsif count=1000 then
printf(1,"One thousandth: %d\n\n",n)
exit
end if
end if
n += 1
mpz_mul_si(pow,pow,base)
end while
end for
|
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. | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <initializer_list>
#include <map>
#include <vector>
const int MAX_ALL_FACTORS = 100000;
const int algorithm = 2;
int divisions = 0;
//Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.
class Term {
private:
long m_coefficient;
long m_exponent;
public:
Term(long c, long e) : m_coefficient(c), m_exponent(e) {
// empty
}
Term(const Term &t) : m_coefficient(t.m_coefficient), m_exponent(t.m_exponent) {
// empty
}
long coefficient() const {
return m_coefficient;
}
long degree() const {
return m_exponent;
}
Term operator -() const {
return { -m_coefficient, m_exponent };
}
Term operator *(const Term &rhs) const {
return { m_coefficient * rhs.m_coefficient, m_exponent + rhs.m_exponent };
}
Term operator +(const Term &rhs) const {
if (m_exponent != rhs.m_exponent) {
throw std::runtime_error("Exponents not equal");
}
return { m_coefficient + rhs.m_coefficient, m_exponent };
}
friend std::ostream &operator<<(std::ostream &, const Term &);
};
std::ostream &operator<<(std::ostream &os, const Term &t) {
if (t.m_coefficient == 0) {
return os << '0';
}
if (t.m_exponent == 0) {
return os << t.m_coefficient;
}
if (t.m_coefficient == 1) {
if (t.m_exponent == 1) {
return os << 'x';
}
return os << "x^" << t.m_exponent;
}
if (t.m_coefficient == -1) {
if (t.m_exponent == 1) {
return os << "-x";
}
return os << "-x^" << t.m_exponent;
}
if (t.m_exponent == 1) {
return os << t.m_coefficient << 'x';
}
return os << t.m_coefficient << "x^" << t.m_exponent;
}
class Polynomial {
public:
std::vector<Term> polynomialTerms;
Polynomial() {
polynomialTerms.push_back({ 0, 0 });
}
Polynomial(std::initializer_list<int> values) {
if (values.size() % 2 != 0) {
throw std::runtime_error("Length must be even.");
}
bool ready = false;
long t;
for (auto v : values) {
if (ready) {
polynomialTerms.push_back({ t, v });
} else {
t = v;
}
ready = !ready;
}
std::sort(
polynomialTerms.begin(), polynomialTerms.end(),
[](const Term &t, const Term &u) {
return u.degree() < t.degree();
}
);
}
Polynomial(const std::vector<Term> &termList) {
if (termList.size() == 0) {
polynomialTerms.push_back({ 0, 0 });
} else {
for (auto t : termList) {
if (t.coefficient() != 0) {
polynomialTerms.push_back(t);
}
}
if (polynomialTerms.size() == 0) {
polynomialTerms.push_back({ 0, 0 });
}
std::sort(
polynomialTerms.begin(), polynomialTerms.end(),
[](const Term &t, const Term &u) {
return u.degree() < t.degree();
}
);
}
}
Polynomial(const Polynomial &p) : Polynomial(p.polynomialTerms) {
// empty
}
long leadingCoefficient() const {
return polynomialTerms[0].coefficient();
}
long degree() const {
return polynomialTerms[0].degree();
}
bool hasCoefficientAbs(int coeff) {
for (auto term : polynomialTerms) {
if (abs(term.coefficient()) == coeff) {
return true;
}
}
return false;
}
Polynomial operator+(const Term &term) const {
std::vector<Term> termList;
bool added = false;
for (size_t index = 0; index < polynomialTerms.size(); index++) {
auto currentTerm = polynomialTerms[index];
if (currentTerm.degree() == term.degree()) {
added = true;
if (currentTerm.coefficient() + term.coefficient() != 0) {
termList.push_back(currentTerm + term);
}
} else {
termList.push_back(currentTerm);
}
}
if (!added) {
termList.push_back(term);
}
return Polynomial(termList);
}
Polynomial operator*(const Term &term) const {
std::vector<Term> termList;
for (size_t index = 0; index < polynomialTerms.size(); index++) {
auto currentTerm = polynomialTerms[index];
termList.push_back(currentTerm * term);
}
return Polynomial(termList);
}
Polynomial operator+(const Polynomial &p) const {
std::vector<Term> termList;
int thisCount = polynomialTerms.size();
int polyCount = p.polynomialTerms.size();
while (thisCount > 0 || polyCount > 0) {
if (thisCount == 0) {
auto polyTerm = p.polynomialTerms[polyCount - 1];
termList.push_back(polyTerm);
polyCount--;
} else if (polyCount == 0) {
auto thisTerm = polynomialTerms[thisCount - 1];
termList.push_back(thisTerm);
thisCount--;
} else {
auto polyTerm = p.polynomialTerms[polyCount - 1];
auto thisTerm = polynomialTerms[thisCount - 1];
if (thisTerm.degree() == polyTerm.degree()) {
auto t = thisTerm + polyTerm;
if (t.coefficient() != 0) {
termList.push_back(t);
}
thisCount--;
polyCount--;
} else if (thisTerm.degree() < polyTerm.degree()) {
termList.push_back(thisTerm);
thisCount--;
} else {
termList.push_back(polyTerm);
polyCount--;
}
}
}
return Polynomial(termList);
}
Polynomial operator/(const Polynomial &v) {
divisions++;
Polynomial q;
Polynomial r(*this);
long lcv = v.leadingCoefficient();
long dv = v.degree();
while (r.degree() >= v.degree()) {
long lcr = r.leadingCoefficient();
long s = lcr / lcv;
Term term(s, r.degree() - dv);
q = q + term;
r = r + v * -term;
}
return q;
}
friend std::ostream &operator<<(std::ostream &, const Polynomial &);
};
std::ostream &operator<<(std::ostream &os, const Polynomial &p) {
auto it = p.polynomialTerms.cbegin();
auto end = p.polynomialTerms.cend();
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
if (it->coefficient() > 0) {
os << " + " << *it;
} else {
os << " - " << -*it;
}
it = std::next(it);
}
return os;
}
std::vector<int> getDivisors(int number) {
std::vector<int> divisiors;
long root = (long)sqrt(number);
for (int i = 1; i <= root; i++) {
if (number % i == 0) {
divisiors.push_back(i);
int div = number / i;
if (div != i && div != number) {
divisiors.push_back(div);
}
}
}
return divisiors;
}
std::map<int, std::map<int, int>> allFactors;
std::map<int, int> getFactors(int number) {
if (allFactors.find(number) != allFactors.end()) {
return allFactors[number];
}
std::map<int, int> factors;
if (number % 2 == 0) {
auto factorsDivTwo = getFactors(number / 2);
factors.insert(factorsDivTwo.begin(), factorsDivTwo.end());
if (factors.find(2) != factors.end()) {
factors[2]++;
} else {
factors.insert(std::make_pair(2, 1));
}
if (number < MAX_ALL_FACTORS) {
allFactors.insert(std::make_pair(number, factors));
}
return factors;
}
long root = (long)sqrt(number);
long i = 3;
while (i <= root) {
if (number % i == 0) {
auto factorsDivI = getFactors(number / i);
factors.insert(factorsDivI.begin(), factorsDivI.end());
if (factors.find(i) != factors.end()) {
factors[i]++;
} else {
factors.insert(std::make_pair(i, 1));
}
if (number < MAX_ALL_FACTORS) {
allFactors.insert(std::make_pair(number, factors));
}
return factors;
}
i += 2;
}
factors.insert(std::make_pair(number, 1));
if (number < MAX_ALL_FACTORS) {
allFactors.insert(std::make_pair(number, factors));
}
return factors;
}
std::map<int, Polynomial> COMPUTED;
Polynomial cyclotomicPolynomial(int n) {
if (COMPUTED.find(n) != COMPUTED.end()) {
return COMPUTED[n];
}
if (n == 1) {
// Polynomial: x - 1
Polynomial p({ 1, 1, -1, 0 });
COMPUTED.insert(std::make_pair(1, p));
return p;
}
auto factors = getFactors(n);
if (factors.find(n) != factors.end()) {
// n prime
std::vector<Term> termList;
for (int index = 0; index < n; index++) {
termList.push_back({ 1, index });
}
Polynomial cyclo(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (factors.size() == 2 && factors.find(2) != factors.end() && factors[2] == 1 && factors.find(n / 2) != factors.end() && factors[n / 2] == 1) {
// n = 2p
int prime = n / 2;
std::vector<Term> termList;
int coeff = -1;
for (int index = 0; index < prime; index++) {
coeff *= -1;
termList.push_back({ coeff, index });
}
Polynomial cyclo(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (factors.size() == 1 && factors.find(2) != factors.end()) {
// n = 2^h
int h = factors[2];
std::vector<Term> termList;
termList.push_back({ 1, (int)pow(2, h - 1) });
termList.push_back({ 1, 0 });
Polynomial cyclo(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (factors.size() == 1 && factors.find(n) != factors.end()) {
// n = p^k
int p = 0;
int k = 0;
for (auto iter = factors.begin(); iter != factors.end(); ++iter) {
p = iter->first;
k = iter->second;
}
std::vector<Term> termList;
for (int index = 0; index < p; index++) {
termList.push_back({ 1, index * (int)pow(p, k - 1) });
}
Polynomial cyclo(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (factors.size() == 2 && factors.find(2) != factors.end()) {
// n = 2^h * p^k
int p = 0;
for (auto iter = factors.begin(); iter != factors.end(); ++iter) {
if (iter->first != 2) {
p = iter->first;
}
}
std::vector<Term> termList;
int coeff = -1;
int twoExp = (int)pow(2, factors[2] - 1);
int k = factors[p];
for (int index = 0; index < p; index++) {
coeff *= -1;
termList.push_back({ coeff, index * twoExp * (int)pow(p, k - 1) });
}
Polynomial cyclo(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (factors.find(2) != factors.end() && ((n / 2) % 2 == 1) && (n / 2) > 1) {
// CP(2m)[x] = CP(-m)[x], n odd integer > 1
auto cycloDiv2 = cyclotomicPolynomial(n / 2);
std::vector<Term> termList;
for (auto term : cycloDiv2.polynomialTerms) {
if (term.degree() % 2 == 0) {
termList.push_back(term);
} else {
termList.push_back(-term);
}
}
Polynomial cyclo(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
}
// General Case
if (algorithm == 0) {
// slow - uses basic definition
auto divisors = getDivisors(n);
// Polynomial: (x^n - 1)
Polynomial cyclo({ 1, n, -1, 0 });
for (auto i : divisors) {
auto p = cyclotomicPolynomial(i);
cyclo = cyclo / p;
}
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (algorithm == 1) {
// Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
auto divisors = getDivisors(n);
int maxDivisor = INT_MIN;
for (auto div : divisors) {
maxDivisor = std::max(maxDivisor, div);
}
std::vector<int> divisorExceptMax;
for (auto div : divisors) {
if (maxDivisor % div != 0) {
divisorExceptMax.push_back(div);
}
}
// Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
auto cyclo = Polynomial({ 1, n, -1, 0 }) / Polynomial({ 1, maxDivisor, -1, 0 });
for (int i : divisorExceptMax) {
auto p = cyclotomicPolynomial(i);
cyclo = cyclo / p;
}
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else if (algorithm == 2) {
// Fastest
// Let p ; q be primes such that p does not divide n, and q q divides n.
// Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
int m = 1;
auto cyclo = cyclotomicPolynomial(m);
std::vector<int> primes;
for (auto iter = factors.begin(); iter != factors.end(); ++iter) {
primes.push_back(iter->first);
}
std::sort(primes.begin(), primes.end());
for (auto prime : primes) {
// CP(m)[x]
auto cycloM = cyclo;
// Compute CP(m)[x^p].
std::vector<Term> termList;
for (auto t : cycloM.polynomialTerms) {
termList.push_back({ t.coefficient(), t.degree() * prime });
}
cyclo = Polynomial(termList) / cycloM;
m = m * prime;
}
// Now, m is the largest square free divisor of n
int s = n / m;
// Compute CP(n)[x] = CP(m)[x^s]
std::vector<Term> termList;
for (auto t : cyclo.polynomialTerms) {
termList.push_back({ t.coefficient(), t.degree() * s });
}
cyclo = Polynomial(termList);
COMPUTED.insert(std::make_pair(n, cyclo));
return cyclo;
} else {
throw std::runtime_error("Invalid algorithm");
}
}
int main() {
// initialization
std::map<int, int> factors;
factors.insert(std::make_pair(2, 1));
allFactors.insert(std::make_pair(2, factors));
// rest of main
std::cout << "Task 1: cyclotomic polynomials for n <= 30:\n";
for (int i = 1; i <= 30; i++) {
auto p = cyclotomicPolynomial(i);
std::cout << "CP[" << i << "] = " << p << '\n';
}
std::cout << "Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\n";
int n = 0;
for (int i = 1; i <= 10; i++) {
while (true) {
n++;
auto cyclo = cyclotomicPolynomial(n);
if (cyclo.hasCoefficientAbs(i)) {
std::cout << "CP[" << n << "] has coefficient with magnitude = " << i << '\n';
n--;
break;
}
}
}
return 0;
} |
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.
| #Elixir | Elixir | import Integer
defmodule Rectangle do
def cut_it(h, w) when is_odd(h) and is_odd(w), do: 0
def cut_it(h, w) when is_odd(h), do: cut_it(w, h)
def cut_it(_, 1), do: 1
def cut_it(h, 2), do: h
def cut_it(2, w), do: w
def cut_it(h, w) do
grid = List.duplicate(false, (h + 1) * (w + 1))
t = div(h, 2) * (w + 1) + div(w, 2)
if is_odd(w) do
grid = grid |> List.replace_at(t, true) |> List.replace_at(t+1, true)
walk(h, w, div(h, 2), div(w, 2) - 1, grid) + walk(h, w, div(h, 2) - 1, div(w, 2), grid) * 2
else
grid = grid |> List.replace_at(t, true)
count = walk(h, w, div(h, 2), div(w, 2) - 1, grid)
if h == w, do: count * 2,
else: count + walk(h, w, div(h, 2) - 1, div(w, 2), grid)
end
end
defp walk(h, w, y, x, grid, count\\0)
defp walk(h, w, y, x,_grid, count) when y in [0,h] or x in [0,w], do: count+1
defp walk(h, w, y, x, grid, count) do
blen = (h + 1) * (w + 1) - 1
t = y * (w + 1) + x
grid = grid |> List.replace_at(t, true) |> List.replace_at(blen-t, true)
Enum.reduce(next(w), count, fn {nt, dy, dx}, cnt ->
if Enum.at(grid, t+nt), do: cnt, else: cnt + walk(h, w, y+dy, x+dx, grid)
end)
end
defp next(w), do: [{w+1, 1, 0}, {-w-1, -1, 0}, {-1, 0, -1}, {1, 0, 1}] # {next,dy,dx}
end
Enum.each(1..9, fn w ->
Enum.each(1..w, fn h ->
if is_even(w * h), do: IO.puts "#{w} x #{h}: #{Rectangle.cut_it(w, h)}"
end)
end) |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Raku | Raku | use Lingua::EN::Numbers;
my @cyclops = 0, |flat lazy ^∞ .map: -> $exp {
my @oom = (exp($exp, 10) ..^ exp($exp + 1, 10)).grep: { !.contains: 0 }
|@oom.hyper.map: { $_ ~ 0 «~« @oom }
}
my @prime-cyclops = @cyclops.grep: { .is-prime };
for '', @cyclops,
'prime ', @prime-cyclops,
'blind prime ', @prime-cyclops.grep( { .trans('0' => '').is-prime } ),
'palindromic prime ', @prime-cyclops.grep( { $_ eq .flip } )
-> $type, $iterator {
say "\n\nFirst 50 {$type}cyclops numbers:\n" ~ $iterator[^50].batch(10)».fmt("%7d").join("\n") ~
"\n\nFirst {$type}cyclops number > 10,000,000: " ~ comma($iterator.first: * > 1e7 ) ~
" - at (zero based) index: " ~ comma $iterator.first: * > 1e7, :k;
} |
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.
| #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>
int main( ) {
std::string datestring ("March 7 2009 7:30pm EST" ) ;
//we must first parse the date string into a date , a time and a time
//zone part , to take account of present restrictions in the input facets
//of the Boost::DateTime library used for this example
std::vector<std::string> elements ;
//parsing the date string
boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
elements[ 2 ] ; //we must add 0 to avoid trouble with the boost::date_input format strings
std::string timepart = elements[ 3 ] ;
std::string timezone = elements[ 4 ] ;
const char meridians[ ] = { 'a' , 'p' } ;
//we have to find out if the time is am or pm, to change the hours appropriately
std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
timepart = timepart.substr( 0 , found ) ; //we chop off am or pm
elements.clear( ) ;
boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
long hour = std::atol( (elements.begin( ))->c_str( ) ) ;// hours in the string
if ( twelve_hour == "p" ) //it's post meridian, we're converting to 24-hour-clock
hour += 12 ;
long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ;
boost::local_time::tz_database tz_db ;
tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
//according to the time zone database, this corresponds to one possible EST time zone
boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
//this is the string input format to initialize the date field
boost::gregorian::date_input_facet *f =
new boost::gregorian::date_input_facet( "%B %d %Y" ) ;
std::stringstream ss ;
ss << datepart ;
ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
boost::gregorian::date d ;
ss >> d ;
boost::posix_time::time_duration td ( hour , minute , 0 ) ;
//that's how we initialize the New York local time , by using date and adding
//time duration with values coming from parsed date input string
boost::local_time::local_date_time lt ( d , td , dyc ,
boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
std::cout << "local time: " << lt << '\n' ;
ss.str( "" ) ;
ss << lt ;
//we have to add 12 hours, so a new time duration object is created
boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
boost::local_time::local_date_time ltlater = lt + td2 ; //local time 12 hours later
boost::gregorian::date_facet *f2 =
new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ;
//what's New York time in the Berlin time zone ?
boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; //choose the output forman appropriate for the time zone
std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
return 0 ;
}
|
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
| #OCaml | OCaml | let srnd x =
(* since OCaml's built-in int type is at least 31 (note: not 32) bits wide,
and this problem takes mod 2^31, it is just enough if we treat it as
an unsigned integer, which means taking the logical right shift *)
let seed = ref x in
fun () ->
seed := (!seed * 214013 + 2531011) land 0x7fffffff;
!seed lsr 16
let deal s =
let rnd = srnd s in
let t = Array.init 52 (fun i -> i) in
let cards =
Array.init 52 (fun j ->
let n = 52 - j in
let i = rnd() mod n in
let this = t.(i) in
t.(i) <- t.(pred n);
this)
in
(cards)
let show cards =
let suits = "CDHS"
and nums = "A23456789TJQK" in
Array.iteri (fun i card ->
Printf.printf "%c%c%c"
nums.[card / 4]
suits.[card mod 4]
(if (i mod 8) = 7 then '\n' else ' ')
) cards;
print_newline()
let () =
let s =
try int_of_string Sys.argv.(1)
with _ -> 11982
in
Printf.printf "Deal %d:\n" s;
let cards = deal s in
show cards |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Sidef | Sidef | subset Integer < Number { .is_int }
subset MyIntLimit < Integer { . ~~ (1 ..^ 10) }
class MyInt(value < MyIntLimit) {
method to_s { value.to_s }
method get_value { value.get_value }
method ==(Number x) { value == x }
method ==(MyInt x) { value == x.value }
method AUTOLOAD(_, name, *args) {
var results = [value.(name)(args.map {|n| Number(n) }...)]
results.map{|r| r.kind_of(Number) ? MyInt(r.int) : r}...
}
}
#
## Example:
#
var a = MyInt(2) # creates a new object of type `MyInt`
a += 7 # adds 7 to a
say a # => 9
say a/2 # => 4
var b = (a - 3) # b is of type `MyInt`
say b # => 6
say a.as_hex.dump # => "9" -- an hexadecimal string
a -= 6 # a=3
var c = (a + b) # MyInt(3) + MyInt(6)
say c # => 9
say c.class # => MyInt
a *= 2 # a=6
say a+b # error: class `MyInt` does not match MyInt(12) |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of 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.
| #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
for (int i = 2008; i <= 2121; i++)
{
DateTime date = new DateTime(i, 12, 25);
if (date.DayOfWeek == DayOfWeek.Sunday)
{
Console.WriteLine(date.ToString("dd MMM yyyy"));
}
}
}
} |
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
| #ALGOL_W | ALGOL W | begin % returns true if cusip is a valid CUSIP code %
logical procedure isCusip ( string(9) value cusip ) ;
begin
% returns the base 39 digit corresponding to a character of a CUSIP code %
integer procedure cusipDigit( string(1) value cChar ) ;
if cChar >= "0" and cChar <= "9" then ( decode( cChar ) - decode( "0" ) )
else if cChar >= "A" and cChar <= "Z" then ( decode( cChar ) - decode( "A" ) ) + 10
else if cChar = "*" then 36
else if cChar = "@" then 37
else if cChar = "#" then 38
else % invalid digit % -999 ;
integer checkDigit, sum;
checkDigit := cusipDigit( cusip( 8 // 1 ) );
for cPos := 1 until 8 do begin
integer digit;
digit := cusipDigit( cusip( ( cPos - 1 ) // 1 ) );
if not odd( cPos ) then digit := digit * 2;
sum := sum + ( digit div 10 ) + ( digit rem 10 )
end for_cPos ;
( ( 10 - ( sum rem 10 ) ) rem 10 ) = checkDigit
end isCusip ;
begin % task test cases %
procedure testCusip ( string(9) value cusip ) ;
write( s_w := 0, cusip, if isCusip( cusip ) then " valid" else " invalid" );
testCusip( "037833100" );
testCusip( "17275R102" );
testCusip( "38259P508" );
testCusip( "594918104" );
testCusip( "68389X106" );
testCusip( "68389X105" )
end testCases
end. |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- isCusip :: String -> Bool
on isCusip(s)
set cs to "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*&#"
set ns to mapMaybe(elemIndex(cs), s)
script go
on |λ|(f, x)
set fx to apply(f, x)
(fx div 10) + (fx mod 10)
end |λ|
end script
9 = length of ns and item -1 of ns = (10 - (sum(zipWith(go, ¬
cycle({my identity, my double}), ¬
take(8, ns))) mod 10)) mod 10
end isCusip
-------------------------- TEST ---------------------------
on run
script test
on |λ|(s)
s & " -> " & isCusip(s)
end |λ|
end script
unlines(map(test, ¬
{"037833100", "17275R102", "38259P508", ¬
"594918104", "68389X106", "68389X105"}))
end run
-- 037833100 -> true
-- 17275R102 -> true
-- 38259P508 -> true
-- 594918104 -> true
-- 68389X106 -> false
-- 68389X105 -> true
-------------------- GENERIC FUNCTIONS --------------------
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
-- Constructor for a pair of values, possibly of two different types.
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- apply ($) :: (a -> b) -> a -> b
on apply(f, x)
-- The value of f(x)
mReturn(f)'s |λ|(x)
end apply
-- cycle :: [a] -> Generator [a]
on cycle(xs)
script
property lng : 1 + (length of xs)
property i : missing value
on |λ|()
if missing value is i then
set i to 1
else
set nxt to (1 + i) mod lng
if 0 = ((1 + i) mod lng) then
set i to 1
else
set i to nxt
end if
end if
return item i of xs
end |λ|
end script
end cycle
-- double :: Num -> Num
on double(x)
2 * x
end double
-- elemIndex :: Eq a => [a] -> a -> Maybe Int
on elemIndex(xs)
script
on |λ|(x)
set lng to length of xs
repeat with i from 1 to lng
if x = (item i of xs) then return Just(i - 1)
end repeat
return Nothing()
end |λ|
end script
end elemIndex
-- identity :: a -> a
on identity(x)
-- The argument unchanged.
x
end identity
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- The mapMaybe function is a version of map which can throw out
-- elements. In particular, the functional argument returns
-- something of type Maybe b. If this is Nothing, no element is
-- added on to the result list. If it just Just b, then b is
-- included in the result list.
-- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
on mapMaybe(mf, xs)
script
property g : mReturn(mf)
on |λ|(a, x)
set mb to g's |λ|(x)
if Nothing of mb then
a
else
a & (Just of mb)
end if
end |λ|
end script
foldl(result, {}, xs)
end mapMaybe
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith |
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
| #Apex | Apex |
Datetime dtNow = datetime.now();
String strDt1 = dtNow.format('yyyy-MM-dd');
String strDt2 = dtNow.format('EEEE, MMMM dd, yyyy');
system.debug(strDt1); // "2007-11-10"
system.debug(strDt2); //"Sunday, November 10, 2007"
|
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.
| #AutoHotkey | AutoHotkey | Damm(num){
row := 1, Damm := [[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]]
for i, v in StrSplit(SubStr(num, 1, -1)){
++row := Damm[row, v+1]
}
return (SubStr(num, 0)=row-1 && !Damm[row, row])
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Quackery | Quackery | [ number$
space 4 of swap join
-5 split nip echo$ ] is rjust ( n --> )
[ 5 times
[ 10 times
[ behead rjust ]
cr ]
drop ] is display ( [ --> )
[ temp take
over join
temp put ] is dax ( [ --> )
[ 2dup ** 1+
unrot * 1+ mod 0 = ] is curzon ( n n --> b )
5 times
[ i^ 1+ 2 *
say "Curzon numbers base "
dup echo cr
1
[] temp put
[ 2dup curzon if dax
temp share
size 1000 < while
1+ again ]
2drop
temp take
50 split swap display
say " ... "
-1 peek echo cr cr ]
|
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Raku | Raku | sub curzon ($base) { lazy (1..∞).hyper.map: { $_ if (exp($_, $base) + 1) %% ($base × $_ + 1) } };
for <2 4 6 8 10> {
my $curzon = .&curzon;
say "\nFirst 50 Curzon numbers using a base of $_:\n" ~
$curzon[^50].batch(25)».fmt("%4s").join("\n") ~
"\nOne thousandth: " ~ $curzon[999]
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Rust | Rust | // [dependencies]
// rug = "1.15.0"
fn is_curzon(n: u32, k: u32) -> bool {
use rug::{Complete, Integer};
(Integer::u_pow_u(k, n).complete() + 1) % (k * n + 1) == 0
}
fn main() {
for k in (2..=10).step_by(2) {
println!("Curzon numbers with base {k}:");
let mut count = 0;
let mut n = 1;
while count < 50 {
if is_curzon(n, k) {
count += 1;
print!("{:4}{}", n, if count % 10 == 0 { "\n" } else { " " });
}
n += 1;
}
loop {
if is_curzon(n, k) {
count += 1;
if count == 1000 {
break;
}
}
n += 1;
}
println!("1000th Curzon number with base {k}: {n}\n");
}
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Sidef | Sidef | func is_curzon(n, k) {
powmod(k, n, k*n + 1).is_congruent(-1, k*n + 1) && (n > 0)
}
for k in (2 .. 10 `by` 2) {
say "\nFirst 50 Curzon numbers using a base of #{k}:"
say 50.by {|n| is_curzon(n, k) }.join(' ')
say ("1000th term: ", 1000.th {|n| is_curzon(n,k) })
} |
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. | #C.23 | C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using IntMap = System.Collections.Generic.Dictionary<int, int>;
public static class CyclotomicPolynomial
{
public static void Main2() {
Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:");
for (int i = 1; i <= 30; i++) {
var p = GetCyclotomicPolynomial(i);
Console.WriteLine($"CP[{i}] = {p.ToString()}");
}
Console.WriteLine();
Console.WriteLine("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:");
for (int i = 1, n = 0; i <= 10; i++) {
while (true) {
n++;
var p = GetCyclotomicPolynomial(n);
if (p.Any(t => Math.Abs(t.Coefficient) == i)) {
Console.WriteLine($"CP[{n}] has coefficient with magnitude = {i}");
n--;
break;
}
}
}
}
private const int MaxFactors = 100_000;
private const int Algorithm = 2;
private static readonly Term x = new Term(1, 1);
private static readonly Dictionary<int, Polynomial> polyCache =
new Dictionary<int, Polynomial> { [1] = x - 1 };
private static readonly Dictionary<int, IntMap> factorCache =
new Dictionary<int, IntMap> { [2] = new IntMap { [2] = 1 } };
private static Polynomial GetCyclotomicPolynomial(in int n) {
if (polyCache.TryGetValue(n, out var result)) return result;
var factors = GetFactors(n);
if (factors.ContainsKey(n)) { //n is prime
result = new Polynomial(from exp in ..n select x[exp]);
} else if (factors.Count == 2 && factors.Contains(2, 1) && factors.Contains(n/2, 1)) { //n = 2p
result = new Polynomial(from i in ..(n/2) select (IsOdd(i) ? -x : x)[i]);
} else if (factors.Count == 1 && factors.TryGetValue(2, out int h)) { //n = 2^h
result = x[1<<(h-1)] + 1;
} else if (factors.Count == 1 && !factors.ContainsKey(n)) { // n = p^k
(int p, int k) = factors.First();
result = new Polynomial(from i in ..p select x[i * (int)Math.Pow(p, k-1)]);
} else if (factors.Count == 2 && factors.ContainsKey(2)) { //n = 2^h * p^k
(int p, int k) = factors.First(entry => entry.Key != 2);
int twoExp = 1 << (factors[2] - 1);
result = new Polynomial(from i in ..p select (IsOdd(i) ? -x : x)[i * twoExp * (int)Math.Pow(p, k-1)]);
} else if (factors.ContainsKey(2) && IsOdd(n/2) && n/2 > 1) { // CP(2m)[x] = CP[-m][x], n is odd > 1
Polynomial cycloDiv2 = GetCyclotomicPolynomial(n/2);
result = new Polynomial(from term in cycloDiv2 select IsOdd(term.Exponent) ? -term : term);
#pragma warning disable CS0162
} else if (Algorithm == 0) {
var divisors = GetDivisors(n);
result = x[n] - 1;
foreach (int d in divisors) result /= GetCyclotomicPolynomial(d);
} else if (Algorithm == 1) {
var divisors = GetDivisors(n).ToList();
int maxDivisor = divisors.Max();
result = (x[n] - 1) / (x[maxDivisor] - 1);
foreach (int d in divisors.Where(div => maxDivisor % div == 0)) {
result /= GetCyclotomicPolynomial(d);
}
} else if (Algorithm == 2) {
int m = 1;
result = GetCyclotomicPolynomial(m);
var primes = factors.Keys.ToList();
primes.Sort();
foreach (int prime in primes) {
var cycloM = result;
result = new Polynomial(from term in cycloM select term.Coefficient * x[term.Exponent * prime]);
result /= cycloM;
m *= prime;
}
int s = n / m;
result = new Polynomial(from term in result select term.Coefficient * x[term.Exponent * s]);
#pragma warning restore CS0162
} else {
throw new InvalidOperationException("Invalid algorithm");
}
polyCache[n] = result;
return result;
}
private static bool IsOdd(int i) => (i & 1) != 0;
private static bool Contains(this IntMap map, int key, int value) => map.TryGetValue(key, out int v) && v == value;
private static int GetOrZero(this IntMap map, int key) => map.TryGetValue(key, out int v) ? v : 0;
private static IEnumerable<T> Select<T>(this Range r, Func<int, T> f) => Enumerable.Range(r.Start.Value, r.End.Value - r.Start.Value).Select(f);
private static IntMap GetFactors(in int n) {
if (factorCache.TryGetValue(n, out var factors)) return factors;
factors = new IntMap();
if (!IsOdd(n)) {
foreach (var entry in GetFactors(n/2)) factors.Add(entry.Key, entry.Value);
factors[2] = factors.GetOrZero(2) + 1;
return Cache(n, factors);
}
for (int i = 3; i * i <= n; i+=2) {
if (n % i == 0) {
foreach (var entry in GetFactors(n/i)) factors.Add(entry.Key, entry.Value);
factors[i] = factors.GetOrZero(i) + 1;
return Cache(n, factors);
}
}
factors[n] = 1;
return Cache(n, factors);
}
private static IntMap Cache(int n, IntMap factors) {
if (n < MaxFactors) factorCache[n] = factors;
return factors;
}
private static IEnumerable<int> GetDivisors(int n) {
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
yield return i;
int div = n / i;
if (div != i && div != n) yield return div;
}
}
}
public sealed class Polynomial : IEnumerable<Term>
{
public Polynomial() { }
public Polynomial(params Term[] terms) : this(terms.AsEnumerable()) { }
public Polynomial(IEnumerable<Term> terms) {
Terms.AddRange(terms);
Simplify();
}
private List<Term>? terms;
private List<Term> Terms => terms ??= new List<Term>();
public int Count => terms?.Count ?? 0;
public int Degree => Count == 0 ? -1 : Terms[0].Exponent;
public int LeadingCoefficient => Count == 0 ? 0 : Terms[0].Coefficient;
public IEnumerator<Term> GetEnumerator() => Terms.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public override string ToString() => Count == 0 ? "0" : string.Join(" + ", Terms).Replace("+ -", "- ");
public static Polynomial operator *(Polynomial p, Term t) => new Polynomial(from s in p select s * t);
public static Polynomial operator +(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms));
public static Polynomial operator -(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms.Select(t => -t)));
public static Polynomial operator *(Polynomial p, Polynomial q) => new Polynomial(from s in p from t in q select s * t);
public static Polynomial operator /(Polynomial p, Polynomial q) => p.Divide(q).quotient;
public (Polynomial quotient, Polynomial remainder) Divide(Polynomial divisor) {
if (Degree < 0) return (new Polynomial(), this);
Polynomial quotient = new Polynomial();
Polynomial remainder = this;
int lcv = divisor.LeadingCoefficient;
int dv = divisor.Degree;
while (remainder.Degree >= divisor.Degree) {
int lcr = remainder.LeadingCoefficient;
Term div = new Term(lcr / lcv, remainder.Degree - dv);
quotient.Terms.Add(div);
remainder += divisor * -div;
}
quotient.Simplify();
remainder.Simplify();
return (quotient, remainder);
}
private void Simplify() {
if (Count < 2) return;
Terms.Sort((a, b) => -a.CompareTo(b));
for (int i = Terms.Count - 1; i > 0; i--) {
Term s = Terms[i-1];
Term t = Terms[i];
if (t.Exponent == s.Exponent) {
Terms[i-1] = new Term(s.Coefficient + t.Coefficient, s.Exponent);
Terms.RemoveAt(i);
}
}
Terms.RemoveAll(t => t.IsZero);
}
}
public readonly struct Term : IEquatable<Term>, IComparable<Term>
{
public Term(int coefficient, int exponent = 0) => (Coefficient, Exponent) = (coefficient, exponent);
public Term this[int exponent] => new Term(Coefficient, exponent); //Using x[exp] because x^exp has low precedence
public int Coefficient { get; }
public int Exponent { get; }
public bool IsZero => Coefficient == 0;
public static Polynomial operator +(Term left, Term right) => new Polynomial(left, right);
public static Polynomial operator -(Term left, Term right) => new Polynomial(left, -right);
public static implicit operator Term(int coefficient) => new Term(coefficient);
public static Term operator -(Term t) => new Term(-t.Coefficient, t.Exponent);
public static Term operator *(Term left, Term right) => new Term(left.Coefficient * right.Coefficient, left.Exponent + right.Exponent);
public static bool operator ==(Term left, Term right) => left.Equals(right);
public static bool operator !=(Term left, Term right) => !left.Equals(right);
public static bool operator <(Term left, Term right) => left.CompareTo(right) < 0;
public static bool operator >(Term left, Term right) => left.CompareTo(right) > 0;
public static bool operator <=(Term left, Term right) => left.CompareTo(right) <= 0;
public static bool operator >=(Term left, Term right) => left.CompareTo(right) >= 0;
public bool Equals(Term other) => Exponent == other.Exponent && Coefficient == other.Coefficient;
public override bool Equals(object? obj) => obj is Term t && Equals(t);
public override int GetHashCode() => Coefficient.GetHashCode() * 31 + Exponent.GetHashCode();
public int CompareTo(Term other) {
int c = Exponent.CompareTo(other.Exponent);
if (c != 0) return c;
return Coefficient.CompareTo(other.Coefficient);
}
public override string ToString() => (Coefficient, Exponent) switch {
(0, _) => "0",
(_, 0) => $"{Coefficient}",
(1, 1) => "x",
(-1, 1) => "-x",
(_, 1) => $"{Coefficient}x",
(1, _) => $"x^{Exponent}",
(-1, _) => $"-x^{Exponent}",
_ => $"{Coefficient}x^{Exponent}"
};
}
} |
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.
| #Go | Go | package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
} |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #REXX | REXX | /*REXX pgm finds 1st N cyclops (Θ) #s, Θ primes, blind Θ primes, palindromic Θ primes*/
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP /*build array of semaphores for primes.*/
w= max(10, length( commas(@.#) ) ) /*max width of a number in any column. */
pri?= 0; bli?= 0; pal?= 0; call 0 ' first ' commas(n) " cyclops numbers"
pri?= 1; bli?= 0; pal?= 0; call 0 ' first ' commas(n) " prime cyclops numbers"
pri?= 1; bli?= 1; pal?= 0; call 0 ' first ' commas(n) " blind prime cyclops numbers"
pri?= 1; bli?= 0; pal?= 1; call 0 ' first ' commas(n) " palindromic prime cyclops numbers"
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
0: parse arg title; idx= 1 /*get the title of this output section.*/
say ' index │'center(title, 1 + cols*(w+1) ) /*display the output title. */
say '───────┼'center("" , 1 + cols*(w+1), '─') /* " " " separator*/
finds= 0; $= /*the number of finds (so far); $ list.*/
do j=0 until finds== n; L= length(j) /*find N cyclops numbers, start at 101.*/
if L//2==0 then do; j= left(1, L+1, 0) /*Is J an even # of digits? Yes, bump J*/
iterate /*use a new J that has odd # of digits.*/
end
z= pos(0, j); if z\==(L+1)%2 then iterate /* " " " " (zero in mid)? " */
if pos(0, j, z+1)>0 then iterate /* " " " " (has two 0's)? " */
if pri? then if \!.j then iterate /*Need a cyclops prime? Then skip.*/
if bli? then do; ?= space(translate(j, , 0), 0) /*Need a blind cyclops prime ?*/
if \!.? then iterate /*Not a blind cyclops prime? Then skip.*/
end
if pal? then do; r= reverse(j) /*Need a palindromic cyclops prime? */
if r\==j then iterate /*Cyclops number not palindromic? Skip.*/
if \!.r then iterate /* " palindrome not prime? " */
end
finds= finds + 1 /*bump the number of palindromic primes*/
$= $ right( commas(j), w) /*add a palindromic prime ──► $ list.*/
if finds//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible show residual output.*/
say '───────┴'center("" , 1 + cols*(w+1), '─'); say
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0; hip= 7890987 - 1 /*placeholders for primes (semaphores).*/
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*define some low primes. */
!.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1 /* " " " " flags. */
#= 6; sq.#= @.# ** 2 /*number of primes so far; prime square*/
do j=@.#+2 by 2 for max(0, hip%2-@.#%2-1) /*find odd primes from here on. */
parse var j '' -1 _ /*get the last dec. digit of J.*/
if _==5 then iterate; if j// 3==0 then iterate /*÷ by 5? ÷ by 3? Skip.*/
if j// 7==0 then iterate; if j//11==0 then iterate /*÷ " 7? ÷ by 11? " */
do k=6 while sq.k<=j /* [↓] divide by the known odd primes.*/
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # Ps; assign next P; P sq; P# */
end /*j*/; 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.
| #Clojure | Clojure | (import java.util.Date
java.text.SimpleDateFormat)
(defn time+12 [s]
(let [sdf (SimpleDateFormat. "MMMM d yyyy h:mma zzz")]
(-> (.parse sdf s)
(.getTime ,)
(+ , 43200000)
long
(Date. ,)
(->> , (.format sdf ,))))) |
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.
| #COBOL | COBOL | identification division.
program-id. date-manipulation.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 given-date.
05 filler value z"March 7 2009 7:30pm EST".
01 date-spec.
05 filler value z"%B %d %Y %I:%M%p %Z".
01 time-struct.
05 tm-sec usage binary-long.
05 tm-min usage binary-long.
05 tm-hour usage binary-long.
05 tm-mday usage binary-long.
05 tm-mon usage binary-long.
05 tm-year usage binary-long.
05 tm-wday usage binary-long.
05 tm-yday usage binary-long.
05 tm-isdst usage binary-long.
05 tm-gmtoff usage binary-c-long.
05 tm-zone usage pointer.
01 scan-index usage pointer.
01 time-t usage binary-c-long.
01 time-tm usage pointer.
01 reform-buffer pic x(64).
01 reform-length usage binary-long.
01 current-locale usage pointer.
01 iso-spec constant as "YYYY-MM-DDThh:mm:ss+hh:mm".
01 iso-date constant as "2009-03-07T19:30:00-05:00".
01 date-integer pic 9(9).
01 time-integer pic 9(9).
procedure division.
call "strptime" using
by reference given-date
by reference date-spec
by reference time-struct
returning scan-index
on exception
display "error calling strptime" upon syserr
end-call
display "Given: " given-date
if scan-index not equal null then
*> add 12 hours, and reform as local
call "mktime" using time-struct returning time-t
add 43200 to time-t
perform form-datetime
*> reformat as Pacific time
set environment "TZ" to "PST8PDT"
call "tzset" returning omitted
perform form-datetime
*> reformat as Greenwich mean
set environment "TZ" to "GMT"
call "tzset" returning omitted
perform form-datetime
*> reformat for Tokyo time, as seen in Hong Kong
set environment "TZ" to "Japan"
call "tzset" returning omitted
call "setlocale" using by value 6 by content z"en_HK.utf8"
returning current-locale
on exception
display "error with setlocale" upon syserr
end-call
move z"%c" to date-spec
perform form-datetime
else
display "date parse error" upon syserr
end-if
*> A more standard COBOL approach, based on ISO8601
display "Given: " iso-date
move integer-of-formatted-date(iso-spec, iso-date)
to date-integer
move seconds-from-formatted-time(iso-spec, iso-date)
to time-integer
add 43200 to time-integer
if time-integer greater than 86400 then
subtract 86400 from time-integer
add 1 to date-integer
end-if
display " " substitute(formatted-datetime(iso-spec
date-integer, time-integer, -300), "T", "/")
goback.
form-datetime.
call "localtime" using time-t returning time-tm
call "strftime" using
by reference reform-buffer
by value length(reform-buffer)
by reference date-spec
by value time-tm
returning reform-length
on exception
display "error calling strftime" upon syserr
end-call
if reform-length > 0 and <= length(reform-buffer) then
display " " reform-buffer(1 : reform-length)
else
display "date format error" upon syserr
end-if
.
end program date-manipulation.
|
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
| #PARI.2FGP | PARI/GP | card(n)=concat(["A","2","3","4","5","6","7","8","9","T","J","Q","K"][n\4+1],["C","D","H","S"][n%4+1]);
nextrand()={
(state=(214013*state+2531011)%2^31)>>16
};
deal(seed)={
my(deck=vector(52,n,n-1),t);
local(state=seed);
forstep(last=52,1,-1,
t=nextrand()%last+1;
print1(card(deck[t]),if(last%8==5,"\n"," "));
deck[t]=deck[last]
)
}; |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Swift | Swift | struct SmallInt {
var value: Int
init(value: Int) {
guard value >= 1 && value <= 10 else {
fatalError("SmallInts must be in the range [1, 10]")
}
self.value = value
}
static func +(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value + rhs.value) }
static func -(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value - rhs.value) }
static func *(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value * rhs.value) }
static func /(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value / rhs.value) }
}
extension SmallInt: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) { self.init(value: value) }
}
extension SmallInt: CustomStringConvertible {
public var description: String { "\(value)" }
}
let a: SmallInt = 1
let b: SmallInt = 9
let c: SmallInt = 10
let d: SmallInt = 2
print(a + b)
print(c - b)
print(a * c)
print(c / d)
print(a + c) |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Tcl | Tcl | namespace eval ::myIntType {
variable value_cache
array set value_cache {}
variable type integer
variable min 1
variable max 10
variable errMsg "cannot set %s to %s: must be a $type between $min and $max"
}
proc ::myIntType::declare varname {
set ns [namespace current]
uplevel [list trace add variable $varname write ${ns}::write]
uplevel [list trace add variable $varname unset ${ns}::unset_var]
}
proc ::myIntType::unset_var {varname args} {
variable value_cache
unset value_cache($varname)
}
proc ::myIntType::validate {value} {
variable type
variable min
variable max
expr {[string is $type -strict $value] && $min <= $value && $value <= $max}
}
proc ::myIntType::write {varname args} {
variable value_cache
upvar $varname var
set value $var
if {[validate $value]} {
set value_cache($varname) $value
} else {
if {[info exists value_cache($varname)]} {
set var $value_cache($varname)
}
variable errMsg
error [format $errMsg $varname $value]
}
} |
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.
| #C.2B.2B | C++ | #include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
int main( ) {
using namespace boost::gregorian ;
std::cout
<< "Yuletide holidays must be allowed in the following years:\n" ;
for ( int i = 2008 ; i < 2121 ; i++ ) {
greg_year gy = i ;
date d ( gy, Dec , 25 ) ;
if ( d.day_of_week( ) == Sunday ) {
std::cout << i << std::endl ;
}
}
std::cout << "\n" ;
return 0 ;
} |
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
| #Arturo | Arturo | validCUSIP?: function [cusip][
s: 0
alpha: `A`..`Z`
loop.with:'i chop cusip 'c [
v: 0
case ø
when? [numeric? c] -> v: to :integer to :string c
when? [in? c alpha] -> v: (index alpha c) + 1 + 9
when? [c = `*`] -> v: 36
when? [c = `@`] -> v: 37
when? [c = `#`] -> v: 38
else []
if odd? i -> v: 2 * v
s: s + (v / 10) + (v % 10)
]
check: (10 - (s % 10)) % 10
return check = to :integer to :string last cusip
]
loop ["037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105"] 'cusip [
print [cusip "=>" (validCUSIP? cusip)? -> "VALID" -> "INVALID"]
] |
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
| #AppleScript | AppleScript | set {year:y, month:m, day:d, weekday:w} to (current date)
tell (y * 10000 + m * 100 + d) as text to set shortFormat to text 1 thru 4 & "-" & text 5 thru 6 & "-" & text 7 thru 8
set longFormat to (w as text) & (", " & m) & (space & d) & (", " & y)
return (shortFormat & linefeed & longFormat) |
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.
| #AWK | AWK | # syntax: GAWK -f DAMM_ALGORITHM.AWK
BEGIN {
damm_init()
leng = split("5724,5727,112946",arr,",") # test cases
for (i=1; i<=leng; i++) {
n = arr[i]
printf("%s %s\n",damm_check(n),n)
}
exit(0)
}
function damm_check(n, a,i) {
a = 0
for (i=1; i<=length(n); i++) {
a = substr(damm[a],substr(n,i,1)+1,1)
}
return(a == 0 ? "T" : "F")
}
function damm_init() {
# 0123456789
damm[0] = "0317598642"
damm[1] = "7092154863"
damm[2] = "4206871359"
damm[3] = "1750983426"
damm[4] = "6123045978"
damm[5] = "3674209581"
damm[6] = "5869720134"
damm[7] = "8945362017"
damm[8] = "9438617205"
damm[9] = "2581436790"
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Vlang | Vlang | import math.big
fn main() {
zero := big.zero_int
one := big.one_int
for k := i64(2); k <= 10; k += 2 {
bk := big.integer_from_i64(k)
println("The first 50 Curzon numbers using a base of $k:")
mut count := 0
mut n := i64(1)
mut pow := big.integer_from_i64(k)
mut curzon50 := []i64{}
for {
z := pow + one
d := k*n + 1
bd := big.integer_from_i64(d)
if z%bd == zero {
if count < 50 {
curzon50 << n
}
count++
if count == 50 {
for i in 0..curzon50.len {
print("${curzon50[i]:4} ")
if (i+1)%10 == 0 {
println('')
}
}
print("\nOne thousandth: ")
}
if count == 1000 {
println(n)
break
}
}
n++
pow *= bk
}
println('')
}
} |
http://rosettacode.org/wiki/Curzon_numbers | Curzon numbers | A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1.
Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1.
Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.
Generalized Curzon numbers only exist for even base integers.
Task
Find and show the first 50 Generalized Curzon numbers for even base integers from 2 through 10.
Stretch
Find and show the one thousandth.
See also
Numbers Aplenty - Curzon numbers
OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
and even though it is not specifically mentioned that they are Curzon numbers:
OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| #Wren | Wren | /* curzon_numbers.wren */
import "./gmp" for Mpz
import "./seq" for Lst
import "./fmt" for Fmt
for (k in [2, 4, 6, 8, 10]) {
System.print("The first 50 Curzon numbers using a base of %(k):")
var count = 0
var n = 1
var pow = Mpz.from(k)
var curzon50 = []
while (true) {
var z = pow + Mpz.one
var d = k*n + 1
if (z.isDivisibleUi(d)) {
if (count < 50) curzon50.add(n)
count = count + 1
if (count == 50) {
for (chunk in Lst.chunks(curzon50, 10)) Fmt.print("$4d", chunk)
System.write("\nOne thousandth: ")
}
if (count == 1000) {
System.print(n)
break
}
}
n = n + 1
pow.mul(k)
}
System.print()
} |
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. | #D | D | import std.algorithm;
import std.exception;
import std.format;
import std.functional;
import std.math;
import std.range;
import std.stdio;
immutable MAX_ALL_FACTORS = 100_000;
immutable ALGORITHM = 2;
//Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.
struct Term {
private long m_coefficient;
private long m_exponent;
public this(long c, long e) {
m_coefficient = c;
m_exponent = e;
}
public long coefficient() const {
return m_coefficient;
}
public long exponent() const {
return m_exponent;
}
public Term opUnary(string op)() const {
static if (op == "-") {
return Term(-m_coefficient, m_exponent);
} else {
assert(false, "Not implemented");
}
}
public Term opBinary(string op)(Term term) const {
static if (op == "+") {
if (exponent() != term.exponent()) {
assert(false, "Error 102: Exponents not equals.");
}
return Term(coefficient() + term.coefficient(), exponent());
} else if (op == "*") {
return Term(coefficient() * term.coefficient(), exponent() + term.exponent());
} else {
assert(false, "Not implemented: " ~ op);
}
}
public void toString(scope void delegate(const(char)[]) sink) const {
auto spec = singleSpec("%s");
if (m_coefficient == 0) {
sink("0");
} else if (m_exponent == 0) {
formatValue(sink, m_coefficient, spec);
} else if (m_coefficient == 1) {
if (m_exponent == 1) {
sink("x");
} else {
sink("x^");
formatValue(sink, m_exponent, spec);
}
} else if (m_coefficient == -1) {
if (m_exponent == 1) {
sink("-x");
} else {
sink("-x^");
formatValue(sink, m_exponent, spec);
}
} else if (m_exponent == 1) {
formatValue(sink, m_coefficient, spec);
sink("x");
} else {
formatValue(sink, m_coefficient, spec);
sink("x^");
formatValue(sink, m_exponent, spec);
}
}
}
struct Polynomial {
private Term[] terms;
public this(const Term[] ts...) {
terms = ts.dup;
terms.sort!"b.exponent < a.exponent";
}
bool hasCoefficientAbs(int coeff) const {
foreach (term; terms) {
if (abs(term.coefficient) == coeff) {
return true;
}
}
return false;
}
public long leadingCoefficient() const {
return terms[0].coefficient();
}
public long degree() const {
if (terms.empty) {
return -1;
}
return terms[0].exponent();
}
public Polynomial opBinary(string op)(Term term) const {
static if (op == "+") {
Term[] newTerms;
auto added = false;
foreach (currentTerm; terms) {
if (currentTerm.exponent() == term.exponent()) {
added = true;
if (currentTerm.coefficient() + term.coefficient() != 0) {
newTerms ~= currentTerm + term;
}
} else {
newTerms ~= currentTerm;
}
}
if (!added) {
newTerms ~= term;
}
return Polynomial(newTerms);
} else if (op == "*") {
Term[] newTerms;
foreach (currentTerm; terms) {
newTerms ~= currentTerm * term;
}
return Polynomial(newTerms);
} else {
assert(false, "Not implemented: " ~ op);
}
}
public Polynomial opBinary(string op)(Polynomial rhs) const {
static if (op == "+") {
Term[] newTerms;
auto thisCount = terms.length;
auto polyCount = rhs.terms.length;
while (thisCount > 0 || polyCount > 0) {
if (thisCount == 0) {
newTerms ~= rhs.terms[polyCount - 1];
polyCount--;
} else if (polyCount == 0) {
newTerms ~= terms[thisCount - 1];
thisCount--;
} else {
auto thisTerm = terms[thisCount - 1];
auto polyTerm = rhs.terms[polyCount - 1];
if (thisTerm.exponent() == polyTerm.exponent()) {
auto t = thisTerm + polyTerm;
if (t.coefficient() != 0) {
newTerms ~= t;
}
thisCount--;
polyCount--;
} else if (thisTerm.exponent() < polyTerm.exponent()) {
newTerms ~= thisTerm;
thisCount--;
} else {
newTerms ~= polyTerm;
polyCount--;
}
}
}
return Polynomial(newTerms);
} else if (op == "/") {
Polynomial q;
auto r = Polynomial(terms);
auto lcv = rhs.leadingCoefficient();
auto dv = rhs.degree();
while (r.degree() >= rhs.degree()) {
auto lcr = r.leadingCoefficient();
auto s = lcr / lcv;
auto term = Term(s, r.degree() - dv);
q = q + term;
r = r + rhs * -term;
}
return q;
} else {
assert(false, "Not implemented: " ~ op);
}
}
public int opApply(int delegate(Term) dg) const {
foreach (term; terms) {
auto rv = dg(term);
if (rv != 0) {
return rv;
}
}
return 0;
}
public void toString(scope void delegate(const(char)[]) sink) const {
auto spec = singleSpec("%s");
if (!terms.empty) {
formatValue(sink, terms[0], spec);
foreach (t; terms[1..$]) {
if (t.coefficient > 0) {
sink(" + ");
formatValue(sink, t, spec);
} else {
sink(" - ");
formatValue(sink, -t, spec);
}
}
}
}
}
void putAll(K, V)(ref V[K] a, V[K] b) {
foreach (k, v; b) {
a[k] = v;
}
}
void merge(K, V, F)(ref V[K] a, K k, V v, F f) {
if (k in a) {
a[k] = f(a[k], v);
} else {
a[k] = v;
}
}
int sum(int a, int b) {
return a + b;
}
int[int] getFactorsImpl(int number) {
int[int] factors;
if (number % 2 == 0) {
if (number > 2) {
auto factorsDivTwo = memoize!getFactorsImpl(number / 2);
factors.putAll(factorsDivTwo);
}
factors.merge(2, 1, &sum);
return factors;
}
auto root = sqrt(cast(real) number);
auto i = 3;
while (i <= root) {
if (number % i == 0) {
factors.putAll(memoize!getFactorsImpl(number / i));
factors.merge(i, 1, &sum);
return factors;
}
i += 2;
}
factors[number] = 1;
return factors;
}
alias getFactors = memoize!getFactorsImpl;
int[] getDivisors(int number) {
int[] divisors;
auto root = cast(int)sqrt(cast(real) number);
foreach (i; 1..root) {
if (number % i == 0) {
divisors ~= i;
}
auto div = number / i;
if (div != i && div != number) {
divisors ~= div;
}
}
return divisors;
}
Polynomial cyclotomicPolynomialImpl(int n) {
if (n == 1) {
// Polynomial: x - 1
return Polynomial(Term(1, 1), Term(-1, 0));
}
auto factors = getFactors(n);
if (n in factors) {
// n prime
Term[] terms;
foreach (i; 0..n) {
terms ~= Term(1, i);
}
return Polynomial(terms);
} else if (factors.length == 2 && 2 in factors && factors[2] == 1 && (n / 2) in factors && factors[n / 2] == 1) {
// n = 2p
auto prime = n / 2;
Term[] terms;
auto coeff = -1;
foreach (i; 0..prime) {
coeff *= -1;
terms ~= Term(coeff, i);
}
return Polynomial(terms);
} else if (factors.length == 1 && 2 in factors) {
// n = 2^h
auto h = factors[2];
Term[] terms;
terms ~= Term(1, 2 ^^ (h - 1));
terms ~= Term(1, 0);
return Polynomial(terms);
} else if (factors.length == 1 && n !in factors) {
// n = p^k
auto p = 0;
auto k = 0;
foreach (prime, v; factors) {
if (prime > p) {
p = prime;
k = v;
}
}
Term[] terms;
foreach (i; 0..p) {
terms ~= Term(1, (i * p) ^^ (k - 1));
}
return Polynomial(terms);
} else if (factors.length == 2 && 2 in factors) {
// n = 2^h * p^k
auto p = 0;
auto k = 0;
foreach (prime, v; factors) {
if (prime != 2 && prime > p) {
p = prime;
k = v;
}
}
Term[] terms;
auto coeff = -1;
auto twoExp = 2 ^^ (factors[2] - 1);
foreach (i; 0..p) {
coeff *= -1;
auto exponent = i * twoExp * p ^^ (k - 1);
terms ~= Term(coeff, exponent);
}
return Polynomial(terms);
} else if (2 in factors && n / 2 % 2 == 1 && n / 2 > 1) {
// CP(2m)[x] = CP(-m)[x], n odd integer > 1
auto cycloDiv2 = memoize!cyclotomicPolynomialImpl(n / 2);
Term[] terms;
foreach (term; cycloDiv2) {
if (term.exponent() % 2 == 0) {
terms ~= term;
} else {
terms ~= -term;
}
}
return Polynomial(terms);
}
if (ALGORITHM == 0) {
// Slow - uses basic definition.
auto divisors = getDivisors(n);
// Polynomial: ( x^n - 1 )
auto cyclo = Polynomial(Term(1, n), Term(-1, 0));
foreach (i; divisors) {
auto p = memoize!cyclotomicPolynomialImpl(i);
cyclo = cyclo / p;
}
return cyclo;
}
if (ALGORITHM == 1) {
// Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
auto divisors = getDivisors(n);
auto maxDivisor = int.min;
foreach (div; divisors) {
maxDivisor = max(maxDivisor, div);
}
int[] divisorsExceptMax;
foreach (div; divisors) {
if (maxDivisor % div != 0) {
divisorsExceptMax ~= div;
}
}
// Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
auto cyclo = Polynomial(Term(1, n), Term(-1, 0)) / Polynomial(Term(1, maxDivisor), Term(-1, 0));
foreach (i; divisorsExceptMax) {
auto p = memoize!cyclotomicPolynomialImpl(i);
cyclo = cyclo / p;
}
return cyclo;
}
if (ALGORITHM == 2) {
// Fastest
// Let p ; q be primes such that p does not divide n, and q q divides n.
// Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
auto m = 1;
auto cyclo = memoize!cyclotomicPolynomialImpl(m);
auto primes = factors.keys;
primes.sort;
foreach (prime; primes) {
// CP(m)[x]
auto cycloM = cyclo;
// Compute CP(m)[x^p].
Term[] terms;
foreach (term; cycloM) {
terms ~= Term(term.coefficient(), term.exponent() * prime);
}
cyclo = Polynomial(terms) / cycloM;
m *= prime;
}
// Now, m is the largest square free divisor of n
auto s = n / m;
// Compute CP(n)[x] = CP(m)[x^s]
Term[] terms;
foreach (term; cyclo) {
terms ~= Term(term.coefficient(), term.exponent() * s);
}
return Polynomial(terms);
}
assert(false, "Error 103: Invalid algorithm");
}
alias cyclotomicPolynomial = memoize!cyclotomicPolynomialImpl;
void main() {
writeln("Task 1: cyclotomic polynomials for n <= 30:");
foreach (i; 1 .. 31) {
auto p = cyclotomicPolynomial(i);
writefln("CP[%d] = %s", i, p);
}
writeln;
writeln("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:");
auto n = 0;
foreach (i; 1 .. 11) {
while (true) {
n++;
auto cyclo = cyclotomicPolynomial(n);
if (cyclo.hasCoefficientAbs(i)) {
writefln("CP[%d] has coefficient with magnitude = %d", n, i);
n--;
break;
}
}
}
} |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #Groovy | Groovy | class CutRectangle {
private static int[][] dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]]
static void main(String[] args) {
cutRectangle(2, 2)
cutRectangle(4, 3)
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return
}
int[][] grid = new int[h][w]
Stack<Integer> stack = new Stack<>()
int half = (int) ((w * h) / 2)
long bits = (long) Math.pow(2, half) - 1
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = (int) (i / w)
int c = i % w
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0
grid[h - r - 1][w - c - 1] = 1 - grid[r][c]
}
stack.push(0)
grid[0][0] = 2
int count = 1
while (!stack.empty()) {
int pos = stack.pop()
int r = (int) (pos / w)
int c = pos % w
for (int[] dir : dirs) {
int nextR = r + dir[0]
int nextC = c + dir[1]
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC)
grid[nextR][nextC] = 2
count++
}
}
}
}
if (count == half) {
printResult(grid)
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr) {
println(Arrays.toString(a))
}
println()
}
} |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Ruby | Ruby | require 'prime'
NONZEROS = %w(1 2 3 4 5 6 7 8 9)
cyclopes = Enumerator.new do |y|
(0..).each do |n|
NONZEROS.repeated_permutation(n) do |lside|
NONZEROS.repeated_permutation(n) do |rside|
y << (lside.join + "0" + rside.join).to_i
end
end
end
end
prime_cyclopes = Enumerator.new {|y| cyclopes.each {|c| y << c if c.prime?} }
blind_prime_cyclopes = Enumerator.new {|y| prime_cyclopes.each {|c| y << c if c.to_s.delete("0").to_i.prime?} }
palindromic_prime_cyclopes = Enumerator.new {|y| prime_cyclopes.each {|c| y << c if c.to_s == c.to_s.reverse} }
n, m = 50, 10_000_000
["cyclopes", "prime cyclopes", "blind prime cyclopes", "palindromic prime cyclopes"].zip(
[cyclopes, prime_cyclopes, blind_prime_cyclopes, palindromic_prime_cyclopes]).each do |name, enum|
cycl, idx = enum.each_with_index.detect{|n, i| n > m}
puts "The first #{n} #{name} are: \n#{enum.take(n).to_a}\nFirst #{name} term > #{m}: #{cycl} at index: #{idx}.", ""
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.
| #Crystal | Crystal | time = Time.parse("March 7 2009 7:30pm EST", "%B %-d %Y %l:%M%p", Time::Location.load("EST"))
time += 12.hours
puts time # 2009-03-08 07:30:00 -05:00
puts time.in(Time::Location.load("Europe/Berlin")) # 2009-03-08 13:30:00 +01:00
|
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.
| #D | D |
import std.stdio;
import std.format;
import std.datetime;
import std.algorithm;
enum months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
void main()
{
// input
string date = "March 7 2009 7:30pm EST";
// parsing date string to integer values
string month, md, tz;
int day, year, hour, minute;
date.formattedRead("%s %d %d %d:%d%s %s", &month, &day, &year, &hour, &minute, &md, &tz);
int mon = cast (int) months.countUntil(month) + 1;
// convert to 24-hour
if (md == "pm")
hour += 12;
// create date from integer
DateTime dt = DateTime(year, mon, day, hour, minute);
// output
writeln(dt);
writeln(dt + 12.hours);
}
|
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
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use utf8;
sub deal {
my $s = shift;
my $rnd = sub {
return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 );
};
my @d;
for my $b (split "", "A23456789TJQK") {
push @d, map("$_$b", qw/♣ ♦ ♥ ♠/);
}
for my $idx (reverse 0 .. $#d) {
my $r = $rnd->() % ($idx + 1);
@d[$r, $idx] = @d[$idx, $r];
}
return [reverse @d];
}
my $hand_idx = shift(@ARGV) // 11_982;
my $cards = deal($hand_idx);
my $num_cards_in_height = 8;
my $string = '';
while (@$cards)
{
$string .= join(' ', splice(@$cards, 0, 8)) . "\n";
}
binmode STDOUT, ':encoding(utf-8)';
print "Hand $hand_idx\n";
print $string; |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Toka | Toka | needs quotes
{
variable update
[ update @ [ ! ] [ @ ] ifTrueFalse update off ] is action
[ dup >r 0 11 r> within [ update on ] [ drop ." Out of bounds\n " ] ifTrueFalse ]
[ ` [ invoke cell-size malloc # ` action compile ` ] invoke is ]
} is value:1-10:
is to
value:1-10: foo
1 to foo
foo . |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #UNIX_Shell | UNIX Shell | typeset -i boundedint
function boundedint.set {
nameref var=${.sh.name}
if (( 1 <= .sh.value && .sh.value <= 10 )); then
# stash the valid value as a backup, in case we need to restore it
typeset -i var.previous_value=${.sh.value}
else
print -u2 "value out of bounds"
# restore previous value
.sh.value=${var.previous_value}
fi
}
boundedint=-5; echo $boundedint
boundedint=5; echo $boundedint
boundedint=15; echo $boundedint |
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.
| #Clojure | Clojure |
(import '(java.util GregorianCalendar))
(defn yuletide [start end]
(filter #(= (. (new GregorianCalendar %
(. GregorianCalendar DECEMBER) 25) get (. GregorianCalendar DAY_OF_WEEK))
(. GregorianCalendar SUNDAY)) (range start (inc end))))
(yuletide 2008 2121)
|
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #AutoHotkey | AutoHotkey | Cusip_Check_Digit(cusip){
sum := 0, i := 1, x := StrSplit(cusip)
while (i <= 8) {
c := x[i]
if c is digit
v := c
else if c is alpha
v := Asc(c) - 64 + 9
else if (c = "*")
v := 36
else if (c = "@")
v := 37
else if (c = "#")
v := 38
if (i/2 = Floor(i/2))
v *= 2
sum += Floor(v/10) + Mod(v, 10)
i++
}
return (Mod(10 - Mod(sum, 10), 10) = x[9])
} |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program dateFormat.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BRK, 0x2d @ Linux syscall
.equ CHARPOS, '@'
.equ GETTIME, 0x4e @ call system linux gettimeofday
/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: @
.struct timeval_sec + 4
timeval_usec: @
.struct timeval_usec + 4
timeval_end:
.struct 0
timezone_min: @
.struct timezone_min + 4
timezone_dsttime: @
.struct timezone_dsttime + 4
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "Date : @/@/@ \n" @ message result
szMessResult1: .asciz "Date day : @ @ @ @ \n" @ message result
szJan: .asciz "Janvier"
szFev: .asciz "Février"
szMars: .asciz "Mars"
szAvril: .asciz "Avril"
szMai: .asciz "Mai"
szJuin: .asciz "Juin"
szJuil: .asciz "Juillet"
szAout: .asciz "Aout"
szSept: .asciz "Septembre"
szOct: .asciz "Octobre"
szNov: .asciz "Novembre"
szDec: .asciz "Décembre"
szLundi: .asciz "Lundi"
szMardi: .asciz "Mardi"
szMercredi: .asciz "Mercredi"
szJeudi: .asciz "Jeudi"
szVendredi: .asciz "Vendredi"
szSamedi: .asciz "Samedi"
szDimanche: .asciz "Dimanche"
szCarriageReturn: .asciz "\n"
.align 4
tbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
tbMonthName: .int szJan
.int szFev
.int szMars
.int szAvril
.int szMai
.int szJuin
.int szJuil
.int szAout
.int szSept
.int szOct
.int szNov
.int szDec
tbDayName: .int szLundi
.int szMardi
.int szMercredi
.int szJeudi
.int szVendredi
.int szSamedi
.int szDimanche
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sZoneConv: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrstTVal
ldr r1,iAdrstTZone
mov r7,#GETTIME
svc 0
cmp r0,#-1 @ error ?
beq 99f
ldr r1,iAdrstTVal
ldr r0,[r1,#timeval_sec] @ timestemp in second
bl dateFormatNum
ldr r0,[r1,#timeval_sec] @ timestemp in second
bl dateFormatAlpha
ldr r0,iTStest1
bl dateFormatNum
ldr r0,iTStest1
bl dateFormatAlpha
ldr r0,iTStest2
bl dateFormatNum
ldr r0,iTStest2
bl dateFormatAlpha
ldr r0,iTStest3
bl dateFormatNum
ldr r0,iTStest3
bl dateFormatAlpha
b 100f
99:
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0,#0 @ return code
mov r7,#EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszMessError: .int szMessError
iAdrstTVal: .int stTVal
iAdrstTZone: .int stTZone
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iTStest1: .int 1609508339 @ 01/01/2021
iTStest2: .int 1657805939 @ 14/07/2022
iTStest3: .int 1767221999 @ 31/12/2025
/******************************************************************/
/* date format numeric */
/******************************************************************/
/* r0 contains the timestamp in seconds */
dateFormatNum:
push {r1-r11,lr} @ save registers
ldr r2,iSecJan2020
sub r0,r0,r2 @ total secondes to 01/01/2020
mov r1,#60
bl division
mov r0,r2
mov r6,r3 @ compute secondes
mov r1,#60
bl division
mov r7,r3 @ compute minutes
mov r0,r2
mov r1,#24
bl division
mov r8,r3 @ compute hours
mov r0,r2
mov r11,r0
mov r1,#(365 * 4 + 1)
bl division
lsl r9,r2,#2 @ multiply by 4 = year1
mov r1,#(365 * 4 + 1)
mov r0,r11
bl division
mov r10,r3
ldr r1,iAdrtbDayMonthYear
mov r2,#3
mov r3,#12
1:
mul r11,r3,r2
ldr r4,[r1,r11,lsl #2] @ load days by year
cmp r10,r4
bge 2f
sub r2,r2,#1
cmp r2,#0
bne 1b
2: @ r2 = year2
mov r5,#11
mul r11,r3,r2
lsl r11,#2
add r11,r1 @ table address
3:
ldr r4,[r11,r5,lsl #2] @ load days by month
cmp r10,r4
bge 4f
subs r5,r5,#1
bne 3b
4: @ r5 = month - 1
mul r11,r3,r2
add r11,r5
ldr r1,iAdrtbDayMonthYear
ldr r3,[r1,r11,lsl #2]
sub r0,r10,r3
add r0,r0,#1 @ final compute day
ldr r1,iAdrsZoneConv
bl conversion10 @ this function do not zero final
mov r11,#0 @ store zero final
strb r11,[r1,r0]
ldr r0,iAdrszMessResult
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at first @ character
mov r3,r0
add r0,r5,#1 @ final compute month
cmp r0,#12
subgt r0,#12
ldr r1,iAdrsZoneConv
bl conversion10
mov r11,#0 @ store zero final
strb r11,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
ldr r11,iYearStart
add r0,r9,r11
add r0,r0,r2 @ final compute year = 2020 + year1 + year2
ldr r1,iAdrsZoneConv
bl conversion10
mov r11,#0 @ store zero final
strb r11,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
bl affichageMess
100:
pop {r1-r11,lr} @ restaur registers
bx lr @ return
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* date format alphanumeric */
/******************************************************************/
/* r0 contains the timestamp in seconds */
dateFormatAlpha:
push {r1-r10,lr} @ save registers
ldr r2,iSecJan2020
sub r0,r0,r2 @ total secondes to 01/01/2020
mov r6,r0
mov r1,#60
bl division
mov r0,r2
mov r1,#60
bl division
mov r0,r2
mov r1,#24
bl division
mov r0,r2
mov r8,r0
mov r1,#(365 * 4 + 1)
bl division
lsl r9,r2,#2 @ multiply by 4 = year1
mov r1,#(365 * 4 + 1)
mov r0,r8
bl division
mov r10,r3 @ reste
ldr r1,iAdrtbDayMonthYear
mov r7,#3
mov r3,#12
1:
mul r8,r3,r7
ldr r4,[r1,r8,lsl #2] @ load days by year
cmp r10,r4
bge 2f
sub r7,r7,#1
cmp r7,#0
bne 1b
2: @ r7 = year2
mov r5,#11
mul r8,r3,r7
lsl r8,#2
add r8,r1
3:
ldr r4,[r8,r5,lsl #2] @ load days by month
cmp r10,r4
bge 4f
subs r5,r5,#1
bne 3b
4: @ r5 = month - 1
mov r0,r6 @ number secondes depuis 01/01/2020
ldr r1,iNbSecByDay
bl division
mov r0,r2
mov r1,#7
bl division
add r2,r3,#2
cmp r2,#7
subge r2,#7
ldr r1,iAdrtbDayName
ldr r1,[r1,r2,lsl #2]
ldr r0,iAdrszMessResult1
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r8,#12
mul r11,r8,r7
add r11,r5
ldr r1,iAdrtbDayMonthYear
ldr r8,[r1,r11,lsl #2]
sub r0,r10,r8
add r0,r0,#1 @ final compute day
ldr r1,iAdrsZoneConv
bl conversion10 @ this function do not zero final
mov r8,#0 @ store zero final
strb r8,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at first @ character
mov r3,r0
ldr r1,iAdrtbMonthName
cmp r5,#12
subge r5,#12
ldr r1,[r1,r5,lsl #2] @ month name
mov r0,r3
bl strInsertAtCharInc @ insert result at first @ character
mov r3,r0
ldr r0,iYearStart
add r0,r7
add r0,r9 @ final compute year = 2020 + year1 + year2
ldr r1,iAdrsZoneConv
bl conversion10 @ this function do not zero final
mov r8,#0 @ store zero final
strb r8,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at first @ character
bl affichageMess
100:
pop {r1-r10,lr} @ restaur registers
bx lr @ return
iAdrszMessResult1: .int szMessResult1
iSecJan2020: .int 1577836800
iAdrtbDayMonthYear: .int tbDayMonthYear
iYearStart: .int 2020
iAdrtbMonthName: .int tbMonthName
iAdrtbDayName: .int tbDayName
iNbSecByDay: .int 3600 * 24
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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.
| #BASIC | BASIC | 10 DEFINT D,I,X,Y: DIM DT(9,9)
20 FOR Y=0 TO 9: FOR X=0 TO 9: READ DT(X,Y): NEXT X,Y
30 INPUT N$: IF N$="" THEN END
40 D=0
50 FOR I=1 TO LEN(N$): D=DT(VAL(MID$(N$,I,1)),D): NEXT I
60 IF D THEN PRINT "FAIL" ELSE PRINT "PASS"
70 GOTO 30
100 DATA 0,3,1,7,5,9,8,6,4,2
110 DATA 7,0,9,2,1,5,4,8,6,3
120 DATA 4,2,0,6,8,7,1,3,5,9
130 DATA 1,7,5,0,9,8,3,4,2,6
140 DATA 6,1,2,3,0,4,5,9,7,8
150 DATA 3,6,7,4,2,0,9,5,8,1
160 DATA 5,8,6,9,7,2,0,1,3,4
170 DATA 8,9,4,5,3,6,2,0,1,7
180 DATA 9,4,3,8,6,1,7,2,0,5
190 DATA 2,5,8,1,4,3,6,7,9,0 |
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.
| #11l | 11l | F addN(n)
F adder(x)
R x + @=n
R adder
V add2 = addN(2)
V add3 = addN(3)
print(add2(7))
print(add3(7)) |
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. | #Fermat | Fermat |
&(J=x); {adjoin x as the variable in the polynomials}
Func Cyclotomic(n) =
if n=1 then x-1 fi; {first cyclotomic polynomial is x^n-1}
r:=x^n-1; {caclulate cyclotomic by division}
for d = 1 to n-1 do
if Divides(d,n) then
r:=r\Cyclotomic(d)
fi;
od;
r.; {return the polynomial}
Func Hascoef(n, k) =
p:=Cyclotomic(n);
for d = 0 to Deg(p) do
if |(Coef(p,d))|=k then Return(1) fi
od;
0.;
for d = 1 to 30 do
!!(d,' : ',Cyclotomic(d))
od;
for m = 1 to 10 do
i:=1;
while not Hascoef(i, m) do
i:+
od;
!!(m,' : ',i);
od; |
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.
| #Haskell | Haskell | import qualified Data.Vector.Unboxed.Mutable as V
import Data.STRef
import Control.Monad (forM_, when)
import Control.Monad.ST
dir :: [(Int, Int)]
dir = [(1, 0), (-1, 0), (0, -1), (0, 1)]
data Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] }
cutIt :: STRef s Env -> ST s ()
cutIt env = do
e <- readSTRef env
when (odd $ h e) $ modifySTRef env $ \en -> en { h = w e,
w = h e }
e <- readSTRef env
if odd (h e)
then modifySTRef env $ \en -> en { ret = 0 }
else
if w e == 1
then modifySTRef env $ \en -> en { ret = 1 }
else do
let blen = (h e + 1) * (w e + 1) - 1
t = (h e `div` 2) * (w e + 1) + (w e `div` 2)
modifySTRef env $ \en -> en { len = blen,
count = 0,
next = [ w e + 1, (negate $ w e) - 1, -1, 1] }
grid <- V.replicate (blen + 1) False
case odd (w e) of
True -> do
V.write grid t True
V.write grid (t + 1) True
walk grid (h e `div` 2) (w e `div` 2 - 1)
e1 <- readSTRef env
let res1 = count e1
modifySTRef env $ \en -> en { count = 0 }
walk grid (h e `div` 2 - 1) (w e `div` 2)
modifySTRef env $ \en -> en { ret = res1 +
(count en * 2) }
False -> do
V.write grid t True
walk grid (h e `div` 2) (w e `div` 2 - 1)
e2 <- readSTRef env
let count2 = count e2
if h e == w e
then modifySTRef env $ \en -> en { ret =
count2 * 2 }
else do
walk grid (h e `div` 2 - 1)
(w e `div` 2)
modifySTRef env $ \en -> en { ret =
count en }
where
walk grid y x = do
e <- readSTRef env
if y <= 0 || y >= h e || x <= 0 || x >= w e
then modifySTRef env $ \en -> en { count = count en + 1 }
else do
let t = y * (w e + 1) + x
V.write grid t True
V.write grid (len e - t) True
forM_ (zip (next e) [0..3]) $ \(n, d) -> do
g <- V.read grid (t + n)
when (not g) $
walk grid (y + fst (dir !! d)) (x + snd (dir !! d))
V.write grid t False
V.write grid (len e - t) False
cut :: (Int, Int) -> Int
cut (x, y) = runST $ do
env <- newSTRef $ Env { w = y, h = x, len = 0, count = 0, ret = 0, next = [] }
cutIt env
result <- readSTRef env
return $ ret result
main :: IO ()
main = do
mapM_ (\(x, y) -> when (even (x * y)) (putStrLn $
show x ++ " x " ++ show y ++ ": " ++ show (cut (x, y))))
[ (x, y) | x <- [1..10], y <- [1..x] ]
|
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Sidef | Sidef | func cyclops_numbers(base = 10) {
Enumerator({|callback|
var digits = @(1 .. base-1)
for k in (0 .. Inf `by` 2) {
digits.variations_with_repetition(k, {|*a|
a = (a.first(a.len>>1) + [0] + a.last(a.len>>1))
callback(a.flip.digits2num(base))
})
}
})
}
func palindromic_cyclops_numbers(base = 10) {
Enumerator({|callback|
var digits = @(1 .. base-1)
for k in (0..Inf) {
digits.variations_with_repetition(k, {|*a|
a = (a + [0] + a.flip)
callback(a.flip.digits2num(base))
})
}
})
}
func prime_cyclops(base = 10) {
var iter = cyclops_numbers(base)
Enumerator({|callback|
iter.each {|n|
callback(n) if n.is_prime
}
})
}
func blind_prime_cyclops(base = 10) {
var iter = prime_cyclops(base)
Enumerator({|callback|
iter.each {|n|
var k = (n.len(base)-1)>>1
var r = ipow(base, k)
if (r*idiv(n, r*base) + n%r -> is_prime) {
callback(n)
}
}
})
}
func palindromic_prime_cyclops(base = 10) {
var iter = palindromic_cyclops_numbers(base)
Enumerator({|callback|
iter.each {|n|
callback(n) if n.is_prime
}
})
}
for text,f in ([
['', cyclops_numbers],
['prime', prime_cyclops],
['blind prime', blind_prime_cyclops],
['palindromic prime', palindromic_prime_cyclops],
]) {
with (50) {|k|
say "First #{k} #{text} cyclops numbers:"
f().first(k).each_slice(10, {|*a|
a.map { '%7s' % _ }.join(' ').say
})
}
var min = 10_000_000
var iter = f()
var index = 0
var arr = Enumerator({|callback|
iter.each {|n|
callback([index, n]) if (n > min)
++index
}
}).first(1)[0]
say "\nFirst #{text} term > #{min.commify}: #{arr[1].commify} at (zero based) index: #{arr[0].commify}\n"
} |
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.
| #Delphi | Delphi |
program DateManipulation;
{$APPTYPE CONSOLE}
uses
SysUtils,
DateUtils;
function MonthNumber(aMonth: string): Word;
begin
//Convert a string value representing the month
//to its corresponding numerical value
if aMonth = 'January' then Result:= 1
else if aMonth = 'February' then Result:= 2
else if aMonth = 'March' then Result:= 3
else if aMonth = 'April' then Result:= 4
else if aMonth = 'May' then Result:= 5
else if aMonth = 'June' then Result:= 6
else if aMonth = 'July' then Result:= 7
else if aMonth = 'August' then Result:= 8
else if aMonth = 'September' then Result:= 9
else if aMonth = 'October' then Result:= 10
else if aMonth = 'November' then Result:= 11
else if aMonth = 'December' then Result:= 12
else Result:= 12;
end;
function ParseString(aDateTime: string): TDateTime;
var
strDay,
strMonth,
strYear,
strTime: string;
iDay,
iMonth,
iYear: Word;
TimePortion: TDateTime;
begin
//Decode the month from the given string
strMonth:= Copy(aDateTime, 1, Pos(' ', aDateTime) - 1);
Delete(aDateTime, 1, Pos(' ', aDateTime));
iMonth:= MonthNumber(strMonth);
//Decode the day from the given string
strDay:= Copy(aDateTime, 1, Pos(' ', aDateTime) - 1);
Delete(aDateTime, 1, Pos(' ', aDateTime));
iDay:= StrToIntDef(strDay, 30);
//Decode the year from the given string
strYear:= Copy(aDateTime, 1, Pos(' ', aDateTime) -1);
Delete(aDateTime, 1, Pos(' ', aDateTime));
iYear:= StrToIntDef(strYear, 1899);
//Decode the time value from the given string
strTime:= Copy(aDateTime, 1, Pos(' ', aDateTime) -1);
//Encode the date value and assign it to result
Result:= EncodeDate(iYear, iMonth, iDay);
//Encode the time value and add it to result
if TryStrToTime(strTime, TimePortion) then
Result:= Result + TimePortion;
end;
function Add12Hours(aDateTime: string): string;
var
tmpDateTime: TDateTime;
begin
//Adding 12 hours to the given
//date time string value
tmpDateTime:= ParseString(aDateTime);
tmpDateTime:= IncHour(tmpDateTime, 12);
//Formatting the output
Result:= FormatDateTime('mm/dd/yyyy hh:mm AM/PM', tmpDateTime);
end;
begin
Writeln(Add12Hours('March 7 2009 7:30pm EST'));
Readln;
end.
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Phix | Phix | with javascript_semantics
atom seed
function xrnd()
seed = and_bits(seed*214013+2531011,#7FFFFFFF)
return floor(seed/power(2,16))
end function
sequence cards = repeat(0,52)
procedure deal(integer game_num)
seed = game_num
for i=1 to 52 do
cards[i] = 52-i
end for
for i=1 to 51 do
integer j = 52-mod(xrnd(),53-i)
integer s = cards[i]
cards[i] = cards[j]
cards[j] = s
end for
end procedure
constant suits = "CDHS",
ranks = "A23456789TJQK"
procedure show()
for idx=1 to 52 do
integer rank = floor(cards[idx]/4)+1
integer suit = mod(cards[idx],4)+1
integer eol = remainder(idx-1,13)=12
printf(1,"%c%c%s",{ranks[rank],suits[suit],iff(eol?"\n":" ")})
end for
end procedure
integer game_num = 1
--integer game_num=617
deal(game_num)
printf(1,"hand %d\n",{game_num})
show()
|
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Ursala | Ursala | #import nat
my_number ::
the_number %n -|~bounds.&BZ,~&B+ nleq~~lrlXPrX@G+ ~/the_number bounds|-?(~the_number,<'out of bounds'>!%)
bounds %nW ~bounds.&B?(~bounds,(1,10)!)
add = my_number$[the_number: sum+ ~the_number~~]
mul = my_number$[the_number: product+ ~the_number~~] |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Visual_Basic | Visual Basic | Private mvarValue As Integer
Public Property Let Value(ByVal vData As Integer)
If (vData > 10) Or (vData < 1) Then
Error 380 'Invalid property value; could also use 6, Overflow
Else
mvarValue = vData
End If
End Property
Public Property Get Value() As Integer
Value = mvarValue
End Property
Private Sub Class_Initialize()
'vb defaults to 0 for numbers; let's change that...
mvarValue = 1
End Sub |
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.
| #CLU | CLU | weekday = proc (d: date) returns (int)
y: int := d.year
m: int := d.month
if m<3
then y, m := y-1, m+10
else m := m-2
end
c: int := y/100
y := y//100
z: int := (26*m-2)/10 + d.day + y + y/4 + c/4 - 2*c + 777
return(z//7)
end weekday
start_up = proc ()
po: stream := stream$primary_output()
for year: int in int$from_to(2008, 2121) do
if weekday(date$create(25, 12, year, 0, 0, 0))=0 then
stream$putl(po, int$unparse(year))
end
end
end start_up |
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
| #AWK | AWK |
# syntax: GAWK -f CUSIP.AWK
BEGIN {
n = split("037833100,17275R102,38259P508,594918104,68389X106,68389X105",arr,",")
for (i=1; i<=n; i++) {
printf("%9s %s\n",arr[i],cusip(arr[i]))
}
exit(0)
}
function cusip(n, c,i,sum,v,x) {
# returns: 1=OK, 0=NG, -1=bad data
if (length(n) != 9) {
return(-1)
}
for (i=1; i<=8; i++) {
c = substr(n,i,1)
if (c ~ /[0-9]/) {
v = c
}
else if (c ~ /[A-Z]/) {
v = index("ABCDEFGHIJKLMNOPQRSTUVWXYZ",c) + 9
}
else if (c == "*") {
v = 36
}
else if (c == "@") {
v = 37
}
else if (c == "#") {
v = 38
}
else {
return(-1)
}
if (i ~ /[02468]/) {
v *= 2
}
sum += int(v / 10) + (v % 10)
}
x = (10 - (sum % 10)) % 10
return(substr(n,9,1) == x ? 1 : 0)
}
|
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
| #Arturo | Arturo | currentTime: now
print to :string.format: "YYYY-MM-dd" currentTime
print to :string.format: "dddd, MMMM dd, YYYY" currentTime |
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
| #AutoHotkey | AutoHotkey | FormatTime, Date1, , yyyy-MM-dd ; "2007-11-10"
FormatTime, Date2, , LongDate ; "Sunday, November 10, 2007"
MsgBox %Date1% `n %Date2% |
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.
| #BCPL | BCPL | get "libhdr"
let damm(ns) = valof
$( let dt = table
0,3,1,7,5,9,8,6,4,2,
7,0,9,2,1,5,4,8,6,3,
4,2,0,6,8,7,1,3,5,9,
1,7,5,0,9,8,3,4,2,6,
6,1,2,3,0,4,5,9,7,8,
3,6,7,4,2,0,9,5,8,1,
5,8,6,9,7,2,0,1,3,4,
8,9,4,5,3,6,2,0,1,7,
9,4,3,8,6,1,7,2,0,5,
2,5,8,1,4,3,6,7,9,0
let idgt = 0
for i=1 to ns%0
test '0' <= ns%i <= '9'
do idgt := dt!(ns%i-'0' + 10*idgt)
or resultis false
resultis idgt = 0
$)
let check(ns) be
writef("%S: %S*N", ns, damm(ns) -> "pass", "fail")
let start() be
$( check("5724")
check("5727")
check("112946")
check("112949")
$) |
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.
| #BQN | BQN | 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 ⟩
Digits ← 10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
Damm ← {0=0(table⊑˜⋈)˜´⌽Digits 𝕩}
Damm¨5724‿5727‿112946 |
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.
| #Ada | Ada | generic
type Argument_1 (<>) is limited private;
type Argument_2 (<>) is limited private;
type Argument_3 (<>) is limited private;
type Return_Value (<>) is limited private;
with function Func
(A : in Argument_1;
B : in Argument_2;
C : in Argument_3)
return Return_Value;
package Curry_3 is
generic
First : in Argument_1;
package Apply_1 is
generic
Second : in Argument_2;
package Apply_2 is
function Apply_3
(Third : in Argument_3)
return Return_Value;
end Apply_2;
end Apply_1;
end Curry_3; |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #Aime | Aime | ri(list l)
{
l[0] = apply.apply(l[0]);
}
curry(object o)
{
(o.__count - 1).times(ri, list(o));
}
main(void)
{
o_wbfxinteger.curry()(16)(3)(12)(16)(1 << 30);
0;
}
|
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. | #Go | Go | package main
import (
"fmt"
"log"
"math"
"sort"
"strings"
)
const (
algo = 2
maxAllFactors = 100000
)
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
type term struct{ coef, exp int }
func (t term) mul(t2 term) term {
return term{t.coef * t2.coef, t.exp + t2.exp}
}
func (t term) add(t2 term) term {
if t.exp != t2.exp {
log.Fatal("exponents unequal in term.add method")
}
return term{t.coef + t2.coef, t.exp}
}
func (t term) negate() term { return term{-t.coef, t.exp} }
func (t term) String() string {
switch {
case t.coef == 0:
return "0"
case t.exp == 0:
return fmt.Sprintf("%d", t.coef)
case t.coef == 1:
if t.exp == 1 {
return "x"
} else {
return fmt.Sprintf("x^%d", t.exp)
}
case t.exp == 1:
return fmt.Sprintf("%dx", t.coef)
}
return fmt.Sprintf("%dx^%d", t.coef, t.exp)
}
type poly struct{ terms []term }
// pass coef, exp in pairs as parameters
func newPoly(values ...int) poly {
le := len(values)
if le == 0 {
return poly{[]term{term{0, 0}}}
}
if le%2 != 0 {
log.Fatalf("odd number of parameters (%d) passed to newPoly function", le)
}
var terms []term
for i := 0; i < le; i += 2 {
terms = append(terms, term{values[i], values[i+1]})
}
p := poly{terms}.tidy()
return p
}
func (p poly) hasCoefAbs(coef int) bool {
for _, t := range p.terms {
if iabs(t.coef) == coef {
return true
}
}
return false
}
func (p poly) add(p2 poly) poly {
p3 := newPoly()
le, le2 := len(p.terms), len(p2.terms)
for le > 0 || le2 > 0 {
if le == 0 {
p3.terms = append(p3.terms, p2.terms[le2-1])
le2--
} else if le2 == 0 {
p3.terms = append(p3.terms, p.terms[le-1])
le--
} else {
t := p.terms[le-1]
t2 := p2.terms[le2-1]
if t.exp == t2.exp {
t3 := t.add(t2)
if t3.coef != 0 {
p3.terms = append(p3.terms, t3)
}
le--
le2--
} else if t.exp < t2.exp {
p3.terms = append(p3.terms, t)
le--
} else {
p3.terms = append(p3.terms, t2)
le2--
}
}
}
return p3.tidy()
}
func (p poly) addTerm(t term) poly {
q := newPoly()
added := false
for i := 0; i < len(p.terms); i++ {
ct := p.terms[i]
if ct.exp == t.exp {
added = true
if ct.coef+t.coef != 0 {
q.terms = append(q.terms, ct.add(t))
}
} else {
q.terms = append(q.terms, ct)
}
}
if !added {
q.terms = append(q.terms, t)
}
return q.tidy()
}
func (p poly) mulTerm(t term) poly {
q := newPoly()
for i := 0; i < len(p.terms); i++ {
ct := p.terms[i]
q.terms = append(q.terms, ct.mul(t))
}
return q.tidy()
}
func (p poly) div(v poly) poly {
q := newPoly()
lcv := v.leadingCoef()
dv := v.degree()
for p.degree() >= v.degree() {
lcp := p.leadingCoef()
s := lcp / lcv
t := term{s, p.degree() - dv}
q = q.addTerm(t)
p = p.add(v.mulTerm(t.negate()))
}
return q.tidy()
}
func (p poly) leadingCoef() int {
return p.terms[0].coef
}
func (p poly) degree() int {
return p.terms[0].exp
}
func (p poly) String() string {
var sb strings.Builder
first := true
for _, t := range p.terms {
if first {
sb.WriteString(t.String())
first = false
} else {
sb.WriteString(" ")
if t.coef > 0 {
sb.WriteString("+ ")
sb.WriteString(t.String())
} else {
sb.WriteString("- ")
sb.WriteString(t.negate().String())
}
}
}
return sb.String()
}
// in place descending sort by term.exp
func (p poly) sortTerms() {
sort.Slice(p.terms, func(i, j int) bool {
return p.terms[i].exp > p.terms[j].exp
})
}
// sort terms and remove any unnecesary zero terms
func (p poly) tidy() poly {
p.sortTerms()
if p.degree() == 0 {
return p
}
for i := len(p.terms) - 1; i >= 0; i-- {
if p.terms[i].coef == 0 {
copy(p.terms[i:], p.terms[i+1:])
p.terms[len(p.terms)-1] = term{0, 0}
p.terms = p.terms[:len(p.terms)-1]
}
}
if len(p.terms) == 0 {
p.terms = append(p.terms, term{0, 0})
}
return p
}
func getDivisors(n int) []int {
var divs []int
sqrt := int(math.Sqrt(float64(n)))
for i := 1; i <= sqrt; i++ {
if n%i == 0 {
divs = append(divs, i)
d := n / i
if d != i && d != n {
divs = append(divs, d)
}
}
}
return divs
}
var (
computed = make(map[int]poly)
allFactors = make(map[int]map[int]int)
)
func init() {
f := map[int]int{2: 1}
allFactors[2] = f
}
func getFactors(n int) map[int]int {
if f, ok := allFactors[n]; ok {
return f
}
factors := make(map[int]int)
if n%2 == 0 {
factorsDivTwo := getFactors(n / 2)
for k, v := range factorsDivTwo {
factors[k] = v
}
factors[2]++
if n < maxAllFactors {
allFactors[n] = factors
}
return factors
}
prime := true
sqrt := int(math.Sqrt(float64(n)))
for i := 3; i <= sqrt; i += 2 {
if n%i == 0 {
prime = false
for k, v := range getFactors(n / i) {
factors[k] = v
}
factors[i]++
if n < maxAllFactors {
allFactors[n] = factors
}
return factors
}
}
if prime {
factors[n] = 1
if n < maxAllFactors {
allFactors[n] = factors
}
}
return factors
}
func cycloPoly(n int) poly {
if p, ok := computed[n]; ok {
return p
}
if n == 1 {
// polynomial: x - 1
p := newPoly(1, 1, -1, 0)
computed[1] = p
return p
}
factors := getFactors(n)
cyclo := newPoly()
if _, ok := factors[n]; ok {
// n is prime
for i := 0; i < n; i++ {
cyclo.terms = append(cyclo.terms, term{1, i})
}
} else if len(factors) == 2 && factors[2] == 1 && factors[n/2] == 1 {
// n == 2p
prime := n / 2
coef := -1
for i := 0; i < prime; i++ {
coef *= -1
cyclo.terms = append(cyclo.terms, term{coef, i})
}
} else if len(factors) == 1 {
if h, ok := factors[2]; ok {
// n == 2^h
cyclo.terms = append(cyclo.terms, term{1, 1 << (h - 1)}, term{1, 0})
} else if _, ok := factors[n]; !ok {
// n == p ^ k
p := 0
for prime := range factors {
p = prime
}
k := factors[p]
for i := 0; i < p; i++ {
pk := int(math.Pow(float64(p), float64(k-1)))
cyclo.terms = append(cyclo.terms, term{1, i * pk})
}
}
} else if len(factors) == 2 && factors[2] != 0 {
// n = 2^h * p^k
p := 0
for prime := range factors {
if prime != 2 {
p = prime
}
}
coef := -1
twoExp := 1 << (factors[2] - 1)
k := factors[p]
for i := 0; i < p; i++ {
coef *= -1
pk := int(math.Pow(float64(p), float64(k-1)))
cyclo.terms = append(cyclo.terms, term{coef, i * twoExp * pk})
}
} else if factors[2] != 0 && ((n/2)%2 == 1) && (n/2) > 1 {
// CP(2m)[x] == CP(-m)[x], n odd integer > 1
cycloDiv2 := cycloPoly(n / 2)
for _, t := range cycloDiv2.terms {
t2 := t
if t.exp%2 != 0 {
t2 = t.negate()
}
cyclo.terms = append(cyclo.terms, t2)
}
} else if algo == 0 {
// slow - uses basic definition
divs := getDivisors(n)
// polynomial: x^n - 1
cyclo = newPoly(1, n, -1, 0)
for _, i := range divs {
p := cycloPoly(i)
cyclo = cyclo.div(p)
}
} else if algo == 1 {
// faster - remove max divisor (and all divisors of max divisor)
// only one divide for all divisors of max divisor
divs := getDivisors(n)
maxDiv := math.MinInt32
for _, d := range divs {
if d > maxDiv {
maxDiv = d
}
}
var divsExceptMax []int
for _, d := range divs {
if maxDiv%d != 0 {
divsExceptMax = append(divsExceptMax, d)
}
}
// polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
cyclo = newPoly(1, n, -1, 0)
cyclo = cyclo.div(newPoly(1, maxDiv, -1, 0))
for _, i := range divsExceptMax {
p := cycloPoly(i)
cyclo = cyclo.div(p)
}
} else if algo == 2 {
// fastest
// let p, q be primes such that p does not divide n, and q divides n
// then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
m := 1
cyclo = cycloPoly(m)
var primes []int
for prime := range factors {
primes = append(primes, prime)
}
sort.Ints(primes)
for _, prime := range primes {
// CP(m)[x]
cycloM := cyclo
// compute CP(m)[x^p]
var terms []term
for _, t := range cycloM.terms {
terms = append(terms, term{t.coef, t.exp * prime})
}
cyclo = newPoly()
cyclo.terms = append(cyclo.terms, terms...)
cyclo = cyclo.tidy()
cyclo = cyclo.div(cycloM)
m *= prime
}
// now, m is the largest square free divisor of n
s := n / m
// Compute CP(n)[x] = CP(m)[x^s]
var terms []term
for _, t := range cyclo.terms {
terms = append(terms, term{t.coef, t.exp * s})
}
cyclo = newPoly()
cyclo.terms = append(cyclo.terms, terms...)
} else {
log.Fatal("invalid algorithm")
}
cyclo = cyclo.tidy()
computed[n] = cyclo
return cyclo
}
func main() {
fmt.Println("Task 1: cyclotomic polynomials for n <= 30:")
for i := 1; i <= 30; i++ {
p := cycloPoly(i)
fmt.Printf("CP[%2d] = %s\n", i, p)
}
fmt.Println("\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
n := 0
for i := 1; i <= 10; i++ {
for {
n++
cyclo := cycloPoly(n)
if cyclo.hasCoefAbs(i) {
fmt.Printf("CP[%d] has coefficient with magnitude = %d\n", n, i)
n--
break
}
}
}
} |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #J | J | init=: - {. 1: NB. initial state: 1 square choosen
prop=: < {:,~2 ~:/\ ] NB. propagate: neighboring squares (vertically)
poss=: I.@,@(prop +. prop"1 +. prop&.|. +. prop&.|."1)
keep=: poss -. <:@#@, - I.@, NB. symmetrically valid possibilities
N=: <:@-:@#@, NB. how many neighbors to add
step=: [: ~.@; <@(((= i.@$) +. ])"0 _~ keep)"2
all=: step^:N@init |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.