-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcribbage.go
More file actions
638 lines (566 loc) · 16.3 KB
/
cribbage.go
File metadata and controls
638 lines (566 loc) · 16.3 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Copyright (c) 2020, Michael Cook <michael@waxrat.com>. All rights reserved.
/*
Analyze cribbage hands.
Given a cribbage hand (six cards), which two cards should you discard
to the crib to maximize your chances of getting the best score?
*/
package main
import (
"os"
"fmt"
"sort"
"math"
)
func equals(a, b string) {
if a != b {
panic(fmt.Sprintf("*OOPS* '%v' != '%v'", a, b))
}
}
func equali(a, b int) {
if a != b {
panic(fmt.Sprintf("*OOPS* '%v' != '%v'", a, b))
}
}
func assert(a bool) {
if !a {
panic(fmt.Sprintf("*OOPS*"))
}
}
type rankT int
type suitT int
type cardT struct {
rank rankT
suit suitT
}
func (card cardT) String() string {
return fmt.Sprintf("%c%c", card.rank, card.suit)
}
type handT struct {
slots [52]cardT
numCards int
}
func (hand *handT) cards() []cardT {
return hand.slots[:hand.numCards]
}
func (hand *handT) push(card cardT) {
assert(!hand.has(card))
hand.slots[hand.numCards] = card
hand.numCards++
}
func (hand *handT) pop() cardT {
hand.numCards--
return hand.slots[hand.numCards]
}
func (hand handT) has(wanted cardT) bool {
for _, card := range hand.cards() {
if wanted == card {
return true
}
}
return false
}
func (hand handT) value(i int) int {
r := hand.cards()[i].rank
switch r {
case 'A':
return 1
case '2', '3', '4', '5', '6', '7', '8', '9':
return int(r) - '0'
case 'T', 'J', 'Q', 'K':
return 10
}
panic(fmt.Sprintf("bad rank %v", r))
}
func (hand handT) order(i int) int {
r := hand.cards()[i].rank
switch r {
case 'A':
return 1
case '2', '3', '4', '5', '6', '7', '8', '9':
return int(r) - '0'
case 'T':
return 10
case 'J':
return 11
case 'Q':
return 12
case 'K':
return 13
}
panic(fmt.Sprintf("bad rank %v", r))
}
func (hand handT) String() string {
sep := false
text := ""
for _, card := range hand.cards() {
if sep {
text += " "
}
sep = true
text += card.String()
}
return text
}
func makeHand(text string) handT {
hand := handT{}
rank := rankT(-1)
for _, c := range text {
if c >= 'a' && c <= 'z' {
c += 'A' - 'a'
}
switch c {
case 'H', 'C', 'S', 'D':
if rank == -1 {
panic(fmt.Sprintf("Malformed hand '%s'", text))
}
hand.push(cardT{rank, suitT(c)})
rank = -1
case 'A', '2', '3', '4', '5', '6', '7', '8', '9',
'T', 'J', 'Q', 'K':
if rank != -1 {
panic(fmt.Sprintf("Malformed hand '%s'", text))
}
rank = rankT(c)
case ' ', '-':
break
default:
panic(fmt.Sprintf("Malformed hand '%s'", text))
}
}
if rank != -1 {
panic(fmt.Sprintf("Malformed hand '%s'", text))
}
return hand
}
func score15s(hand handT) int {
equali(hand.numCards, 5)
a := hand.value(0)
b := hand.value(1)
c := hand.value(2)
d := hand.value(3)
e := hand.value(4)
num15s := 0
// five cards - C(5,5)=1
if a + b + c + d + e == 15 {
num15s++
}
// four cards - C(5,4)=5
if a + b + c + d == 15 {
num15s++
}
if a + b + c + e == 15 {
num15s++
}
if a + b + d + e == 15 {
num15s++
}
if a + c + d + e == 15 {
num15s++
}
if b + c + d + e == 15 {
num15s++
}
// three cards - C(5,3)=10
if a + b + c == 15 {
num15s++
}
if a + b + d == 15 {
num15s++
}
if a + b + e == 15 {
num15s++
}
if a + c + d == 15 {
num15s++
}
if a + c + e == 15 {
num15s++
}
if a + d + e == 15 {
num15s++
}
if b + c + d == 15 {
num15s++
}
if b + c + e == 15 {
num15s++
}
if b + d + e == 15 {
num15s++
}
if c + d + e == 15 {
num15s++
}
// two cards - C(5,2)=10
if a + b == 15 {
num15s++
}
if a + c == 15 {
num15s++
}
if a + d == 15 {
num15s++
}
if a + e == 15 {
num15s++
}
if b + c == 15 {
num15s++
}
if b + d == 15 {
num15s++
}
if b + e == 15 {
num15s++
}
if c + d == 15 {
num15s++
}
if c + e == 15 {
num15s++
}
if d + e == 15 {
num15s++
}
return 2 * num15s
}
func scorePairs(hand handT) int {
numPairs := 0
for ai := 0; ai < hand.numCards - 1; ai++ {
for bi := ai + 1; bi < hand.numCards; bi++ {
if hand.slots[ai].rank == hand.slots[bi].rank {
numPairs++
}
}
}
return 2 * numPairs
}
type patternT struct {
score int
delta [4]int
}
const x = -1 // match any rank
var patterns = []patternT{
patternT{12, [4]int{0, 1, 1, 0}}, // AA233
patternT{ 9, [4]int{1, 1, 0, 0}}, // A2333
patternT{ 9, [4]int{1, 0, 0, 1}}, // A2223
patternT{ 9, [4]int{0, 0, 1, 1}}, // AAA23
patternT{ 8, [4]int{1, 1, 1, 0}}, // A2344
patternT{ 8, [4]int{1, 1, 0, 1}}, // A2334
patternT{ 8, [4]int{1, 0, 1, 1}}, // A2234
patternT{ 8, [4]int{0, 1, 1, 1}}, // AA234
patternT{ 6, [4]int{x, 1, 1, 0}}, // xA233
patternT{ 6, [4]int{x, 1, 0, 1}}, // xA223
patternT{ 6, [4]int{x, 0, 1, 1}}, // xAA23
patternT{ 6, [4]int{1, 1, 0, x}}, // A233x
patternT{ 6, [4]int{1, 0, 1, x}}, // A223x
patternT{ 6, [4]int{0, 1, 1, x}}, // AA23x
patternT{ 5, [4]int{1, 1, 1, 1}}, // A2345
patternT{ 4, [4]int{x, 1, 1, 1}}, // xA234
patternT{ 4, [4]int{1, 1, 1, x}}, // A234x
patternT{ 3, [4]int{x, x, 1, 1}}, // xxA23
patternT{ 3, [4]int{x, 1, 1, x}}, // xA23x
patternT{ 3, [4]int{1, 1, x, x}}, // A23xx
}
func scoreRuns(hand handT) int {
equali(hand.numCards, 5)
// Make a sorted sequence of the orders of the cards in the hand.
// The order of Ace is 1, Two is 2, ..., Ten is 10, Jack is 11,
// Queen is 12, King is 13.
orders := []int{
hand.order(0),
hand.order(1),
hand.order(2),
hand.order(3),
hand.order(4),
}
sort.Ints(orders)
// Compare the sorted hand to the PATTERNS. Look at the difference between
// the two cards in each pair of adjacent cards. Stop at the first match.
for _, pattern := range patterns {
previous := orders[0]
j := 0
for {
delta := pattern.delta[j]
order := orders[j + 1]
if delta != x && delta != order - previous {
break
}
previous = order
j++
if j == 4 {
return pattern.score
}
}
}
return 0
}
func scoreFlush(hand handT, isCrib bool) int {
equali(hand.numCards, 5)
suit := hand.slots[0].suit
for i := 1; i < 4; i++ {
if suit != hand.slots[i].suit {
return 0
}
}
// First 4 are the same suit, check the cut card
if suit == hand.slots[4].suit {
return 5
}
// In the crib, a flush counts only if all five cards are the same suit
if isCrib {
return 0
}
return 4
}
func scoreNobs(hand handT) int {
// nobs: one point for the Jack of the same suit as the cut card
equali(hand.numCards, 5)
cutSuit := hand.slots[4].suit
for i := 0; i < 4; i++ {
if hand.slots[i].rank == 'J' &&
hand.slots[i].suit == cutSuit {
return 1
}
}
return 0
}
func scoreHand(hand handT, isCrib bool) int {
return score15s(hand) +
scorePairs(hand) +
scoreRuns(hand) +
scoreFlush(hand, isCrib) +
scoreNobs(hand)
}
const (
maxScore = 29 + 24 // 29 in hand, 24 in crib (44665)
minScore = -29 // 0 in hand, 29 in opp crib
numScores = maxScore - minScore + 1
)
type tallyT struct {
scores [numScores]int
}
func (tally *tallyT) increment(i int) {
tally.scores[i - minScore]++
}
type statisticsT struct {
mean float64
stdev float64
min int
max int
}
func (stats statisticsT) String() string {
return fmt.Sprintf("%.1f %.1f %d..%d", stats.mean, stats.stdev, stats.min, stats.max)
}
func makeStatistics(tally tallyT, numHands int) statisticsT {
min := 0
for i, score := range tally.scores {
if score != 0 {
min = i + minScore
break
}
}
max := 0
for i, score := range tally.scores {
if score != 0 {
max = i + minScore
}
}
sum := 0.0
for score := min; score <= max; score++ {
sum += float64(score * tally.scores[score - minScore])
}
mean := sum / float64(numHands)
sumdev := 0.0
for score := min; score <= max; score++ {
d := float64(score) - mean
sumdev += d * d;
}
stdev := math.Sqrt(sumdev / float64(numHands))
return statisticsT{mean, stdev, min, max}
}
type chooseT struct {
hand handT
numChoose int
chosen handT
i int
iStack []int
resume bool
}
/* A chan-based implementation of `choose` was measured to be 56% slower than
the following func-based implementation */
func choose(hand handT, numChoose int) *chooseT {
c := new(chooseT)
c.hand = hand
c.numChoose = numChoose
return c
}
func (c *chooseT) more() bool {
if c.resume {
c.resume = false
c.chosen.pop()
// i = iStack.pop() + 1
c.i = c.iStack[len(c.iStack) - 1] + 1
c.iStack = c.iStack[:len(c.iStack)-1]
}
for {
if c.chosen.numCards == c.numChoose {
c.resume = true
return true
}
if c.i != c.hand.numCards {
c.chosen.push(c.hand.cards()[c.i])
c.iStack = append(c.iStack, c.i)
c.i++
} else if len(c.iStack) > 0 {
c.chosen.pop()
// i = iStack.pop() + 1
c.i = c.iStack[len(c.iStack) - 1] + 1
c.iStack = c.iStack[:len(c.iStack)-1]
} else {
return false
}
}
}
func makeDeck(exclude handT) handT {
// Make an entire deck of cards but leave out any cards in `exclude`
deck := handT{}
for _, suit := range "HCDS" {
for _, rank := range "A23456789TJQK" {
card := cardT{rankT(rank), suitT(suit)}
if !exclude.has(card) {
deck.push(card)
}
}
}
return deck
}
func analyzeHand(hand handT) {
/*
Find all possible pairs of cards to discard to the crib.
There are C(6,2)=15 possible discards in a cribbage hand.
*/
discard := choose(hand, 2)
for discard.more() {
hold := handT{}
for _, card := range hand.cards() {
if !discard.chosen.has(card) {
hold.push(card)
}
}
deck := makeDeck(hand)
equali(deck.numCards, 46)
mineTally := tallyT{} // scores when the crib is mine
theirsTally := tallyT{} // scores then the crib is theirs
numHands := 0
dealt := choose(deck, 2)
for dealt.more() {
card1 := dealt.chosen.slots[0]
card2 := dealt.chosen.slots[1]
crib := discard.chosen
crib.push(card1)
crib.push(card2)
for _, cut := range deck.cards() {
if cut == card1 || cut == card2 {
continue
}
hold.push(cut)
holdScore := scoreHand(hold, false)
hold.pop()
crib.push(cut)
cribScore := scoreHand(crib, true)
crib.pop()
mineScore := holdScore + cribScore
theirsScore := holdScore - cribScore
numHands++
mineTally.increment(mineScore)
theirsTally.increment(theirsScore)
}
}
// deck size: 46, C(46,2)=1035
// remaining_deck size: 44
equali(numHands, 1035 * 44);
ifMine := makeStatistics(mineTally, numHands)
ifTheirs := makeStatistics(theirsTally, numHands)
fmt.Printf("%s [%s] [%s]\n", discard.chosen, ifMine, ifTheirs)
}
}
func main() {
equals("5H 5C 5S JD 5D", makeHand("5H 5C 5S JD 5D").String())
equals("5H 5C 5S JD 5D", makeHand("5h5c5sjd5d").String())
equals("AH AS JH AC AD", makeHand("ah-as-jh-ac-ad").String())
assert(makeHand("5H").has(cardT{'5', 'H'}))
assert(!makeHand("5C").has(cardT{'5', 'H'}))
assert(!makeHand("6H").has(cardT{'5', 'H'}))
equali( 4, score15s(makeHand("AH 2H 3H JH QH")))
equali( 8, score15s(makeHand("5H 2H 3H JH QH")))
equali(16, score15s(makeHand("5H 5S 5C 5D TH")))
equali( 8, score15s(makeHand("6C 6D 4D 4S 5D")))
equali(12, scorePairs(makeHand("5H 5S 5C 5D TH")))
equali( 8, scorePairs(makeHand("TS 5S 5C 5D TH")))
equali( 4, scorePairs(makeHand("6C 6D 4D 4S 5D")))
equali( 9, scoreRuns(makeHand("AH 2H 3H 3D 3C")))
equali( 9, scoreRuns(makeHand("KH KD KC JH QH"))) // same pattern A2333
equali( 9, scoreRuns(makeHand("AH 2H 2D 2C 3H")))
equali( 9, scoreRuns(makeHand("AH AD AC 2H 3H")))
equali( 8, scoreRuns(makeHand("AH 2H 3H 4H 4D")))
equali( 8, scoreRuns(makeHand("AH 2H 3H 3D 4H")))
equali( 8, scoreRuns(makeHand("AH 2H 2C 3H 4H")))
equali( 8, scoreRuns(makeHand("AS AH 2H 3H 4H")))
equali( 6, scoreRuns(makeHand("JH AH 2H 3D 3H")))
equali( 6, scoreRuns(makeHand("JH AH 2S 2H 3H")))
equali( 6, scoreRuns(makeHand("JH AH AS 2H 3H")))
equali( 6, scoreRuns(makeHand("AH 2H 3S 3H JH")))
equali( 6, scoreRuns(makeHand("AH 2H 2S 3H JH")))
equali( 6, scoreRuns(makeHand("AH AS 2H 3H JH")))
equali( 5, scoreRuns(makeHand("AH 2H 3H 4H 5H")))
equali( 4, scoreRuns(makeHand("JH AH 2H 3H 4H")))
equali( 4, scoreRuns(makeHand("AH 2H 3H 4H JH")))
equali( 3, scoreRuns(makeHand("JH QH AH 2H 3H")))
equali( 3, scoreRuns(makeHand("JH AH 2H 3H TH")))
equali( 3, scoreRuns(makeHand("AH 2H 3H JH TH")))
equali( 0, scoreRuns(makeHand("AH 8H 3H JH TH")))
equali(12, scoreRuns(makeHand("6C 6D 4D 4S 5D")))
equali( 5, scoreFlush(makeHand("5H 6H 7H 8H 9H"), false))
equali( 4, scoreFlush(makeHand("5H 6H 7H 8H 9D"), false))
equali( 0, scoreFlush(makeHand("5H 6H 7H 8H 9D"), true))
equali( 0, scoreFlush(makeHand("5H 6H 7H 8D 9D"), false))
equali( 1, scoreNobs(makeHand("JH 2C 3C 4C 5H")))
equali( 0, scoreNobs(makeHand("JH 2C 3C 4C 5C")))
equali(12, scoreHand(makeHand("AH AS JH AC AD"), false)) // 4oak ("of a kind")
equali(13, scoreHand(makeHand("AH AS JD AC AD"), false)) // ...plus right jack
equali( 5, scoreHand(makeHand("AH 3H 7H TH JH"), false)) // 5 hearts
equali( 5, scoreHand(makeHand("AH 3H 7H TH JH"), true)) // 5 hearts but crib
equali( 4, scoreHand(makeHand("AH 3H 7H TH JS"), false)) // 4 hearts
equali( 0, scoreHand(makeHand("AH 3H 7S TH JH"), false)) // 4 hearts but with cut
equali( 0, scoreHand(makeHand("AH 3H 7H TH JS"), true)) // 4 hearts but crib
equali( 7, scoreHand(makeHand("AH 2S 3C 5D JH"), false)) // 15/4 + run/3
equali(20, scoreHand(makeHand("7H 7S 7C 8D 8H"), false)) // 15/12 + 3oak + 2oak
equali(15, scoreHand(makeHand("AH 2H 3H 3S 3D"), false)) // triple run/3
equali(15, scoreHand(makeHand("3H AH 3S 2H 3D"), false)) // triple run/3
equali(29, scoreHand(makeHand("5H 5C 5S JD 5D"), false))
equali(28, scoreHand(makeHand("5H 5C 5S 5D JD"), false))
equali(24, scoreHand(makeHand("6C 4D 6D 4S 5D"), false))
{
t := tallyT{}
for i, v := range []int{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 907, 411, 1419, 650,
1855, 663, 1908, 931, 1671, 650, 1699, 530, 607, 137,
291, 160, 228, 111, 66, 106, 5, 61, 7, 26, 0, 30, 0,
41, 0, 4, 3, 0, 0, 0, 2, 0, 0, 1 } {
t.scores[i] = v
}
s := makeStatistics(t, 15180)
equals(s.String(), "22.9 0.8 16..53")
}
for _, arg := range os.Args[1:] {
hand := makeHand(arg)
if hand.numCards != 6 {
panic(fmt.Sprintf("Wrong number of cards in hand: %s", hand))
}
fmt.Printf("[ %s ]\n", hand)
analyzeHand(hand)
fmt.Println()
}
}