File: patsolve.cpp

package info (click to toggle)
kpat 4%3A4.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 4,984 kB
  • ctags: 1,520
  • sloc: cpp: 15,530; xml: 16; makefile: 9; sh: 2
file content (1139 lines) | stat: -rw-r--r-- 26,801 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
/*
 * Copyright (C) 1998-2002 Tom Holroyd <tomh@kurage.nimh.nih.gov>
 * Copyright (C) 2006-2009 Stephan Kulow <coolo@kde.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of 
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "patsolve.h"

#include "../patpile.h"

#include "KCardDeck"

#include <KDebug>

#include <cctype>
#include <cmath>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <sys/types.h>


#ifdef ERR
#undef ERR
#endif

long all_moves = 0;

/* This is a 32 bit FNV hash.  For more information, see
http://www.isthe.com/chongo/tech/comp/fnv/index.html */

#define FNV1_32_INIT 0x811C9DC5
#define FNV_32_PRIME 0x01000193

#define fnv_hash(x, hash) (((hash) * FNV_32_PRIME) ^ (x))

/* Hash a buffer. */

static inline quint32 fnv_hash_buf(quint8 *s, int len)
{
	int i;
	quint32 h;

	h = FNV1_32_INIT;
	for (i = 0; i < len; i++) {
		h = fnv_hash(*s++, h);
	}

	return h;
}

/* Hash a 0 terminated string. */

static inline quint32 fnv_hash_str(quint8 *s)
{
	quint32 h;

	h = FNV1_32_INIT;
	while (*s) {
		h = fnv_hash(*s++, h);
	}

	return h;
}


/* Hash a pile. */

void Solver::hashpile(int w)
{
   	W[w][Wlen[w]] = 0;
	Whash[w] = fnv_hash_str(W[w]);

	/* Invalidate this pile's id.  We'll calculate it later. */

	Wpilenum[w] = -1;
}

#define MAXDEPTH 400

bool Solver::recursive(POSITION *parent)
{
    int i, alln, a, numout = 0;

    if ( parent == NULL ) {
        init();
        recu_pos.clear();
        delete Stack;
        Stack = new POSITION[MAXDEPTH];
        memset( Stack, 0, sizeof( POSITION ) * MAXDEPTH );
    }

    /* Fill in the Possible array. */

    alln = get_possible_moves(&a, &numout);
    assert(alln < MAXMOVES);

    if (alln == 0) {
        if ( isWon() ) {
            Status = SolutionExists;
            Q_ASSERT(parent); // it just is never called with a won game
            win(parent);
            return true;
        }
        return false;
    }

    /* Prioritize these moves.  Automoves don't get queued, so they
       don't need a priority. */

    if (!a) {
        prioritize(Possible, alln);
    }

    /* Now copy to safe storage and return.  Non-auto moves out get put
       at the end.  Queueing them isn't a good idea because they are still
       good moves, even if they didn't pass the automove test.  So we still
       do the recursive solve() on them, but only after queueing the other
       moves. */

    if ( parent && parent->depth >= MAXDEPTH - 2 )
        return false;

    MOVE *mp0 = new_array(MOVE, alln+1);
    if (mp0 == NULL) {
        return false;
    }
    MOVE *mp = mp0;
    for (i = 0; i < alln; ++i) {
        if (Possible[i].card_index != -1) {
            *mp = Possible[i];      /* struct copy */
            mp++;
        }
    }
    mp->card_index = -1;
    ++alln;

    bool fit = false;
    for (mp = mp0; mp->card_index != -1; ++mp) {

        int depth = 0;
        if (parent != NULL)
            depth = parent->depth + 1;

        make_move(mp);

        /* Calculate indices for the new piles. */
        pilesort();

        /* See if this is a new position. */

        Total_generated++;
        POSITION *pos = &Stack[depth];
        pos->queue = NULL;
        pos->parent = parent;
        pos->node = pack_position();
        quint8 *key = (quint8 *)pos->node + sizeof(TREE);
#if 0
        qint32 hash = fnv_hash_buf(key, mm->Pilebytes);
        if ( recu_pos.contains( hash ) )
        {
            undo_move( mp );
            mm->give_back_block( (quint8 *)pos->node );
            continue;
        }
        recu_pos[hash] = true;
#else
        for ( int i = 0; i < depth; ++i )
        {
            quint8 *tkey = (quint8 *)Stack[i].node + sizeof(TREE);
            if ( !memcmp( key, tkey, mm->Pilebytes ) )
            {
                key = 0;
                break;
            }
        }
        if ( !key )
        {
            undo_move( mp );
            mm->give_back_block( (quint8 *)pos->node );
            continue;
        }
#endif
        Total_positions++;
        if ( Total_positions % 10000 == 0 )
            kDebug() << "positions" << Total_positions;

        pos->move = *mp;                 /* struct copy */
        pos->cluster = 0;
        pos->depth = depth;
        pos->nchild = 0;

        bool ret = recursive(pos);
        fit |= ret;
        undo_move(mp);
        mm->give_back_block( (quint8 *)pos->node );
        if ( ret )
            break;
    }

    MemoryManager::free_array(mp0, alln);

    if ( parent == NULL ) {
        printf( "Total %ld\n", Total_generated );
        delete [] Stack;
        Stack = 0;
    }
    return fit;
}


