dealbreaker 1.4.0

A data-driven solver for patience / solitaire card games: describe a game's rules as data, get solutions or proofs of unsolvability.
Documentation
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
//! Scoring positions, for games played for points (Poker Squares, Cribbage Squares).
//!
//! A score rule names a grid group; each row and each column is a hand. The solver needs two
//! things from it: the exact score of a position, and an upper bound on the score of any
//! position reachable from it. The bound is what lets a search discard a line of play without
//! exploring it, so it must never be too low.
//!
//! Jokers are wild: in each hand, a joker counts as whichever card scores that hand best.

use std::sync::Arc;

use crate::card::Card;
use crate::game::{Game, State};
use crate::rules::{CribbagePoints, PokerPoints};

/// Poker hands in the usual ranking order.
const PAIR: usize = 1;
const TWO_PAIR: usize = 2;
const THREE: usize = 3;
const STRAIGHT: usize = 4;
const FLUSH: usize = 5;
const FULL_HOUSE: usize = 6;
const FOUR: usize = 7;
const STRAIGHT_FLUSH: usize = 8;
const ROYAL_FLUSH: usize = 9;

/// Where the cards still to enter the scored group can come from.
#[derive(Clone, Debug)]
pub(crate) enum Pool {
    /// Cards leave the scored group, so nothing in it is settled: no bound.
    Unbounded,
    /// Any card outside the group may still arrive.
    Outside,
    /// Cards arrive only from the waste, one at a time, and the waste is fed only from the
    /// stock when empty: the next cards are known exactly (the waste card, then the stock from
    /// the top).
    NextFromStock { stock: u16, waste: u16 },
}

/// What the cribbage starter will be, as far as the bound can tell.
#[derive(Clone, Debug)]
pub(crate) enum StarterBound {
    /// No starter, ever.
    None,
    /// The bottom card of a pile nothing enters or leaves.
    Fixed(u16),
    /// The waste card after the grid is filled from the waste ([`Pool::NextFromStock`]).
    NextInSequence,
    /// Any card outside the grid.
    Unknown,
}

/// How a line of cards scores.
#[derive(Clone, Debug)]
pub(crate) enum HandScoring {
    Poker {
        /// Points by hand, indexed by the constants above (0: nothing).
        points: [u32; 10],
        /// Hands, most points first.
        order: [usize; 10],
        /// Points never fall as hands rise, so the highest hand a joker can make scores best.
        monotone: bool,
    },
    Cribbage {
        points: CribbagePoints,
        /// The pile whose bottom card is the starter (a waste holds just the one).
        starter: Option<u16>,
        starter_bound: StarterBound,
        /// Best fifteens, pairs and runs reachable from each rank multiset (see [`rank_key`]).
        best: Arc<Vec<u32>>,
    },
}

/// A compiled score rule.
#[derive(Clone, Debug)]
pub(crate) struct Score {
    pub group: u16,
    /// Piles of each line (rows, then columns).
    pub lines: Vec<Vec<u16>>,
    pub hands: HandScoring,
    pub pool: Pool,
    /// Rows are interchangeable, and so are columns: permuting either gives an equally good
    /// position. Then a card going into an empty row only needs trying in the first empty row
    /// (likewise columns).
    pub symmetric: bool,
    /// Grid size.
    pub rows: u16,
    pub columns: u16,
}

/// Hands ordered by their points, most first.
pub(crate) fn points_order(points: &[u32; 10]) -> [usize; 10] {
    let mut o = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    o.sort_by_key(|&h| std::cmp::Reverse(points[h]));
    o
}

pub(crate) fn points_table(p: &PokerPoints) -> [u32; 10] {
    [
        0,
        p.pair,
        p.two_pair,
        p.three,
        p.straight,
        p.flush,
        p.full_house,
        p.four,
        p.straight_flush,
        p.royal_flush,
    ]
}

/// The ten straights, as rank bit sets (bit r for rank r; the ace is bit 1 and bit 14).
const STRAIGHTS: [u16; 10] = {
    let mut w = [0u16; 10];
    let mut lo = 1;
    while lo <= 10 {
        w[lo - 1] = 0b11111 << lo;
        lo += 1;
    }
    w
};
const ROYAL: u16 = 0b11111 << 10;

/// A rank's bits: the ace is low and high.
fn rank_bit(r: u8) -> u16 {
    if r == 1 {
        1 << 1 | 1 << 14
    } else {
        1 << r
    }
}

/// Card counts for one line (or a pool of cards). Jokers are only counted.
#[derive(Clone, Default)]
struct Counts {
    rank: [u16; 14],
    suit: [u16; 4],
    total: u32,
    jokers: u32,
    /// Ranks present, overall and per suit (see [`rank_bit`]).
    ranks: u16,
    suit_ranks: [u16; 4],
}

impl Counts {
    fn add(&mut self, c: Card) {
        self.total += 1;
        if c.is_joker() {
            self.jokers += 1;
            return;
        }
        self.rank[c.rank() as usize] += 1;
        self.suit[c.suit() as usize] += 1;
        let bit = rank_bit(c.rank());
        self.ranks |= bit;
        self.suit_ranks[c.suit() as usize] |= bit;
    }

    /// Real cards.
    fn real(&self) -> u32 {
        self.total - self.jokers
    }
}

