minesweeprs 0.2.0

Probabalistic minesweeper solver, based on https://mrgris.com/projects/minesweepr/
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
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
#![doc = include_str!("../README.md")]
#![allow(clippy::too_many_lines)]
use std::cmp::{max, min, Ordering};
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::{empty, once, Rev};
use std::ops::RangeInclusive;

use either::Either;
use internal_util::{
    comb,
    fact_div,
    graph_traverse,
    map_reduce,
    peek,
    pop,
    CustomInto,
    FrozenMap,
    FrozenSet,
};
use itertools::Itertools;
use typed_arena::Arena;
mod internal_util;
pub mod util;

type SuperCell<'arena, 'cell, T> = &'arena FrozenSet<&'cell T>;

pub trait Cell: Hash + Eq + Debug {}
impl<T: Hash + Eq + Debug + ?Sized> Cell for T {
}

/// Represents the board geometry for traditional minesweeper, where the board
/// has fixed dimensions and a fixed total of mines.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct BoardInfo {
    /// Total number of cells on the board; all cells contained in rules and all
    /// 'uncharted' (completely unknown) cells
    pub total_cells: usize,
    /// Total number of mines contained within cells counted in total_cells
    pub total_mines: usize,
}

pub type Error = &'static str;

/// Solve a minesweeper board.
///
/// Takes in a list of rules, information about the board (either a
/// [`BoardInfo`] representing the board data, or an [`f64`] representing the
/// fixed probability of an unknown cell being a mine), and a tag to use for any
/// cells not explicitly mentioned in the rules.
pub fn solve<'cell, T: Cell + ?Sized>(
    rules: &[Rule<'cell, T>],
    mine_prevalence: impl CustomInto<Either<BoardInfo, f64>>,
    other_tag: impl Into<&'cell T>,
) -> Result<HashMap<&'cell T, f64>, Error> {
    // - Single cells are allocated by the caller, and passed in to `Rule` as
    //   references.
    // - Super-cells are allocated by `condense_supercells()`, but are stored in an
    //   arena due to lifetime requirements.
    // - All other allocations require their own arenas, to avoid reliance on `Rc`,
    //   and `Shared` (essentially a wrapper around `Rc<RefCell>`).
    //   - `InternalRule`s may be allocated dynamically, such as by generating them
    //     from a `PermutationSet`, and so must be stored in the arena.
    //   - Super-cell groups are allocated dynamically, for construction of `Rule`s
    let rule_arena = Arena::new();
    let super_cell_arena = Arena::new();
    let ruleset_arena = Arena::new();
    let permutation_arena = Arena::new();
    let permutation_set_arena = Arena::new();
    let super_cell_group_arena = Arena::new();

    // fn solve<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    //     rules: &[Rule<'cell, T>],
    //     mine_prevalence: impl CustomInto<Either<BoardInfo, f64>>,
    //     other_tag: impl Into<&'cell T>,
    //     rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
    //     ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell,
    // T>>>,     super_cell_arena: &'arena Arena<FrozenSet<&'cell T>>,
    //     permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
    //     permutation_set_arena: &'arena Arena<PermutationSet<'arena, 'cell, T>>,
    //     super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell,
    // T>>>, ) -> Result<HashMap<&'cell T, f64>, Error> {
    let mine_prevalence = mine_prevalence.into();
    let (internal_rules, all_cells) = condense_supercells(
        rules,
        &rule_arena,
        &super_cell_arena,
        &super_cell_group_arena,
    )?;
    let mut reduced = reduce_rules(
        &internal_rules,
        &rule_arena,
        &ruleset_arena,
        &super_cell_group_arena,
    );

    let mut determined = reduced
        .iter()
        .filter(|r| r.is_trivial())
        .cloned()
        .collect::<HashSet<_>>();
    reduced.retain(|r| !r.is_trivial());

    let mut fronts = permute_and_interfere(
        ruleset_arena.alloc(reduced),
        &rule_arena,
        &ruleset_arena,
        &permutation_arena,
        &permutation_set_arena,
        &super_cell_group_arena,
    )?
    .split_fronts(&ruleset_arena, &permutation_arena, &permutation_set_arena);

    determined.extend(
        fronts
            .iter()
            .filter(|f| f.is_trivial())
            .map(PermutedRuleset::trivial_rule),
    );
    fronts.retain(|f| !f.is_trivial());

    let mut stats = fronts
        .into_iter()
        .map(|f| enumerate_front(f))
        .collect::<Result<Vec<_>, _>>()?;
    stats.extend(determined.into_iter().map(|r| r.tally()));

    let cell_probs = cell_probabilities(stats, mine_prevalence, all_cells)?;
    let cells = expand_cells::<'_, 'cell, _>(cell_probs, other_tag.into()).collect();
    Ok(cells)
    // }
    // solve(
    //     rules,
    //     mine_prevalence,
    //     other_tag,
    //     &rule_arena,
    //     &ruleset_arena,
    //     &super_cell_arena,
    //     &permutation_arena,
    //     &permutation_set_arena,
    //     &super_cell_group_arena,
    // )
}

/// Basic representation of an axiom from a minesweeper game; N mines contained
/// within a set of M cells.
///
/// This is only used during the very early stages of the algorithm; it's
/// quickly converted into an [`InternalRule`]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Rule<'cell, T: Cell + ?Sized> {
    /// How many mines are contained within the cells.
    num_mines: usize,
    /// The cells used by the rule. Each cell is a unique, identifying tag that
    /// represents that cell.
    cells: FrozenSet<&'cell T>,
}
impl<'cell, T: Cell + ?Sized> Rule<'cell, T> {
    pub fn new(num_mines: usize, cells: impl IntoIterator<Item = &'cell T>) -> Self {
        Self {
            num_mines,
            cells: cells.into_iter().collect(),
        }
    }

    /// Condense super-cells and convert into an [`InternalRule`].
    ///
    /// `rule_supercells_map` is a pre-computed super-cell mapping.
    fn condensed<'arena>(
        &self,
        rule_supercells_map: &HashMap<
            &Self,
            &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
        >,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> Result<&'arena InternalRule<'arena, 'cell, T>, Error> {
        InternalRule::new(
            self.num_mines,
            // default to handle degenerate rules
            rule_supercells_map
                .get(self)
                .copied()
                .unwrap_or_else(|| &*super_cell_group_arena.alloc(FrozenSet::new())),
            self.cells.len(),
        )
        .map(|rule| &*rule_arena.alloc(rule))
    }
}

/// Analogue of [`Rule`] but containing super-cells (set of cells that only ever
/// appear together).
///
/// This is the common rule form used throughout most of the algorithm.
#[derive(Copy, Debug, PartialEq, Eq, Hash)]
struct InternalRule<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// The total number of mines
    num_mines: usize,
    /// The total number of base cells
    num_cells: usize,
    /// The super-cells used by the rule
    super_cells: &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> Clone for InternalRule<'arena, 'cell, T> {
    fn clone(&self) -> Self {
        Self {
            num_mines: self.num_mines,
            num_cells: self.num_cells,
            super_cells: self.super_cells,
        }
    }
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> InternalRule<'arena, 'cell, T> {
    pub fn new(
        num_mines: usize,
        super_cells: &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
        num_cells: usize,
    ) -> Result<Self, Error> {
        if num_mines <= num_cells {
            Ok(Self {
                num_mines,
                num_cells,
                super_cells,
            })
        } else {
            Err("Rule with more mines than cells")
        }
    }

    /// If the rule is completely full or completely empty of mines, split into
    /// a sub-rule for each super-cell.
    pub fn decompose(
        &self,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> Box<dyn Iterator<Item = Self> + '_> {
        if self.num_mines == 0 || self.num_mines == self.num_cells {
            // Degenerate rules (those with no cells) disappear here
            Box::new(self.super_cells.iter().map(|&super_cell| {
                let size = super_cell.len();
                Self::new(
                    if self.num_mines > 0 { size } else { 0 },
                    super_cell_group_arena.alloc([super_cell].into()),
                    size,
                )
                .expect("Decomposing a rule should always be valid")
            }))
        } else {
            Box::new(once(self.clone()))
        }
    }

    /// If another rule is a sub-rule of this one, return a new rule covering
    /// only the difference
    pub fn subtract(
        &self,
        other: &Self,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> Self {
        Self::new(
            self.num_mines - other.num_mines,
            super_cell_group_arena.alloc(self.super_cells - &other.super_cells),
            self.num_cells - other.num_cells,
        )
        .expect("Subtracting a rule should always result in a valid rule")
    }

    /// Generate all possible mine permutations for this rule
    pub fn permute(&self) -> impl Iterator<Item = Permutation<'arena, 'cell, T>> + '_ {
        /// Generate all permutations of `count` mines among `cells`.
        ///
        /// `permu` represents the sub-permutation in progress, and is used by
        /// recursive calls.
        fn permute<'arena, 'cell: 'arena, T: Cell + ?Sized>(
            count: usize,
            mut cells: VecDeque<&'arena FrozenSet<&'cell T>>,
            permu: HashSet<(&'arena FrozenSet<&'cell T>, usize)>,
        ) -> Box<dyn Iterator<Item = Permutation<'arena, 'cell, T>> + 'arena> {
            if count == 0 {
                Box::new(once(Permutation::new(
                    permu
                        .union(&cells.iter().map(|&cell| (cell, 0)).collect())
                        .cloned(),
                )))
            } else {
                let remaining_size = cells.iter().map(|cell| cell.len()).sum::<usize>();
                if remaining_size == count {
                    Box::new(once(Permutation::new(
                        permu
                            .union(
                                &cells.iter().map(|&cell| (cell, cell.len())).collect(),
                            )
                            .cloned(),
                    )))
                } else if remaining_size >= count {
                    struct Iter<'a, 'arena: 'a, 'cell: 'arena, T: Cell + ?Sized> {
                        cell: &'arena FrozenSet<&'cell T>,
                        multiplicity: usize,
                        multiplicity_iter: Rev<RangeInclusive<usize>>,
                        inner: Box<
                            dyn Iterator<Item = Permutation<'arena, 'cell, T>> + 'a,
                        >,
                        cells: VecDeque<&'arena FrozenSet<&'cell T>>,
                        count: usize,
                        permu: HashSet<(&'arena FrozenSet<&'cell T>, usize)>,
                    }
                    impl<'a, 'arena: 'a, 'cell: 'arena, T: Cell + ?Sized> Iterator
                        for Iter<'a, 'arena, 'cell, T>
                    {
                        type Item = Permutation<'arena, 'cell, T>;

                        fn next(&mut self) -> Option<Self::Item> {
                            match self.inner.next() {
                                Some(permutation) => Some(permutation),
                                None => {
                                    self.multiplicity =
                                        self.multiplicity_iter.next()?;
                                    self.inner = permute(
                                        self.count - self.multiplicity,
                                        self.cells.clone(),
                                        self.permu
                                            .union(
                                                &[(self.cell, self.multiplicity)]
                                                    .into(),
                                            )
                                            .cloned()
                                            .collect(),
                                    );
                                    self.next()
                                },
                            }
                        }
                    }
                    let cell = cells.pop_front().expect(concat!(
                        "count >= 1, remaining_size >= count, so",
                        " cells must not be empty",
                    ));
                    Box::new(Iter {
                        cell,
                        multiplicity: 0,
                        multiplicity_iter: (0..=min(count, cell.len())).rev(),
                        inner: Box::new(empty()),
                        cells,
                        count,
                        permu,
                    })
                } else {
                    Box::new(empty())
                }
            }
        }

        let cells = self.super_cells.iter().cloned().collect();
        permute(self.num_mines, cells, HashSet::new())
            .collect_vec()
            .into_iter()
    }

    /// Returns `true` if this rule is a sub-rule of `other`.
    ///
    /// 'sub-rule' means that this rule's cells are a subset of the super-rule's
    /// cells. Equivalent rules are sub-rules of each other.
    pub fn is_subule_of(&self, other: &Self) -> bool {
        self.super_cells.is_subset(&other.super_cells)
    }

    /// Returns `true` if this rule is trivial, i.e. has only one permutation.
    pub fn is_trivial(&self) -> bool {
        self.super_cells.len() == 1
    }

    /// Build a [`FrontTally`] from this *trivial* rule only.
    ///
    /// # Panics
    ///
    /// Panics if this rule is not trivial.
    pub fn tally(&self) -> FrontTally<'arena, 'cell, T> {
        FrontTally::from_rule(self)
    }
}