/* Generate an array of the moves we can make from this position. */

MOVE *Solver::get_moves(int *nmoves)
{
	int i, n, alln, a = 0, numout = 0;
	MOVE *mp, *mp0;

	/* Fill in the Possible array. */

        alln = n = get_possible_moves(&a, &numout);
	if (debug)  
	  {
	    print_layout();
	    fprintf( stderr, "moves %d\n", n );
	    for (int j = 0; j < n; j++) {
	      fprintf( stderr,  "  " );
	      if ( Possible[j].totype == O_Type )
                fprintf( stderr, "move from %d out (at %d) Prio: %d\n", Possible[j].from,
                         Possible[j].turn_index, Possible[j].pri );
	      else
                fprintf( stderr, "move %d from %d to %d (%d) Prio: %d\n", Possible[j].card_index,
                         Possible[j].from, Possible[j].to,
                         Possible[j].turn_index, Possible[j].pri );
	    }
	  }

	/* No moves?  Maybe we won. */

	if (n == 0) {
            /* No more moves - won or lost */
            //print_layout();
            return NULL;
	}

	/* Prioritize these moves.  Automoves don't get queued, so they
	don't need a priority. */

	if (!a) {
		prioritize(Possible, alln);
	}

	/* Now copy to safe storage and return.  Non-auto moves out get put
	at the end.  Queueing them isn't a good idea because they are still
	good moves, even if they didn't pass the automove test.  So we still
	do the recursive solve() on them, but only after queueing the other
	moves. */

	mp = mp0 = new_array(MOVE, n);
	if (mp == NULL) {
		return NULL;
	}
	*nmoves = n;
	i = 0;
	if (a || numout == 0) {
		for (i = 0; i < alln; ++i) {
			if (Possible[i].card_index != -1) {
				*mp = Possible[i];      /* struct copy */
				mp++;
			}
		}
	} else {
		for (i = numout; i < alln; ++i) {
			if (Possible[i].card_index != -1) {
				*mp = Possible[i];      /* struct copy */
				mp++;
			}
		}
		for (i = 0; i < numout; ++i) {
			if (Possible[i].card_index != -1) {
				*mp = Possible[i];      /* struct copy */
				mp++;
			}
		}
	}

	return mp0;
}

/* Test the current position to see if it's new (or better).  If it is, save
it, along with the pointer to its parent and the move we used to get here. */

int Posbytes;

/* Comparison function for sorting the W piles. */

int Solver::wcmp(int a, int b)
{
	if (m_newer_piles_first) {
		return Wpilenum[b] - Wpilenum[a];       /* newer piles first */
	} else {
		return Wpilenum[a] - Wpilenum[b];       /* older piles first */
	}
}

void Solver::pilesort(void)
{
    	/* Make sure all the piles have id numbers. */

	for (int w = 0; w < m_number_piles; w++) {
		if (Wpilenum[w] < 0) {
			Wpilenum[w] = get_pilenum(w);
			if (Wpilenum[w] < 0) {
				return;
			}
		}
                //fprintf( stderr, "%d ", Wpilenum[w] );
	}
        //fprintf( stderr, "\n" );
}

