-
Notifications
You must be signed in to change notification settings - Fork 0
/
deeper.c
4676 lines (4382 loc) · 112 KB
/
deeper.c
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
/*
* deep scrabble solitaire searcher.
* principles:
* - gaddag for dictionary data, mmapped read-only (align, largepage)
- fast movegen RE Steven A. Gordon + Appel et al.
- keep board state instead of recomputing stuff
- fast C coded bit ops with macros and inline functions
- use packed structs instead of objects, low mem, fast access, cache
- multi-threading, per thread cached data, low contention
- lots and lots of stats
- high optimization level
- checkpoint/restart, save/restore state to disk
- CLI instead of GUI, no display overhead.
- exhaustive search if possible, heuristics if needed.
*/
#include <stdio.h>
#include <string.h> // strdup
#include <stdlib.h> // rand, malloc, and much much more
#include <sys/mman.h> // mmap
#include <sys/stat.h> // fstat
#include <fcntl.h> // open, etc
#include <strings.h> // str*
#include <unistd.h> // getopt, seek
#include <ctype.h> // isupper, etc
#include <limits.h> // LONG_MAX
#include <errno.h> // errno
#if defined(__sun)
#include <sys/types.h>
#include <sys/time.h>
#else /* sun */
#include <inttypes.h>
#include <linux/types.h>
#include <time.h>
#include <stdint.h>
#endif /* sun */
#include "deeper.h"
/* inline optimized code. Use -O4 or so to get really good perf */
#ifdef _popc
inline int
popc(uint32_t w)
{
int c;
_popc(w,c);
return c;
}
#endif
/* ffb = find first bit. ffs is taken. */
#ifdef _ffs
inline int
ffb(uint32_t w)
{
int c;
_ffs(w,c);
return c;
}
#endif
void printmove(move_t *m, int rev);
/* Globals. */
/* dictionary */
gn_t *gaddag = NULL; // dictionary data (mmapped buffer) RDONLY
bs_t *bitset = NULL; // bitset data (mmapped) RDONLY
int dfd = -1; // dictionary file desc
int bsfd = -1; // bitset filed desc
char *dfn = NULL; // dictionary file name
unsigned long g_cnt = 0; // how big is gaddag (in entries)
/* bag */
bag_t globalbag = NULL; // we only do 1 bag at a time
bagstr_t bagstr = NULL; // printable/readable bag contents
char bagtag = '_'; // A-Z character naming bag/problem set
char *bagname = NULL; // name bag as string
int baglen = 100; // strlen(bagstr)
/* rack */
char *rackstr = NULL;
/* starting stuff */
static const rack_t emptyrack = { {0,0,0,0,0,0,0,0 } }; // all nulls
static const move_t emptymove = { 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
board_t emptyboard; // no tiles played
board_t startboard; // legal start moves marked
gstats_t nullstats = { 0,0,0,0,0,0,0}; // all 0s
position_t startp;
static const scthingy_t newsct = { 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 };
/* diag, debug and stats */
int verbose = 0; // level of info output
unsigned long dflags = 0; // for DBG statements
int stats = 0; // report stats while running
char *gcgfn = NULL; // save result here
gstats_t globalstats; // global statistics
unsigned long gmcnt = 0; // global mv counter.
/* other options */
int doscore = 0; // report scores as well
int dotimes = 0; // set if we should time ourselves.
int level = 0; // degree of strategy strength
char *infile = 0; // move input file.
int strat = 0; // move choosing strategy.
int dostats = 0; // how much stat info to report.
/* job/process control */
int dtrap = 0; // debugger trap counter
int globaldone = 0; // set to stop all threads.
void
usage(char *me)
{
vprintf(VNORM, "%s [-LASMG] [-P] [-I file] [move...]\n", me);
vprintf(VVERB,
"\t-L: lookup moves in dictionary\n"
"\t-A: print all anagrams of moves\n"
"\t-S: score moves as if played on board\n"
"\t-M: make each move on board, show results\n"
"\t-G: generate list of possible moves using move\n"
"\t-P: set playthru mode for moves\n"
"\t-I file: read moves from input file\n");
vprintf(VNORM, "%s -T n [-n lvl] [-b bag] [-B str]\n", me);
vprintf(VVERB,
"\t-T n: use strategy number n to play game\n"
"\t-n lvl: for progressive strats, use level lvl\n"
"\t-b [?]A-Z|name: Set bag name. A-Z are built-in, ?=randomize.\n"
"\t-B str: set bag to string of tiles (A-Z or ? for blank.\n");
vprintf(VNORM, " [-D bits|word] [-vqts] [-d dict]\n");
vprintf(VVERB,
"\t-D bits|word turn on specified debug flags\n"
"\t-v: increase verbosity level, cumulative\n"
"\t-q: no messages, only return values. Cancels -v.\n"
"\t-t: time and report operations\n"
"\t-s: collect and report statistics. Use twice for more.\n"
"\t-d name: use name.gaddag as dictionary. [default=ENABLE]\n");
vprintf(VNORM, " [-o file] [-R str]\n");
vprintf(VVERB,
"\t-o name: save best move to name.gcg\n"
"\t-R str: set rack to string of tiles (A-Z or ? for blank.)\n");
vprintf(VVERB,
"\t move = rc:word or cr:word, r=1-15, c=A-O, word is 1-15 letters.\n"
"\t If rc is omitted, uses starting position of 8H.\n"
"\t Put row (number) first for horizontal moves. Use lowercase\n"
"\t letter for blank played, '?' for unplayed blank.\n");
}
/* TODO: test which one is faster. */
inline bs_t
lstr2bs(letter_t *lstr)
{
int i = 0;
bs_t bs = 0;
#ifdef NOTDEF
while (lstr[i] != '\0') {
setbit(&bs, lstr[i]-1);
i++;
}
#else
for (i=0; lstr[i] != '\0'; i++) {
setbit(&bs, lstr[i]-1);
}
#endif
return bs;
}
/*
* convert character string cstr to a letter string lstr. detects invalid
* characters. Returns number of invalid characters, but does conversion
* even if there are some.
* played determines which chars are valid:
* UNPLAYED: A-Z,?,^ (and null char)
* PLAYED: A-Z,a-z (and null)
* JUSTPLAY: valid for either PLAYED or UNPLAYED
*/
inline int
c2lstr(char *cstr, char *lstr, int played)
{
int inv = 0;
int i = 0;
if (lstr == NULL) return -1;
if (cstr == NULL) return 0;
while (cstr[i] != '\0') {
lstr[i] = c2l(cstr[i]);
if (played == UNPLAYED) {
if (!is_rvalid(lstr[i])) inv++;
} else if (played == PLAYED) {
if (!is_bvalid(lstr[i])) inv++;
} else if (played == JUSTPLAY) {
if ((!is_bvalid(lstr[i])) && (!is_rvalid(lstr[i])))
inv++;
}
i++;
}
lstr[i] = '\0';
if (played != JUSTPLAY) {
return inv;
} else {
return 0;
}
}
/* force chars to upper case. must be UNPLAYED */
inline int
casec2lstr(char *cstr, char *lstr)
{
int inv = 0;
int i = 0;
if (lstr == NULL) return -1;
if (cstr == NULL) return 0;
while (cstr[i] != '\0') {
lstr[i] = c2l(toupper(cstr[i]));
if (!is_rvalid(lstr[i])) inv++;
i++;
}
return inv;
}
inline void
deblankstr(letter_t *lstr)
{
int i = 0;
while (lstr[i] != '\0') {
lstr[i] = deblank(lstr[i]);
i++;
}
}
inline int
casel2cstr(const char *lstr, char *cstr)
{
int inv = 0;
int i = 0;
if (cstr == NULL) return -1;
if (lstr == NULL) return 0;
while (lstr[i] != '\0') {
cstr[i] = toupper(l2c(lstr[i]));
if (!is_bvalid(lstr[i])) inv++;
i++;
}
cstr[i] = '\0';
return inv;
}
inline int
l2cstr(const char *lstr, char *cstr)
{
int inv = 0;
int i = 0;
if (cstr == NULL) return -1;
if (lstr == NULL) return 0;
while (lstr[i] != '\0') {
cstr[i] = l2c(lstr[i]);
if (!is_bvalid(lstr[i])) inv++;
i++;
}
cstr[i] = '\0';
return inv;
}
/* letter to char reverse string */
inline int
l2crstr(char *lstr, char *cstr)
{
int inv = 0;
int i = 0, j = 0;
if (cstr == NULL) return -1;
if (lstr == NULL) return 0;
i = strlen(lstr) -1;
while (i >= 0) {
cstr[j] = l2c(lstr[i]);
if (!is_bvalid(lstr[i])) inv++;
i--; j++;
}
return inv;
}
/* reverse the first n chars of a string in place. */
inline void
revnstr(char *str, int n)
{
char *end = str + n - 1;
while (str < end)
{
*str ^= *end; *end ^= *str; *str ^= *end;
str++; end--;
}
}
/* reverse a string in place. */
inline void
revstr(char *str)
{
char *end = str + strlen(str) - 1;
while (str < end)
{
*str ^= *end; *end ^= *str; *str ^= *end;
str++; end--;
}
}
/*
* linux systems DON'T HAVE gethrtime. So we have to "fake" it with
* a less efficient equivalent.
*/
#ifndef HRTIME
hrtime_t gethrtime()
{
struct timespec ts;
(void)clock_gettime(CLOCK_REALTIME, &ts);
return ((uint64_t)ts.tv_sec * 1000000000LU + (uint64_t)ts.tv_nsec);
}
#endif
int
getdict(char *name)
{
char *fullname;
int rv;
struct stat st;
size_t len;
ASSERT(strlen(DFNEND) >= strlen(BSNEND));
if (name == NULL) {
name = DDFN;
}
fullname = malloc(strlen(name) + strlen(DFNEND) + 1);
if (fullname == NULL) {
VERB(VNORM, "failed to alloc %d bytes for filename\n", strlen(name) + strlen(DFNEND) + 1) {
perror("malloc");
}
return -5;
}
strcpy(fullname, name);
strcat(fullname, DFNEND);
dfd = open(fullname, O_RDONLY);
if (dfd < 0) {
VERB(VNORM, "gaddag file %s failed to open\n", fullname) {
perror("open");
}
return -1;
}
rv = fstat(dfd, &st);
if (rv < 0) {
VERB(VNORM, "cannot fstat open file %s\n", fullname) {
perror("fstat");
}
return -2;
}
len = st.st_size;
if (len % sizeof(gn_t)) {
vprintf(VNORM, "gaddag data not aligned properly\n");
return -3;
}
g_cnt = len / sizeof(gn_t);
ASSERT(len < GDSIZE);
#if defined(__sun)
#define MMFLAGS MAP_SHARED | MAP_ALIGN
gaddag = (gn_t *)mmap((void *)GDSIZE, GDSIZE, PROT_READ, MMFLAGS, dfd, 0);
#else
// #define MMFLAGS MAP_SHARED | MAP_HUGETLB | MAP_LOCKED | MAP_POPULATE
// #define MMFLAGS MAP_SHARED | MAP_LOCKED | MAP_POPULATE
//#define MMFLAGS MAP_SHARED | MAP_LOCKED
//#define MMFLAGS MAP_SHARED | MAP_HUGETLB
#define MMFLAGS MAP_SHARED
gaddag = (gn_t *)mmap(0, GDSIZE, PROT_READ, MMFLAGS, dfd, 0);
#endif
if (gaddag == MAP_FAILED) {
VERB(VNORM, "failed to mmap %d bytes of gaddag\n", len) {
perror("mmap");
}
return -4;
}
#if defined(__sun)
{
struct memcntl_mha mha;
int rv;
mha.mha_cmd = MHA_MAPSIZE_VA;
mha.mha_flags = 0;
mha.mha_pagesize = GDSIZE;
rv = memcntl((caddr_t)gaddag, GDSIZE, MC_HAT_ADVISE, (char *)&mha, 0, 0);
if (rv != 0) {
VERB(VVERB, "failed to set gaddag pagesize to %lu\n", GDSIZE){
perror("memcntl");
}
}
}
#endif /* __sun */
strcpy(fullname, name);
strcat(fullname, BSNEND);
bsfd = open(fullname, O_RDONLY);
if (bsfd < 0) {
VERB(VNORM, "bitset file %s failed to open\n", fullname) {
perror("open");
}
return -1;
}
rv = fstat(bsfd, &st);
if (rv < 0) {
VERB(VNORM, "cannot fstat open file %s\n", fullname) {
perror("fstat");
}
return -2;
}
len = st.st_size;
if (len % sizeof(bs_t)) {
vprintf(VNORM, "bitset data not aligned properly\n");
return -3;
}
if ((len/sizeof(bs_t)) != g_cnt) {
vprintf(VNORM, "bitset data does not match gaddag size\n");
return -5;
}
ASSERT(len < GDSIZE);
#if defined(__sun)
bitset = (bs_t *)mmap((void *)GDSIZE, GDSIZE, PROT_READ, MMFLAGS, bsfd, 0);
#else
bitset = (bs_t *)mmap(0, GDSIZE, PROT_READ, MAP_SHARED, bsfd, 0);
#endif
if (bitset == MAP_FAILED) {
VERB(VNORM, "failed to mmap %d bytes of bitset\n", len) {
perror("mmap");
}
return -4;
}
#if defined(__sun)
{
struct memcntl_mha mha;
int rv;
mha.mha_cmd = MHA_MAPSIZE_VA;
mha.mha_flags = 0;
mha.mha_pagesize = GDSIZE;
rv = memcntl((caddr_t)bitset, GDSIZE, MC_HAT_ADVISE, (char *)&mha, 0, 0);
if (rv != 0) {
VERB(VVERB, "failed to set bitset pagesize to %lu\n", GDSIZE){
perror("memcntl");
}
}
}
#endif
return g_cnt;
}
void
printlrstr(letter_t *lstr) {
char cstr[20] = "";
int rv;
rv = l2crstr(lstr, cstr);
printf("%s", cstr);
}
void
printlstr(const letter_t *lstr) {
char cstr[20] = "";
int rv;
rv = l2cstr(lstr, cstr);
printf("%s", cstr);
}
/*
* fill rack: take letters from bag and put them in the rack.
* copy over null and marked slots. Only take up to 7. Don't
* go past end of bag. Return number of tiles put on rack.
*/
int
fillrack(rack_t *r, bag_t b, int *bagpos)
{
int i, cnt = 0;
if (*bagpos >= baglen) {
return 0;
}
for (i=0; i < 7; i++) {
if ((r->tiles[i] == '\0') || (r->tiles[i] == MARK)) {
r->tiles[i] = b[*bagpos];
*bagpos += 1; cnt++;
}
if (*bagpos >= baglen) {
break;
}
}
DBG(DBG_RACK, "bag now at %d, filled %d tiles to make ", *bagpos, cnt) {
printlstr(r->tiles); printf("\n");
}
return cnt;
}
/*
* rack handling, combined operation.
* copy letters from oldr to newr, except for L. re-create rbs
* along the way.
* ORDER IS IMPORTANT: assume oldr is sorted, and keep newr the same way.
*/
inline void
rackem(rack_t const *oldr, rack_t *newr, bs_t *rbs, letter_t L)
{
letter_t const *op = oldr->tiles;
letter_t *np = newr->tiles;
*rbs = 0;
while (*op != '\0') {
if (*op != L) {
*np = *op;
setbit(rbs, *op - 1);
np++;
} else {
L = '\0'; // don't remove it twice
}
op++;
}
*np = '\0';
}
/* remove a letter from the rack, mainstain bitset. */
char *
pluckrack2(rack_t *r, letter_t l, bs_t *bs)
{
char *lp;
if (r == NULL) return NULL;
if (is_pblank(l)) l = UBLANK;
lp = strchr(r->tiles, l);
if (lp != NULL) {
*lp = MARK;
} else {
VERB(VVERB, "Missing letter %c from rack ", l2c(l)) {
printlstr(r->tiles); printf("\n");
}
}
VERB(VNOISY, "Plucked2 rack now ") {
printlstr(r->tiles); printf("\n");
}
if (strchr(r->tiles, l) == NULL) {
clrbit(bs, l-1);
}
return lp;
}
/* remove a letter from the rack */
char *
pluckrack(rack_t *r, letter_t l)
{
char *lp;
if (r == NULL) return NULL;
if (is_pblank(l)) l = UBLANK;
lp = strchr(r->tiles, l);
if (lp != NULL) {
*lp = MARK;
} else {
VERB(VVERB, "Missing letter %c from rack ", l2c(l)) {
printlstr(r->tiles); printf("\n");
}
}
VERB(VNOISY, "Plucked rack now ") {
printlstr(r->tiles); printf("\n");
}
return lp;
}
/* initialize a bunch of things. 0 = success. */
int
initstuff()
{
int r, c;
unsigned int random;
/* seed rng */
random = (getpid() * time(NULL)) >> 4;
srand(random);
random = 0;
/* bag. Names bags A-Z, or custom. '?' mean randomize */
bagtag = '\0';
if (bagname == NULL) {
if (bagstr == NULL) {
bagname = "?random";
} else {
bagname = "_adhoc";
}
}
ASSERT(bagname != NULL);
bagtag = bagname[0];
if (bagtag == '?') {
random = 1;
if (bagname[1] != '\0') bagname++;
bagtag = bagname[0];
}
if ((bagstr == NULL) && isupper(bagtag))
bagstr = bags[bagtag - 'A'];
if ((bagstr == NULL) && random) {
bagstr = basebag;
}
if (bagstr == NULL) {
vprintf(VNORM, "No bag contents specified\n");
return 1;
}
baglen = strlen(bagstr);
ASSERT((bagtag != '\0' ) && (bagname != NULL) && (bagstr != NULL));
DBG(DBG_BAG, "bag [%c]%s = %s\n", bagtag, bagname, bagstr);
globalbag = strdup(bagstr); // to get size allocated
if (casec2lstr(bagstr, globalbag) != 0) {
vprintf(VNORM, "bag string has invalid characters.\n"
"Use only letters and '?' for blank\n");
return 1;
}
if (random) {
int shakes;
int s1, s2, len;
letter_t tl;
len = strlen(globalbag);
shakes = len * len * 2;
/* shake the bag. */
while (shakes--) {
s1 = rand();
s2 = (s1/len) % len;
s1 %= len;
tl = globalbag[s1];
globalbag[s1] = globalbag[s2];
globalbag[s2] = tl;
}
vprintf(VVERB, "bag %s was shaken.\n", bagname);
}
/* set up empty board */
for (r = 0; r < BOARDY; r++) {
for (c = 0; c < BOARDX; c++) {
emptyboard.spaces[r][c].b.all = 0;
emptyboard.spaces[r][c].mbs[0] = 0;
emptyboard.spaces[r][c].mbs[1] = 0;
switch (boni[r][c]) {
case DL:
case TL:
emptyboard.spaces[r][c].b.f.lm = boni[r][c] + 1;
emptyboard.spaces[r][c].b.f.wm = 1;
break;
case DW:
case TW:
emptyboard.spaces[r][c].b.f.wm = boni[r][c] - 1;
emptyboard.spaces[r][c].b.f.lm = 1;
break;
default:
emptyboard.spaces[r][c].b.f.lm = 1;
emptyboard.spaces[r][c].b.f.wm = 1;
}
}
}
/* mark all legal start moves */
startboard = emptyboard; // does this still work? YES.
startboard.spaces[STARTR][STARTC].b.f.anchor = 2;
startboard.spaces[STARTR][STARTC].mbs[M_HORIZ] = ALLPHABITS;
startboard.spaces[STARTR][STARTC].mbs[M_VERT] = ALLPHABITS;
// init stats
globalstats.evals = 0;
globalstats.evtime = 0;
globalstats.maxdepth = 0;
globalstats.maxwidth = 0;
globalstats.wordhs = 0;
globalstats.gamehs = 0;
/* make up our starting position. */
startp.b = startboard;
startp.sc = 0;
startp.bagndx = 0;
startp.r = emptyrack;
startp.m = emptymove;
startp.prev = NULL;
startp.next = NULL;
startp.state = START;
startp.stats = nullstats;
startp.mvcnt = 0;
startp.mvndx = -1;
if (rackstr != NULL) {
if (strlen(rackstr) > 7) {
vprintf(VNORM, "rack can only have up to 7 letters.\n");
return 1;
}
if (casec2lstr(rackstr, startp.r.tiles) != 0) {
vprintf(VNORM, "rack string has invalid characters.\n"
"Use only letters and '?' for blank\n");
return 1;
}
DBG(DBG_RACK, "starting with a rack of:") {
printlstr(startp.r.tiles); printf("\n");
}
}
return 0;
}
/* used in call to qsort() */
inline int
lcmp(const void *l1, const void *l2)
{
return *(const char *)l1 - *(const char *)l2;
}
void
printnode(char *msg, uint32_t nid)
{
char l = gl(gaddag[nid]);
printf("%s: node %d = [%d|%c|%c|%c(%d)]\n", msg, nid, gc(gaddag[nid]),
gs(gaddag[nid])?'$': ' ', gf(gaddag[nid])? '.': ' ',l?l2c(l):' ',l );
}
/*
* a compare function for a letter versus a gaddag-letter.
* 0 = a match.
* <0 = l is past gl (l > gl)
* >0 = l before gl (l < gl)
* a blank (played or unplayed) matches any gl except SEP.
*/
inline int
cmplgl(letter_t l, letter_t g)
{
if (is_blank(l) && (g != SEP)) {
return 0;
}
return (l - g);
}
/* given a letter, find corresponding nodeid in nid.
* we can assume that the bit for l is set. (Maybe not).
* NOTE: can't optimize by assuming uint32_t << 32 == 0. it's not.
* BUG: SPARC gcc optimization messes this up.
*/
inline int
gotol(letter_t l, int nid)
{
uint32_t bits;
bits = bitset[nid] << (32 -l);
return nid + popc(bits) - 1;
// return nid + popc(bitset[nid] << (32-l)) -1;
}
/* return the next letter, and fix up bs */
inline letter_t
nextl(bs_t *bs, int *curid)
{
letter_t l;
uint32_t idbs = bitset[*curid];
l = ffb(*bs);
if (l==0) return 0;
*curid += popc( (uint32_t)(idbs<<((uint32_t)(32-l))) )-1;
clrbit(bs, l-1);
return l;
}
/*
* compute final bit set given node id.
*/
bs_t
finals(int nid)
{
bs_t bs = 0;
letter_t l;
bs_t nbs;
int newid;
if (nid < 0) return bs; /* just in case */
nbs = bitset[nid];
l = nextl(&nbs, &nid);
while (l != '\0') {
if (gf(gaddag[nid])) {
setbit(&bs, l-1);
}
l = nextl(&nbs, &nid);
}
return bs;
}
/* isroom: given dir and side, is there room over there? */
/* don't be too clever. We can assume current r,c are in bounds.*/
inline int
isroom(int r, int c, int dir, int side)
{
// printf("isroom %d,%d, dir=%d, side=%d\n", r, c, dir, side);
if (dir == M_HORIZ) {
if (((side < 0) && (c > 0)) || ((side > 0) && (c < 14)))
return 1;
} else {
if (((side < 0) && (r > 0)) || ((side > 0) && (r < 14)))
return 1;
}
return 0;
}
/* ultimate nld: nldn. No letter directly next to.
* returns 0 iff the NEXT space is NOT a played tile. Could be empty or
* at the edge of the board.
* dir is H(0) or V(1), side is -1(before) or 1(after).
*/
inline int
nldn(board_t *b, int r, int c, int dir, int side)
{
int dr = dir * side;
int dc = (1 - dir) * side;
int ve = (c-7)/7;
int he = (r-7)/7;
return (( (dr&&(dr==he)) || (dc&&(dc==ve)) )||(b->spaces[r+dr][c+dc].b.f.letter == 0));
}
/* next space empty. returns a 1 IFF the NEXT space is on the board and
* does not have a tile played on it.
*/
inline int
nse(board_t *b, int r, int c, int dir, int side)
{
int dr = dir * side;
int dc = (1 - dir) * side;
if (isroom(r,c,dir,side)) {
return (b->spaces[r+dr][c+dc].b.f.letter == 0);
}
}
/* sublime: next door neighbor. Takes board, position, dir, side,
* Returns: <0 if off of board
* 0 if empty space
* l(>0) if space contains a letter (sp.b.f.letter)
* clever bits: (x-7)/8 is 0 iff 0<=X<=14. To test the current space,
* set side to 0.
*/
int
ndn(board_t *b, int r, int c, const int dir, const int side)
{
r += dir*side; c += (1-dir)*side;
if (!(((c-7)/8) + ((r-7)/8))) {
return b->spaces[r][c].b.f.letter;
}
return -1;
}
/* goes with mm8.
* row,col is the gap space. nid shoud be the child of the last letter
* played next to gap.
*/
bs_t
dobridge2(board_t *b, int nid, int row, int col, int dir, int end)
{
int cr = row, cc = col;
space_t *sp;
bs_t gbs = 0;
bs_t bs;
letter_t gl;
letter_t nl;
int dr, dc;
int curid = nid;
int gid, gcid;
sp = &(b->spaces[row][col]);
ASSERT(sp->b.f.letter == '\0');
dr = end * dir;
dc = end * (1 - dir);
bs = bitset[nid];
/* prune with other side of gap. */
// bs &= b->spaces[cr+dr][cc+dc].mnid[dir];
if (bs == 0) return 0;
while (gl = nextl(&bs, &curid)) {
gid = gotol(gl, curid);
gcid = gc(gaddag[gid]);
while ( (nl = ndn(b, cr, cc, dir, end)) > 0) {
if (l2b(nl) & bitset[gcid]) {
gid = gotol(gl, gcid);
gcid = gc(gaddag[gid]);
if (gid <= 0) break;
cr += dr; cc += dc;
} else {
break;
}
}
if ((nl == 0) && (gf(gaddag[gid]))) {
setbit(&gbs, gl - 1);
}
}
return gbs;
}
/* dobridge: in the case where the cross move set falls into a "gap"
* between played tiles, we have more work to do. End is -1 for
* "before" and +1 for "after". The row,col are the end of the word.
* We can assume that at least two more squares are past the end.
* nid corresponds to the letter in the word, NOT the gap.
*/
void
dobridge(board_t *b, int nid, int row, int col, int dir, int end)
{
int cr=row, cc=col;
bs_t nbs, cbs;
bs_t fbs = 0;
letter_t spl, wl;
int dc, dr;
int gid, lid;
ASSERT(b->spaces[cr][cc].b.f.letter != '\0');
dr = dir * end;
dc = (1 - dir) * end;
if (nid <= 0) {
b->spaces[row+dr][col+dc].mbs[1-dir] = 0;
return;
}
// gid = gc(gaddag[nid]);
gid = nid;
nbs = bitset[gid];
while (spl = nextl(&nbs, &gid)) {
gid = gotol(spl, gid);
lid = gc(gaddag[gid]);
if (lid <= 0) {
continue;
}
cr = row + 2* dr;
cc = col + 2* dc;
while ((wl = b->spaces[cr][cc].b.f.letter) != '\0') {
ASSERT(wl != '\0');
if ((!(l2b(wl) & bitset[lid])) || (lid <= 0)) {
/* it's not a word. */
break;
}
if (nldn(b, cr, cc, dir, dr+dc) && gf(gaddag[lid])) {
setbit(&fbs, spl - 1);
break;
}
cr+=dr;cc+=dc;
lid = gotol(wl,lid);
lid = gc(gaddag[lid]);
}
}
b->spaces[row+dr][col+dc].mbs[1-dir] = fbs;
}
/* anagram using bitset. */
int
doanagram_e(uint32_t nodeid, letter_t *sofar, int depth, letter_t *rest)
{
int anas = 0;
int curid = -1;
bs_t bs = 0;
bs_t lbs;
letter_t l;
letter_t *lp;
DBG(DBG_ANA, "doing anagram lvl %d", depth) {
printnode(" with", nodeid);
}
lbs = lstr2bs(rest);
curid = nodeid;
bs = bitset[nodeid] & lbs;
while (l = nextl(&bs, &curid)) {
DBG(DBG_ANA, "matched %c from ", l2c(l)) {
printlstr(rest);
printnode(" using", curid);
}
sofar[depth] = l;
/* remove l from rest. */
lp = strchr(rest, l);
*lp = MARK;
if (gf(gaddag[curid])) {
anas++;
VERB(VNORM, " ") {
printlrstr(sofar); printf("\n");
}
}
anas += doanagram_e(gc(gaddag[curid]), sofar, depth+1, rest);
*lp = l;
}
/* if there is a '?', do another round. */
if (lbs & UBLBIT) {
curid = nodeid;
bs = ALLPHABITS & bitset[nodeid];
lp = strchr(rest, UBLANK);
*lp = MARK;
while (l = nextl(&bs, &curid)) {
DBG(DBG_ANA, "blank %c from ", l2c(l|BB)) {