-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdealer.cpp
1479 lines (1357 loc) · 45.1 KB
/
dealer.cpp
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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include "bittwiddle.h"
#include "pregen.h"
#include "dds.h"
#include <getopt.h>
#include "tree.h"
#include "pointcount.h"
#include "dealer.h"
#include "c4.h"
#include "pbn.h"
#include "genlib.h"
#include "shuffle.h"
#include "uniform_int.h"
#include "card.h"
#if __BMI2__
#include <x86intrin.h>
#endif
#include <algorithm>
#include <limits>
#if 1
#define debugf noop
#else
/**
* Trace eval_tree and value operations
*/
#define debugf printf
#endif
/**
* Do nothing function to replace printf if not wanting debug prints
*/
template<typename... Args>
void noop(Args... args) {}
namespace DEFUN() {
/**
* Implement dynamic value typing for scripts. It supports 32bit integers and
* an associative table mapping each opening lead card to tricks taken by
* declarer.
*
* Implementation enforces unique ownership to underlying data. This requirement
* helps memory management to avoid leeks from pointer to array which may have
* to be copied.
*
* @TODO: Convert to template type with evaltree using static typing
*/
struct value {
/**
* Construct an integer typed value
*/
value(int v = 0);
/**
* Construct an array typed value
*/
value(value_array *varr);
/**
* Create a copy from a variable
*/
value(treebase *tb);
/**
* Assignment takes ownership of underlying data
*/
value& operator=(value&& other);
/**
* Move constructor takes ownership of underlying data
*/
value(value&& other);
/**
* Destructor makes sure underlying data is freed if there is an owned
* pointer
*/
~value();
/**
* Helper to check if content is a pointer to array or an integer
*/
inline bool is_array() const;
/// Access the key information (card) from the array
inline int key(unsigned index) const;
/**
* Apply a function object to all underlying values. If underlying value is
* an integer then visit calls fn once with an integer value. If underlying
* value is an array then visit calls fn one to thirteen times with an
* integer value.
*
* @param fn Function object used to process stored value(s)
* @return Reference to this object
*/
template<typename fn_t>
inline const value& visit(fn_t fn) const;
/**
* Use a function object to modify all underlying values. It calls fn for
* each underlying value and returns the modified value object.
*
* @param fn Function object which modifies stored value(s)
* @return The modified value object after the transform operation
*/
template<typename fn_t>
inline value transform(fn_t fn);
/**
* Use a function object to modify two value objects. It calls fn with two
* arguments which match to value from this object and o object.
*
* If this or o object are different types then scalar value stays constant
* while array value changes for each call to fn
*
* @param o Other value object which provides values to the second argument
* @param fn Function object which modifies stored value(s)
* @return The modified value after the transform operation.
*/
template<typename fn_t>
inline value transform(value& o, fn_t fn);
/**
* Allow conversion to treebase pointer which is used to store script
* variable values.
*/
explicit inline operator treebase*();
/**
* Convert the underlying value to bool assuming all values must be true to
* evaluate the array as true.
*/
explicit inline operator bool() const;
/**
* Calculate an average integer value
*/
explicit inline operator int() const;
/**
* Calculate an average floating point value
*/
explicit inline operator double() const;
/** Arithmetic addition
* @return value object takes ownership of underlying array
*/
inline value operator+(value& o);
/** Arithmetic subtraction
* @return value object takes ownership of underlying array
*/
inline value operator-(value& o);
/** Arithmetic multiplication
* @return value object takes ownership of underlying array
*/
inline value operator*(value& o);
/** Arithmetic division
*
* Division operation checks for division by zero. It returns INT_MAX, INT_MIN
* or zero if denominator is zero. Return value depends on numerator.
*
* @return value object takes ownership of underlying array
*/
inline value operator/(value& o);
/** Arithmetic modulo
*
* Modulo operation checks for division by zero. It return zero if
* denominator is zero.
*
* @return value object takes ownership of underlying array
*/
inline value operator%(value& o);
/** Compare equality
* @return value object takes ownership of underlying array
*/
inline value operator==(value& o);
/** Compare inequality
* @return value object takes ownership of underlying array
*/
inline value operator!=(value& o);
/** Compare less than
* @return value object takes ownership of underlying array
*/
inline value operator<(value& o);
/** Compare less than or equal
* @return value object takes ownership of underlying array
*/
inline value operator<=(value& o);
/** Compare greater than
* @return value object takes ownership of underlying array
*/
inline value operator>(value& o);
/** Compare greater than or equal
* @return value object takes ownership of underlying array
*/
inline value operator>=(value& o);
/** Apply logical not
* @return value object takes ownership of underlying array
*/
inline value operator!();
private:
/**
* Integer values are shifted one up and lowest bit is set. This allows code
* later to check the lowest bit for type of value.
*/
union {
intptr_t value_;
value_array *varray_;
};
};
value::value(int v) :
value_{v << 1 | 1}
{
debugf("%s %d\n", __func__, v);
}
value::value(value_array *varr) :
varray_{varr}
{
debugf("%s %p\n", __func__, varr);
assert((value_ & 1) == 0);
}
value::~value()
{
debugf("%s %p\n", __func__, varray_);
if (is_array())
free(varray_);
}
bool value::is_array() const
{
return (value_ & 1) == 0;
}
template<typename fn_t>
const value& value::visit(fn_t fn) const
{
if (is_array()) {
size_t end = std::find(std::begin(varray_->key), std::end(varray_->key), 0)
- std::begin(varray_->key);
std::for_each(std::begin(varray_->value), std::begin(varray_->value) + end, fn);
} else
fn(value_ >> 1);
return *this;
}
template<typename fn_t>
value value::transform(fn_t fn)
{
debugf("%s %p\n", __func__, varray_);
if (is_array()) {
size_t end = std::find(std::begin(varray_->key), std::end(varray_->key), 0)
- std::begin(varray_->key);
std::transform(std::begin(varray_->value), std::begin(varray_->value) + end,
std::begin(varray_->value), fn);
} else {
value_ = fn(value_ >> 1) << 1 | 1;
}
return std::move(*this);
}
template<typename fn_t>
value value::transform(value &o, fn_t fn)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (o.is_array()) {
if (!is_array()) {
int temp = value_ >> 1;
varray_ = (value_array*)malloc(sizeof(*varray_));
std::uninitialized_fill(std::begin(varray_->value), std::end(varray_->value), temp);
std::uninitialized_copy(std::begin(o.varray_->key), std::end(o.varray_->key), std::begin(varray_->key));
}
size_t end1 = std::find(std::begin(varray_->key), std::end(varray_->key), 0)
- std::begin(varray_->key);
size_t end2 = std::find(std::begin(o.varray_->key), std::end(o.varray_->key), 0)
- std::begin(o.varray_->key);
std::transform(std::begin(varray_->value), std::begin(varray_->value) + std::min(end1, end2),
std::begin(o.varray_->value),
std::begin(varray_->value), fn);
} else if (is_array()) {
size_t end = std::find(std::begin(varray_->key), std::end(varray_->key), 0)
- std::begin(varray_->key);
std::transform(std::begin(varray_->value), std::begin(varray_->value) + end,
std::begin(varray_->value),
[&fn, &o](int value) {return fn(value, o.value_ >> 1);} );
} else {
value_ = fn(value_ >> 1, o.value_ >> 1) << 1 | 1;
}
return std::move(*this);
}
value::value(treebase *tb) :
value_{reinterpret_cast<intptr_t>(tb)}
{
if (is_array()) {
varray_ = (value_array*)malloc(sizeof(*varray_));
memcpy(varray_, tb, sizeof(*varray_));
}
debugf("%s %p -> %p\n", __func__, tb, varray_);
}
value& value::operator=(value&& other)
{
std::swap(value_, other.value_);
debugf("%s %p\n", __func__, varray_);
return *this;
}
value::value(value &&other) :
value_{0}
{
std::swap(value_, other.value_);
debugf("%s %p\n", __func__, varray_);
}
int value::key(unsigned index) const
{
assert(is_array());
debugf("%s %p\n", __func__, varray_);
return varray_->key[index];
}
value::operator treebase*()
{
debugf("%s %p\n", __func__, varray_);
treebase* rv = reinterpret_cast<treebase*>(value_);
// Make sure we don't free pointer in destructor;
value_ &= 1;
return rv;
}
value::operator bool() const
{
debugf("%s %p\n", __func__, varray_);
bool rv = true;
visit([&rv](int value) { rv = rv && value; });
return rv;
}
value::operator int() const
{
debugf("%s %p\n", __func__, varray_);
int rv = 0;
unsigned cnt = 0;
visit([&rv,&cnt](int value) { rv += value; ++cnt;});
return rv/cnt;
}
value::operator double() const
{
debugf("%s %p\n", __func__, varray_);
double rv = 0;
unsigned cnt = 0;
visit([&rv,&cnt](int value) { rv += value; ++cnt;});
return rv/cnt;
}
value value::operator+(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o + *this;
return transform(o, [](int a, int b) {return a + b;});
}
value value::operator-(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
return transform(o, [](int a, int b) {return a - b;});
}
value value::operator*(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o * *this;
return transform(o, [](int a, int b) {return a * b;});
}
value value::operator/(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
return transform(o, [](int a, int b) {
if (b==0)
return a > 0 ? std::numeric_limits<decltype(a)>::max() :
a < 0 ? std::numeric_limits<decltype(a)>::min() : 0;
return a / b;});
}
value value::operator%(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
return transform(o, [](int a, int b) {if (b == 0) return 0; return a % b;});
}
value value::operator==(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o == *this;
return transform(o, [](int a, int b) {return a == b;});
}
value value::operator!=(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o != *this;
return transform(o, [](int a, int b) {return a != b;});
}
value value::operator<(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o >= *this;
return transform(o, [](int a, int b) {return a < b;});
}
value value::operator<=(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o > *this;
return transform(o, [](int a, int b) {return a <= b;});
}
value value::operator>(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o <= *this;
return transform(o, [](int a, int b) {return a > b;});
}
value value::operator>=(value &o)
{
debugf("%s %p %p\n", __func__, varray_, o.varray_);
if (!is_array() && o.is_array())
return o < *this;
return transform(o, [](int a, int b) {return a >= b;});
}
value value::operator!()
{
debugf("%s %p\n", __func__, varray_);
return transform([](int a) {return !a;});
}
/* Global variables */
/**
* Cache expensive computation for scripts. (e.g. hcp)
*/
static struct handstat hs[4];
/* Function definitions */
static int true_dd (const union board *d, int l, int c); /* prototype */
static struct globals *gp;
/**
* Initialize evalcontatract action
*/
static void initevalcontract () {
int i, j, k;
for (i = 0; i < 2; i++)
for (j = 0; j < 5; j++)
for (k = 0; k < 14; k++)
gp->results[i][j][k] = 0;
}
/**
* Cache double dummy results. If no cached value for the hand then it call
* true_dd() to run the double dummy solver.
*
* @param d Board used for double dummy solving
* @param l Declarer's compass direction
* @param c Contract denomination to solve
* @return The number of tricks declarer can take
*/
static int dd (const union board *d, int l, int c) {
/* results-cached version of dd() */
/* the dd cache, and the gp->ngen it refers to */
static int cached_ngen = -1;
static char cached_tricks[4][5];
/* invalidate cache if it's another deal */
if (gp->ngen != cached_ngen) {
memset (cached_tricks, -1, sizeof (cached_tricks));
cached_ngen = gp->ngen;
}
if (cached_tricks[l][c] == -1) {
/* cache the costly computation's result */
cached_tricks[l][c] = true_dd (d, l, c);
}
/* return the cached value */
return cached_tricks[l][c];
}
/**
* Run double dummy solver for all cards in the opening lead hand.
*
* @param d Board used for double dummy solving
* @param l Declarer's compass direction
* @param c Contract denomination to solve
* @return Array of tricks each lead would allow declarer to take
*/
static struct value lead_dd (const union board *d, int l, int c) {
char res[13];
struct value_array *arr = (value_array *)mycalloc(1, sizeof(*arr));
unsigned idx, fill = 0;
memset(res, -1, sizeof(res));
card hand = gptr->predealt.hands[(l+1) % 4];
// Validate that script provides 13 cards for opening lead hand
if (hand_count_cards(hand) != 13) {
char errmsg[512];
snprintf(errmsg, sizeof(errmsg),
"Opening lead hand (%s) doesn't have 13 cards defined with predeal when calling leadtricks(%s, %s).\n"
"Compass parameter to leadtriks function is the declarer of hand like tricks function.\n",
player_name[(l+1) % 4], player_name[l], suit_name[c]);
error(errmsg);
}
// Run the double dummy solver
solveLead(d, l, c, hand, res);
// Convert results to associative array
for (idx = 0; idx < sizeof(res); idx++) {
// Results are set from the highest bit index to the lowest
card c = hand_extract_card(hand);
hand &= ~c;
// If there is -1 tricks it means the card doesn't have solution. It is
// caused by libdds solving only one of equal cards.
if (res[idx] == -1)
continue;
// Convert card to the bit position index
arr->key[fill] = C_BITPOS(c);
arr->value[fill] = res[idx];
fill++;
}
for (; fill < sizeof(res); fill++)
arr->value[fill] = -1;
return {arr};
}
/**
* Read double dummy results from library.dat
* @param pn The compass of declarer
* @param dn The contract denomination
* @return The number of tricks taken by declarer
*/
static int get_tricks (int pn, int dn) {
int tk = gp->libtricks[dn];
int resu;
resu = (pn ? (tk >> (4 * pn)) : tk) & 0x0F;
return resu;
}
/**
* Run double dummy solver or read result from library.dat provided data.
* @param d The board to analyze
* @param l The compass of declarer
* @param c The contract denomination
* @return The number of tricks declarer can take
*/
static int true_dd (const union board *d, int l, int c) {
if (gp->loading) {
int resu = get_tricks (l, c);
/* This will get the number of tricks EW can get. If the user wanted NS,
we have to subtract 13 from that number. */
return ((l == 0) || (l == 2)) ? 13 - resu : resu;
} else {
return solve(d, l, c);
}
}
/**
* Collect double dummy results for evalcontract action.
*/
static void evalcontract () {
int s;
for (s = 0; s < 5; s++) {
gp->results[1][s][dd (&gp->curboard, 2, s)]++; /* south declarer */
gp->results[0][s][dd (&gp->curboard, 0, s)]++; /* north declarer */
}
}
/**
* Check if shape function has the nr shape index bit set
* @param nr The index of hand shape to check
* @param s The shape function to check
* @return 1 if the shape bit is set
*/
static int checkshape (unsigned nr, struct shape *s)
{
unsigned idx = nr / 32;
unsigned bit = nr % 32;
int r = (s->bits[idx] & (1 << bit)) != 0;
return r;
}
/**
* Check if player has a card in their hand
*/
static card statichascard (const union board *d, int player, card onecard) {
return hand_has_card(d->hands[player], onecard);
}
/*
* Calculate and cache hcp for a player
*
* @param d Current board to analyze
* @param hsbase The base of handstat cache
* @param compass The player to calculate stats for
* @param suit The suit to calculate or 4 for complete hand
*/
static int hcp (const union board *d, struct handstat *hsbase, int compass, int suit)
{
assert (compass >= COMPASS_NORTH && compass <= COMPASS_WEST);
assert ((suit >= SUIT_CLUB && suit <= SUIT_SPADE) || suit == 4);
struct handstat *hs = &hsbase[compass];
/* Cache interleaves generation and actual value */
if (hs->hs_points[suit*2] != gp->ngen) {
/* No cached value so has to calculate it */
const hand h = suit == 4 ? d->hands[compass] :
d->hands[compass] & suit_masks[suit];
hs->hs_points[suit*2] = gp->ngen;
hs->hs_points[suit*2+1] = getpc(idxHcp, h);
}
return hs->hs_points[suit*2+1];
}
/**
* Calculate and cache control points for a player
*
* @param d The board to analyze
* @param hsbase The cache structure
* @param compass The player who's controls to calculate
* @param suit The suit to calculate controls, if 4 the all suits
* @return The total control points
*/
static int control (const union board *d, struct handstat *hsbase, int compass, int suit)
{
assert (compass >= COMPASS_NORTH && compass <= COMPASS_WEST);
assert ((suit >= SUIT_CLUB && suit <= SUIT_SPADE) || suit == 4);
struct handstat *hs = &hsbase[compass];
if (hs->hs_control[suit*2] != gp->ngen) {
/* No cached value so has to calculate it */
const hand h = suit == 4 ? d->hands[compass] :
d->hands[compass] & suit_masks[suit];
hs->hs_control[suit*2] = gp->ngen;
hs->hs_control[suit*2+1] = getpc(idxControls, h);
}
return hs->hs_control[suit*2+1];
}
/**
* Calculate suit length for a player.
*/
static inline int staticsuitlength (const union board* d,
int compass,
int suit)
{
assert (suit >= SUIT_CLUB && suit <= SUIT_SPADE);
assert(compass >= COMPASS_NORTH && compass <= COMPASS_WEST);
hand h = d->hands[compass] & suit_masks[suit];
return hand_count_cards(h);
}
int suitlength (const union board* d,
int compass,
int suit)
{
return staticsuitlength(d, compass, suit);
}
/**
* Calculate shape index for a player. Shape index is used to check shape
* functions in scripts.
*
* @param d The board to analyze
* @param hsbase The cache
* @param compass The player to analyze
* @return
*/
static int distrbit (const union board* d, struct handstat *hsbase, int compass)
{
assert(compass >= COMPASS_NORTH && compass <= COMPASS_WEST);
struct handstat *hs = &hsbase[compass];
if (hs->hs_bits[0] != gp->ngen) {
hs->hs_bits[0] = gp->ngen;
hs->hs_bits[1] = getshapenumber(staticsuitlength(d, compass, SUIT_CLUB),
staticsuitlength(d, compass, SUIT_DIAMOND),
staticsuitlength(d, compass, SUIT_HEART));
}
return hs->hs_bits[1];
}
/**
* Count losers
*
* @param d The board to analyze
* @param hsbase The cache
* @param compass The player to analyze
* @param suit The suit to analyze. If 4 then analyze all suits
*/
static int loser (const union board *d, struct handstat *hsbase, int compass, int suit)
{
assert (compass >= COMPASS_NORTH && compass <= COMPASS_WEST);
assert ((suit >= SUIT_CLUB && suit <= SUIT_SPADE) || suit == 4);
struct handstat *hs = &hsbase[compass];
if (hs->hs_loser[suit*2] != gp->ngen) {
/* No cached value so has to calculate it */
hs->hs_loser[suit*2] = gp->ngen;
if (suit == 4) {
hs->hs_loser[4*2+1] = 0;
for (suit = SUIT_CLUB; suit <= SUIT_SPADE; suit++)
hs->hs_loser[4*2+1] += loser(d, hsbase, compass, suit);
} else {
const int length = staticsuitlength(d, compass, suit);
const hand h = d->hands[compass] & suit_masks[suit];
int control = getpc(idxControlsInt, h);
int winner = getpc(idxWinnersInt, h);
switch (length) {
case 0:
/* A void is 0 losers */
hs->hs_loser[suit*2+1] = 0;
break;
case 1:
{
/* Singleton A 0 losers, K or Q 1 loser */
int losers[] = {1, 1, 0};
assert (control <= 2 && "Control count for a singleton should be at most 2");
hs->hs_loser[suit*2+1] = losers[control];
break;
}
case 2:
{
/* Doubleton AK 0 losers, Ax or Kx 1, Qx 2 */
int losers[] = {2, 1, 1, 0};
assert (control <= 3 && "Control count for a doubleton should be at most 3");
hs->hs_loser[suit*2+1] = losers[control];
break;
}
default:
/* Losers, first correct the number of losers */
hs->hs_loser[suit*2+1] = 3 - winner;
break;
}
}
}
return hs->hs_loser[suit*2+1];
}
/**
* Initialize point count and cache variables
*/
static void initprogram (void)
{
initpc();
/* clear the handstat cache */
memset(hs, -1, sizeof(hs));
}
/* Specific routines for EXHAUST_MODE */
/**
* Print statistics for a hand
*/
static inline void exh_print_stats (struct handstat *hs, int hs_length[4]) {
int s;
for (s = SUIT_CLUB; s <= SUIT_SPADE; s++) {
printf (" Suit %d: ", s);
printf ("Len = %2d, Points = %2d\n", hs_length[s], hs->hs_points[s*2+1]);
}
printf (" Totalpoints: %2d\n", hs->hs_points[s*2+1]);
}
/**
* Print cards shuffled in exhaust mode
*/
static inline void exh_print_cards (hand vector,
unsigned exh_vect_length,
card *exh_card_at_bit)
{
#if __BMI2__
(void)exh_vect_length;
hand hand = _pdep_u64(vector, exh_card_at_bit[0]);
while (hand) {
card c = hand_extract_card(hand);
printcard(c);
hand = hand_remove_card(hand, c);
}
#else
for (unsigned i = 0; i < exh_vect_length; i++) {
if (vector & (1u << i)) {
card onecard = exh_card_at_bit[i];
printcard(onecard);
}
}
#endif
}
/**
* Prints state of hands which are shuffled in exhaust mode
*/
static inline void exh_print_vector (struct handstat *hs,
unsigned exh_player[2],
unsigned exh_vectordeal,
unsigned exh_vect_length,
card *exh_card_at_bit)
{
int s;
int hs_length[4];
hand mask = (1u << exh_vect_length) - 1;
printf ("Player %d: ", exh_player[0]);
exh_print_cards(~exh_vectordeal & mask, exh_vect_length, exh_card_at_bit);
printf ("\n");
for (s = SUIT_CLUB; s < NSUITS; s++) {
hs_length[s] = staticsuitlength(&gp->curboard, exh_player[0], s);
hcp(&gp->curboard, hs, exh_player[0], s);
hcp(&gp->curboard, hs, exh_player[1], s);
}
exh_print_stats (hs + exh_player[0], hs_length);
printf ("Player %d: ", exh_player[1]);
exh_print_cards(exh_vectordeal, exh_vect_length, exh_card_at_bit);
printf ("\n");
for (s = SUIT_CLUB; s < NSUITS; s++)
hs_length[s] = staticsuitlength(&gp->curboard, exh_player[1], s);
exh_print_stats (hs + exh_player[1], hs_length);
}
/**
* Return score for a given number of tricks which can be an array of tricks
*
* @param vuln Vulnerability used for scoring
* @param suit The denomination of contract
* @param level The level of contract
* @param dbl Is contract doubled
* @param tricks Tricks taken in the contract
* @return Score for the result
*/
static struct value score (int vuln, int suit, int level, int dbl, struct value& tricks) {
return tricks.transform([&](int value) {
return scoreone(vuln, suit, level, dbl, value);
});
}
/**
* Evaluate a script
*
* @param b The script in AST format
* @param shuffle The shuffling state
* @return The results of tree evaluation
*/
static struct value evaltree (struct treebase *b, std::unique_ptr<shuffle> &shuffle) {
struct tree *t = (struct tree*)b;
debugf("%s %d\n", __func__, b->tr_type);
switch (b->tr_type) {
default:
assert (0);
case TRT_NUMBER:
return {t->tr_int1};
case TRT_VAR:
if (gp->ngen != t->tr_int1) {
value r = evaltree(t->tr_leaf1, shuffle);
t->tr_int1 = gp->ngen;
t->tr_leaf2 = static_cast<treebase*>(r);
}
return {t->tr_leaf2};
case TRT_AND2:
{
value r = evaltree(t->tr_leaf1, shuffle);
if (!static_cast<bool>(r))
return static_cast<bool>(r);
return static_cast<bool>(evaltree(t->tr_leaf2, shuffle));
}
case TRT_OR2:
{
value r = evaltree(t->tr_leaf1, shuffle);
if (r)
return static_cast<bool>(r);
return static_cast<bool>(evaltree(t->tr_leaf2, shuffle));
}
case TRT_ARPLUS:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) + rho;
}
case TRT_ARMINUS:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) - rho;
}
case TRT_ARTIMES:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) * rho;
}
case TRT_ARDIVIDE:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) / rho;
}
case TRT_ARMOD:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) % rho;
}
case TRT_CMPEQ:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) == rho;
}
case TRT_CMPNE:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) != rho;
}
case TRT_CMPLT:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) < rho;
}
case TRT_CMPLE:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) <= rho;
}
case TRT_CMPGT:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) > rho;
}
case TRT_CMPGE:
{
value rho = evaltree(t->tr_leaf2, shuffle);
return evaltree(t->tr_leaf1, shuffle) >= rho;
}
case TRT_NOT:
return !evaltree(t->tr_leaf1, shuffle);
case TRT_LENGTH: /* suit, compass */
assert (t->tr_int1 >= SUIT_CLUB && t->tr_int1 <= SUIT_SPADE);
assert (t->tr_int2 >= COMPASS_NORTH && t->tr_int2 <= COMPASS_WEST);
return {staticsuitlength(&gp->curboard, t->tr_int2, t->tr_int1)};
case TRT_HCPTOTAL: /* compass */
assert (t->tr_int1 >= COMPASS_NORTH && t->tr_int1 <= COMPASS_WEST);
return {hcp(&gp->curboard, hs, t->tr_int1, 4)};
case TRT_PT0TOTAL: /* compass */
case TRT_PT1TOTAL: /* compass */
case TRT_PT2TOTAL: /* compass */
case TRT_PT3TOTAL: /* compass */
case TRT_PT4TOTAL: /* compass */
case TRT_PT5TOTAL: /* compass */
case TRT_PT6TOTAL: /* compass */
case TRT_PT7TOTAL: /* compass */
case TRT_PT8TOTAL: /* compass */
case TRT_PT9TOTAL: /* compass */
assert (t->tr_int1 >= COMPASS_NORTH && t->tr_int1 <= COMPASS_WEST);
return {getpc(idxTens + (b->tr_type - TRT_PT0TOTAL) / 2, gp->curboard.hands[t->tr_int1])};
case TRT_HCP: /* compass, suit */
assert (t->tr_int1 >= COMPASS_NORTH && t->tr_int1 <= COMPASS_WEST);
assert (t->tr_int2 >= SUIT_CLUB && t->tr_int2 <= SUIT_SPADE);
return {hcp(&gp->curboard, hs, t->tr_int1, t->tr_int2)};
case TRT_PT0: /* compass, suit */
case TRT_PT1: /* compass, suit */
case TRT_PT2: /* compass, suit */
case TRT_PT3: /* compass, suit */
case TRT_PT4: /* compass, suit */
case TRT_PT5: /* compass, suit */