#define NBUCKETS 65521           /* the largest 16 bit prime */
#define NPILES   65536           /* a 16 bit code */

typedef struct bucketlist {
	quint8 *pile;           /* 0 terminated copy of the pile */
	quint32 hash;         /* the pile's hash code */
	int pilenum;            /* the unique id for this pile */
	struct bucketlist *next;
} BUCKETLIST;

BUCKETLIST *Bucketlist[NBUCKETS];
int Pilenum;                    /* the next pile number to be assigned */

BUCKETLIST *Pilebucket[NPILES]; /* reverse lookup for unpack to get the bucket
				   from the pile */

/* Compact position representation.  The position is stored as an
array with the following format:
	pile0# pile1# ... pileN# (N = Nwpiles)
where each pile number is packed into 16 bits (so a pile take 2 bytes).
Positions in this format are unique can be compared with memcmp().  The O
cells are encoded as a cluster number: no two positions with different
cluster numbers can ever be the same, so we store different clusters in
different trees.  */

int Treebytes;

TREE *Solver::pack_position(void)
{
	int j, k, w;
	quint8 *p;
	TREE *node;

	/* Allocate space and store the pile numbers.  The tree node
	will get filled in later, by insert_node(). */

	p = mm->new_from_block(Treebytes);
	if (p == NULL) {
                Status = UnableToDetermineSolvability;
		return NULL;
	}
	node = (TREE *)p;
	p += sizeof(TREE);

	/* Pack the pile numers j into bytes p.
		       j             j
		+--------+----:----+--------+
		|76543210|7654:3210|76543210|
		+--------+----:----+--------+
		    p         p         p
	*/

	k = 0;
        quint16 *p2 = ( quint16* ) p;
	for (w = 0; w < m_number_piles; ++w) {
		j = Wpilenum[w];
                if ( j < 0 )
                {
                    mm->give_back_block( p );
                    return NULL;
                }
                *p2++ = j;
	}

	return node;
}

/* Like strcpy() but return the length of the string. */

static inline int strecpy(unsigned char *d, unsigned char *s)
{
	int i;

	i = 0;
	while ((*d++ = *s++) != '\0') {
		i++;
	}

	return i;
}

/* Unpack a compact position rep.  T cells must be restored from the
array following the POSITION struct. */

void Solver::unpack_position(POSITION *pos)
{
	int i, k, w;
	quint8 c;
	BUCKETLIST *l;

        unpack_cluster(pos->cluster);

	/* Unpack bytes p into pile numbers j.
		    p         p         p
		+--------+----:----+--------+
		|76543210|7654:3210|76543210|
		+--------+----:----+--------+
		       j             j
	*/

	k = w = i = c = 0;
	quint16 *p2 = ( quint16* )( (quint8 *)(pos->node) + sizeof(TREE) );
	while (w < m_number_piles) {
                i = *p2++;
		Wpilenum[w] = i;
		l = Pilebucket[i];
		i = strecpy(W[w], l->pile);
		Wp[w] = &W[w][i - 1];
		Wlen[w] = i;
		Whash[w] = l->hash;
		w++;
	}
}

void Solver::printcard(card_t card, FILE *outfile)
{
    static char Rank[] = " A23456789TJQK";
    static char Suit[] = "DCHS";

    if (RANK(card) == NONE) {
        fprintf(outfile, "   ");
    } else {
        if ( DOWN(card ) )
            fprintf(outfile, "|%c%c ", Rank[RANK(card)], Suit[SUIT(card)]);
        else
            fprintf(outfile, "%c%c ", Rank[RANK(card)], Suit[SUIT(card)]);
    }
}

/* Win.  Print out the move stack. */

void Solver::win(POSITION *pos)
{
    int i, nmoves;
    POSITION *p;
    MOVE **mpp, **mpp0;

    /* Go back up the chain of parents and store the moves
       in reverse order. */

    i = 0;
    for (p = pos; p->parent; p = p->parent) {
        i++;
    }
    nmoves = i;

    //printf("Winning in %d moves.\n", nmoves);

    mpp0 = new_array(MOVE *, nmoves);
    if (mpp0 == NULL) {
        Status = UnableToDetermineSolvability;
        return; /* how sad, so close... */
    }
    mpp = mpp0 + nmoves - 1;
    for (p = pos; p->parent; p = p->parent) {
        *mpp-- = &p->move;
    }

    for (i = 0, mpp = mpp0; i < nmoves; ++i, ++mpp)
        winMoves.append( **mpp );

    MemoryManager::free_array(mpp0, nmoves);
}