/// The best (highest-ranking) poker hand among these cards, each joker standing for any card.
fn hand(c: &Counts) -> usize {
    if c.jokers == 0 {
        return hand_no_jokers(c);
    }
    // With nothing to draw but the jokers, which can be anything, possible means present.
    15 - (possible(c, &Counts::default(), c.jokers, c.jokers) | 1).leading_zeros() as usize
}

/// Fast exact poker hand classifier when there are no jokers.
#[inline]
fn hand_no_jokers(c: &Counts) -> usize {
    if c.total < 2 {
        return 0;
    }
    let (mut pairs, mut three, mut four) = (0u8, 0u8, false);
    for &cnt in &c.rank[1..14] {
        match cnt {
            0 | 1 => {}
            2 => pairs += 1,
            3 => three += 1,
            _ => four = true,
        }
    }
    let full_house = three >= 2 || (three >= 1 && pairs > 0);
    let flush_suit = if c.total >= 5 {
        c.suit.iter().position(|&s| s >= 5)
    } else {
        None
    };
    if let Some(s) = flush_suit {
        let sr = c.suit_ranks[s];
        if (sr & ROYAL) == ROYAL {
            return ROYAL_FLUSH;
        }
        for w in STRAIGHTS {
            if (sr & w) == w {
                return STRAIGHT_FLUSH;
            }
        }
        if four {
            return FOUR;
        }
        if full_house {
            return FULL_HOUSE;
        }
        return FLUSH;
    }
    if four {
        return FOUR;
    }
    if full_house {
        return FULL_HOUSE;
    }
    if c.total >= 5 {
        for w in STRAIGHTS {
            if (c.ranks & w) == w {
                return STRAIGHT;
            }
        }
    }
    if three >= 1 {
        THREE
    } else if pairs >= 2 {
        TWO_PAIR
    } else if pairs == 1 {
        PAIR
    } else {
        0
    }
}

/// Points for a poker line. Each joker stands for the card that scores best: with points that
/// follow the hands' ranking that's the highest hand it can make, otherwise every card is tried.
fn poker_points(c: &Counts, points: &[u32; 10], monotone: bool) -> u32 {
    if c.jokers == 0 || monotone {
        return points[hand(c)];
    }
    let mut most = 0;
    for f in 0..52u8 {
        let mut d = c.clone();
        d.jokers -= 1;
        d.total -= 1;
        d.add(Card::from_face(f));
        most = most.max(poker_points(&d, points, monotone));
    }
    most
}

/// Which poker hands (as a bit set) a line holding `have` (real cards) could make with up to
/// `slots` more cards drawn from `pool`, of which up to `wild` may be any card at all. Bit 0,
/// no hand, is always set. Possible is relaxed: each hand is tested alone, as if every other
/// card could be anything, so it can say yes when the truth is no, never the reverse. With an
/// empty pool and `wild == slots` filling the line, it is exact.
#[allow(clippy::needless_range_loop)]
fn possible(have: &Counts, pool: &Counts, slots: u32, wild: u32) -> u16 {
    let mut set = 1u16;
    // Cards needed from the pool to hold `n` of rank r.
    let need_rank = |r: usize, n: u16| -> Option<u32> {
        let k = n.saturating_sub(have.rank[r]) as u32;
        (pool.rank[r] as u32 + wild >= k && k <= slots).then_some(k)
    };
    // Cheapest cost to reach 2, 3 and 4 of a rank, and the second cheapest pair (other rank).
    let (mut pair, mut pair2, mut pair_rank) = (u32::MAX, u32::MAX, 0usize);
    let (mut three, mut four) = (false, false);
    let mut full = false;
    let mut k3 = [u32::MAX; 14];
    for r in 1..14 {
        if let Some(k) = need_rank(r, 2) {
            if k < pair {
                pair2 = pair;
                pair = k;
                pair_rank = r;
            } else if k < pair2 {
                pair2 = k;
            }
        }
        if let Some(k) = need_rank(r, 3) {
            three = true;
            k3[r] = k;
        }
        four |= need_rank(r, 4).is_some();
    }
    if pair != u32::MAX {
        set |= 1 << PAIR;
    }
    if pair2 != u32::MAX && pair + pair2 <= slots {
        set |= 1 << TWO_PAIR;
    }
    if three {
        set |= 1 << THREE;
        for (r, &k) in k3.iter().enumerate() {
            let other = if r == pair_rank { pair2 } else { pair };
            if k != u32::MAX && other != u32::MAX && k + other <= slots {
                full = true;
                break;
            }
        }
    }
    if full {
        set |= 1 << FULL_HOUSE;
    }
    if four {
        set |= 1 << FOUR;
    }
    if (0..4).any(|s| {
        let k = 5u32.saturating_sub(have.suit[s] as u32);
        pool.suit[s] as u32 + wild >= k && k <= slots
    }) {
        set |= 1 << FLUSH;
    }
    let reachable = |missing: u16, from: u16| {
        missing.count_ones() <= slots && (missing & !from).count_ones() <= wild
    };
    for w in STRAIGHTS {
        if reachable(w & !have.ranks, pool.ranks) {
            set |= 1 << STRAIGHT;
            // A straight flush needs the same ranks in one suit.
            for s in 0..4 {
                if reachable(w & !have.suit_ranks[s], pool.suit_ranks[s]) {
                    set |= 1
                        << if w == ROYAL {
                            ROYAL_FLUSH
                        } else {
                            STRAIGHT_FLUSH
                        };
                }
            }
        }
    }
    set
}

