-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsolver.cc
More file actions
2312 lines (2077 loc) · 78.2 KB
/
solver.cc
File metadata and controls
2312 lines (2077 loc) · 78.2 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>
#ifdef __BMI2__
#include <immintrin.h>
#endif
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include <algorithm>
#include <functional>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <vector>
// 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
enum { SPADE, HEART, DIAMOND, CLUB, NUM_SUITS, NOTRUMP = NUM_SUITS };
enum { TWO, TEN = 8, JACK, QUEEN, KING, ACE, NUM_RANKS };
enum { WEST, NORTH, EAST, SOUTH, NUM_SEATS };
const int TOTAL_TRICKS = NUM_RANKS;
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
}
const 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);
}
char suit_of[TOTAL_CARDS];
char rank_of[TOTAL_CARDS];
char card_of[NUM_SUITS][16];
char name_of[TOTAL_CARDS][4];
int SuitOf(int card) { return 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 * NUM_RANKS); }
const char* NameOf(int card) { return name_of[card]; }
bool LowerRank(int card1, int card2) { return card1 > card2; }
bool HigherRank(int card1, int card2) { return card1 < card2; }
struct CardInitializer {
CardInitializer() {
for (int card = 0; card < TOTAL_CARDS; ++card) {
suit_of[card] = card / NUM_RANKS;
rank_of[card] = NUM_RANKS - 1 - card % NUM_RANKS;
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;
struct Options {
char* code = nullptr;
char* input_file = nullptr;
char* shuffle_seats = nullptr;
int trump = -1;
int guess_tricks = -1;
int displaying_depth = -1;
int stats_level = 0;
int show_hands_mask = 2;
bool deal_only = false;
bool discard_suit_bottom = false;
bool randomize = false;
bool ignore_trump_and_lead = false;
bool play_interactively = false;
void Read(int argc, char* argv[]) {
int c;
while ((c = getopt(argc, argv, "c:df:im:oprs:t:D:G:S:")) != -1) {
switch (c) {
// clang-format off
case 'c': code = optarg; break;
case 'd': discard_suit_bottom = true; break;
case 'f': input_file = optarg; break;
case 'i': ignore_trump_and_lead = true; break;
case 'm': show_hands_mask = atoi(optarg); break;
case 'o': deal_only = true; break;
case 'p': play_interactively = true; break;
case 'r': randomize = true; break;
case 's': shuffle_seats = optarg; break;
case 't': trump = CharToSuit(optarg[0]); break;
case 'D': displaying_depth = atoi(optarg); break;
case 'G': guess_tricks = atoi(optarg); break;
case 'S': stats_level = atoi(optarg); break;
// clang-format on
}
}
}
void ShowUsage(char* name) {
printf("%s A fast double-dummy solver for the card game of Bridge.\n", name);
printf("\t-r Solve a random deal.\n"
"\t-f <file> Solve a deal in the input file. See files in *_deals/ for examples.\n"
"\t-c <code> Solve a deal defined by its unique code. See -m below.\n"
"\t-p Play interactively, possibly exploring all paths.\n"
"\n"
"\t-s <seats> Shuffle hands in the specified seats, a combination of {W, N, E, S}.\n"
"\t-m <mask> Mask for showing a deal. The following values can be added.\n"
"\t 1 Show the deal's unique code\n"
"\t 2 Show the deal in compact format\n"
"\t 4 Show the deal in expanded format\n"
"\t-o Show the deal without solving it.\n"
"\t-i Ignore the trump and the lead specified in the input file.\n"
"\t-t <trump> Solve for the specified trump, one of {N, S, H, D, C}.\n"
"\t-d Discard only the smallest card in a suit, imprecise but faster.\n");
exit(0);
}
} options;
double Now() {
timeval now;
gettimeofday(&now, nullptr);
return now.tv_sec + now.tv_usec * 1e-6;
}
template <class T>
int BitSize(T v) {
return sizeof(v) * 8;
}
uint64_t PackBits(uint64_t source, uint64_t mask) {
#ifdef __BMI2__
return _pext_u64(source, mask);
#else
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;
#endif
}
uint64_t UnpackBits(uint64_t source, uint64_t mask) {
#ifdef __BMI2__
return _pdep_u64(source, mask);
#else
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;
#endif
}
class Cards {
public:
Cards() : bits(0) {}
Cards(uint64_t b) : bits(b) {}
uint64_t Value() const { return bits; }
int Size() const { return __builtin_popcountll(bits); }
bool Have(int card) const { return bits & Bit(card); }
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 ((1ULL << TOTAL_CARDS) - 1) ^ bits; }
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); }
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;
};
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, std::vector<int> seats) {
std::mt19937 random(static_cast<uint64_t>(Now() * 1000));
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(char* code) {
uint64_t values[3];
int num_values = sscanf(code, "%lX,%lX,%lX", values, values + 1, values + 2);
assert(num_values == 3);
auto mask = (1ULL << TOTAL_CARDS) - 1;
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]);
}
Cards partnership_cards(int seat) const {
return hands[seat].Union(hands[(seat + 2) % NUM_SEATS]);
}
Cards opponent_cards(int seat) const {
return hands[(seat + 1) % NUM_SEATS].Union(hands[(seat + 3) % NUM_SEATS]);
}
const Cards& operator[](int seat) const { return hands[seat]; }
Cards& operator[](int seat) { return hands[seat]; }
int num_tricks() const { return hands[WEST].Size(); }
void Show() const {
for (int seat = 0; seat < NUM_SEATS; ++seat) {
hands[seat].Show();
if (seat < NUM_SEATS - 1) printf(", ");
}
puts("");
}
void ShowCode() const {
uint64_t values[3];
auto mask = (1ULL << TOTAL_CARDS) - 1;
for (int seat = 0; seat < NUM_SEATS - 1; ++seat) {
values[seat] = PackBits(hands[seat].Value(), mask);
mask &= ~hands[seat].Value();
}
printf("# %lX,%lX,%lX\n", values[0], values[1], values[2]);
}
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, int input_size>
class Cache {
public:
Cache(const char* name, int bits)
: cache_name(name), bits(bits), size(1 << bits), entries(new Entry[size]) {
Reset();
}
void Reset() {
probe_distance = 0;
load_count = lookups = lookup_probes = hits = updates = update_probes = 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)\n",
updates, update_probes, update_probes * 1.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);
}
const Entry* Lookup(Cards cards[input_size]) const {
STATS(++lookups);
uint64_t hash = Hash(cards);
uint64_t index = hash >> (BitSize(hash) - bits);
for (int d = 0; d < probe_distance; ++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(Cards cards[input_size]) {
if (load_count >= size * 3 / 4) Resize();
STATS(++updates);
uint64_t hash = Hash(cards);
uint64_t index = hash >> (BitSize(hash) - bits);
// Linear probing benefits from hardware prefetch.
for (int d = 0; ; ++d) {
Entry& entry = entries[(index + d) & (size - 1)];
if (entry.hash == hash) return &entry;
if (entry.hash == 0) {
probe_distance = std::max(probe_distance, d + 1);
++load_count;
entry.Reset(hash);
return &entry;
}
STATS(++update_probes);
}
}
private:
uint64_t Hash(Cards cards[input_size]) const {
static constexpr uint64_t hash_rand[2] = {0x9b8b4567327b23c7ULL, 0x643c986966334873ULL};
uint64_t sum = 0;
for (int i = 0; i < (input_size + 1) / 2; ++i)
sum += (cards[i * 2].Value() + hash_rand[i * 2]) *
(cards[i * 2 + 1].Value() + hash_rand[i * 2 + 1]);
return sum;
}
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;
probe_distance = 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) {
probe_distance = std::max(probe_distance, d + 1);
old_entries[i].MoveTo(entry);
++load_count;
break;
}
}
}
}
const char* cache_name;
int bits;
int size;
int probe_distance;
std::unique_ptr<Entry[]> entries;
mutable int load_count;
mutable int lookups, lookup_probes, hits;
mutable int updates, update_probes;
};
#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;
};
template <class T>
class Vector {
public:
~Vector() { clear(); }
void clear() {
for (size_t i = 0; i < count; ++i) (*this)[i].~T();
count = capacity = 0;
delete[] items;
items = nullptr;
}
void resize(size_t new_size) {
if (capacity < new_size) {
capacity = std::max(capacity * 2, (int)new_size);
auto old_items = items;
items = new char[capacity * sizeof(T)];
memcpy(items, old_items, count * sizeof(T));
delete[] old_items;
}
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 padding;
Vector<Pattern> patterns;
Pattern(const Hands& hands = Hands(), Bounds bounds = Bounds())
: hands(hands), bounds(bounds) {}
void Reset() {
hands = Hands();
bounds = {0, TOTAL_TRICKS};
patterns.clear();
}
void MoveFrom(Pattern& p) {
hands = p.hands;
bounds = p.bounds;
patterns.swap(p.patterns);
}
const Pattern* Lookup(const Pattern& new_pattern, int beta) const {
for (size_t i = 0; i < patterns.size(); ++i) {
auto& pattern = patterns[i];
if (!(new_pattern <= pattern)) continue;
if (pattern.bounds.Cutoff(beta)) return &pattern;
if (auto detail = pattern.Lookup(new_pattern, beta)) return detail;
}
return nullptr;
}
void Update(Pattern& new_pattern) {
for (size_t i = 0; i < patterns.size(); ++i) {
auto& pattern = patterns[i];
if (new_pattern == pattern) {
pattern.UpdateBounds(new_pattern.bounds);
return;
} else if (new_pattern <= pattern) {
// Old pattern is more generic. Add new pattern under.
new_pattern.bounds = new_pattern.bounds.Intersect(pattern.bounds);
CHECK(!new_pattern.bounds.Empty());
if (new_pattern.bounds != pattern.bounds) pattern.Update(new_pattern);
return;
} else if (pattern <= new_pattern) {
// New pattern is more generic. Absorb sub-patterns.
pattern.UpdateBounds(new_pattern.bounds);
if (pattern.bounds != new_pattern.bounds) new_pattern.Append(pattern);
else new_pattern.patterns.swap(pattern.patterns);
for (++i; i < patterns.size(); ++i) {
auto& old_pattern = patterns[i];
if (!(old_pattern <= new_pattern)) continue;
old_pattern.UpdateBounds(new_pattern.bounds);
if (old_pattern.bounds != new_pattern.bounds) new_pattern.Append(old_pattern);
else if (!new_pattern.patterns.size()) new_pattern.patterns.swap(old_pattern.patterns);
else new_pattern.Append(old_pattern.patterns);
Delete(i);
--i;
}
pattern.MoveFrom(new_pattern);
return;
}
}
Append(new_pattern);
}
void UpdateBounds(Bounds new_bounds) {
auto old_bounds = bounds;
bounds = bounds.Intersect(new_bounds);
CHECK(!bounds.Empty());
if (bounds == old_bounds) return;
for (size_t i = 0; i < patterns.size(); ++i) {
patterns[i].UpdateBounds(bounds);
if (patterns[i].bounds != bounds) continue;
// Get the subpatterns out as resizing patterns in Append renders
// patterns[i].patterns invalid.
Vector<Pattern> subpatterns;
subpatterns.swap(patterns[i].patterns);
Append(subpatterns);
Delete(i);
--i;
}
}
void Append(Pattern& new_pattern) {
patterns.resize(patterns.size() + 1);
patterns.back().MoveFrom(new_pattern);
}
void Append(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]);
}
void Delete(size_t i) {
patterns[i].MoveFrom(patterns.back());
patterns.pop_back();
}
// This pattern is more detailed than (a subset of) the other pattern.
bool operator<=(const Pattern& p) const {
return hands[WEST].Include(p.hands[WEST]) & hands[NORTH].Include(p.hands[NORTH]) &
hands[EAST].Include(p.hands[EAST]) & hands[SOUTH].Include(p.hands[SOUTH]);
}
bool operator==(const Pattern& p) const {
return (p.hands[WEST] == hands[WEST]) & (p.hands[NORTH] == hands[NORTH]) &
(p.hands[EAST] == hands[EAST]) & (p.hands[SOUTH] == hands[SOUTH]);
}
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;
auto packed = relative_rank_winners.Suit(suit).Value() >> (suit * NUM_RANKS);
rank_winners.Add(Cards(UnpackBits(packed, all_cards.Suit(suit).Value())));
}
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(", ");
}
puts(level > 1 && bounds == parent_bounds ? " dup" : "");
}
for (size_t i = 0; i < patterns.size(); ++i) patterns[i].Show(shape, level + 1, bounds);
}
};
struct ShapeEntry {
uint64_t hash;
Pattern pattern;
#ifdef _DEBUG
Shape shape;
short seat_to_play;
mutable uint16_t hits, cuts;
void Show() const {
printf("hash %016lx shape %016lx seat %c size %ld total size %d hits %d cuts %d\n",
hash, shape.Value(), SeatLetter(seat_to_play), pattern.patterns.size(), Size(),
hits, cuts);
pattern.Show(shape, 0);
}
#endif
int Size() const { return pattern.Size() - 1; }
void Reset(uint64_t hash_in) {
hash = hash_in;
pattern.Reset();
#ifdef _DEBUG
shape = Shape();
seat_to_play = -1;
hits = cuts = 0;
#endif
}
void MoveTo(ShapeEntry& to) {
to.hash = hash;
to.pattern.MoveFrom(pattern);
#ifdef _DEBUG
to.shape = shape;
to.seat_to_play = seat_to_play;
to.hits = hits;
to.cuts = cuts;
#endif
}
std::pair<const Hands*, Bounds> Lookup(const Pattern& new_pattern, int beta) const {
STATS(++hits);
if (pattern.bounds.Cutoff(beta) && new_pattern <= pattern) {
STATS(++cuts);
CHECK(pattern.Lookup(new_pattern, beta));
return {&pattern.hands, pattern.bounds};
}
auto cached_pattern = pattern.Lookup(new_pattern, beta);
if (cached_pattern) {
STATS(++cuts);
const_cast<Pattern*>(&pattern)->hands = cached_pattern->hands;
const_cast<Pattern*>(&pattern)->bounds = cached_pattern->bounds;
return {&cached_pattern->hands, cached_pattern->bounds};
}
return {nullptr, Bounds{}};
}
};
struct CutoffEntry {
uint64_t hash;
// Cut-off card depending on the seat to play.
char card[NUM_SEATS];
int Size() const { return 1; }
void Show() const {}
void Reset(uint64_t hash_in) {
hash = hash_in;
memset(card, TOTAL_CARDS, sizeof(card));
}
void MoveTo(CutoffEntry& to) { memcpy(&to, this, sizeof(*this)); }
};
#pragma pack(pop)
Cache<ShapeEntry, 2> common_bounds_cache("Common Bounds Cache", 15);
Cache<CutoffEntry, 2> cutoff_cache("Cut-off Cache", 16);
struct Trick {
Shape shape;
Cards all_cards;
Hands relative_hands;
int lead_suit;
// A relative hand contains relative cards.
void ComputeRelativeHands(int depth, const Hands& hands) {
if (depth < 4) {
for (int suit = 0; suit < NUM_SUITS; ++suit)
ConvertToRelativeSuit(hands, suit, all_cards.Suit(suit));
} else {
// Recompute the relative cards for suits changed by the last trick.
auto prev_trick = this - 1;
auto prev_trick_cards = prev_trick->all_cards.Different(all_cards);
relative_hands = prev_trick->relative_hands;
while (prev_trick_cards) {
auto suit = SuitOf(prev_trick_cards.Top());
prev_trick_cards.ClearSuit(suit);
ConvertToRelativeSuit(hands, suit, all_cards.Suit(suit));
}
}
}
// Whether a card is equivalent to one of the tried cards.
bool IsEquivalent(int card, Cards tried_suit_cards, Cards hand) const {
if (!tried_suit_cards) return false;
if (auto above = tried_suit_cards.Slice(0, card))
if (all_cards.Slice(above.Bottom(), card) == hand.Slice(above.Bottom(), card))
return true;
if (auto below = tried_suit_cards.Slice(card + 1, TOTAL_CARDS))
if (all_cards.Slice(card, below.Top()) == hand.Slice(card, below.Top()))
return true;
return false;
}
Cards FilterEquivalent(Cards playable_cards) const {
Cards filtered_cards;
for (int suit = 0; suit < NUM_SUITS; ++suit) {
auto suit_cards = playable_cards.Suit(suit);
if (!suit_cards) continue;
int prev_card = suit_cards.Top();
filtered_cards.Add(prev_card);
suit_cards.Remove(prev_card);
for (int card : suit_cards) {
if (RelativeRank(prev_card, suit) != RelativeRank(card, suit) + 1)
filtered_cards.Add(card);
prev_card = card;
}
}
return filtered_cards;
}
// A pattern hand contains relative cards and rank-irrelevant cards.
std::pair<Hands, Cards> ComputePatternHands(Cards rank_winners) const {
Cards relative_rank_winners, extended_rank_winners;
for (int suit = 0; suit < NUM_SUITS; ++suit) {
if (!rank_winners.Suit(suit)) continue;
int bottom_rank_winner = RelativeCard(rank_winners.Suit(suit).Bottom(), suit);
for (int seat = 0; seat < NUM_SEATS; ++seat) {
if (!relative_hands[seat].Have(bottom_rank_winner)) continue;
auto suit_cards = relative_hands[seat].Suit(suit);
// Extend bottom rank winner to its lowest equivalent card.
bottom_rank_winner += __builtin_ctzll(~(suit_cards.Value() >> (bottom_rank_winner + 1)));
// Suit bottom can't win by rank. Compensate the inaccuracy of fast tricks.
if (bottom_rank_winner == relative_hands.all_cards().Suit(suit).Bottom())
// Extend bottom rank winner to its highest equivalent card and go one rank higher.
bottom_rank_winner -= __builtin_clzll(~(suit_cards.Value() << (63 - bottom_rank_winner)));
break;
}
relative_rank_winners.Add(Cards(MaskOf(suit)).Slice(0, bottom_rank_winner + 1));
auto packed = relative_rank_winners.Suit(suit).Value() >> (suit * NUM_RANKS);
extended_rank_winners.Add(Cards(UnpackBits(packed, all_cards.Suit(suit).Value())));
}
Hands pattern_hands;
for (int seat = 0; seat < NUM_SEATS; ++seat)
pattern_hands[seat] = relative_hands[seat].Intersect(relative_rank_winners);
return {pattern_hands, extended_rank_winners};
}
private:
void ConvertToRelativeSuit(const Hands& hands, int suit, Cards all_suit_cards) {
for (int seat = 0; seat < NUM_SEATS; ++seat) {
auto packed = PackBits(hands[seat].Suit(suit).Value(), all_suit_cards.Value());
relative_hands[seat].ClearSuit(suit);
relative_hands[seat].Add(Cards(packed << (suit * NUM_RANKS)));
}
}
int RelativeRank(int card, int suit) const {
return ACE - all_cards.Suit(suit).Slice(0, card).Size();
}
int RelativeCard(int card, int suit) const {
return CardOf(suit, RelativeRank(card, suit));
}
};
struct Stat {
int num_visits = 0;
int num_branches = 0;
void Show(int depth) {
if (num_visits)
printf("%2d: %7d * %.2f\n", depth, num_visits, double(num_branches) / num_visits);
}
} stats[TOTAL_CARDS];
class Play {
public:
Play() {}
Play(Play* plays, Trick* trick, Hands& hands, int trump, int depth, int seat_to_play)
: plays(plays),
trick(trick),
hands(hands),
trump(trump),
depth(depth),
seat_to_play(seat_to_play) {}