/* Initialize the hash buckets. */

void Solver::init_buckets(void)
{
	int i;

	/* Packed positions need 3 bytes for every 2 piles. */

	i = ( m_number_piles ) * sizeof( quint16 );
	i += ( m_number_piles ) & 0x1;

        mm->Pilebytes = i;

	memset(Bucketlist, 0, sizeof(Bucketlist));
	Pilenum = 0;
	Treebytes = sizeof(TREE) + mm->Pilebytes;

	/* In order to keep the TREE structure aligned, we need to add
	up to 7 bytes on Alpha or 3 bytes on Intel -- but this is still
	better than storing the TREE nodes and keys separately, as that
	requires a pointer.  On Intel for -f Treebytes winds up being
	a multiple of 8 currently anyway so it doesn't matter. */

#define ALIGN_BITS 0x7
	if (Treebytes & ALIGN_BITS) {
		Treebytes |= ALIGN_BITS;
		Treebytes++;
	}
	Posbytes = sizeof(POSITION);
	if (Posbytes & ALIGN_BITS) {
		Posbytes |= ALIGN_BITS;
		Posbytes++;
	}
}


/* For each pile, return a unique identifier.  Although there are a
large number of possible piles, generally fewer than 1000 different
piles appear in any given game.  We'll use the pile's hash to find
a hash bucket that contains a short list of piles, along with their
identifiers. */

int Solver::get_pilenum(int w)
{
	int bucket, pilenum;
	BUCKETLIST *l, *last;

	/* For a given pile, get its unique pile id.  If it doesn't have
	one, add it to the appropriate list and give it one.  First, get
	the hash bucket. */

	bucket = Whash[w] % NBUCKETS;

	/* Look for the pile in this bucket. */

	last = NULL;
	for (l = Bucketlist[bucket]; l; l = l->next) {
		if (l->hash == Whash[w] &&
		    strncmp((char*)l->pile, (char*)W[w], Wlen[w]) == 0) {
			break;
		}
		last = l;
	}

	/* If we didn't find it, make a new one and add it to the list. */

	if (l == NULL) {
		if (Pilenum >= NPILES ) {
                        Status = UnableToDetermineSolvability;
			//qDebug() << "out of piles";
			return -1;
		}
		l = mm_allocate(BUCKETLIST);
		if (l == NULL) {
                        Status = UnableToDetermineSolvability;
			//qDebug() << "out of buckets";
			return -1;
		}
		l->pile = new_array(quint8, Wlen[w] + 1);
		if (l->pile == NULL) {
                    Status = UnableToDetermineSolvability;
                    MemoryManager::free_ptr(l);
		    //qDebug() << "out of memory";
                    return -1;
		}

		/* Store the new pile along with its hash.  Maintain
		a reverse mapping so we can unpack the piles swiftly. */

		strncpy((char*)l->pile, (char*)W[w], Wlen[w] + 1);
		l->hash = Whash[w];
		l->pilenum = pilenum = Pilenum++;
		l->next = NULL;
		if (last == NULL) {
			Bucketlist[bucket] = l;
		} else {
			last->next = l;
		}
		Pilebucket[pilenum] = l;
	}

#if 0
if (w < 4) {
        fprintf( stderr, "get_pile_num %d ", l->pilenum );
        for (int i = 0; i < Wlen[w]; ++i) {
            printcard(W[w][i], stderr);
        }
        fprintf( stderr, "\n" );
}
#endif
	return l->pilenum;
}

void Solver::free_buckets(void)
{
	int i, j;
	BUCKETLIST *l, *n;

	for (i = 0; i < NBUCKETS; i++) {
		l = Bucketlist[i];
		while (l) {
			n = l->next;
			j = strlen((char*)l->pile);    /* @@@ use block? */
                        MemoryManager::free_array(l->pile, j + 1);
                        MemoryManager::free_ptr(l);
			l = n;
		}
	}
}