/// Condense super-cells by finding sets of ordinary cells that only ever appear
/// together. Returns a set of [`InternalRule`] corresponding to the original
/// ruleset.
///
/// Note that *all* cells are converted into super-cells for ease of processing
/// later (and type-safety), even if that cell does not group with any others.
/// The result would be a singleton super-cell.
///
/// # Arguments
///
/// * `rules` - The rules to condense
fn condense_supercells<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    rules: &[Rule<'cell, T>],
    rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
    super_cell_arena: &'arena Arena<FrozenSet<&'cell T>>,
    super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
) -> Result<
    (
        Vec<&'arena InternalRule<'arena, 'cell, T>>,
        Vec<&'arena FrozenSet<&'cell T>>,
    ),
    Error,
> {
    // For each cell, the rules it appears in
    let cell_rules_map = map_reduce(
        rules.iter(),
        |rule| rule.cells.iter().map(move |&cell| (cell, rule)),
        |rules| rules.into_iter().collect::<FrozenSet<_>>(),
    );

    // For each group of rules a cell appears in, the cells that share those rules
    // (these cells thus only ever appear together in the same rules)
    let rules_supercell_map = map_reduce(
        cell_rules_map.into_iter(),
        |(cell, rules)| [(rules, cell)].into_iter(),
        |cells| &*super_cell_arena.alloc(cells.into_iter().collect::<FrozenSet<_>>()),
    );

    // For each original rule, the super cells appearing in that rule
    let rule_supercells_map = map_reduce(
        rules_supercell_map.iter(),
        |(rules, cell)| {
            rules
                .iter()
                .map(|&rule| (rule, &**cell))
                .collect_vec()
                .into_iter()
        },
        |cells| {
            &*super_cell_group_arena.alloc(cells.into_iter().collect::<FrozenSet<_>>())
        },
    );

    Ok((
        rules
            .iter()
            .map(|rule| {
                rule.condensed(&rule_supercells_map, rule_arena, super_cell_group_arena)
            })
            .collect::<Result<Vec<_>, Error>>()?,
        rules_supercell_map.into_values().collect(),
    ))
}

/// Reduce the ruleset using logical deduction.
fn reduce_rules<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    rules: &[&'arena InternalRule<'arena, 'cell, T>],
    rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
    ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
    super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
) -> HashSet<&'arena InternalRule<'arena, 'cell, T>> {
    let mut reducer = RuleReducer::new();
    reducer.add_rules(
        rules.iter().copied(),
        rule_arena,
        ruleset_arena,
        super_cell_group_arena,
    );
    reducer.reduce_all(rule_arena, ruleset_arena, super_cell_group_arena)
}

/// During the logical deduction phase, if all rules are nodes in a graph, this
/// represents a directed edge in that graph indicating that `super_rule` can be
/// reduced by `sub_rule`.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct Reduceable<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// The larger rule.
    super_rule: &'arena InternalRule<'arena, 'cell, T>,
    /// The smaller rule, that can reduce the larger rule.
    sub_rule: &'arena InternalRule<'arena, 'cell, T>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> Reduceable<'arena, 'cell, T> {
    pub fn new(
        super_rule: &'arena InternalRule<'arena, 'cell, T>,
        sub_rule: &'arena InternalRule<'arena, 'cell, T>,
    ) -> Self {
        Self {
            super_rule,
            sub_rule,
        }
    }

    /// Calculate the attractiveness of this reduction. Favour reductions that
    /// involve larger rules, and amongst same-sized rules, those that yield
    /// mine counts towards the extremes - such rules have fewer permutations.
    pub fn metric(&self) -> (usize, usize, usize) {
        let num_reduced_cells = self.super_rule.num_cells - self.sub_rule.num_cells;
        let num_reduced_mines = self.super_rule.num_mines - self.sub_rule.num_mines;
        (
            self.super_rule.num_cells,
            self.sub_rule.num_cells,
            num_reduced_mines.abs_diff(num_reduced_cells / 2),
        )
    }

    /// Perform the reduction.
    pub fn reduce(
        &self,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> InternalRule<'arena, 'cell, T> {
        self.super_rule
            .subtract(&self.sub_rule, super_cell_group_arena)
    }

    /// Is this reduction contained within the given set of rules?
    pub fn contained_within(
        &self,
        rules: &HashSet<&'arena InternalRule<'arena, 'cell, T>>,
    ) -> bool {
        rules.contains(&self.super_rule) && rules.contains(&self.sub_rule)
    }
}
impl<T: Cell + ?Sized> Ord for Reduceable<'_, '_, T> {
    /// Use the metric to determine the ordering.
    fn cmp(&self, other: &Self) -> Ordering {
        self.metric().cmp(&other.metric())
    }
}
impl<T: Cell + ?Sized> PartialOrd for Reduceable<'_, '_, T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// A utility structure, mapping cells to the rules they appear in.
#[derive(Debug, PartialEq, Eq)]
struct CellRulesMap<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// Cell -> Rules the cell appears in.
    map: HashMap<
        SuperCell<'arena, 'cell, T>,
        &'arena mut HashSet<&'arena InternalRule<'arena, 'cell, T>>,
    >,
    /// All rules known to the map.
    rules: HashSet<&'arena InternalRule<'arena, 'cell, T>>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> CellRulesMap<'arena, 'cell, T> {
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
            rules: HashSet::new(),
        }
    }

    pub fn add_rules(
        &mut self,
        rules: impl Iterator<Item = &'arena InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
    ) {
        for rule in rules {
            self.add_rule(rule, ruleset_arena);
        }
    }

    pub fn add_rule(
        &mut self,
        rule: &'arena InternalRule<'arena, 'cell, T>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
    ) {
        for super_cell in rule.super_cells.iter() {
            (*self
                .map
                .entry(super_cell)
                .or_insert_with(|| ruleset_arena.alloc(HashSet::new())))
            .insert(rule);
        }
        self.rules.insert(rule);
    }

    pub fn remove_rule(&mut self, rule: &InternalRule<'arena, 'cell, T>) {
        for super_cell in rule.super_cells.iter() {
            self.map
                .get_mut(super_cell)
                .expect("Attempted to remove a rule that was not present")
                .remove(rule);
        }
        self.rules.remove(rule);
    }

    /// Return the set of rules that overlap `rule` i.e. share at least one
    /// cell.
    pub fn overlapping_rules(
        &self,
        rule: &InternalRule<'arena, 'cell, T>,
    ) -> HashSet<&'arena InternalRule<'arena, 'cell, T>> {
        let empty = HashSet::new();
        let mut rules = rule
            .super_cells
            .iter()
            .flat_map(|&super_cell| {
                self.map
                    .get(super_cell)
                    .map(|val| &**val)
                    .map_or_else(|| empty.iter(), |map| map.iter())
                    .copied()
            })
            .collect::<HashSet<_>>();
        rules.remove(rule);
        rules
    }

    /// Return pairs of all rules that overlap each other. Each pair is
    /// represented twice (`(a, b)` and `(b, a)`) to support processing of
    /// asymmetric relationships.
    pub fn interference_edges(
        &self,
    ) -> HashSet<(
        &'arena InternalRule<'arena, 'cell, T>,
        &'arena InternalRule<'arena, 'cell, T>,
    )> {
        self.rules
            .iter()
            .flat_map(|&rule| {
                self.overlapping_rules(rule)
                    .into_iter()
                    .map(move |overlapping| (rule, overlapping))
            })
            .collect()
    }

    /// Partition the ruleset into disjoint sub-rulesets of related rules.
    ///
    /// That is, all rules in a sub-ruleset are related to each other in some
    /// way through some number of overlaps, and no rules from separate
    /// sub-rulesets overlap each other. Returns a set of partitions, each a set
    /// of rules.
    pub fn partition(
        &self,
    ) -> HashSet<FrozenSet<&'arena InternalRule<'arena, 'cell, T>>> {
        let mut related_rules: HashMap<_, _> = self
            .rules
            .iter()
            .map(|&rule| (rule, self.overlapping_rules(rule)))
            .collect();
        let mut partitions = HashSet::new();
        while !related_rules.is_empty() {
            let start = peek(related_rules.keys());
            let partition = graph_traverse(&related_rules, start);
            for rule in &partition {
                related_rules.remove(rule);
            }
            partitions.insert(partition.into());
        }
        partitions
    }

    /// Return all cells contained in the ruleset.
    pub fn super_cells(&self) -> FrozenSet<SuperCell<'arena, 'cell, T>> {
        self.map.keys().cloned().collect()
    }
}