// ----- Cribbage ---------------------------------------------------------------------------

/// Points from fifteens, pairs and runs: the part of a cribbage hand that depends only on
/// ranks. `count[r]` cards of rank r (1..=13).
fn rank_points(p: &CribbagePoints, count: &[u8; 14]) -> u32 {
    let mut values = [0u8; 16];
    let mut n = 0;
    for r in 1..14u8 {
        for _ in 0..count[r as usize] {
            if n < values.len() {
                values[n] = r.min(10);
                n += 1;
            }
        }
    }
    let mut fifteens = 0u32;
    if p.fifteen > 0 {
        // Subset sums by dynamic programming: ways[t] = subsets so far adding to t.
        let mut ways = [0u32; 16];
        ways[0] = 1;
        for &v in &values[..n] {
            for t in (v as usize..16).rev() {
                ways[t] += ways[t - v as usize];
            }
        }
        fifteens = ways[15];
    }
    let pairs: u32 = count
        .iter()
        .map(|&c| c as u32 * (c as u32).saturating_sub(1) / 2)
        .sum();
    let mut runs = 0u32;
    let mut r = 1;
    while r < 14 {
        if count[r] == 0 {
            r += 1;
            continue;
        }
        let start = r;
        let mut ways = 1u32;
        while r < 14 && count[r] > 0 {
            ways *= count[r] as u32;
            r += 1;
        }
        let len = (r - start) as u32;
        if len >= 3 {
            runs += len * ways;
        }
    }
    fifteens
        .saturating_mul(p.fifteen)
        .saturating_add(pairs.saturating_mul(p.pair))
        .saturating_add(runs.saturating_mul(p.run_card))
}

/// A cribbage hand's points: the line's cards plus the starter, jokers standing for whatever
/// scores best. A flush needs `full` (the line complete) and four or more cards in the line.
pub(crate) fn cribbage_hand(
    p: &CribbagePoints,
    line: &[Card],
    starter: Option<Card>,
    full: bool,
) -> u32 {
    if let Some(i) = line.iter().position(|c| c.is_joker()) {
        let mut v = line.to_vec();
        return (0..52u8)
            .map(|f| {
                v[i] = Card::from_face(f);
                cribbage_hand(p, &v, starter, full)
            })
            .max()
            .unwrap_or(0);
    }
    if starter.is_some_and(|c| c.is_joker()) {
        return (0..52u8)
            .map(|f| cribbage_hand(p, line, Some(Card::from_face(f)), full))
            .max()
            .unwrap_or(0);
    }
    let mut count = [0u8; 14];
    for c in line.iter().chain(starter.iter()) {
        count[c.rank() as usize] += 1;
    }
    let mut pts = rank_points(p, &count);
    if full && line.len() >= 4 && line.iter().all(|c| c.suit() == line[0].suit()) {
        pts = pts.saturating_add(p.flush);
        if starter.is_some_and(|s| s.suit() == line[0].suit()) {
            pts = pts.saturating_add(p.flush_starter);
        }
    }
    if let Some(st) = starter {
        if line.iter().any(|c| c.rank() == 11 && c.suit() == st.suit()) {
            pts = pts.saturating_add(p.nobs);
        }
    }
    pts
}

/// Cards in the largest hand [`best_rank_points`] covers: a four-card line and the starter.
const MAX_HAND: usize = 5;

/// A key for a multiset of up to [`MAX_HAND`] ranks: its ranks in ascending order, as base-14
/// digits.
fn rank_key(count: &[u8; 14]) -> usize {
    let mut k = 0usize;
    for (r, &n) in count.iter().enumerate().skip(1) {
        for _ in 0..n {
            k = k * 14 + r;
        }
    }
    k
}

/// For every multiset of up to five ranks, the most rank points (fifteens, pairs, runs) of any
/// five-card multiset containing it with at most `cap` cards of a rank. Adding a card never
/// loses rank points, so this bounds every such hand of five or fewer cards that contains the
/// multiset.
pub(crate) fn best_rank_points(p: &CribbagePoints, cap: u8) -> Vec<u32> {
    let mut best = vec![0u32; 14usize.pow(MAX_HAND as u32)];
    // Multisets by size, largest first, so each extension is known before it's needed.
    fn each(size: usize, min: usize, count: &mut [u8; 14], f: &mut dyn FnMut(&[u8; 14])) {
        if size == 0 {
            f(count);
            return;
        }
        for r in min..14 {
            count[r] += 1;
            each(size - 1, r, count, f);
            count[r] -= 1;
        }
    }
    let mut count = [0u8; 14];
    for size in (0..=MAX_HAND).rev() {
        each(size, 1, &mut count, &mut |c| {
            let v = if size == MAX_HAND {
                rank_points(p, c)
            } else {
                let mut c2 = *c;
                (1..14)
                    .filter(|&r| c[r] < cap)
                    .map(|r| {
                        c2[r] += 1;
                        let v = best[rank_key(&c2)];
                        c2[r] -= 1;
                        v
                    })
                    .max()
                    .unwrap_or(0)
            };
            best[rank_key(c)] = v;
        });
    }
    best
}

impl Score {
    fn line_counts(&self, s: &State, line: &[u16]) -> Counts {
        let mut c = Counts::default();
        for &p in line {
            for &card in &s.piles[p as usize] {
                c.add(card);
            }
        }
        c
    }