/* Solve patience games.  Prioritized breadth-first search.  Simple breadth-
first uses exponential memory.  Here the work queue is kept sorted to give
priority to positions with more cards out, so the solution found is not
guaranteed to be the shortest, but it'll be better than with a depth-first
search. */

void Solver::doit()
{
	int i, q;
	POSITION *pos;
	MOVE m;
        memset( &m, 0, sizeof( MOVE ) );

	/* Init the queues. */

	for (i = 0; i < NQUEUES; ++i) {
		Qhead[i] = NULL;
	}
	Maxq = 0;

	/* Queue the initial position to get started. */

	hash_layout();
	pilesort();
	m.card_index = -1;
        m.turn_index = -1;
	pos = new_position(NULL, &m);
	if ( pos == NULL )
        {
            Status = UnableToDetermineSolvability;
            return;
        }
	queue_position(pos, 0);

	/* Solve it. */

        while ((pos = dequeue_position()) != NULL) {
		q = solve(pos);
		if (!q) {
                    free_position(pos, true);
		}
	}
}

/* Generate all the successors to a position and either queue them or
recursively solve them.  Return whether any of the child nodes, or their
descendents, were queued or not (if not, the position can be freed). */

bool Solver::solve(POSITION *parent)
{
	int i, nmoves, qq;
	MOVE *mp, *mp0;
	POSITION *pos;

        bool q;
        all_moves++;

	/* If we've won already (or failed), we just go through the motions
	but always return false from any position.  This enables the cleanup
	of the move stack and eventual destruction of the position store. */

	if (Status != NoSolutionExists) {
		return false;
	}

        {
            QMutexLocker lock( &endMutex );
            if ( m_shouldEnd )
            {
                Status = SearchAborted;
                return false;
            }
        }

        if ( max_positions != -1 && Total_positions > ( unsigned long )max_positions )
        {
            Status = MemoryLimitReached;
            return false;
        }


	/* Generate an array of all the moves we can make. */

	if ((mp0 = get_moves(&nmoves)) == NULL) {
            if ( isWon() ) {
                Status = SolutionExists;
                win( parent );
            }
            return false;
	}

        if ( parent->depth == 0 )
        {
            Q_ASSERT( firstMoves.count() == 0 );
            for (int j = 0; j < nmoves; ++j)
                firstMoves.append( Possible[j] );
        }

	parent->nchild = nmoves;

	/* Make each move and either solve or queue the result. */

	q = false;
	for (i = 0, mp = mp0; i < nmoves; ++i, ++mp) {
		make_move(mp);

		/* Calculate indices for the new piles. */

		pilesort();

		/* See if this is a new position. */

		if ((pos = new_position(parent, mp)) == NULL) {
			undo_move(mp);
			parent->nchild--;
			continue;
		}

		/* If this position is in a new cluster, a card went out.
		Don't queue it, just keep going.  A larger cutoff can also
		force a recursive call, which can help speed things up (but
		reduces the quality of solutions).  Otherwise, save it for
		later. */

		if (pos->cluster != parent->cluster || !nmoves) {
			qq = solve(pos);
			undo_move(mp);
			if (!qq) {
				free_position(pos, false);
			}
			q |= (bool)qq;
		} else {
			queue_position(pos, mp->pri);
			undo_move(mp);
			q = true;
		}
	}
        MemoryManager::free_array(mp0, nmoves);

	/* Return true if this position needs to be kept around. */
	return q;
}

/* We can't free the stored piles in the trees, but we can free some of the
POSITION structs.  We have to be careful, though, because there are many
threads running through the game tree starting from the queued positions.
The nchild element keeps track of descendents, and when there are none left
in the parent we can free it too after solve() returns and we get called
recursively (rec == true). */

void Solver::free_position(POSITION *pos, int rec)
{
    /* We don't really free anything here, we just push it onto a
       freelist (using the queue member), so we can use it again later. */

    if (!rec) {
        pos->queue = Freepos;
        Freepos = pos;
        pos->parent->nchild--;
    } else {
        do {
            pos->queue = Freepos;
            Freepos = pos;
            pos = pos->parent;
            if (pos == NULL) {
                return;
            }
            pos->nchild--;
        } while (pos->nchild == 0);
    }
}