/// Manager structure that performs the 'logical deduction' phase of the solver.
/// Maintains a set of active rules, tracks which rules overlap with other
/// rules, and iteratively reduces them until no further reductions are
/// possible.
#[derive(Debug)]
struct RuleReducer<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// Current set of active rules.
    active_rules: HashSet<&'arena InternalRule<'arena, 'cell, T>>,
    /// Lookup for rules containing a given cell.
    cell_rules_map: CellRulesMap<'arena, 'cell, T>,
    /// Current list of all possible reductions.
    candidate_reductions: BinaryHeap<Reduceable<'arena, 'cell, T>>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> RuleReducer<'arena, 'cell, T> {
    pub fn new() -> Self {
        Self {
            active_rules: HashSet::new(),
            cell_rules_map: CellRulesMap::new(),
            candidate_reductions: BinaryHeap::new(),
        }
    }

    /// Add a set of rules to the active ruleset.
    pub fn add_rules<'a>(
        &mut self,
        rules: impl Iterator<Item = &'a InternalRule<'arena, 'cell, T>>,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) where
        'arena: 'a,
    {
        for rule in rules {
            self.add_rule(rule, rule_arena, ruleset_arena, super_cell_group_arena);
        }
    }

    /// Add a single rule to the active ruleset.
    pub fn add_rule(
        &mut self,
        rule: &InternalRule<'arena, 'cell, T>,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) {
        for base_rule in rule.decompose(super_cell_group_arena) {
            self.add_base_rule(rule_arena.alloc(base_rule), ruleset_arena);
        }
    }

    /// Helper for adding a rule
    pub fn add_base_rule(
        &mut self,
        rule: &'arena InternalRule<'arena, 'cell, T>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
    ) {
        self.active_rules.insert(rule);
        self.cell_rules_map.add_rule(rule, ruleset_arena);
        self.update_reduceables(rule);
    }

    /// Add a new reduction to the list of possible reductions.
    pub fn add_reduceable(&mut self, reduction: Reduceable<'arena, 'cell, T>) {
        self.candidate_reductions.push(reduction);
    }

    /// Update the index of which rules are reduceable by others.
    pub fn update_reduceables(&mut self, rule: &'arena InternalRule<'arena, 'cell, T>) {
        for overlapping in self.cell_rules_map.overlapping_rules(rule) {
            if overlapping.is_subule_of(rule) {
                // This path is followed if the rules are equivalent
                self.add_reduceable(Reduceable::new(rule, overlapping));
            } else if rule.is_subule_of(&overlapping) {
                self.add_reduceable(Reduceable::new(overlapping, rule));
            }
        }
    }

    /// Remove a rule from the active ruleset/index; presumably because it was
    /// reduced away.
    pub fn remove_rule(&mut self, rule: &InternalRule<'arena, 'cell, T>) {
        self.active_rules.remove(rule);
        self.cell_rules_map.remove_rule(rule);
        // Can't remove the inner contents of candidate_reductions, so instead
        // rules are checked for validity when they're popped.
    }

    /// Get the next reduction that can be performed, highest-value first.
    pub fn get_next_reduction(&mut self) -> Option<Reduceable<'arena, 'cell, T>> {
        while let Some(reduction) = self.candidate_reductions.pop() {
            if reduction.contained_within(&self.active_rules) {
                return Some(reduction);
            }
        }
        None
    }

    /// Perform a single reduction.
    pub fn reduce(
        &mut self,
        reduction: Reduceable<'arena, 'cell, T>,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) {
        let reduced_rule = reduction.reduce(super_cell_group_arena);
        self.remove_rule(&reduction.super_rule);
        self.add_rule(
            &reduced_rule,
            rule_arena,
            ruleset_arena,
            super_cell_group_arena,
        );
    }

    /// Perform all possible reductions and return the resulting reduced
    /// ruleset.
    pub fn reduce_all(
        mut self,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> HashSet<&'arena InternalRule<'arena, 'cell, T>> {
        while let Some(reduction) = self.get_next_reduction() {
            self.reduce(reduction, rule_arena, ruleset_arena, super_cell_group_arena);
        }
        self.active_rules
    }
}

/// A single permutation of N mines among a set of (super-)cells.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct Permutation<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// Super-cell -> number of mines in that super-cell
    ///
    /// The cell set is determined implicitly from the mapping, so all cells in
    /// the set must have an entry, even if they have 0 mines.
    mapping: FrozenMap<SuperCell<'arena, 'cell, T>, usize>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> Permutation<'arena, 'cell, T> {
    pub fn new(
        mapping: impl IntoIterator<Item = (SuperCell<'arena, 'cell, T>, usize)>,
    ) -> Self {
        Self {
            mapping: mapping.into_iter().collect(),
        }
    }

    /// Return a sub-permutation containing only the cells in `sub_cells`.
    pub fn subset(
        &self,
        sub_cells: impl Iterator<Item = SuperCell<'arena, 'cell, T>>,
    ) -> Self {
        Self::new(sub_cells.map(|cell| {
            let mapped = self.mapping[&cell];
            (cell, mapped)
        }))
    }

    /// Is this permutation consistent with `other`? I.E. do the cells they have
    /// in common have matching numbers of mines assigned?
    pub fn is_compatible(&self, other: &Self) -> bool {
        let overlap = self
            .cells()
            .intersection(&other.cells())
            .cloned()
            .collect::<HashSet<_>>();
        self.subset(overlap.iter().cloned()) == other.subset(overlap.into_iter())
    }

    /// Combine two permutations, assuming they are compatible.
    ///
    /// # Panics
    ///
    /// Panics if the permutations are not compatible.
    pub fn combine(&self, other: &Self) -> Self {
        assert!(self
            .mapping
            .iter()
            .filter(|(cell, _)| other.mapping.contains_key(*cell))
            .all(|(cell, value)| other.mapping[cell] == *value));
        let mut map = self.mapping.clone().into_inner();
        for (&k, &v) in other.mapping.iter() {
            map.insert(k, v);
        }
        Self::new(map)
    }

    /// Return the total number of mines in this permutation.
    pub fn k(&self) -> usize {
        self.mapping.values().sum::<usize>()
    }

    /// Return the set of cells in this permutation.
    pub fn cells(&self) -> HashSet<SuperCell<'arena, 'cell, T>> {
        self.mapping.keys().copied().collect()
    }

    /// Count the number of permutations this permutation would correspond to if
    /// each super-cell were broken up into singleton cells.
    ///
    /// E.G. `N` mines in a super-cell of `M` cells has `comb(M, N)` actual
    /// configurations.
    pub fn multiplicity(&self) -> usize {
        self.mapping
            .iter()
            .map(|(&super_cell, &k)| comb(super_cell.len(), k))
            .product::<usize>()
    }
}