    fn grid_full(&self, s: &State) -> bool {
        self.lines[..self.rows as usize]
            .iter()
            .flatten()
            .all(|&p| !s.piles[p as usize].is_empty())
    }

    /// True when cards can leave the scored group, so `bound()` is always `u32::MAX`.
    pub(crate) fn is_unbounded(&self) -> bool {
        matches!(self.pool, Pool::Unbounded)
    }

    /// Does every row of the grid score at least `n` points as a hand of its own?
    pub(crate) fn every_row_scores(&self, s: &State, n: u32) -> bool {
        match &self.hands {
            HandScoring::Poker {
                points, monotone, ..
            } => self.lines[..self.rows as usize]
                .iter()
                .all(|l| poker_points(&self.line_counts(s, l), points, *monotone) >= n),
            HandScoring::Cribbage { .. } => false,
        }
    }

    /// Total shortfall across rows below `target` (0 when every row meets `target`).
    pub(crate) fn each_row_shortfall(&self, s: &State, target: u32) -> u32 {
        match &self.hands {
            HandScoring::Poker {
                points, monotone, ..
            } => self.lines[..self.rows as usize]
                .iter()
                .fold(0u32, |acc, l| {
                    let v = poker_points(&self.line_counts(s, l), points, *monotone);
                    acc.saturating_add(target.saturating_sub(v))
                }),
            HandScoring::Cribbage { .. } => target.saturating_mul(self.rows as u32),
        }
    }

    /// Points for a position.
    pub fn score(&self, s: &State) -> u32 {
        match &self.hands {
            HandScoring::Poker {
                points, monotone, ..
            } => self.lines.iter().fold(0u32, |acc, l| {
                acc.saturating_add(poker_points(&self.line_counts(s, l), points, *monotone))
            }),
            HandScoring::Cribbage {
                points, starter, ..
            } => {
                let starter = starter
                    .filter(|_| self.grid_full(s))
                    .and_then(|p| s.piles[p as usize].first())
                    .map(|c| c.up());
                let mut total = 0u32;
                let mut cards = Vec::new();
                for line in &self.lines {
                    cards.clear();
                    let mut full = true;
                    for &p in line {
                        let pile = &s.piles[p as usize];
                        full &= !pile.is_empty();
                        cards.extend(pile.iter().map(|c| c.up()));
                    }
                    total = total.saturating_add(cribbage_hand(points, &cards, starter, full));
                }
                if starter.is_some_and(|c| c.is_joker() || c.rank() == 11) {
                    total = total.saturating_add(points.heels);
                }
                total
            }
        }
    }

    /// An upper bound on the score of any position reachable from `s`.
    pub fn bound(&self, g: &Game, s: &State) -> u32 {
        let outside = || {
            let mut c = Counts::default();
            for (p, pile) in s.piles.iter().enumerate() {
                if g.pile_group[p] != self.group {
                    for &card in pile {
                        c.add(card);
                    }
                }
            }
            c
        };
        // The cards that may still arrive, and the card after them in sequence.
        let (pool, total, next) = match &self.pool {
            Pool::Unbounded => return u32::MAX,
            Pool::Outside => {
                let c = outside();
                let t = c.total;
                (c, t, Counts::default())
            }
            Pool::NextFromStock { stock, waste } => {
                let free: u32 = g.groups[self.group as usize]
                    .piles()
                    .map(|p| self.room(g, s, p))
                    .sum();
                let mut c = Counts::default();
                let mut next = Counts::default();
                let mut left = free;
                let sequence = s.piles[*waste as usize]
                    .iter()
                    .rev()
                    .chain(s.piles[*stock as usize].iter().rev());
                for &card in sequence {
                    if left == 0 {
                        next.add(card.up());
                        break;
                    }
                    c.add(card.up());
                    left -= 1;
                }
                let t = c.total;
                (c, t, next)
            }
        };
        match &self.hands {
            HandScoring::Poker { points, order, .. } => {
                let mut sum = 0u32;
                for line in &self.lines {
                    let have = self.line_counts(s, line);
                    let slots = self.line_room(g, s, line).min(total);
                    // Held jokers are free choices that use no slot; arriving ones, at most
                    // one per slot.
                    let held = have.jokers;
                    let set = possible(&have, &pool, slots + held, held + pool.jokers.min(slots));
                    let best = order
                        .iter()
                        .copied()
                        .find(|&h| set >> h & 1 != 0)
                        .map_or(0, |h| points[h]);
                    sum = sum.saturating_add(best);
                }
                sum
            }
            HandScoring::Cribbage {
                points,
                starter_bound,
                best,
                ..
            } => {
                let starter = match starter_bound {
                    StarterBound::None => Counts::default(),
                    StarterBound::Fixed(p) => {
                        let mut c = Counts::default();
                        if let Some(&card) = s.piles[*p as usize].first() {
                            c.add(card.up());
                        }
                        c
                    }
                    StarterBound::NextInSequence => next,
                    StarterBound::Unknown => outside(),
                };
                let mut sum = 0u32;
                for line in &self.lines {
                    let have = self.line_counts(s, line);
                    let slots = self.line_room(g, s, line).min(total);
                    sum = sum.saturating_add(self.cribbage_line_bound(
                        points,
                        best,
                        &have,
                        &pool,
                        slots,
                        &starter,
                        line.len(),
                    ));
                }
                if points.heels > 0 && (starter.jokers > 0 || starter.rank[11] > 0) {
                    sum = sum.saturating_add(points.heels);
                }
                sum
            }
        }
    }