/* Save positions for consideration later.  pri is the priority of the move
that got us here.  The work queue is kept sorted by priority (simply by
having separate queues). */

void Solver::queue_position(POSITION *pos, int pri)
{
	/* In addition to the priority of a move, a position gets an
	additional priority depending on the number of cards out.  We use a
	"queue squashing function" to map nout to priority.  */

        int nout = getOuts();

        static qreal Yparam[] = { 0.0032, 0.32, -3.0 };
	qreal x = (Yparam[0] * nout + Yparam[1]) * nout + Yparam[2];
	pri += (int)floor(x + .5);

	if (pri < 0) {
		pri = 0;
	} else if (pri >= NQUEUES) {
		pri = NQUEUES - 1;
	}
	if (pri > Maxq) {
		Maxq = pri;
	}

	/* We always dequeue from the head.  Here we either stick the move
	at the head or tail of the queue, depending on whether we're
	pretending it's a stack or a queue. */

	pos->queue = NULL;
	if (Qhead[pri] == NULL) {
		Qhead[pri] = pos;
	} else {
            pos->queue = Qhead[pri];
            Qhead[pri] = pos;
	}
}

/* Return the position on the head of the queue, or NULL if there isn't one. */

POSITION *Solver::dequeue_position()
{
	int last;
	POSITION *pos;
	static int qpos = 0;
	static int minpos = 0;

	/* This is a kind of prioritized round robin.  We make sweeps
	through the queues, starting at the highest priority and
	working downwards; each time through the sweeps get longer.
	That way the highest priority queues get serviced the most,
	but we still get lots of low priority action (instead of
	ignoring it completely). */

	last = false;
	do {
		qpos--;
		if (qpos < minpos) {
			if (last) {
				return NULL;
			}
			qpos = Maxq;
			minpos--;
			if (minpos < 0) {
				minpos = Maxq;
			}
			if (minpos == 0) {
				last = true;
			}
		}
	} while (Qhead[qpos] == NULL);

	pos = Qhead[qpos];
	Qhead[qpos] = pos->queue;

	/* Decrease Maxq if that queue emptied. */

	while (Qhead[qpos] == NULL && qpos == Maxq && Maxq > 0) {
		Maxq--;
		qpos--;
		if (qpos < minpos) {
			minpos = qpos;
		}
	}

	/* Unpack the position into the work arrays. */

	unpack_position(pos);

	return pos;
}

Solver::Solver()
{
    mm = new MemoryManager();
    Freepos = NULL;
    m_newer_piles_first = true;
    /* Work arrays. */
    W = 0;
    Wp = 0;

    Wlen = 0;

    Whash = 0;
    Wpilenum = 0;
    Stack = 0;
}

Solver::~Solver()
{
    delete mm;

    for ( int i = 0; i < m_number_piles; ++i )
    {
        delete [] W[i];
    }

    delete [] W;
    delete [] Wp;
    delete [] Wlen;
    delete [] Whash;
    delete [] Wpilenum;
}

void Solver::init()
{
    m_shouldEnd = false;
    init_buckets();
    mm->init_clusters();

    winMoves.clear();
    firstMoves.clear();

    /* Reset stats. */

    Status = NoSolutionExists;
    Total_positions = 0;
    Total_generated = 0;
    depth_sum = 0;
}

void Solver::free()
{
    free_buckets();
    mm->free_clusters();
    mm->free_blocks();
    Freepos = NULL;
}


Solver::ExitStatus Solver::patsolve( int _max_positions, bool _debug )
{
    max_positions = _max_positions;
    debug = _debug;

    /* Initialize the suitable() macro variables. */
    init();

    /* Go to it. */
    doit();

    if ( Status == SearchAborted ) // thread quit
    {
        firstMoves.clear();
        winMoves.clear();
    }
#if 0
    printf("%ld positions generated (%f).\n", Total_generated, depth_sum / Total_positions);
    printf("%ld unique positions.\n", Total_positions);
    printf("Mem_remain = %ld\n", ( long int )mm->Mem_remain);
#endif
    free();
    return Status;
}

void Solver::print_layout()
{
}