/// A set of permutations of the same cell set and total number of mines.
///
/// Might by the full set of possible permutations, or a subset as particular
/// permutations may be removed due to outside conflicts.
#[derive(Debug, PartialEq, Eq)]
struct PermutationSet<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// The set of super-cells that this permutation set is over.
    super_cells: &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
    /// The total number of mines in this permutation set.
    k: usize,
    /// The set of [`Permutation`]s - all permutations must share the same set
    /// of cells and number of mines (`super_cells` and `k`)
    permutations: HashSet<&'arena Permutation<'arena, 'cell, T>>,
    /// Whether this set has been constrained by outside information. Accurate
    /// only if the `PermutationSet` was created with the full set of
    /// possibilities (or if `true`).
    constrained: bool,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> Clone
    for PermutationSet<'arena, 'cell, T>
{
    fn clone(&self) -> Self {
        Self {
            super_cells: self.super_cells,
            k: self.k,
            permutations: self.permutations.clone(),
            constrained: self.constrained,
        }
    }
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> PermutationSet<'arena, 'cell, T> {
    pub fn new(
        super_cells: &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
        k: usize,
        permutations: impl IntoIterator<Item = &'arena Permutation<'arena, 'cell, T>>,
    ) -> Self {
        Self {
            super_cells,
            k,
            permutations: permutations.into_iter().collect(),
            constrained: false,
        }
    }

    /// Build a `PermutationSet` from all possible permutations of the given
    /// rule.
    pub fn from_rule(
        rule: &InternalRule<'arena, 'cell, T>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
    ) -> Self {
        Self::new(
            rule.super_cells,
            rule.num_mines,
            rule.permute().map(|perm| &*permutation_arena.alloc(perm)),
        )
    }

    /// Create an [`InternalRule`] from this set.
    ///
    /// Note that the set generated by `Self::from_rule(self.to_rule())` may not
    /// match this set, as it cannot account for permutations removed from this
    /// set due to outside constraints.
    pub fn to_rule(&self) -> InternalRule<'arena, 'cell, T> {
        InternalRule::new(
            self.k,
            self.super_cells,
            self.super_cells
                .iter()
                .map(|super_cell| super_cell.len())
                .sum::<usize>(),
        )
        .expect("Should be impossible to create an invalid rule from a PermutationSet")
    }

    /// Iterate over the [`Permutation`]s in this set.
    pub fn iter(
        &self,
    ) -> impl Iterator<Item = &'arena Permutation<'arena, 'cell, T>> + '_ {
        self.permutations.iter().copied()
    }

    /// Does this set contain the given [`Permutation`]?
    pub fn contains(&self, p: &Permutation<'arena, 'cell, T>) -> bool {
        self.permutations.contains(p)
    }

    /// Remove the given [`Permutation`] from this set, for example if that
    /// permutation conflicts with another rule.
    pub fn remove(&mut self, permu: &Permutation<'arena, 'cell, T>) {
        self.permutations.remove(permu);
        self.constrained = true;
    }

    /// Is this set empty?
    pub fn is_empty(&self) -> bool {
        self.permutations.is_empty()
    }

    /// Return a new `PermutationSet` containing only the [`Permutation`]s that
    /// are compatible with `permu`.
    pub fn compatible(&self, permu: &Permutation<'arena, 'cell, T>) -> Self {
        Self::new(
            self.super_cells,
            self.k,
            self.permutations
                .iter()
                .filter(|p| p.is_compatible(permu))
                .cloned(),
        )
    }

    /// Return a new `PermutationSet` consisting of the sub-setted
    /// [`Permutation`]s from this set.
    pub fn subset(
        &self,
        cell_subset: &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
    ) -> Option<Self> {
        let permu_subset = self
            .permutations
            .iter()
            .map(|p| &*permutation_arena.alloc(p.subset(cell_subset.iter().cloned())))
            .collect::<HashSet<_>>();
        let mut k_sub = permu_subset.iter().map(|p| p.k()).collect::<HashSet<_>>();
        if k_sub.len() == 1 {
            Some(Self::new(
                cell_subset,
                pop(&mut k_sub).unwrap(),
                permu_subset,
            ))
        } else {
            None
        }
    }

    /// Determine if the `PermutationSet` is the cartesian product of `N`
    /// smaller permutation sets; if so, return the decomposition.
    ///
    /// This set may be constrained, in which case at least one subset of the
    /// decomposition (if one exists) will also be constrained.
    ///
    /// Optimises if the set has not been constrained; full permutation-sets
    /// decompose to themselves.
    pub fn decompose(
        &self,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> Vec<Self> {
        if self.constrained {
            self.force_decompose(1, permutation_arena, super_cell_group_arena)
        } else {
            vec![self.clone()]
        }
    }

    /// Determine if the `PermutationSet` is the cartesian product of `N`
    /// smaller permutation sets; if so, return the decomposition.
    ///
    /// This set may be constrained, in which case at least one subset of the
    /// decomposition (if one exists) will also be constrained.
    fn force_decompose(
        &self,
        k_floor: usize,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> Vec<Self> {
        for k in k_floor..=(self.super_cells.len() / 2) {
            for cell_subset in self.super_cells.iter().combinations(k) {
                let cell_subset = &*super_cell_group_arena
                    .alloc(cell_subset.into_iter().cloned().collect::<FrozenSet<_>>());
                let Some((
                    permu_subset,
                    permu_remainder,
                )) = self.split(cell_subset, permutation_arena, super_cell_group_arena)
                else {
                    continue;
                };

                // We've found a cartesian divisor!
                let mut divisors = vec![permu_subset];
                divisors.extend(permu_remainder.force_decompose(
                    k,
                    permutation_arena,
                    super_cell_group_arena,
                ));
                return divisors;
            }
        }
        vec![self.clone()]
    }

    /// Helper function for [`Self::decompose()`]. Given a subset of cells,
    /// return the two `PermutationSet`s for the subset and the set of remaining
    /// cells, provided `cell_subset` is a valid decomposor; return `None` if
    /// not.
    fn split(
        &self,
        cell_subset: &'arena FrozenSet<SuperCell<'arena, 'cell, T>>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) -> Option<(Self, Self)> {
        let cell_remainder = super_cell_group_arena.alloc(
            self.super_cells
                .difference(cell_subset)
                .cloned()
                .collect::<FrozenSet<_>>(),
        );
        let permu_subset = self.subset(cell_subset, permutation_arena)?;

        let mut permu_remainders = map_reduce(
            self.permutations.iter().copied(),
            |p| [(p.subset(cell_subset.iter().copied()), p)].into_iter(),
            |pv| {
                pv.into_iter()
                    .map(|p| {
                        permutation_arena
                            .alloc(p.subset(cell_remainder.iter().copied()))
                    })
                    .collect::<FrozenSet<_>>()
            },
        )
        .into_values()
        .collect::<HashSet<_>>();

        if permu_remainders.len() == 1 {
            let permu_remainders = pop(&mut permu_remainders).unwrap();
            let other_k = permu_subset.k;
            Some((
                permu_subset,
                Self::new(
                    cell_remainder,
                    self.k - other_k,
                    permu_remainders.into_iter().map(|p| &*p),
                ),
            ))
        } else {
            None
        }
    }
}

/// A set of rules and the available permutations for each, eliminating
/// permutations which are mutually-inconsistent across the ruleset.
#[derive(Debug, PartialEq, Eq)]
struct PermutedRuleset<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// The ruleset.
    rules: &'arena mut HashSet<&'arena InternalRule<'arena, 'cell, T>>,
    /// Lookup for cell -> rules containing that cell.
    cell_rules_map: CellRulesMap<'arena, 'cell, T>,
    /// The supercells of the ruleset.
    super_cells: FrozenSet<SuperCell<'arena, 'cell, T>>,
    /// `InternalRule` -> `PermutationSet` for that rule.
    permu_map: HashMap<
        &'arena InternalRule<'arena, 'cell, T>,
        &'arena mut PermutationSet<'arena, 'cell, T>,
    >,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> PermutedRuleset<'arena, 'cell, T> {
    /// # Arguments
    ///
    /// * `permu_map`: If creating a subset of another `PermutedRuleset`, will
    ///   be the `permu_map` for the new PermutedRuleset; for a new one, will be
    ///   computed automatically.
    pub fn new(
        rules: &'arena mut HashSet<&'arena InternalRule<'arena, 'cell, T>>,
        permu_map: Option<
            HashMap<
                &'arena InternalRule<'arena, 'cell, T>,
                &'arena mut PermutationSet<'arena, 'cell, T>,
            >,
        >,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        permutation_set_arena: &'arena Arena<PermutationSet<'arena, 'cell, T>>,
    ) -> Self {
        let mut cell_rules_map = CellRulesMap::new();
        cell_rules_map.add_rules(rules.iter().cloned(), ruleset_arena);
        let super_cells = cell_rules_map.super_cells();
        Self {
            cell_rules_map,
            super_cells,
            permu_map: match permu_map {
                Some(permu_map) => {
                    // Pre-processed by Self::filter
                    permu_map
                },
                None => {
                    rules
                        .iter()
                        .map(|&rule| {
                            (
                                rule,
                                permutation_set_arena.alloc(PermutationSet::from_rule(
                                    rule,
                                    permutation_arena,
                                )),
                            )
                        })
                        .collect()
                },
            },
            rules,
        }
    }

    /// Determine what permutations are possible for each rule, taking into
    /// account the constraints of all overlapping rules. Eliminate impossible
    /// permutations.
    pub fn cross_eliminate(&mut self) -> Result<(), Error> {
        let mut interferences = self.cell_rules_map.interference_edges();
        // We can't just iterate over `interferences`, as eliminating a permutation may
        // in turn invalidate permutations in other overlapping rules that have already
        // been processed, causing a cascade effect. Therefore, treat the list of
        // interferences like a queue.
        while let Some((rule, overlapping)) = pop(&mut interferences) {
            let mut changed = false;
            for permu in self.permu_map[&rule].iter().collect_vec() {
                // Copy the set into a list so we can mutate it
                if self.permu_map[&overlapping].compatible(&permu).is_empty() {
                    // This permutation has no compatible permutation in the
                    // overlapping rule. Therefore, it can never occur.
                    self.permu_map
                        .get_mut(&rule)
                        .expect("self.permu_map[rule] has already been accessed")
                        .remove(&permu);
                    changed = true;
                }
            }

            if self.permu_map[&rule].is_empty() {
                // No possible configurations for this rule remain.
                return Err(
                    "Rule is constrained such that it has no valid mine permutations"
                );
            } else if changed {
                // Other rules that overlap this one must be recalculated.
                interferences.extend(
                    self.cell_rules_map
                        .overlapping_rules(&rule)
                        .into_iter()
                        .map(|other| (other, rule)),
                );
            }
        }
        Ok(())
    }

    /// After computing the possible permutations of the rules, analyse and
    /// decompose rules into sub-rules, if possible. This can eliminate
    /// dependencies among the initial set of rules, and thus potentially split
    /// what would have been one rule front into several.
    ///
    /// This is analogous to the previous `reduce_rules` step, but with more
    /// advanced logical analysis - exploiting information gained from the
    /// permutation phase.
    ///
    /// Some unproven postulates:
    /// - Among all cartesian decompositions from all rules, none will be
    ///   reduceable with another (decomposed rules may have duplicates,
    ///   though).
    /// - Cartesian decomposition will have effectively re-reduced all rules in
    ///   the set, even non-decomposed rules; there will be no possible
    ///   reductions between a decomposed rule and an original rule.
    /// - Re-permuting amongst the decomposed ruleset will produce the same
    ///   permutation sets
    pub fn rereduce(
        &mut self,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        permutation_set_arena: &'arena Arena<PermutationSet<'arena, 'cell, T>>,
        super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
    ) {
        let mut superseded_rules = HashSet::new();
        let mut decompositions = HashMap::new();
        for (&rule, permu_set) in self.permu_map.iter() {
            let decomp = permu_set.decompose(permutation_arena, super_cell_group_arena);
            if decomp.len() > 1 {
                superseded_rules.insert(rule);
                // Collapse duplicate decompositions by keying by cell set
                decompositions
                    .extend(decomp.into_iter().map(|dc| (dc.super_cells, dc)));
            }
        }

        for rule in superseded_rules {
            self.remove_rule(rule);
        }
        for permu_set in decompositions.into_values() {
            self.add_permu_set(
                permutation_set_arena.alloc(permu_set),
                rule_arena,
                ruleset_arena,
            );
        }
    }

    pub fn remove_rule(&mut self, rule: &InternalRule<'arena, 'cell, T>) {
        self.rules.remove(rule);
        self.cell_rules_map.remove_rule(rule);
        self.permu_map.remove(rule);
    }

    /// Add a decomposed rule to the ruleset.
    pub fn add_permu_set(
        &mut self,
        permu_set: &'arena mut PermutationSet<'arena, 'cell, T>,
        rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
    ) {
        let rule = rule_arena.alloc(permu_set.to_rule());
        self.rules.insert(rule);
        self.cell_rules_map.add_rule(rule, ruleset_arena);
        self.permu_map.insert(rule, permu_set);
    }

    /// Return a `PermutedRuleset` built from this one containing only a subset
    /// of its rules.
    pub fn filter(
        &mut self,
        rule_subset: &'arena mut HashSet<&'arena InternalRule<'arena, 'cell, T>>,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        permutation_set_arena: &'arena Arena<PermutationSet<'arena, 'cell, T>>,
    ) -> Self {
        // This works because the sets are independent; all rules are used exactly once
        let permu_map = rule_subset
            .iter()
            .map(|&rule| {
                self.permu_map
                    .remove_entry(rule)
                    .expect("Entry should be present")
            })
            .collect();
        Self::new(
            rule_subset,
            Some(permu_map),
            ruleset_arena,
            permutation_arena,
            permutation_set_arena,
        )
    }

    /// Split the ruleset into combinatorially-independent 'fronts'.
    pub fn split_fronts(
        mut self,
        ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
        permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
        permutation_set_arena: &'arena Arena<PermutationSet<'arena, 'cell, T>>,
    ) -> Vec<Self> {
        self.cell_rules_map
            .partition()
            .into_iter()
            .map(|rule_subset| {
                self.filter(
                    ruleset_arena.alloc(rule_subset.iter().cloned().collect()),
                    ruleset_arena,
                    permutation_arena,
                    permutation_set_arena,
                )
            })
            .collect()
    }

    /// Is this ruleset trivial? (i.e. does it contain only one rule?)
    pub fn is_trivial(&self) -> bool {
        self.rules.len() == 1
    }

    /// If this ruleset is trivial, return the single rule it contains.
    ///
    /// # Panics
    ///
    /// Panics if the ruleset is not trivial.
    pub fn trivial_rule(&self) -> &'arena InternalRule<'arena, 'cell, T> {
        assert!(self.is_trivial());
        let singleton = peek(self.rules.iter().cloned());
        // Postulate: Any singleton rule must also be trivial
        assert!(singleton.is_trivial());
        singleton
    }

    /// Enumerate all possible mine configurations for this ruleset.
    pub fn enumerate(
        &self,
    ) -> Box<dyn Iterator<Item = Permutation<'arena, 'cell, T>> + '_> {
        EnumerationState::new(self).enumerate()
    }
}

/// Process the set of rules and analyse the relationships and constraints among
/// them.
fn permute_and_interfere<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    rules: &'arena mut HashSet<&'arena InternalRule<'arena, 'cell, T>>,
    rule_arena: &'arena Arena<InternalRule<'arena, 'cell, T>>,
    ruleset_arena: &'arena Arena<HashSet<&'arena InternalRule<'arena, 'cell, T>>>,
    permutation_arena: &'arena Arena<Permutation<'arena, 'cell, T>>,
    permutation_set_arena: &'arena Arena<PermutationSet<'arena, 'cell, T>>,
    super_cell_group_arena: &'arena Arena<FrozenSet<SuperCell<'arena, 'cell, T>>>,
) -> Result<PermutedRuleset<'arena, 'cell, T>, Error> {
    let mut permuted_ruleset = PermutedRuleset::new(
        rules,
        None,
        ruleset_arena,
        permutation_arena,
        permutation_set_arena,
    );
    permuted_ruleset.cross_eliminate()?;
    permuted_ruleset.rereduce(
        rule_arena,
        ruleset_arena,
        permutation_arena,
        permutation_set_arena,
        super_cell_group_arena,
    );
    Ok(permuted_ruleset)
}