    /// The most a cribbage line holding `have` could score, with up to `slots` more cards from
    /// `pool` and a starter from `starter` (no starter if it's empty). Fifteens, pairs and runs
    /// are bounded together; flush and nobs separately.
    #[allow(clippy::too_many_arguments)]
    fn cribbage_line_bound(
        &self,
        p: &CribbagePoints,
        best: &[u32],
        have: &Counts,
        pool: &Counts,
        slots: u32,
        starter: &Counts,
        line_len: usize,
    ) -> u32 {
        let has_starter = starter.total > 0;
        // A starter of one known real card is fixed; otherwise it's one more free choice.
        let known = (starter.total == 1 && starter.jokers == 0)
            .then(|| (1..14).find(|&r| starter.rank[r] > 0).unwrap());
        let fixed_n: usize =
            have.rank.iter().map(|&c| c as usize).sum::<usize>() + usize::from(known.is_some());
        let free = (have.jokers + slots) as usize + usize::from(has_starter && known.is_none());
        if fixed_n + free > MAX_HAND {
            // Bigger hands than the table knows: no useful bound.
            return u32::MAX / 4;
        }
        let mut fixed = [0u8; 14];
        for r in 1..14 {
            fixed[r] = have.rank[r] as u8;
        }
        if let Some(r) = known {
            fixed[r] += 1;
        }
        let rank_part = if free == 0 {
            rank_points(p, &fixed)
        } else if free <= 2 {
            // Few enough to try every choice of ranks the arriving cards could have.
            // Precompute fixed cards' subset-sum DP and pair count once, then extend incrementally
            // so `free == 2` avoids recomputing the DP up to 91 times per line.
            let any = have.jokers > 0 || pool.jokers > 0 || starter.jokers > 0;
            let mut avail = [0usize; 13];
            let mut avail_len = 0usize;
            for r in 1..14 {
                if any || pool.rank[r] > 0 || starter.rank[r] > 0 {
                    avail[avail_len] = r;
                    avail_len += 1;
                }
            }
            let avail = &avail[..avail_len];
            let mut base_ways = [0u32; 16];
            base_ways[0] = 1;
            if p.fifteen > 0 {
                for (r, &cnt) in fixed.iter().enumerate().skip(1) {
                    let v = r.min(10);
                    for _ in 0..cnt {
                        for t in (v..16).rev() {
                            base_ways[t] += base_ways[t - v];
                        }
                    }
                }
            }
            let base_pairs: u32 = fixed[1..14]
                .iter()
                .map(|&c| c as u32 * (c as u32).saturating_sub(1) / 2)
                .sum();
            let run_score = |cnt: &[u8; 14]| -> u32 {
                if p.run_card == 0 {
                    return 0;
                }
                let mut runs = 0u32;
                let mut r = 1;
                while r < 14 {
                    if cnt[r] == 0 {
                        r += 1;
                        continue;
                    }
                    let start = r;
                    let mut ways = 1u32;
                    while r < 14 && cnt[r] > 0 {
                        ways *= cnt[r] as u32;
                        r += 1;
                    }
                    let len = (r - start) as u32;
                    if len >= 3 {
                        runs += len * ways;
                    }
                }
                runs.saturating_mul(p.run_card)
            };
            let mut most = base_ways[15]
                .saturating_mul(p.fifteen)
                .saturating_add(base_pairs.saturating_mul(p.pair))
                .saturating_add(run_score(&fixed));
            let mut c = fixed;
            for (i, &a) in avail.iter().enumerate() {
                let va = a.min(10);
                let pairs_a = base_pairs + c[a] as u32;
                c[a] += 1;
                if free == 1 {
                    let f15 = if p.fifteen > 0 {
                        base_ways[15] + base_ways[15 - va]
                    } else {
                        0
                    };
                    let pts = f15
                        .saturating_mul(p.fifteen)
                        .saturating_add(pairs_a.saturating_mul(p.pair))
                        .saturating_add(run_score(&c));
                    most = most.max(pts);
                } else {
                    let mut ways_a = base_ways;
                    if p.fifteen > 0 {
                        for t in (va..16).rev() {
                            ways_a[t] += ways_a[t - va];
                        }
                    }
                    for &b in &avail[i..] {
                        let vb = b.min(10);
                        let pairs_ab = pairs_a + c[b] as u32;
                        c[b] += 1;
                        let f15 = if p.fifteen > 0 {
                            ways_a[15] + ways_a[15 - vb]
                        } else {
                            0
                        };
                        let pts = f15
                            .saturating_mul(p.fifteen)
                            .saturating_add(pairs_ab.saturating_mul(p.pair))
                            .saturating_add(run_score(&c));
                        most = most.max(pts);
                        c[b] -= 1;
                    }
                }
                c[a] -= 1;
            }
            most
        } else {
            best[rank_key(&fixed)]
        };
        let mut pts = rank_part;
        // Flush: every real card of the full line in one suit, the rest able to follow.
        if line_len >= 4 && (p.flush > 0 || p.flush_starter > 0) {
            let mut suits = [0usize; 4];
            let mut nsuits = 0usize;
            for s in 0..4 {
                if have.suit[s] as u32 == have.real() && pool.suit[s] as u32 + pool.jokers >= slots
                {
                    suits[nsuits] = s;
                    nsuits += 1;
                }
            }
            if nsuits > 0 {
                let starter_too = suits[..nsuits]
                    .iter()
                    .any(|&s| starter.suit[s] > 0 || starter.jokers > 0);
                pts = pts.saturating_add(p.flush).saturating_add(if starter_too {
                    p.flush_starter
                } else {
                    0
                });
            }
        }
        // Nobs: a jack in the line of the starter's suit.
        if p.nobs > 0 && has_starter {
            let can_get_jack = |s: usize| {
                have.jokers > 0
                    || (slots > 0 && (pool.jokers > 0 || (pool.suit_ranks[s] >> 11) & 1 != 0))
                    || (have.suit_ranks[s] >> 11) & 1 != 0
            };
            if (0..4).any(|s| (starter.suit[s] > 0 || starter.jokers > 0) && can_get_jack(s)) {
                pts = pts.saturating_add(p.nobs);
            }
        }
        pts
    }