void Solver::setNumberPiles( int p )
{
    m_number_piles = p;

    /* Work arrays. */
    W = new card_t*[m_number_piles];
    for ( int i = 0; i < m_number_piles; ++i )
    {
        W[i] = new card_t[84];
        memset( W[i], 0, sizeof( card_t ) * 84 );
    }
    Wp = new card_t*[m_number_piles];

    Wlen = new int[m_number_piles];

    Whash = new quint32[m_number_piles];
    Wpilenum = new int[m_number_piles];
    memset( Wpilenum, 0, sizeof( int ) * m_number_piles );
}

int Solver::translateSuit( int s )
{
    int suit = s * 0x10;
    if ( suit == PS_DIAMOND )
        return PS_CLUB;
    else if ( suit == PS_CLUB )
        return PS_DIAMOND;
    return suit;
}

int Solver::translate_pile(const KCardPile *pile, card_t *w, int size)
{
    Q_UNUSED( size );
        Q_ASSERT( pile->count() <= size );

        card_t rank, suit;

	rank = suit = NONE;
        for ( int i = 0; i < pile->count(); ++i )
        {
            KCard *c = pile->at( i );
            *w =  + translateSuit( c->suit() ) + c->rank();
            if ( !c->isFaceUp() )
                *w += 1 << 7;
            w++;
	}
	return pile->count();
}

/* Insert key into the tree unless it's already there.  Return true if
it was new. */

MemoryManager::inscode Solver::insert(unsigned int *cluster, int d, TREE **node)
{
	/* Get the cluster number from the Out cell contents. */

        unsigned int k = getClusterNumber();
        *cluster = k;

        /* Get the tree for this cluster. */

	TREELIST *tl = mm->cluster_tree(k);
	if (tl == NULL) {
		return MemoryManager::ERR;
	}

	/* Create a compact position representation. */

	TREE *newtree = pack_position();
	if (newtree == NULL) {
		return MemoryManager::ERR;
	}
        Total_generated++;

        MemoryManager::inscode i2 = mm->insert_node(newtree, d, &tl->tree, node);

	if (i2 != MemoryManager::NEW) {
		mm->give_back_block((quint8 *)newtree);
	}

	return i2;
}


POSITION *Solver::new_position(POSITION *parent, MOVE *m)
{
	unsigned int depth, cluster;
	quint8 *p;
	POSITION *pos;
	TREE *node;

	/* Search the list of stored positions.  If this position is found,
	then ignore it and return (unless this position is better). */

	if (parent == NULL) {
		depth = 0;
	} else {
		depth = parent->depth + 1;
	}
        MemoryManager::inscode i = insert(&cluster, depth, &node);
        if (i == MemoryManager::NEW) {
                Total_positions++;
                depth_sum += depth;
        } else
            return NULL;


	/* A new or better position.  insert() already stashed it in the
	tree, we just have to wrap a POSITION struct around it, and link it
	into the move stack.  Store the temp cells after the POSITION. */

	if (Freepos) {
		p = (quint8 *)Freepos;
		Freepos = Freepos->queue;
	} else {
		p = mm->new_from_block(Posbytes);
		if (p == NULL) {
                        Status = UnableToDetermineSolvability;
			return NULL;
		}
	}

	pos = (POSITION *)p;
	pos->queue = NULL;
	pos->parent = parent;
	pos->node = node;
	pos->move = *m;                 /* struct copy */
	pos->cluster = cluster;
	pos->depth = depth;
	pos->nchild = 0;
#if 0
        QString dummy;
        quint16 *t = ( quint16* )( ( char* )node + sizeof( TREE ) );
        for ( int i = 0; i < m_number_piles; ++i )
        {
            QString s = "      " + QString( "%1" ).arg( ( int )t[i] );
            dummy += s.right( 5 );
        }
        if ( Total_positions % 1000 == 1000 )
            print_layout();
        kDebug() << "new" << dummy;
#endif
	p += sizeof(POSITION);
	return pos;
}

/* Hash the whole layout.  This is called once, at the start. */

void Solver::hash_layout(void)
{
	int w;

	for (w = 0; w < m_number_piles; w++) {
		hashpile(w);
	}
}

void Solver::prioritize(MOVE *, int )
{
}