/// A helper structure to enumerate through all possible mine configurations for
/// a given ruleset.
#[derive(Debug, PartialEq, Eq)]
struct EnumerationState<'rules, 'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// The set of [`Permutation`]s (one per rule) that have been 'fixed' for
    /// the current configuration-in-progress.
    fixed: HashSet<&'arena Permutation<'arena, 'cell, T>>,
    /// The [`PermutedRuleset`] that we are enumerating.
    ruleset: &'rules PermutedRuleset<'arena, 'cell, T>,
    /// The subset of `ruleset` whose permutations are still 'open'
    free: HashMap<
        &'arena InternalRule<'arena, 'cell, T>,
        HashSet<&'arena Permutation<'arena, 'cell, T>>,
    >,
    /// Index for constraining overlapping permutations.
    /// Mapping from (permutation, overlapping_rule) to the [`PermutationSet`]
    /// of valid permutations for the overlapping rule.
    compatible_rule_index: HashMap<
        (
            &'arena Permutation<'arena, 'cell, T>,
            &'arena InternalRule<'arena, 'cell, T>,
        ),
        PermutationSet<'arena, 'cell, T>,
    >,
}
impl<'rules, 'arena, 'cell: 'arena, T: Cell + ?Sized> Clone
    for EnumerationState<'rules, 'arena, 'cell, T>
{
    fn clone(&self) -> Self {
        Self {
            fixed: self.fixed.clone(),
            ruleset: self.ruleset,
            free: self.free.clone(),
            compatible_rule_index: self.compatible_rule_index.clone(),
        }
    }
}
impl<'rules, 'arena, 'cell: 'arena, T: Cell + ?Sized>
    EnumerationState<'rules, 'arena, 'cell, T>
{
    pub fn new(ruleset: &'rules PermutedRuleset<'arena, 'cell, T>) -> Self {
        let mut rv = Self {
            fixed: HashSet::new(),
            ruleset,
            free: ruleset
                .permu_map
                .iter()
                .map(|(&rule, permu_set)| (rule, permu_set.iter().collect()))
                .collect(),
            compatible_rule_index: HashMap::new(),
        };
        rv.build_compatibility_index(&ruleset.permu_map);
        rv
    }

    /// Helper to reduce typing when accessing the overlapping rules.
    pub fn overlapping_rules(
        &self,
        rule: &InternalRule<'arena, 'cell, T>,
    ) -> HashSet<&'arena InternalRule<'arena, 'cell, T>> {
        self.ruleset.cell_rules_map.overlapping_rules(rule)
    }

    /// Generate the constraint index.
    pub fn build_compatibility_index(
        &mut self,
        map: &HashMap<
            &'arena InternalRule<'arena, 'cell, T>,
            &'arena mut PermutationSet<'arena, 'cell, T>,
        >,
    ) {
        for (rule, permu_set) in map.iter() {
            for permu in permu_set.iter() {
                for overlapping in self.overlapping_rules(rule) {
                    let v = map[&overlapping].compatible(permu);
                    self.compatible_rule_index.insert((permu, overlapping), v);
                }
            }
        }
    }

    /// Is the configuration complete? I.E. have all rules been fixed?
    pub fn is_complete(&self) -> bool {
        self.free.is_empty()
    }

    /// Pick an 'open' rule at random and 'fix' each possible permutation for
    /// that rule. In this manner, when done recursively, all valid combinations
    /// are enumerated.
    pub fn into_iter(
        mut self,
    ) -> impl Iterator<Item = EnumerationState<'rules, 'arena, 'cell, T>> + 'rules {
        let state = self.clone();
        let rule = peek(state.free.keys().copied());
        // let permus = self.free[rule].clone();
        // permus
        self.free
            .remove_entry(rule)
            .expect("Rule was taken out of keys")
            .1
            .into_iter()
            .filter_map(move |permu| state.propagate(&rule, permu))
    }

    /// 'Fix' a permutation for a given rule.
    pub fn propagate(
        &self,
        rule: &'arena InternalRule<'arena, 'cell, T>,
        permu: &'arena Permutation<'arena, 'cell, T>,
    ) -> Option<Self> {
        let mut state = self.clone();
        state.propagate_in_place(rule, permu)?;
        Some(state)
    }

    /// 'Fix' a rule permutation and constrain the available permutations of all
    /// overlapping rules, in-place.
    fn propagate_in_place(
        &mut self,
        rule: &'arena InternalRule<'arena, 'cell, T>,
        permu: &'arena Permutation<'arena, 'cell, T>,
    ) -> Option<()> {
        self.fixed.insert(permu);
        self.free.remove(rule)?;

        // Constrain overlapping rules
        let mut cascades = Vec::new();
        for related_rule in self
            .overlapping_rules(rule)
            .into_iter()
            .filter(|r| self.free.contains_key(r))
            .collect_vec()
        {
            // `PermutationSet` of the related rule, constrained *only* by the
            // rule/permutation just fixed
            let allowed_permus =
                self.compatible_rule_index.get(&(permu, related_rule))?;
            // Further constrain the related rule with this new set - is now properly
            // constrained by all fixed rules
            self.free
                .get_mut(related_rule)?
                .retain(|p| allowed_permus.contains(p));

            let linked_permus = self.free.get(&related_rule)?;
            if linked_permus.is_empty() {
                // Conflict - no possible configurations
                return None;
            } else if linked_permus.len() == 1 {
                // Only one possibility - constrain further
                cascades.push((related_rule, peek(linked_permus.iter().cloned())));
            }
        }

        // Cascade if any other rules are now fully constrained
        for (related_rule, constrained_permu) in cascades {
            // May have already been constrained by a prior recursive call
            if self.free.contains_key(&related_rule) {
                self.propagate_in_place(&related_rule, constrained_permu)?;
            }
        }
        Some(())
    }

    /// Convert the set of fixed permutations into a single [`Permutation`]
    /// encompassing the mine configuration for the entire ruleset.
    pub fn mine_config(&self) -> Permutation<'arena, 'cell, T> {
        self.fixed
            .iter()
            .fold(Permutation::new(empty()), |a, b| a.combine(b))
    }

    /// Recursively generate all possible mine configurations for the ruleset.
    pub fn enumerate(
        self,
    ) -> Box<dyn Iterator<Item = Permutation<'arena, 'cell, T>> + 'rules> {
        if self.is_complete() {
            Box::new(once(self.mine_config()))
        } else {
            Box::new(self.into_iter().flat_map(|s| s.enumerate()))
        }
    }
}

