Repository navigation
Expand file tree
/
Copy pathsolver.cc
More file actions
2328 lines (2103 loc) · 83 KB
/
Copy pathsolver.cc
File metadata and controls
2328 lines (2103 loc) · 83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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
#include <assert.h>
#include <ctype.h>
#if defined(__BMI2__) || defined(__SSE4_1__)
#include <immintrin.h>
#elif defined(__ARM_NEON)
#include <arm_neon.h>
#endif
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <random>
#include <vector>
#include "solver.h"
// clang-format off
#ifdef _DEBUG
#define CHECK(statement) assert(statement)
#define VERBOSE(statement) if (depth <= options.displaying_depth) statement
#define STATS(statement) statement
#else
#define CHECK(statement)
#define VERBOSE(statement)
#define STATS(statement)
#endif
// clang-format on
const int TOTAL_CARDS = NUM_RANKS * NUM_SUITS;
const char* SeatName(int seat) {
static const char* seat_names[] = {"West", "North", "East", "South"};
return seat_names[seat];
}
char SeatLetter(int seat) { return SeatName(seat)[0]; }
bool IsNs(int seat) { return seat & 1; }
const char* SuitName(int suit) {
static const char* suit_names[] = {"Spade", "Heart", "Diamond", "Club", "NoTrump"};
return suit_names[suit];
}
const char* SuitSign(int suit) {
static const char* plain_suit_signs[] = {"♠", "♥", "♦", "♣", "NT"};
#ifdef _DEBUG
return plain_suit_signs[suit];
#else
static const char* color_suit_signs[] = {"♠", "\e[31m♥\e[0m", "\e[31m♦\e[0m", "♣", "NT"};
static struct stat stdout_stat;
static bool is_terminal = fstat(1, &stdout_stat) == 0 && S_ISCHR(stdout_stat.st_mode);
return is_terminal ? color_suit_signs[suit] : plain_suit_signs[suit];
#endif
}
char RankName(int rank) {
static const char rank_names[] = "23456789TJQKA";
return rank_names[rank];
}
int CharToSuit(char c) {
for (int suit = SPADE; suit <= NOTRUMP; ++suit)
if (toupper(c) == SuitName(suit)[0]) return suit;
fprintf(stderr, "Unknown suit: %c\n", c);
exit(-1);
}
int CharToRank(char c) {
if (c == '1') return TEN;
for (int rank = TWO; rank <= ACE; ++rank)
if (toupper(c) == RankName(rank)) return rank;
fprintf(stderr, "Unknown rank: %c\n", c);
exit(-1);
}
int CharToSeat(char c) {
for (int seat = WEST; seat <= SOUTH; ++seat)
if (toupper(c) == SeatLetter(seat)) return seat;
fprintf(stderr, "Unknown seat: %c\n", c);
exit(-1);
}
// Number of bits in a suit, in the range of [13, 16]. Pick 16 to avoid divisions.
const int SUIT_SPAN = 16;
// The bit right after the highest valid card bit, also indicating an invalid card.
const int CARD_END = (NUM_SUITS - 1) * SUIT_SPAN + NUM_RANKS;
char suit_of[CARD_END];
char rank_of[CARD_END];
char card_of[NUM_SUITS][16];
char name_of[CARD_END][4];
int SuitOf(int card) { return SUIT_SPAN == 16 ? card / SUIT_SPAN : suit_of[card]; }
int RankOf(int card) { return rank_of[card]; }
int CardOf(int suit, int rank) { return card_of[suit][rank]; }
uint64_t MaskOf(int suit) { return 0x1fffULL << (suit * SUIT_SPAN); }
const char* NameOf(int card) { return name_of[card]; }
const auto DECK_MASK = MaskOf(SPADE) + MaskOf(HEART) + MaskOf(DIAMOND) + MaskOf(CLUB);
bool LowerRank(int card1, int card2) { return card1 > card2; }
bool HigherRank(int card1, int card2) { return card1 < card2; }
struct CardInitializer {
CardInitializer() {
for (int suit = 0; suit < NUM_SUITS; ++suit) {
for (int rank = 0; rank < NUM_RANKS; ++rank) {
int card = suit * SUIT_SPAN + NUM_RANKS - 1 - rank;
suit_of[card] = suit;
rank_of[card] = rank;
card_of[SuitOf(card)][RankOf(card)] = card;
name_of[card][0] = SuitName(SuitOf(card))[0];
name_of[card][1] = RankName(RankOf(card));
name_of[card][2] = '\0';
}
}
}
} card_initializer;
Options options;
template <class T>
int BitSize(T v) {
return sizeof(v) * 8;
}
template <int STAGES = 6>
uint64_t PackBits(uint64_t source, uint64_t mask) {
#ifdef __BMI2__
return _pext_u64(source, mask);
#elif defined(__EMSCRIPTEN__) && !defined(__wasm_simd128__)
// Bit-at-a-time loop: measured faster than the branchless version below on
// weak/narrow cores (older phones/tablets without wasm SIMD) -- its cost
// scales with popcount(mask) (avg ~5.4 for suit-local masks), cheaper
// there than paying the branchless version's larger fixed op count when
// branches are cheap and there's no spare execution width to hide it.
if (source == 0) return 0;
uint64_t packed = 0;
for (uint64_t bit = 1; mask; bit <<= 1, mask &= mask - 1)
if (source & mask & -mask) packed |= bit;
return packed;
#else
// Branchless bit compress (Hacker's Delight 7-4). 4 stages covers a
// suit-local mask (SUIT_SPAN <= 16), 6 the full 64-bit deck.
source &= mask;
uint64_t mk = ~mask << 1;
for (int i = 0; i < STAGES; ++i) {
uint64_t mp = mk ^ (mk << 1);
mp ^= mp << 2;
mp ^= mp << 4;
mp ^= mp << 8;
if constexpr (STAGES > 4) {
mp ^= mp << 16;
mp ^= mp << 32;
}
uint64_t mv = mp & mask;
mask = (mask ^ mv) | (mv >> (1 << i));
uint64_t t = source & mv;
source = (source ^ t) | (t >> (1 << i));
mk &= ~mp;
}
return source;
#endif
}
template <int STAGES = 6>
uint64_t UnpackBits(uint64_t source, uint64_t mask) {
#ifdef __BMI2__
return _pdep_u64(source, mask);
#elif defined(__EMSCRIPTEN__) && !defined(__wasm_simd128__)
// Bit-at-a-time loop -- see PackBits's comment for why this beats the
// branchless version on weak/narrow cores.
if (source == 0) return 0;
uint64_t unpacked = 0;
for (uint64_t bit = 1; source; bit <<= 1, mask &= mask - 1)
if (source & bit) {
unpacked |= mask & -mask;
source &= ~bit;
}
return unpacked;
#else
uint64_t mv[STAGES], mask0 = mask, mk = ~mask << 1;
for (int i = 0; i < STAGES; ++i) {
uint64_t mp = mk ^ (mk << 1);
mp ^= mp << 2;
mp ^= mp << 4;
mp ^= mp << 8;
if constexpr (STAGES > 4) {
mp ^= mp << 16;
mp ^= mp << 32;
}
mv[i] = mp & mask;
mask = (mask ^ mv[i]) | (mv[i] >> (1 << i));
mk &= ~mp;
}
for (int i = STAGES - 1; i >= 0; --i) { // undo in reverse order
uint64_t t = source << (1 << i);
source = (source & ~mv[i]) | (t & mv[i]);
}
return source & mask0;
#endif
}
// True where PackBits/UnpackBits don't care about a mask's absolute
// position (pext/pdep, and the wasm bit-loop fallback) -- so callers can
// skip the shift-to-suit-local-range dance the branchless STAGES<6 path
// needs.
#if defined(__BMI2__) || (defined(__EMSCRIPTEN__) && !defined(__wasm_simd128__))
#define POSITION_INDEPENDENT_BITS 1
#endif
// True where PackBits is a single instruction (pext). Elsewhere it is costly
// enough to be worth skipping when possible.
#ifdef __BMI2__
#define CHEAP_PACK_BITS 1
#endif
class Cards {
public:
Cards() : bits(0) {}
Cards(uint64_t b) : bits(b) {}
uint64_t Value() const { return bits; }
uint64_t PackedValue() const {
if (SUIT_SPAN == NUM_RANKS) return bits;
#ifdef __BMI2__
return PackBits(bits, DECK_MASK);
#else
return Suit(0).Value() + (Suit(1).Value() >> (SUIT_SPAN - NUM_RANKS)) +
(Suit(2).Value() >> (SUIT_SPAN * 2 - NUM_RANKS * 2)) +
(Suit(3).Value() >> (SUIT_SPAN * 3 - NUM_RANKS * 3));
#endif
}
int Size() const { return __builtin_popcountll(bits); }
bool operator==(const Cards& c) const { return bits == c.bits; }
bool operator!=(const Cards& c) const { return bits != c.bits; }
operator bool() const { return bits != 0; }
Cards Slice(int begin, int end) const { return bits & (Bit(end) - Bit(begin)); }
Cards Suit(int suit) const { return bits & MaskOf(suit); }
int Top() const { return __builtin_ctzll(bits); }
int Bottom() const { return BitSize(bits) - 1 - __builtin_clzll(bits); }
Cards Union(const Cards& c) const { return bits | c.bits; }
Cards Intersect(const Cards& c) const { return bits & c.bits; }
Cards Different(const Cards& c) const { return bits & ~c.bits; }
Cards Complement() const { return DECK_MASK ^ bits; }
bool Include(int card) const { return bits & Bit(card); }
bool Include(const Cards& c) const { return Intersect(c) == c; }
bool StrictlyInclude(const Cards& c) const { return Include(c) && bits != c.bits; }
Cards Add(int card) { return bits |= Bit(card); }
Cards Remove(int card) { return bits &= ~Bit(card); }
Cards Add(const Cards& c) { return bits |= c.bits; }
Cards Remove(const Cards& c) { return bits &= ~c.bits; }
Cards ClearSuit(int suit) { return bits &= ~MaskOf(suit); }
uint64_t ShapeParity() const {
uint64_t parity = 0;
for (int suit = 0; suit < NUM_SUITS; ++suit) parity += (Suit(suit).Size() % 2) << suit;
return parity;
}
int Points() const {
int points = 0;
for (int card : *this)
if (RankOf(card) > TEN) points += RankOf(card) - TEN;
return points;
}
void Show() const {
for (int suit = 0; suit < NUM_SUITS; ++suit) {
ShowSuit(suit);
putchar(' ');
}
}
void ShowSuit(int suit) const {
printf("%s ", SuitSign(suit));
if (Suit(suit))
for (int card : Suit(suit)) putchar(NameOf(card)[1]);
else
putchar('-');
}
class Iterator {
public:
Iterator(uint64_t bits) : bits(bits) {}
void operator++() { bits &= bits - 1; }
bool operator!=(const Iterator& it) const { return bits != it.bits; }
int operator*() const { return __builtin_ctzll(bits); }
private:
uint64_t bits;
};
Iterator begin() const { return Iterator(bits); }
Iterator end() const { return Iterator(0); }
private:
static uint64_t Bit(int index) { return uint64_t(1) << index; }
uint64_t bits;
};
// Expands suit-local relative bits back to real card positions in all_cards.
Cards UnpackSuitBits(Cards relative_bits, Cards all_cards, int suit) {
int shift = suit * SUIT_SPAN;
auto packed = relative_bits.Suit(suit).Value() >> shift;
#ifdef POSITION_INDEPENDENT_BITS
return Cards(UnpackBits(packed, all_cards.Suit(suit).Value()));
#else
// Shift the mask down too and the result back up, so UnpackBits<4> applies.
auto suit_mask = all_cards.Suit(suit).Value() >> shift;
return Cards(UnpackBits<4>(packed, suit_mask) << shift);
#endif
}
class Hands {
public:
void Randomize() {
for (int seat = 0; seat < NUM_SEATS; ++seat)
for (int i = 0; i < NUM_RANKS; ++i) hands[seat].Add(CardOf(seat, i));
Shuffle("NEWS");
}
void Shuffle(const char* shuffle_seats) {
std::vector<int> seats;
for (auto* s = shuffle_seats; *s; ++s) seats.push_back(CharToSeat(*s));
Cards cards;
for (int seat : seats) {
cards.Add(hands[seat]);
hands[seat] = Cards();
}
Deal(cards, seats);
}
void Deal(Cards cards, const std::vector<int>& seats) {
// Seed with multiple random_device draws as each one is only 32-bit.
static std::mt19937 random = [] {
std::random_device rd;
std::seed_seq seed{rd(), rd(), rd(), rd()};
return std::mt19937(seed);
}();
std::vector<int> deck;
for (int card : cards) deck.push_back(card);
std::shuffle(deck.begin(), deck.end(), random);
int tricks = deck.size() / seats.size();
for (int seat : seats) {
for (int i = 0; i < tricks; ++i) {
hands[seat].Add(deck.back());
deck.pop_back();
}
}
}
void Decode(const char* code) {
uint64_t values[3];
int num_values =
sscanf(code, "%" SCNx64 ",%" SCNx64 ",%" SCNx64, values, values + 1, values + 2);
assert(num_values == 3);
auto mask = DECK_MASK;
for (int seat = 0; seat < NUM_SEATS - 1; ++seat) {
hands[seat] = UnpackBits(values[seat], mask);
mask &= ~hands[seat].Value();
}
hands[NUM_SEATS - 1] = UnpackBits((1ULL << TOTAL_TRICKS) - 1, mask);
assert(hands[0].Size() == hands[1].Size() && hands[1].Size() == hands[2].Size() &&
hands[2].Size() == hands[3].Size());
}
Cards all_cards() const {
return hands[WEST].Union(hands[NORTH]).Union(hands[EAST]).Union(hands[SOUTH]);
}
const Cards& operator[](int seat) const { return hands[seat]; }
Cards& operator[](int seat) { return hands[seat]; }
// Whether every seat's hand in `other` is a subset of the hand here.
// Pack two adjacent hands into one 128-bit PTESTs.
bool Include(const Hands& other) const {
#ifdef __AVX2__
__m256i a = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(hands));
__m256i b = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(other.hands));
return _mm256_testc_si256(a, b);
#elif defined(__SSE4_1__)
__m128i a0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&hands[WEST]));
__m128i b0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&other.hands[WEST]));
__m128i a1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&hands[EAST]));
__m128i b1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&other.hands[EAST]));
__m128i missing = _mm_or_si128(_mm_andnot_si128(a0, b0), _mm_andnot_si128(a1, b1));
return _mm_testz_si128(missing, missing);
#elif defined(__ARM_NEON)
uint64x2_t a0 = vld1q_u64(reinterpret_cast<const uint64_t*>(&hands[WEST]));
uint64x2_t b0 = vld1q_u64(reinterpret_cast<const uint64_t*>(&other.hands[WEST]));
uint64x2_t a1 = vld1q_u64(reinterpret_cast<const uint64_t*>(&hands[EAST]));
uint64x2_t b1 = vld1q_u64(reinterpret_cast<const uint64_t*>(&other.hands[EAST]));
uint64x2_t missing = vorrq_u64(vbicq_u64(b0, a0), vbicq_u64(b1, a1));
return (vgetq_lane_u64(missing, 0) | vgetq_lane_u64(missing, 1)) == 0;
#else
return hands[WEST].Include(other.hands[WEST]) & hands[NORTH].Include(other.hands[NORTH]) &
hands[EAST].Include(other.hands[EAST]) & hands[SOUTH].Include(other.hands[SOUTH]);
#endif
}
bool Equals(const Hands& other) const {
#ifdef __AVX2__
__m256i a = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(hands));
__m256i b = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(other.hands));
__m256i diff = _mm256_xor_si256(a, b);
return _mm256_testz_si256(diff, diff);
#elif defined(__SSE4_1__)
__m128i a0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&hands[WEST]));
__m128i b0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&other.hands[WEST]));
__m128i a1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&hands[EAST]));
__m128i b1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&other.hands[EAST]));
__m128i diff = _mm_or_si128(_mm_xor_si128(a0, b0), _mm_xor_si128(a1, b1));
return _mm_testz_si128(diff, diff);
#elif defined(__ARM_NEON)
uint64x2_t a0 = vld1q_u64(reinterpret_cast<const uint64_t*>(&hands[WEST]));
uint64x2_t b0 = vld1q_u64(reinterpret_cast<const uint64_t*>(&other.hands[WEST]));
uint64x2_t a1 = vld1q_u64(reinterpret_cast<const uint64_t*>(&hands[EAST]));
uint64x2_t b1 = vld1q_u64(reinterpret_cast<const uint64_t*>(&other.hands[EAST]));
uint64x2_t diff = vorrq_u64(veorq_u64(a0, b0), veorq_u64(a1, b1));
return (vgetq_lane_u64(diff, 0) | vgetq_lane_u64(diff, 1)) == 0;
#else
return (hands[WEST] == other.hands[WEST]) & (hands[NORTH] == other.hands[NORTH]) &
(hands[EAST] == other.hands[EAST]) & (hands[SOUTH] == other.hands[SOUTH]);
#endif
}
int num_tricks() const { return hands[WEST].Size(); }
int num_voids() const {
int voids = 0;
for (int seat = 0; seat < NUM_SEATS; ++seat)
for (int suit = 0; suit < NUM_SUITS; ++suit)
if (hands[seat].Suit(suit).Size() == 0) ++voids;
return voids;
}
void Show() const {
for (int seat = 0; seat < NUM_SEATS; ++seat) {
hands[seat].Show();
if (seat < NUM_SEATS - 1) printf(", ");
}
puts("");
}
std::string Encode() const {
uint64_t values[3];
auto mask = DECK_MASK;
for (int seat = 0; seat < NUM_SEATS - 1; ++seat) {
values[seat] = PackBits(hands[seat].Value(), mask);
mask &= ~hands[seat].Value();
}
char code[64];
snprintf(code, sizeof(code), "%" PRIX64 ",%" PRIX64 ",%" PRIX64, values[0], values[1],
values[2]);
return code;
}
void ShowCompact(int rotation = 0) const {
int seat = (NORTH + rotation) % NUM_SEATS;
printf("%25s ", " ");
hands[seat].Show();
printf("\n");
seat = (WEST + rotation) % NUM_SEATS;
int num_cards = hands[seat].Size();
printf("%*s ", 14 - num_cards, " ");
hands[seat].Show();
seat = (EAST + rotation) % NUM_SEATS;
printf("%*s ", num_cards + 8, " ");
hands[seat].Show();
printf("\n");
seat = (SOUTH + rotation) % NUM_SEATS;
printf("%25s ", " ");
hands[seat].Show();
printf("\n");
}
void ShowDetailed(int rotation = 0) const {
int gap = 26;
int seat = (NORTH + rotation) % NUM_SEATS;
for (int suit = 0; suit < NUM_SUITS; ++suit) {
ShowHandInfo(hands[seat], seat, suit, gap);
hands[seat].ShowSuit(suit);
printf("\n");
}
for (int suit = 0; suit < NUM_SUITS; ++suit) {
gap = 13;
seat = (WEST + rotation) % NUM_SEATS;
ShowHandInfo(hands[seat], seat, suit, gap);
hands[seat].ShowSuit(suit);
gap = 26 - std::max(1, hands[seat].Suit(suit).Size());
seat = (EAST + rotation) % NUM_SEATS;
ShowHandInfo(hands[seat], seat, suit, gap);
hands[seat].ShowSuit(suit);
printf("\n");
}
gap = 26;
seat = (SOUTH + rotation) % NUM_SEATS;
for (int suit = 0; suit < NUM_SUITS; ++suit) {
ShowHandInfo(hands[seat], seat, suit, gap);
hands[seat].ShowSuit(suit);
printf("\n");
}
}
private:
void ShowHandInfo(Cards hand, int seat, int suit, int gap) const {
if (suit == SPADE)
printf("%*s%c ", gap - 2, " ", SeatLetter(seat));
else if (suit == CLUB)
printf("%*s%2d ", gap - 3, " ", hand.Points());
else
printf("%*s", gap, " ");
}
Cards hands[NUM_SEATS];
};
Hands empty_hands;
template <class Entry>
class Cache {
public:
// The hash is stored in Entry and can vary in size.
using HashT = decltype(Entry::hash);
Cache(const char* name, int bits)
: cache_name(name), bits(bits), size(1 << bits), entries(new Entry[size]) {
Reset();
}
void Reset() {
load_count = lookups = lookup_probes = hits = updates = update_probes = overwrites = 0;
for (int i = 0; i < size; ++i) entries[i].Reset(0);
}
void ShowStatistics() const {
printf("--- %s Statistics ---\n", cache_name);
printf("lookups: %8d probes: %8d (%.2f/lookup) hits: %8d (%5.2f%%)\n", lookups,
lookup_probes, lookup_probes * 1.0 / lookups, hits, hits * 100.0 / lookups);
printf("updates: %8d probes: %8d (%.2f/update) overwrites: %8d (%5.2f%%)\n", updates,
update_probes, update_probes * 1.0 / updates, overwrites, overwrites * 100.0 / updates);
printf("entries: %8d loaded: %8d (%5.2f%%)\n", size, load_count, load_count * 100.0 / size);
int recursive_load = 0;
for (int i = 0; i < size; ++i)
if (entries[i].hash != 0) {
recursive_load += entries[i].Size();
STATS(if (options.stats_level > 1) entries[i].Show());
}
if (recursive_load > load_count) printf("recursive load: %8d\n", recursive_load);
}
// Callers compute the hash once and pass it to both Lookup() and, on a miss,
// Update() so a single key is never hashed twice.
HashT Hash(uint64_t value) const {
// When HashT is narrower than 64 bits, keep the high-entropy top bits.
return HashT((value * 0x9b8b4567327b23c7ULL) >> (64 - BitSize(HashT(0))));
}
const Entry* Lookup(HashT hash) const {
STATS(++lookups);
uint64_t index = hash >> (BitSize(hash) - bits);
// Linear probing benefits from hardware prefetch.
for (int d = 0;; ++d) {
const Entry& entry = entries[(index + d) & (size - 1)];
if (entry.hash == hash) {
STATS(++hits);
return &entry;
}
if (entry.hash == 0) break;
STATS(++lookup_probes);
}
return nullptr;
}
Entry* Update(HashT hash) {
if (load_count >= size * 3 / 4) Resize();
STATS(++updates);
uint64_t index = hash >> (BitSize(hash) - bits);
for (int d = 0;; ++d) {
Entry& entry = entries[(index + d) & (size - 1)];
if (entry.hash == hash) {
STATS(++overwrites);
return &entry;
}
if (entry.hash == 0) {
++load_count;
entry.Reset(hash);
return &entry;
}
STATS(++update_probes);
}
}
private:
void Resize() {
auto old_entries = std::move(entries);
int old_size = size;
// Double cache size.
size = 1 << ++bits;
entries.reset(new Entry[size]);
CHECK(entries.get());
for (int i = 0; i < size; ++i) entries[i].hash = 0;
// Move entries in the old cache to the new cache.
load_count = 0;
for (int i = 0; i < old_size; ++i) {
auto hash = old_entries[i].hash;
if (hash == 0) continue;
uint64_t index = hash >> (BitSize(hash) - bits);
for (int d = 0;; ++d) {
Entry& entry = entries[(index + d) & (size - 1)];
if (entry.hash == 0) {
old_entries[i].MoveTo(entry);
++load_count;
break;
}
}
}
}
const char* cache_name;
int bits;
int size;
std::unique_ptr<Entry[]> entries;
mutable int load_count;
mutable int lookups, lookup_probes, hits;
mutable int updates, update_probes, overwrites;
};
#pragma pack(push, 4)
struct Bounds {
char lower;
char upper;
bool Empty() const { return upper < lower; }
Bounds Intersect(Bounds b) const { return {std::max(lower, b.lower), std::min(upper, b.upper)}; }
bool Include(Bounds b) const { return Intersect(b) == b; }
bool operator==(Bounds b) const { return b.lower == lower && b.upper == upper; }
bool operator!=(Bounds b) const { return !(*this == b); }
bool Cutoff(int beta) const { return lower >= beta || upper < beta; }
};
class Shape {
public:
Shape() : value(0) {}
Shape(uint64_t value) : value(value) {}
Shape(const Hands& hands) : value(0) {
for (int seat = 0; seat < NUM_SEATS; ++seat)
for (int suit = 0; suit < NUM_SUITS; ++suit)
value += uint64_t(hands[seat].Suit(suit).Size()) << Offset(seat, suit);
}
void PlayCards(int seat, int c1, int c2, int c3, int c4) {
value -= 1ULL << Offset(seat, SuitOf(c1));
value -= 1ULL << Offset((seat + 1) % NUM_SEATS, SuitOf(c2));
value -= 1ULL << Offset((seat + 2) % NUM_SEATS, SuitOf(c3));
value -= 1ULL << Offset((seat + 3) % NUM_SEATS, SuitOf(c4));
}
int SuitLength(int seat, int suit) const { return (value >> Offset(seat, suit)) & 0xf; }
uint64_t Value() const { return value; }
bool operator==(const Shape& s) const { return value == s.value; }
private:
static int Offset(int seat, int suit) { return 60 - (seat * NUM_SUITS + suit) * 4; }
uint64_t value;
};
// Free-list pool for Vector<T>'s backing storage: one LIFO list per
// power-of-two capacity, refilled in SLAB_SIZE slabs and never freed.
template <class T>
class VectorPool {
public:
static char* Allocate(int size_class) {
STATS(++alloc_calls[size_class]);
char*& head = free_lists[size_class];
if (!head) {
STATS(++miss_calls[size_class]);
Refill(size_class);
}
char* block = head;
head = *reinterpret_cast<char**>(block);
return block;
}
static void Deallocate(char* block, int size_class) {
char*& head = free_lists[size_class];
*reinterpret_cast<char**>(block) = head;
head = block;
}
static void ShowStatistics() {
printf("--- VectorPool<T> Statistics (block = %zu bytes) ---\n", sizeof(T));
uint64_t total_allocs = 0;
for (int i = 0; i < 16; ++i) total_allocs += alloc_calls[i];
for (int i = 0; i < 16; ++i) {
if (!alloc_calls[i]) continue;
printf("class %2d (cap %6zu): allocs %10" PRIu64 " (%5.2f%%) misses %8" PRIu64
" (%6.2f%% of allocs)\n",
i, size_t{1} << i, alloc_calls[i], alloc_calls[i] * 100.0 / total_allocs,
miss_calls[i], miss_calls[i] * 100.0 / alloc_calls[i]);
}
}
private:
static constexpr size_t SLAB_SIZE = 8192;
// One allocation for a full slab, amortizing the malloc call across all of them.
static void Refill(int size_class) {
size_t block_bytes = (1ULL << size_class) * sizeof(T);
size_t num_blocks = SLAB_SIZE / block_bytes;
if (num_blocks == 0) num_blocks = 1;
char* slab = new char[num_blocks * block_bytes];
char*& head = free_lists[size_class];
for (size_t i = 0; i < num_blocks; ++i) {
char* block = slab + i * block_bytes;
*reinterpret_cast<char**>(block) = head;
head = block;
}
}
static inline uint64_t alloc_calls[16] = {};
static inline uint64_t miss_calls[16] = {};
static inline char* free_lists[16] = {};
};
template <class T>
class Vector {
public:
~Vector() { clear(); }
void clear() {
for (size_t i = 0; i < count; ++i) (*this)[i].~T();
// Guard on capacity, not items: __builtin_ctz(0) is UB, and a null-items
// guard could get optimized away since items==nullptr iff capacity==0.
if (capacity) VectorPool<T>::Deallocate(items, __builtin_ctz(capacity));
count = capacity = 0;
items = nullptr;
}
void resize(size_t new_size) {
if (capacity < new_size) {
int size_class = new_size <= 1 ? 0 : 32 - __builtin_clz((unsigned)new_size - 1);
char* new_items = VectorPool<T>::Allocate(size_class);
memcpy(new_items, items, count * sizeof(T));
if (capacity) VectorPool<T>::Deallocate(items, __builtin_ctz(capacity));
items = new_items;
capacity = 1 << size_class;
}
memset(items + count * sizeof(T), 0, (new_size - count) * sizeof(T));
count = new_size;
}
size_t size() const { return count; }
T& operator[](size_t i) { return reinterpret_cast<T*>(items)[i]; }
const T& operator[](size_t i) const { return reinterpret_cast<T*>(items)[i]; }
T& back() { return (*this)[count - 1]; }
const T& back() const { return (*this)[count - 1]; }
void pop_back() {
back().~T();
--count;
}
void swap(Vector<T>& v) {
std::swap(count, v.count);
std::swap(capacity, v.capacity);
std::swap(items, v.items);
}
private:
uint16_t count = 0;
uint16_t capacity = 0;
char* items = nullptr;
};
struct Pattern {
Hands hands;
Bounds bounds;
uint16_t order;
Vector<Pattern> patterns;
#ifdef _DEBUG
mutable uint16_t hits, cuts;
#endif
Pattern(const Hands& hands = Hands(), Bounds bounds = Bounds())
: hands(hands), bounds(bounds), order(hands.all_cards().Size()) {
STATS(hits = cuts = 0);
}
// Takes over p, leaving it with no subpatterns. Any subpatterns this pattern
// owns are overwritten, not freed.
void MoveFrom(Pattern& p) {
memcpy((void*)this, (void*)&p, sizeof(Pattern));
new (&p.patterns) Vector<Pattern>();
}
void swap(Pattern& p) {
std::swap(hands, p.hands);
std::swap(bounds, p.bounds);
std::swap(order, p.order);
patterns.swap(p.patterns);
STATS(std::swap(hits, p.hits));
STATS(std::swap(cuts, p.cuts));
}
static const Pattern* Lookup(const Vector<Pattern>& patterns, const Hands& hands, int beta) {
const Pattern* best = nullptr;
Lookup(patterns, hands, beta, best);
return best;
}
static void Lookup(const Vector<Pattern>& patterns, const Hands& hands, int beta,
const Pattern*& best) {
for (size_t i = 0; i < patterns.size(); ++i) {
auto& pattern = patterns[i];
if (!hands.Include(pattern.hands)) continue;
STATS(++pattern.hits);
if (pattern.bounds.Cutoff(beta)) {
STATS(++pattern.cuts);
best = &pattern;
return;
}
Lookup(pattern.patterns, hands, beta, best);
if (best) return;
}
}
// Patterns are sorted by order, most generic first.
static void Update(Vector<Pattern>& patterns, Pattern& new_pattern) {
size_t n = patterns.size(), pos = 0;
// Local copies: the compiler can't prove new_pattern is disjoint from
// patterns, so it would reload these on every comparison.
const Hands new_hands = new_pattern.hands;
const uint16_t new_order = new_pattern.order;
const Bounds new_bounds = new_pattern.bounds;
// Go under the most generic pattern including the new one.
for (; pos < n && patterns[pos].order <= new_order; ++pos) {
auto& pattern = patterns[pos];
if (!new_hands.Include(pattern.hands)) continue;
if (new_hands.Equals(pattern.hands))
pattern.bounds = pattern.bounds.Intersect(new_bounds);
else
Update(pattern.patterns, new_pattern);
return;
}
// Adopt more specific patterns, dropping those with no tighter bounds but
// keeping their subpatterns. The rest are kept in patterns[pos, kept).
bool sorted = true;
size_t kept = pos;
for (size_t i = pos; i < n; ++i) {
auto& pattern = patterns[i];
if (!pattern.hands.Include(new_hands)) {
if (kept != i) patterns[kept].MoveFrom(pattern);
++kept;
} else if (pattern.bounds.Include(new_bounds)) {
sorted &= pattern.patterns.size() == 0;
Append(new_pattern.patterns, pattern.patterns);
pattern.patterns.clear();
} else {
Append(new_pattern.patterns, pattern);
}
}
if (!sorted) Sort(new_pattern.patterns);
// Shift the kept patterns one slot back and put the new pattern at pos.
// Slot kept owns nothing, so memmove is safe like the relocation in Vector::resize().
if (kept == n) patterns.resize(n + 1);
memmove((void*)&patterns[pos + 1], (void*)&patterns[pos], (kept - pos) * sizeof(Pattern));
patterns[pos].MoveFrom(new_pattern);
while (patterns.size() > kept + 1) patterns.pop_back();
}
static void Sort(Vector<Pattern>& patterns) {
for (size_t i = 1; i < patterns.size(); ++i)
for (size_t j = i; j > 0 && patterns[j - 1].order > patterns[j].order; --j)
patterns[j].swap(patterns[j - 1]);
}
static void Append(Vector<Pattern>& patterns, Pattern& new_pattern) {
patterns.resize(patterns.size() + 1);
patterns.back().MoveFrom(new_pattern);
}
static void Append(Vector<Pattern>& patterns, Vector<Pattern>& new_patterns) {
auto new_size = new_patterns.size();
if (new_size == 0) return;
auto size = patterns.size();
patterns.resize(size + new_size);
for (size_t i = 0; i < new_size; ++i) patterns[size + i].MoveFrom(new_patterns[i]);
}
Cards GetRankWinners(Cards all_cards) const {
Cards relative_rank_winners = hands.all_cards();
Cards rank_winners;
for (int suit = 0; suit < NUM_SUITS; ++suit) {
if (!relative_rank_winners.Suit(suit)) continue;
rank_winners.Add(UnpackSuitBits(relative_rank_winners, all_cards, suit));
}
return rank_winners;
}
int Size() const {
int sum = 1;
for (size_t i = 0; i < patterns.size(); ++i) sum += patterns[i].Size();
return sum;
}
void Show(Shape shape, int level = 1, Bounds parent_bounds = {0, TOTAL_TRICKS}) const {
if (level > 0) {
printf("%*d: (%d %d) ", level * 2, level, bounds.lower, bounds.upper);
for (int seat = 0; seat < NUM_SEATS; ++seat) {
for (int suit = 0; suit < NUM_SUITS; ++suit) {
auto suit_length = shape.SuitLength(seat, suit);
if (suit_length == 0)
putchar('-');
else {
auto rank_winners = hands[seat].Suit(suit);
for (int card : rank_winners) printf("%c", RankName(RankOf(card)));
for (int i = rank_winners.Size(); i < suit_length; ++i) putchar('x');
}
putchar(' ');
}
if (seat < NUM_SEATS - 1) printf(", ");
}
printf(" %2d", order);
STATS(printf(" hits %d cuts %d", hits, cuts));
puts(level > 1 && bounds.Include(parent_bounds) ? " dup" : "");
}
for (size_t i = 0; i < patterns.size(); ++i) patterns[i].Show(shape, level + 1, bounds);
}
};
struct ShapeEntry {
uint64_t hash;
Vector<Pattern> patterns[NUM_SEATS];
#ifdef _DEBUG
Shape shape;
void Show() const {
for (int s = 0; s < NUM_SEATS; ++s) {
if (patterns[s].size() == 0) continue;
printf("hash %016lx shape %016lx seat %c size %ld total size %d\n", hash, shape.Value(),
SeatLetter(s), patterns[s].size(), Size(s));
for (size_t i = 0; i < patterns[s].size(); ++i) patterns[s][i].Show(shape);
}
}
#endif
int Size(int s) const {
int total = 0;
for (size_t i = 0; i < patterns[s].size(); ++i) total += patterns[s][i].Size();
return total;
}
int Size() const {
int total = 0;
for (int s = 0; s < NUM_SEATS; ++s) total += Size(s);
return total;
}
void Reset(uint64_t hash_in) {
hash = hash_in;
for (int s = 0; s < NUM_SEATS; ++s) patterns[s].clear();
#ifdef _DEBUG
shape = Shape();
#endif
}
void MoveTo(ShapeEntry& to) {
to.hash = hash;
for (int s = 0; s < NUM_SEATS; ++s) to.patterns[s].swap(patterns[s]);
#ifdef _DEBUG
to.shape = shape;
#endif
}
};