    /// Cards pile `p` can still take.
    fn room(&self, g: &Game, s: &State, p: u16) -> u32 {
        (g.pile_rules[p as usize].max_cards as usize).saturating_sub(s.piles[p as usize].len())
            as u32
    }

    fn line_room(&self, g: &Game, s: &State, line: &[u16]) -> u32 {
        line.iter().map(|&p| self.room(g, s, p)).sum()
    }

    /// With symmetric rows and columns, placing a card into an empty row other than the first
    /// empty one (or an empty column other than the first) adds nothing new.
    pub fn redundant(&self, g: &Game, s: &State, to: u16) -> bool {
        if !self.symmetric {
            return false;
        }
        let gr = &g.groups[self.group as usize];
        if !gr.piles().contains(&to) {
            return false;
        }
        let i = to - gr.start;
        let (r, c) = (i / self.columns, i % self.columns);
        let empty = |p: u16| s.piles[p as usize].is_empty();
        let row_empty = |r: u16| (0..self.columns).all(|c| empty(gr.start + r * self.columns + c));
        let col_empty = |c: u16| (0..self.rows).all(|r| empty(gr.start + r * self.columns + c));
        (row_empty(r) && (0..r).any(row_empty)) || (col_empty(c) && (0..c).any(col_empty))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::card::Suit;

    fn counts(cards: &[(Suit, u8)]) -> Counts {
        let mut c = Counts::default();
        for &(s, r) in cards {
            c.add(Card::new(s, r));
        }
        c
    }

    use Suit::*;

    #[test]
    fn classifies_hands() {
        let cases: &[(&[(Suit, u8)], usize)] = &[
            (
                &[
                    (Spades, 10),
                    (Spades, 11),
                    (Spades, 12),
                    (Spades, 13),
                    (Spades, 1),
                ],
                ROYAL_FLUSH,
            ),
            (
                &[
                    (Hearts, 1),
                    (Hearts, 2),
                    (Hearts, 3),
                    (Hearts, 4),
                    (Hearts, 5),
                ],
                STRAIGHT_FLUSH,
            ),
            (
                &[
                    (Hearts, 9),
                    (Clubs, 9),
                    (Spades, 9),
                    (Diamonds, 9),
                    (Hearts, 5),
                ],
                FOUR,
            ),
            (
                &[
                    (Hearts, 9),
                    (Clubs, 9),
                    (Spades, 9),
                    (Diamonds, 5),
                    (Hearts, 5),
                ],
                FULL_HOUSE,
            ),
            (
                &[
                    (Hearts, 9),
                    (Hearts, 2),
                    (Hearts, 7),
                    (Hearts, 5),
                    (Hearts, 12),
                ],
                FLUSH,
            ),
            (
                &[
                    (Hearts, 10),
                    (Clubs, 11),
                    (Hearts, 12),
                    (Spades, 13),
                    (Hearts, 1),
                ],
                STRAIGHT,
            ),
            (
                &[
                    (Hearts, 13),
                    (Clubs, 1),
                    (Hearts, 2),
                    (Spades, 3),
                    (Hearts, 4),
                ],
                0,
            ),
            (
                &[
                    (Hearts, 9),
                    (Clubs, 9),
                    (Spades, 9),
                    (Diamonds, 2),
                    (Hearts, 5),
                ],
                THREE,
            ),
            (
                &[
                    (Hearts, 9),
                    (Clubs, 9),
                    (Spades, 5),
                    (Diamonds, 2),
                    (Hearts, 5),
                ],
                TWO_PAIR,
            ),
            (
                &[
                    (Hearts, 9),
                    (Clubs, 9),
                    (Spades, 4),
                    (Diamonds, 2),
                    (Hearts, 5),
                ],
                PAIR,
            ),
            (&[(Hearts, 9), (Clubs, 9)], PAIR),
            (&[(Hearts, 9), (Hearts, 8), (Hearts, 7), (Hearts, 6)], 0),
        ];
        for (cards, want) in cases {
            assert_eq!(hand(&counts(cards)), *want, "{cards:?}");
        }
    }

    fn deck_with_jokers(n: usize) -> Vec<Card> {
        let mut deck: Vec<Card> = (0..52u8).map(Card::from_face).collect();
        deck.extend((0..n).map(|_| Card::joker()));
        deck
    }

    /// The best hand when each joker may be any card, by trying every card.
    fn best_by_substitution(cards: &[Card]) -> usize {
        match cards.iter().position(|c| c.is_joker()) {
            None => {
                let mut c = Counts::default();
                cards.iter().for_each(|&x| c.add(x));
                hand(&c)
            }
            Some(i) => {
                let mut v = cards.to_vec();
                (0..52u8)
                    .map(|f| {
                        v[i] = Card::from_face(f);
                        best_by_substitution(&v)
                    })
                    .max()
                    .unwrap()
            }
        }
    }

    #[test]
    fn jokers_make_the_best_hand() {
        let mut rng = crate::rng::Rng::new(3);
        for i in 0..400 {
            let mut deck = deck_with_jokers(2);
            rng.shuffle(&mut deck);
            // Make sure most lines hold a joker.
            let jokers = 1 + i % 2;
            let mut line: Vec<Card> = deck
                .iter()
                .copied()
                .filter(|c| !c.is_joker())
                .take(5 - jokers)
                .collect();
            line.extend((0..jokers).map(|_| Card::joker()));
            let n = 1 + (rng.next_u64() % 5) as usize;
            let line = &line[5 - n..];
            let mut c = Counts::default();
            line.iter().for_each(|&x| c.add(x));
            assert_eq!(hand(&c), best_by_substitution(line), "{line:?}");
        }
        // Non-monotone points: the joker picks the better-paying, lower hand.
        let english = points_table(
            &crate::rules::PokerTable::Named(crate::rules::PokerScoring::English).points(),
        );
        let mut c = Counts::default();
        for card in ["2H", "3H", "4H", "5H", "JK"] {
            c.add(card.parse().unwrap());
        }
        // A flush (5) or, with the joker as an ace or a six, a straight flush (30).
        assert_eq!(poker_points(&c, &english, false), 30);
        let mut c = Counts::default();
        for card in ["2H", "7H", "4H", "9H", "JK"] {
            c.add(card.parse().unwrap());
        }
        // Flush 5, but a pair pays only 1 and nothing better is possible.
        assert_eq!(poker_points(&c, &english, false), 5);
        let mut odd = english;
        odd[PAIR] = 9;
        assert_eq!(poker_points(&c, &odd, false), 9);
    }

    /// The relaxed test must say yes whenever some real completion makes the hand, held and
    /// arriving jokers included.
    #[test]
    fn possible_hands_cover_every_completion() {
        let mut rng = crate::rng::Rng::new(7);
        for _ in 0..3000 {
            let mut deck = deck_with_jokers(2);
            rng.shuffle(&mut deck);
            let k = (rng.next_u64() % 5) as usize;
            let pool_n = 1 + (rng.next_u64() % 8) as usize;
            let have_cards = &deck[..k];
            let pool_cards = &deck[k..k + pool_n];
            let slots = (5 - k).min(pool_n);
            let mut have = Counts::default();
            have_cards.iter().for_each(|&c| have.add(c));
            let mut pool = Counts::default();
            pool_cards.iter().for_each(|&c| pool.add(c));
            // Every way to fill the slots from the pool.
            let n = pool_cards.len();
            for mask in 0u32..1 << n {
                if mask.count_ones() as usize != slots {
                    continue;
                }
                let mut c = Counts::default();
                have_cards.iter().for_each(|&x| c.add(x));
                (0..n)
                    .filter(|i| mask >> i & 1 != 0)
                    .for_each(|i| c.add(pool_cards[i]));
                let mut cards: Vec<Card> = have_cards.to_vec();
                (0..n)
                    .filter(|i| mask >> i & 1 != 0)
                    .for_each(|i| cards.push(pool_cards[i]));
                let h = if cards.iter().filter(|c| c.is_joker()).count() == 2 {
                    hand(&c)
                } else {
                    best_by_substitution(&cards)
                };
                let slots = slots as u32;
                let set = possible(
                    &have,
                    &pool,
                    slots + have.jokers,
                    have.jokers + pool.jokers.min(slots),
                );
                assert!(
                    set >> h & 1 != 0,
                    "{have_cards:?} + {pool_cards:?}: hand {h} not judged possible"
                );
            }
        }
    }

    // ----- Cribbage ---------------------------------------------------------------------

    /// Cribbage points the slow way, straight from the definitions.
    fn reference_rank_points(p: &CribbagePoints, ranks: &[u8]) -> u32 {
        let n = ranks.len();
        let subsets = || {
            (1u32..1 << n).map(|m| {
                (0..n)
                    .filter(move |i| m >> i & 1 != 0)
                    .map(|i| ranks[i])
                    .collect::<Vec<u8>>()
            })
        };
        let fifteens = subsets()
            .filter(|s| s.iter().map(|&r| r.min(10) as u32).sum::<u32>() == 15)
            .count() as u32;
        let pairs = subsets().filter(|s| s.len() == 2 && s[0] == s[1]).count() as u32;
        let is_run = |s: &Vec<u8>| {
            let mut v = s.clone();
            v.sort();
            v.len() >= 3 && v.windows(2).all(|w| w[1] == w[0] + 1)
        };
        // Runs: every run of cards not inside a longer run.
        let runs: Vec<Vec<u8>> = subsets().filter(is_run).collect();
        let longest = runs.iter().map(|r| r.len()).max().unwrap_or(0);
        let run_cards: u32 = runs
            .iter()
            .filter(|r| r.len() == longest)
            .map(|r| r.len() as u32)
            .sum();
        fifteens * p.fifteen + pairs * p.pair + run_cards * p.run_card
    }

    fn cards(s: &[&str]) -> Vec<Card> {
        s.iter().map(|c| c.parse().unwrap()).collect()
    }

    #[test]
    fn cribbage_hands() {
        let p = CribbagePoints::default();
        let hand = |line: &[&str], starter: &str| {
            cribbage_hand(&p, &cards(line), Some(starter.parse().unwrap()), true)
        };
        // The best hand there is.
        assert_eq!(hand(&["5C", "5D", "5H", "JS"], "5S"), 29);
        // Double double run: 3-4-5 four ways (12), two pairs (4), 3+3+4+5 with either 4 (4).
        assert_eq!(hand(&["3C", "3D", "4H", "4S"], "5S"), 12 + 4 + 4);
        // Nothing: even values never make 15.
        assert_eq!(hand(&["2C", "4D", "6H", "8S"], "QH"), 0);
        // Flush of four, then five with the starter, which also brings nobs.
        assert_eq!(hand(&["2H", "4H", "6H", "JH"], "KC"), 4);
        assert_eq!(hand(&["2H", "4H", "6H", "JH"], "KH"), 5 + 1);
        // A joker counts as its best card: here the fourth five.
        assert_eq!(hand(&["5C", "5D", "5H", "JS"], "JK"), 29);
        assert_eq!(hand(&["5C", "5D", "JK", "JS"], "5S"), 29);
        // No flush in an incomplete line.
        assert_eq!(
            cribbage_hand(&p, &cards(&["2H", "4H", "6H", "JH"]), None, false),
            0
        );

        let mut rng = crate::rng::Rng::new(11);
        for _ in 0..2000 {
            let mut deck = deck_with_jokers(0);
            rng.shuffle(&mut deck);
            let n = 1 + (rng.next_u64() % 5) as usize;
            let ranks: Vec<u8> = deck[..n].iter().map(|c| c.rank()).collect();
            let mut count = [0u8; 14];
            ranks.iter().for_each(|&r| count[r as usize] += 1);
            assert_eq!(
                rank_points(&p, &count),
                reference_rank_points(&p, &ranks),
                "{ranks:?}"
            );
        }
    }

    #[test]
    fn best_rank_points_bounds_every_extension() {
        let p = CribbagePoints::default();
        let best = best_rank_points(&p, 4);
        assert_eq!(best[rank_key(&[0; 14])], 28);
        assert_eq!(best_rank_points(&p, 5)[0], 40);
        let mut rng = crate::rng::Rng::new(5);
        for _ in 0..2000 {
            let mut deck = deck_with_jokers(0);
            rng.shuffle(&mut deck);
            let k = (rng.next_u64() % 5) as usize;
            let mut count = [0u8; 14];
            deck[..k].iter().for_each(|c| count[c.rank() as usize] += 1);
            let b = best[rank_key(&count)];
            let mut full = count;
            deck[k..5].iter().for_each(|c| full[c.rank() as usize] += 1);
            assert!(rank_points(&p, &full) <= b);
            assert!(rank_points(&p, &count) <= b);
        }
    }

    /// The cribbage line bound is never below a real completion, jokers and all.
    #[test]
    fn cribbage_bound_covers_every_completion() {
        let p = CribbagePoints {
            heels: 0,
            ..CribbagePoints::default()
        };
        let score = Score {
            group: 0,
            lines: Vec::new(),
            hands: HandScoring::Poker {
                points: [0; 10],
                order: [0; 10],
                monotone: true,
            },
            pool: Pool::Outside,
            symmetric: false,
            rows: 0,
            columns: 0,
        };
        let best = best_rank_points(&p, 5);
        let mut rng = crate::rng::Rng::new(9);
        for _ in 0..1500 {
            let mut deck = deck_with_jokers(2);
            rng.shuffle(&mut deck);
            let k = (rng.next_u64() % 5) as usize;
            let pool_n = 1 + (rng.next_u64() % 6) as usize;
            let st_n = (rng.next_u64() % 3) as usize;
            let have_cards = &deck[..k];
            let pool_cards = &deck[k..k + pool_n];
            let st_cards = &deck[k + pool_n..k + pool_n + st_n];
            let slots = (4 - k).min(pool_n);
            let mut have = Counts::default();
            have_cards.iter().for_each(|&c| have.add(c));
            let mut pool = Counts::default();
            pool_cards.iter().for_each(|&c| pool.add(c));
            let mut starter = Counts::default();
            st_cards.iter().for_each(|&c| starter.add(c));
            let bound =
                score.cribbage_line_bound(&p, &best, &have, &pool, slots as u32, &starter, 4);
            let n = pool_cards.len();
            for mask in 0u32..1 << n {
                if mask.count_ones() as usize != slots {
                    continue;
                }
                let mut line = have_cards.to_vec();
                (0..n)
                    .filter(|i| mask >> i & 1 != 0)
                    .for_each(|i| line.push(pool_cards[i]));
                let full = line.len() == 4;
                let starters: Vec<Option<Card>> = if st_cards.is_empty() {
                    vec![None]
                } else {
                    st_cards.iter().map(|&c| Some(c)).collect()
                };
                for st in starters {
                    let v = cribbage_hand(&p, &line, st, full);
                    assert!(
                        v <= bound,
                        "{have_cards:?} + {line:?} / {st:?}: {v} > bound {bound}"
                    );
                }
            }
        }
    }
}