/// Tabulation of per-cell mine frequencies.
#[derive(Clone, Debug, PartialEq)]
struct FrontTally<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// Number of mines in configuration -> Sub-tally of configurations with
    /// that number of mines.
    subtallies: HashMap<usize, FrontSubtally<'arena, 'cell, T>>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> FrontTally<'arena, 'cell, T> {
    pub fn new(
        data: impl Iterator<Item = (usize, FrontSubtally<'arena, 'cell, T>)>,
    ) -> Self {
        Self {
            subtallies: data.collect(),
        }
    }

    /// Tally all possible configurations for a front (ruleset).
    ///
    /// The tallies for different total numbers of mines must be maintained
    /// separately, as these will be given different statistical weights later
    /// on.
    pub fn tally(
        &mut self,
        front: PermutedRuleset<'arena, 'cell, T>,
    ) -> Result<(), Error> {
        for config in front.enumerate() {
            (self
                .subtallies
                .entry(config.k())
                .or_insert_with(FrontSubtally::new))
            .add(&config);
        }

        if self.subtallies.is_empty() {
            return Err("Mine front has no possible configurations");
        }

        self.finalise();

        Ok(())
    }

    /// Finalise all sub-tallies (convert running totals to
    /// probabilities/expected values).
    pub fn finalise(&mut self) {
        for subtally in self.subtallies.values_mut() {
            subtally.finalise();
        }
    }

    /// Minimum number of mines found across all configurations.
    pub fn min_mines(&self) -> usize {
        self.subtallies
            .keys()
            .copied()
            .min()
            .expect("Mine front has no possible configurations")
    }

    /// Maximum number of mines found across all configurations.
    pub fn max_mines(&self) -> usize {
        self.subtallies
            .keys()
            .copied()
            .max()
            .expect("Mine front has no possible configurations")
    }

    /// Whether all configurations have the same number of mines (simplifies
    /// statistical weighting later).
    pub fn is_static(&self) -> bool {
        self.subtallies.len() == 1
    }

    pub fn iter(
        &self,
    ) -> impl Iterator<Item = (usize, &FrontSubtally<'arena, 'cell, T>)> + '_ {
        self.subtallies.iter().map(|(&k, v)| (k, v))
    }

    /// Normalise sub-tally totals into relative weights such that sub-totals
    /// remain proportional to each other, and the grand total across all
    /// sub-tallies is `1.0`.
    pub fn normalise(&mut self) {
        let total = self.subtallies.values().map(|s| s.total).sum::<f64>();
        for subtally in self.subtallies.values_mut() {
            subtally.total /= total;
        }
    }

    /// Calculate the per-cell expected mine values, summed and weighted across
    /// all sub-tallies.
    pub fn collapse(
        &mut self,
    ) -> HashMap<Either<SuperCell<'arena, 'cell, T>, UnchartedCell>, f64> {
        self.normalise();
        let collapsed = map_reduce(
            self.subtallies.values(),
            |subtally| subtally.collapse().collect_vec().into_iter(),
            |values| values.into_iter().sum(),
        );
        collapsed
    }

    /// Scale each sub-tally's weight/total according to `scale_func`.
    ///
    /// # Arguments
    ///
    /// * `scale_func` - Function that takes the number of mines in a sub-tally,
    ///   and returns a factor by which to scale the sub-tally (multiplier).
    ///
    /// # Errors
    ///
    /// If `scale_func` returns an error, the error is propagated and processing
    /// does not continue. This `FrontTally` is left in an unspecified state
    /// if this occurs, and should not be used.
    pub fn scale_weights(
        &mut self,
        scale_func: impl Fn(usize) -> Result<f64, Error>,
    ) -> Result<(), Error> {
        for (&num_mines, subtally) in self.subtallies.iter_mut() {
            subtally.total *= scale_func(num_mines)?;
        }
        Ok(())
    }

    /// Update each sub-tally's weight/total according to the given weights.
    pub fn update_weights(&mut self, weights: &HashMap<usize, f64>) {
        for (&num_mines, subtally) in self.subtallies.iter_mut() {
            subtally.total *= weights.get(&num_mines).copied().unwrap_or(0.0);
        }
    }

    /// Tally a trivial rule
    ///
    /// # Panics
    ///
    /// Panics if the rule is not trivial.
    pub fn from_rule(rule: &InternalRule<'arena, 'cell, T>) -> Self {
        assert!(rule.is_trivial());
        Self::new(
            [(
                rule.num_mines,
                FrontSubtally::from_data(
                    comb(rule.num_cells, rule.num_mines) as f64,
                    [(
                        Either::Left(peek(rule.super_cells.iter().cloned())),
                        rule.num_mines as f64,
                    )]
                    .into_iter(),
                ),
            )]
            .into_iter(),
        )
    }

    /// Create a meta-tally representing the mine distribution of all 'other'
    /// cells.
    ///
    /// # Arguments
    ///
    /// * `num_uncharted_cells` - Number of 'other' cells, that are not
    ///   otherwise accounted for.
    /// * `mine_totals` - A mapping suitable for [`Self::update_weights()`];
    ///   number of mines in 'other' region -> relative likelihood.
    pub fn for_other(
        num_uncharted_cells: usize,
        mine_totals: &HashMap<usize, f64>,
    ) -> Self {
        let meta_cell = UnchartedCell::new(num_uncharted_cells);
        Self::new(mine_totals.iter().map(|(&num_mines, &k)| {
            (
                num_mines,
                FrontSubtally::from_data(
                    k,
                    [(Either::Right(meta_cell), num_mines as f64)].into_iter(),
                ),
            )
        }))
    }
}

type CollapseResult<'arena, 'cell, T> =
    (Either<SuperCell<'arena, 'cell, T>, UnchartedCell>, f64);

/// Sub-tabulation of per-cell mine frequencies.
#[derive(Clone, Debug, PartialEq)]
struct FrontSubtally<'arena, 'cell: 'arena, T: Cell + ?Sized> {
    /// The 'weight' of this sub-tally among the others in the [`FrontTally`].
    /// Initially will be a raw count of the configurations in this sub-tally,
    /// but later will be weighted and normalised.
    total: f64,
    /// Per-cell mine counts (pre-finalising) or mine likelihoods
    /// (post-finalising).
    ///
    /// Mapping:
    ///
    /// - Key: A super-cell
    /// - Value:
    ///   - Pre-finalise: Total number of mines in the cell, summed across all
    ///     configurations
    ///   - Post-finalise: Expected number of mines in the cell
    tally: HashMap<Either<SuperCell<'arena, 'cell, T>, UnchartedCell>, f64>,
}
impl<'arena, 'cell: 'arena, T: Cell + ?Sized> FrontSubtally<'arena, 'cell, T> {
    pub fn new() -> Self {
        Self {
            total: 0.0,
            tally: HashMap::new(),
        }
    }

    /// Add a configuration to the tally.
    pub fn add(&mut self, config: &Permutation<'arena, 'cell, T>) {
        let mult = config.multiplicity() as f64;
        self.total += mult;
        for (&super_cell, &n) in config.mapping.iter() {
            *self.tally.entry(Either::Left(super_cell)).or_insert(0.0) +=
                n as f64 * mult;
        }
    }

    /// After all configurations have been summed, compute relative prevalence
    /// from totals.
    pub fn finalise(&mut self) {
        self.tally.values_mut().for_each(|n| *n /= self.total);
    }

    /// Helper function for [`FrontTally::collapse()`]. Emit all cell expected
    /// mine values weighted by this sub-tally's weight.
    pub fn collapse(
        &self,
    ) -> impl Iterator<Item = CollapseResult<'arena, 'cell, T>> + '_ {
        self.tally.iter().map(|(super_cell, &expected_mines)| {
            (super_cell.clone(), self.total * expected_mines)
        })
    }

    /// Build a sub-tally manually. Tally data is expected to be pre-finalised.
    pub fn from_data(
        total: f64,
        tally: impl Iterator<Item = CollapseResult<'arena, 'cell, T>>,
    ) -> Self {
        Self {
            total,
            tally: tally.collect(),
        }
    }
}

/// Enumerate and tabulate all mine configurations for the given front.
///
/// Return a tally where sub-totals are split out by total number of mines in
/// the configuration, and each sub-tally contains a total count of matching
/// configurations, and an expected number of mines in each cell.
fn enumerate_front<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    front: PermutedRuleset<'arena, 'cell, T>,
) -> Result<FrontTally<'arena, 'cell, T>, Error> {
    let mut tally = FrontTally::new(empty());
    tally.tally(front)?;
    Ok(tally)
}

/// Generate the final expected values for all cells in all fronts.
///
/// # Arguments
///
/// * `tallies` - The [`FrontTally`]s to collapse.
/// * `mine_prevalence` - Either the [`BoardInfo`] for the board, or the
///   probability that an individual cell is a mine.
/// * `all_cells` - The set of all (super-)cells from all rules.
///
/// # Returns
///
/// A stream of (cell, expected number of mines) pairs for all cells.
fn cell_probabilities<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    tallies: Vec<FrontTally<'arena, 'cell, T>>,
    mine_prevalence: Either<BoardInfo, f64>,
    all_cells: Vec<SuperCell<'arena, 'cell, T>>,
) -> Result<impl Iterator<Item = CollapseResult<'arena, 'cell, T>>, Error> {
    struct Iter<
        'arena,
        'cell: 'arena,
        T: Cell + ?Sized + 'cell,
        I: Iterator<Item = CollapseResult<'arena, 'cell, T>>,
        J: Iterator<Item = CollapseResult<'arena, 'cell, T>>,
    > {
        inner: Either<I, J>,
    }
    impl<
            'arena,
            'cell: 'arena,
            T: Cell + ?Sized + 'cell,
            I: Iterator<Item = CollapseResult<'arena, 'cell, T>>,
            J: Iterator<Item = CollapseResult<'arena, 'cell, T>>,
        > Iterator for Iter<'arena, 'cell, T, I, J>
    {
        type Item = CollapseResult<'arena, 'cell, T>;

        fn next(&mut self) -> Option<Self::Item> {
            match &mut self.inner {
                Either::Left(iter) => iter.next(),
                Either::Right(iter) => iter.next(),
            }
        }
    }
    Ok(
        weight_subtallies(tallies, mine_prevalence, all_cells)?.flat_map(|tally| {
            Iter {
                inner: match tally {
                    Either::Left(mut tally) => {
                        Either::Left(tally.collapse().into_iter())
                    },
                    Either::Right(tally) => Either::Right(tally.collapse()),
                },
            }
        }),
    )
}

/// Analyse all [`FrontTally`]s as a whole and weight the likelihood of each
/// sub-tally using probability analysis.
fn weight_subtallies<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    mut tallies: Vec<FrontTally<'arena, 'cell, T>>,
    mine_prevalence: Either<BoardInfo, f64>,
    all_cells: Vec<SuperCell<'arena, 'cell, T>>,
) -> Result<
    Box<
        dyn Iterator<Item = Either<FrontTally<'arena, 'cell, T>, FixedProbTally>>
            + 'arena,
    >,
    Error,
> {
    Ok(match mine_prevalence {
        Either::Left(board_info) => {
            // Traditional minesweeper - fixed total number of mines
            let num_uncharted_cells = check_count_consistency(
                &tallies.iter().collect_vec(),
                board_info,
                all_cells,
            )?;
            // Tallies with only one sub-tally don't need weighting.
            let (static_tallies, mut dyn_tallies) = {
                let mut static_tallies = vec![];
                let mut dyn_tallies = vec![];
                for tally in tallies {
                    if tally.is_static() {
                        static_tallies.push(tally);
                    } else {
                        dyn_tallies.push(tally);
                    }
                }
                (static_tallies, dyn_tallies)
            };

            let num_static_mines = static_tallies
                .iter()
                .map(|tally| tally.max_mines())
                .sum::<usize>();
            let at_large_mines = board_info.total_mines - num_static_mines;

            let tally_uncharted =
                combine_fronts(&mut dyn_tallies, num_uncharted_cells, at_large_mines);
            Box::new(
                static_tallies
                    .into_iter()
                    .chain(dyn_tallies.into_iter())
                    .chain(once(tally_uncharted))
                    .map(Either::Left),
            )
        },
        Either::Right(mine_probability) => {
            // Fixed probability of a mine in any given cell - total number of mines
            // varies per game
            let tally_uncharted = weight_nondiscrete(
                tallies.iter_mut().filter(|tally| tally.is_static()),
                mine_probability,
            )?;
            Box::new(
                tallies
                    .into_iter()
                    .map(Either::Left)
                    .chain(once(Either::Right(tally_uncharted))),
            )
        },
    })
}

/// Weight the relative likelihood of each sub-tally in a 'fixed
/// chance'/'variable-mine-count'-style game.
///
/// In this scenario, all fronts are completely independent; no front affects
/// the likelihoods for any other front.
fn weight_nondiscrete<'a, 'arena: 'a, 'cell: 'arena, T: Cell + ?Sized + 'cell>(
    dyn_tallies: impl IntoIterator<Item = &'a mut FrontTally<'arena, 'cell, T>>,
    mine_probability: f64,
) -> Result<FixedProbTally, Error> {
    for tally in dyn_tallies.into_iter() {
        let min_mines = tally.min_mines() as f64;
        tally.scale_weights(|num_mines| {
            nondiscrete_relative_likelihood(
                mine_probability,
                num_mines as f64,
                min_mines,
            )
        })?;
    }

    // Return the fixed mine probability as the chance for 'other' cells. Slightly
    // redundant but saves the client a step. Note that since we don't count the
    // total number of cells in this mode, this is *not* a guarantee that any given
    // game state actually has any 'other' cells.
    Ok(FixedProbTally::new(mine_probability))
}

/// Ensure the minimum/maximum number of mines required across all fronts is
/// compatible with the total number of mines, and remaining space available on
/// the board.
///
/// In the process, compute and return the remaining available space (i.e. the
/// number of 'other' cells not referenced in any rule).
fn check_count_consistency<T: Cell + ?Sized>(
    tallies: &[&FrontTally<'_, '_, T>],
    board_info: BoardInfo,
    all_cells: Vec<&FrozenSet<&T>>,
) -> Result<usize, Error> {
    let (min_possible_mines, max_possible_mines) =
        possible_mine_limits(tallies.into_iter().copied());
    let num_uncharted_cells = board_info.total_cells
        - all_cells
            .into_iter()
            .map(|super_cell| super_cell.len())
            .sum::<usize>();
    if min_possible_mines > board_info.total_mines {
        Err("Minimum possible number of mines exceeds supplied mine count")
    } else if board_info.total_mines > max_possible_mines + num_uncharted_cells {
        Err("Supplied mine count exceeds maximum possible number of mines")
    } else {
        Ok(num_uncharted_cells)
    }
}

/// Assign relative weights to all sub-tallies in all fronts. Because the total
/// number of mines is fixed, we must do a combinatorial analysis to compute the
/// likelihood of each front containing each possible number of mines. In the
/// process, compute the mine count likelihood for the 'other' cells, not part
/// of any front, and return a meta-front encapsulating them.
fn combine_fronts<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    tallies: &mut Vec<FrontTally<'arena, 'cell, T>>,
    num_uncharted_cells: usize,
    at_large_mines: usize,
) -> FrontTally<'arena, 'cell, T> {
    /// Tracks, for a constituent front, how many configurations for each number
    /// of mines in the front.
    struct FrontPerMineTotals {
        /// Mapping: number of mines in front -> number of configurations
        totals: HashMap<usize, f64>,
    }
    impl FrontPerMineTotals {
        pub fn singleton(num_mines: usize, total: f64) -> Self {
            Self {
                totals: [(num_mines, total)].into(),
            }
        }

        /// Total number of configurations across all possible numbers of mines.
        pub fn total_count(&self) -> f64 {
            self.totals.values().sum::<f64>()
        }

        /// Multiply every configuration's count by a fixed factor.
        pub fn multiply(&self, n: f64) -> Self {
            Self {
                totals: self.totals.iter().map(|(&k, &v)| (k, v * n)).collect(),
            }
        }

        /// Compute an aggregate sum of several mappings.
        pub fn sum<'a>(front_totals: impl Iterator<Item = &'a Self>) -> Self {
            Self {
                totals: map_reduce(
                    front_totals,
                    |front_totals| front_totals.totals.iter().map(|(&k, &v)| (k, v)),
                    |vals| vals.into_iter().sum::<f64>(),
                ),
            }
        }
    }

    /// Tracks, for a given number of mines in the [`CombinedFront`], the
    /// [`FrontPerMineTotals`]s corresponding to each constituent front.
    struct AllFrontsPerMineTotals {
        /// A list of [`FrontPerMineTotals`]s
        front_totals: Vec<FrontPerMineTotals>,
    }
    impl AllFrontsPerMineTotals {
        /// The total number of configurations for the given total number of
        /// mines in the combined front.
        pub fn total_count(&self) -> f64 {
            // The count should match for each constituent front, but we don't check
            // The null case is just normalised to 1.0 (I think this is because it's the
            // multiplicative identity)
            self.front_totals
                .get(0)
                .map_or(1.0, |front_total| front_total.total_count())
        }

        pub fn null() -> Self {
            Self {
                front_totals: Vec::new(),
            }
        }

        pub fn singleton(num_mines: usize, total: f64) -> Self {
            Self {
                front_totals: vec![FrontPerMineTotals::singleton(num_mines, total)],
            }
        }

        /// Merge two [`AllFrontsPerMineTotals`]s, by joining them into a single
        /// list and performing the necessary cross-multiplication.
        pub fn join_with(&self, other: &Self) -> Self {
            Self {
                front_totals: self
                    .front_totals
                    .iter()
                    .map(|f| f.multiply(other.total_count()))
                    .chain(
                        other
                            .front_totals
                            .iter()
                            .map(|f| f.multiply(self.total_count())),
                    )
                    .collect(),
            }
        }

        /// Sum a list of [`AllFrontsPerMineTotals`]s on a per-constituent-front
        /// basis.
        pub fn sum(front_sets: &[Self]) -> Self {
            if front_sets.is_empty() {
                return Self::null();
            }
            Self {
                front_totals: {
                    let mut results = vec![];
                    for i in 0..front_sets
                        .iter()
                        .map(|set| set.front_totals.len())
                        .min()
                        .expect("Already validated that there is at least one element")
                    {
                        let mut el = vec![];
                        for front in front_sets {
                            el.push(&front.front_totals[i]);
                        }
                        results.push(FrontPerMineTotals::sum(el.into_iter()));
                    }
                    results
                },
            }
        }
    }

    /// A representation of a combinatorial fusing of multiple fronts/tallies.
    /// Essentially, track (total number of mines in the combined front) -> (for
    /// each front (total number of mines in the constituent front) -> (total
    /// number of configurations for that number of mines))
    struct CombinedFront {
        /// A mapping of (total number of mines in the combined front) -> an
        /// [`AllFrontsPerMineTotals`]
        totals: HashMap<usize, AllFrontsPerMineTotals>,
    }
    impl CombinedFront {
        /// Returns the minimum and maximum number of mines in the combined
        /// front.
        ///
        /// If this `CombinedFront` does not contain *any* elements (should
        /// never be true as creating a null front adds an empty element),
        /// returns `(usize::MAX, 0)`.
        pub fn min_max_mines(&self) -> (usize, usize) {
            self.totals
                .keys()
                .fold((usize::MAX, 0), |(lowest, highest), &next| {
                    (min(lowest, next), max(highest, next))
                })
        }

        /// Create an 'empty' combined front.
        pub fn null() -> Self {
            Self {
                totals: [(0, AllFrontsPerMineTotals::null())].into(),
            }
        }

        /// Build a starter combined front using known counts for each number of
        /// mines.
        pub fn from_counts_per_num_mines(
            mines_with_count: impl Iterator<Item = (usize, f64)>,
        ) -> Self {
            Self {
                totals: mines_with_count
                    .map(|(num_mines, total)| {
                        (
                            num_mines,
                            AllFrontsPerMineTotals::singleton(num_mines, total),
                        )
                    })
                    .collect(),
            }
        }

        /// Build a starter combined front from a [`FrontTally`].
        pub fn from_tally<T: Cell + ?Sized>(tally: &FrontTally<'_, '_, T>) -> Self {
            Self::from_counts_per_num_mines(
                tally
                    .iter()
                    .map(|(num_mines, subtally)| (num_mines, subtally.total)),
            )
        }

        /// Build a starter combined front to represent the 'uncharted cells'
        /// region.
        pub fn for_other(
            min_mines: usize,
            max_mines: usize,
            relative_likelihood: impl Fn(usize) -> f64,
        ) -> Self {
            Self::from_counts_per_num_mines(
                (min_mines..=max_mines).map(|n| (n, relative_likelihood(n))),
            )
        }

        /// Combine two `CombinedFront`s. The two `remaining_mines` parameters
        /// represent the total remaining mines available in all fronts yet to
        /// be combined (excluding `other`). This helps avoid computing
        /// combinations which have a total number of mines that can never
        /// occur. This is also how we converge to a single total number of
        /// mines upon combining all fronts. `at_large_mines` represents the
        /// total number of mines left to be placed.
        pub fn join_with(
            &self,
            other: &Self,
            min_remaining_mines: usize,
            max_remaining_mines: usize,
            at_large_mines: usize,
        ) -> Self {
            let cross_entry = |((a_num_mines, a_fronts), (b_num_mines, b_fronts)): (
                (&usize, &AllFrontsPerMineTotals),
                (&usize, &AllFrontsPerMineTotals),
            )| {
                let combined_mines = a_num_mines + b_num_mines;
                let min_mines_at_end = combined_mines + min_remaining_mines;
                let max_mines_at_end = combined_mines + max_remaining_mines;
                if min_mines_at_end > at_large_mines
                    || max_mines_at_end < at_large_mines
                {
                    None
                } else {
                    Some((combined_mines, a_fronts.join_with(b_fronts)))
                }
            };

            let cross_entries = self
                .totals
                .iter()
                .cartesian_product(other.totals.iter())
                .filter_map(cross_entry);

            let new_totals = map_reduce(cross_entries, once, |vals| {
                AllFrontsPerMineTotals::sum(&vals)
            });
            Self {
                totals: new_totals,
            }
        }

        /// Once all fronts are combined, unwrap the data and return the
        /// underlying counts corresponding to each front.
        pub fn collapse(self) -> impl Iterator<Item = HashMap<usize, f64>> {
            assert_eq!(self.totals.len(), 1);
            let item = peek(self.totals.into_iter());
            item.1.front_totals.into_iter().map(|e| e.totals)
        }
    }

    let (min_tallied_mines, max_tallied_mines) = possible_mine_limits(tallies.iter());
    let min_other_mines = at_large_mines.saturating_sub(max_tallied_mines);
    // `min_tallied_mines` known to be <= `at_large_mines` due to
    // `check_count_consistency()`
    let max_other_mines = min(at_large_mines - min_tallied_mines, num_uncharted_cells);

    let relative_likelihood = |num_free_mines: usize| {
        discrete_relative_likelihood(
            num_uncharted_cells,
            num_free_mines,
            max_other_mines,
        )
        .expect(concat!(
            "num_free_mines and max_other_mines should always",
            " be <= num_uncharted_cells",
        ))
    };

    let all_fronts = tallies
        .iter()
        .map(|t| CombinedFront::from_tally(&t))
        .chain(once(CombinedFront::for_other(
            min_other_mines,
            max_other_mines,
            relative_likelihood,
        )))
        .collect_vec();
    let (mut min_remaining_mines, mut max_remaining_mines) = {
        let (mins, maxs): (Vec<_>, Vec<_>) =
            all_fronts.iter().map(|f| f.min_max_mines()).unzip();
        (
            mins.into_iter().sum::<usize>(),
            maxs.into_iter().sum::<usize>(),
        )
    };
    let mut combined = CombinedFront::null();
    for f in all_fronts {
        // Note that it's only correct to use min/max mines in this way before the front
        // has been combined or modified.
        let (front_min, front_max) = f.min_max_mines();
        min_remaining_mines -= front_min;
        max_remaining_mines -= front_max;
        combined = combined.join_with(
            &f,
            min_remaining_mines,
            max_remaining_mines,
            at_large_mines,
        );
    }

    let front_totals = combined.collapse().collect_vec();
    let (uncharted_total, front_totals) = front_totals
        .split_last()
        .expect("Should always get at least one total out of collapse");

    // Update tallies with adjusted weights
    for (tally, front_total) in tallies.iter_mut().zip(front_totals) {
        tally.update_weights(front_total);
    }

    FrontTally::for_other(num_uncharted_cells, uncharted_total)
}

/// Return the total minimum and maximum possible number of mines across all
/// tallied fronts. Returns (min, max).
fn possible_mine_limits<'a, T: Cell + ?Sized + 'a>(
    tallies: impl Iterator<Item = &'a FrontTally<'a, 'a, T>>,
) -> (usize, usize) {
    tallies
        .map(|tally| (tally.min_mines(), tally.max_mines()))
        .reduce(|(min, max), (tmin, tmax)| (min + tmin, max + tmax))
        .unwrap_or((0, 0))
}

/// Given binomial probability (*p*, *k*, *n*) -> *p*^*k* * (1 - *p*)^(*n* -
/// *k*), return binom_prob(*p*, *k*, *n*) / binom_prob(*p*, *k0*, *n*).
///
/// Note that *n* isn't actually needed! This is because we're calculating a
/// per-configuration weight, and in a true binomial distribution we'd then
/// multiply by `comb(n, k)` - however, we've effectively done that already with
/// the enumeration and tallying phase.
fn nondiscrete_relative_likelihood(p: f64, k: f64, k0: f64) -> Result<f64, Error> {
    if (0.0..=1.0).contains(&p) {
        Ok((p / (1.0 - p)).powf(k - k0))
    } else {
        Err("p must be in [0, 1]")
    }
}

/// Return `comb(n, k) / comb(n, k0)`.
fn discrete_relative_likelihood(n: usize, k: usize, k0: usize) -> Result<f64, Error> {
    if k > n || k0 > n {
        Err("k, k0 must be in [0, n]")
    } else {
        Ok(fact_div(k0, k) * fact_div(n - k0, n - k))
    }
}

/// A meta-cell that represents all the 'other' cells on the board that aren't
/// explicitly mentioned in a rule. See `expand_cells()`.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct UnchartedCell {
    /// The number of 'other' cells.
    pub len: usize,
}
impl UnchartedCell {
    pub fn new(len: usize) -> Self {
        Self {
            len,
        }
    }
}

/// A meta-tally to represent when all 'other' cells are uncounted and assumed
/// to have a fixed chance of being a mine.
struct FixedProbTally {
    p: f64,
}
impl FixedProbTally {
    pub fn new(p: f64) -> Self {
        Self {
            p,
        }
    }

    pub fn collapse<'arena, 'cell: 'arena, T: Cell + ?Sized + 'cell>(
        &self,
    ) -> impl Iterator<Item = CollapseResult<'arena, 'cell, T>> {
        once((Either::Right(UnchartedCell::new(1)), self.p))
    }
}

type ExpandResult<'cell, T> = (&'cell T, f64);

/// Back-convert the expected values for all super-cells into per-cell
/// probabilities for each cell.
fn expand_cells<'arena, 'cell: 'arena, T: Cell + ?Sized>(
    cell_probs: impl Iterator<Item = CollapseResult<'arena, 'cell, T>> + 'arena,
    other_tag: &'cell T,
) -> impl Iterator<Item = (&'cell T, f64)> + 'arena {
    struct Iter<
        'arena,
        'cell: 'arena,
        T: Hash + Eq + ?Sized,
        I: Iterator<Item = CollapseResult<'arena, 'cell, T>>,
    > {
        cell_probs: I,
        inner: Either<
            <HashSet<&'cell T> as IntoIterator>::IntoIter,
            <Option<(&'cell T, f64)> as IntoIterator>::IntoIter,
        >,
        p: f64,
        other_tag: &'cell T,
    }
    impl<
            'arena,
            'cell,
            T: Hash + Eq + ?Sized,
            I: Iterator<Item = CollapseResult<'arena, 'cell, T>>,
        > Iterator for Iter<'arena, 'cell, T, I>
    {
        type Item = ExpandResult<'cell, T>;

        fn next(&mut self) -> Option<Self::Item> {
            match self.inner {
                Either::Left(ref mut inner) => inner.next().map(|t| (t, self.p)),
                Either::Right(ref mut inner) => inner.next(),
            }
            .or_else(|| {
                let (super_cell, p) = self.cell_probs.next()?;
                self.p = p;
                self.inner = match super_cell {
                    Either::Left(cells) => Either::Left((*cells).clone().into_iter()),
                    Either::Right(uncharted) => {
                        Either::Right(
                            // Skip the "other" cells if there aren't any - otherwise,
                            // include exactly one entry.
                            if uncharted.len != 0 {
                                Some((self.other_tag, self.p / (uncharted.len as f64)))
                            } else {
                                None
                            }
                            .into_iter(),
                        )
                    },
                };
                self.next()
            })
        }
    }
    Iter {
        cell_probs,
        inner: Either::Right(None.into_iter()),
        p: 0.0,
        other_tag,
    }
}