black-hole-solitaire / black-hole-solitaire / c-solver / black_hole_solver.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
/* Copyright (c) 2010 Shlomi Fish
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
/*
 * black_hole_solver.c - a solver for Black Hole Solitaire.
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>

#include "config.h"
#include "black_hole_solver.h"
#include "state.h"

#if (BHS_STATE_STORAGE == BHS_STATE_STORAGE_TOKYO_CAB_HASH)
#include "tokyo_cab_hash.h"
#elif (BHS_STATE_STORAGE == BHS_STATE_STORAGE_INTERNAL_HASH)
#include "fcs_hash.h"
#elif (BHS_STATE_STORAGE == BHS_STATE_STORAGE_GOOGLE_SPARSE_HASH)
#include "google_hash.h"
#else
#error Unknown state storage.
#endif

#include "alloc.h"

typedef struct
{
    /*
     * TODO : rename from board_values.
     *
     * This is the ranks of the cards in the columns. It remains constant
     * for the duration of the game.
     * */
    bhs_rank_t board_values[MAX_NUM_COLUMNS][MAX_NUM_CARDS_IN_COL];

    bhs_rank_t initial_foundation;

    bh_solve_hash_t positions;

    bhs_card_string_t initial_foundation_string;
    bhs_card_string_t initial_board_card_strings[MAX_NUM_COLUMNS][MAX_NUM_CARDS_IN_COL];
    int initial_lens[MAX_NUM_COLUMNS];

    bhs_state_key_value_pair_t init_state;
    bhs_state_key_value_pair_t final_state;

    bhs_state_key_value_pair_t * states_in_solution;
    int num_states_in_solution, current_state_in_solution_idx;

    long iterations_num, num_states_in_collection, max_iters_limit;
} bhs_solver_t;

int DLLEXPORT black_hole_solver_create(
    black_hole_solver_instance_t * * ret_instance
)
{
    bhs_solver_t * ret;

    ret = (bhs_solver_t *)malloc(sizeof(*ret));


    if (! ret)
    {
        *ret_instance =  NULL;
        return BLACK_HOLE_SOLVER__OUT_OF_MEMORY;
    }
    else
    {
        ret->states_in_solution = NULL;
        ret->iterations_num = 0;
        ret->num_states_in_collection = 0;
        ret->max_iters_limit = -1;

        bh_solve_hash_init(&(ret->positions));

        *ret_instance = (black_hole_solver_instance_t *)ret;

        return BLACK_HOLE_SOLVER__SUCCESS;
    }
}

#define MAX_RANK 12

static int parse_card(
    const char * * s,
    bhs_rank_t * foundation,
    bhs_card_string_t card
)
{
    strncpy(card, (*s), 2);
    card[2] = '\0';

    switch(*(*s))
    {
        case 'A':
            *foundation = 0;
            break;

        case '2':
            *foundation = 1;
            break;

        case '3':
            *foundation = 2;
            break;

        case '4':
            *foundation = 3;
            break;

        case '5':
            *foundation = 4;
            break;

        case '6':
            *foundation = 5;
            break;

        case '7':
            *foundation = 6;
            break;

        case '8':
            *foundation = 7;
            break;

        case '9':
            *foundation = 8;
            break;

        case 'T':
            *foundation = 9;
            break;

        case 'J':
            *foundation = 10;
            break;

        case 'Q':
            *foundation = 11;
            break;

        case 'K':
            *foundation = 12;
            break;

        default:
            return BLACK_HOLE_SOLVER__UNKNOWN_RANK;
    }

    (*s)++;

    switch (*(*s))
    {
        case 'H':
        case 'S':
        case 'D':
        case 'C':
            break;
        default:
            return BLACK_HOLE_SOLVER__UNKNOWN_SUIT;
    }
    (*s)++;

    return BLACK_HOLE_SOLVER__SUCCESS;
}


extern int DLLEXPORT black_hole_solver_read_board(
    black_hole_solver_instance_t * instance_proto,
    const char * board_string,
    int * error_line_number
)
{
    const char * s, * match;
    bhs_solver_t * solver;
    int ret_code, col_idx;

    solver = (bhs_solver_t *)instance_proto;

    s = board_string;

    /* Read the foundations. */

    while ((*s) == '\n')
    {
        s++;
    }

    match = "Foundations: ";
    if (!strcmp(s, match))
    {
        *error_line_number = 1;
        return BLACK_HOLE_SOLVER__FOUNDATIONS_NOT_FOUND_AT_START;
    }

    s += strlen(match);

    ret_code =
        parse_card(&s,
            &(solver->initial_foundation),
            solver->initial_foundation_string
        );

    if (ret_code)
    {
        *error_line_number = 1;
        return ret_code;
    }

    if (*(s++) != '\n')
    {
        *error_line_number = 1;
        return BLACK_HOLE_SOLVER__TRAILING_CHARS;
    }

    for(col_idx = 0; col_idx < MAX_NUM_COLUMNS; col_idx++)
    {
        int pos_idx = 0;
        while ((*s != '\n') && (*s != '\0'))
        {
            if (pos_idx == MAX_NUM_CARDS_IN_COL)
            {
                *error_line_number = 2+col_idx;
                return BLACK_HOLE_SOLVER__TOO_MANY_CARDS;
            }

            ret_code =
                parse_card(&s,
                    &(solver->board_values[col_idx][pos_idx]),
                    solver->initial_board_card_strings[col_idx][pos_idx]
                );

            if (ret_code)
            {
                *error_line_number = 2+col_idx;
                return ret_code;
            }

            while ((*s) == ' ')
            {
                s++;
            }

            pos_idx++;
        }

        solver->initial_lens[col_idx] = pos_idx;

        if (*s == '\0')
        {
            *error_line_number = 2+col_idx;
            return BLACK_HOLE_SOLVER__NOT_ENOUGH_COLUMNS;
        }
        else
        {
            s++;
        }
    }

    return BLACK_HOLE_SOLVER__SUCCESS;
}

DLLEXPORT extern int black_hole_solver_set_max_iters_limit(
    black_hole_solver_instance_t * instance_proto,
    long limit
)
{
    bhs_solver_t * solver;

    solver = (bhs_solver_t *)instance_proto;
    solver->max_iters_limit = limit;

    return BLACK_HOLE_SOLVER__SUCCESS;
}


extern int DLLEXPORT black_hole_solver_run(
    black_hole_solver_instance_t * ret_instance
)
{
    bhs_solver_t * solver;
    bhs_state_key_value_pair_t * init_state;
    bhs_state_key_value_pair_t state;
    bhs_state_key_value_pair_t next_state;

    int four_cols_idx, four_cols_offset;
    bhs_state_key_value_pair_t * queue;
    int queue_len, queue_max_len;
    int foundations;
    fcs_bool_t no_cards;
    int col_idx, pos;
    bhs_rank_t card;
    long iterations_num, num_states_in_collection;
    long max_iters_limit;

    solver = (bhs_solver_t *)ret_instance;

    init_state = &(solver->init_state);
    memset(init_state, '\0', sizeof(*init_state));
    init_state->key.foundations = solver->initial_foundation;

    max_iters_limit = solver->max_iters_limit;

    if (max_iters_limit < 0)
    {
        max_iters_limit = LONG_MAX;
    }

    for (four_cols_idx = 0, four_cols_offset = 0; four_cols_idx < 4; four_cols_idx++, four_cols_offset += 4)
    {
        init_state->key.data[four_cols_idx] =
            (unsigned char)
            (
              (solver->initial_lens[four_cols_offset])
            | (solver->initial_lens[four_cols_offset+1] << 2)
            | (solver->initial_lens[four_cols_offset+2] << 4)
            | (solver->initial_lens[four_cols_offset+3] << 6)
            )
            ;
    }
    /* Only one left. */
    init_state->key.data[four_cols_idx] = (unsigned char)(solver->initial_lens[four_cols_offset]);

    num_states_in_collection = 0;
    iterations_num = 0;

    bh_solve_hash_insert(
        &(solver->positions),
        init_state
    );

    num_states_in_collection++;

    queue_max_len = 64;

    queue = malloc(sizeof(queue[0]) * queue_max_len);

    queue_len = 0;
    queue[queue_len++] = (*init_state);

    while (queue_len > 0)
    {
        state = queue[--queue_len];
        iterations_num++;

        foundations = state.key.foundations;

        no_cards = TRUE;

        for (col_idx = 0 ; col_idx < MAX_NUM_COLUMNS ; col_idx++)
        {
            if ((pos = (
                (state.key.data[(col_idx >> 2)] >> ((col_idx&(4-1))<<1))
                    &
                    (4-1)
                )
            ))
            {
                no_cards = FALSE;

                card = solver->board_values[col_idx][pos-1];

                if (abs(card-foundations)%(MAX_RANK-1) == 1)
                {
                    next_state = state;
                    next_state.key.foundations = card;
                    next_state.key.data[(col_idx>>2)] &=
                        (~(0x3 << ((col_idx&0x3)<<1)));
                    next_state.key.data[(col_idx>>2)] |=
                        ((pos-1) << ((col_idx&0x3)<<1));
                    next_state.value.parent_state = state.key;
                    next_state.value.col_idx = col_idx;

                    if (! bh_solve_hash_insert(
                        &(solver->positions),
                        &next_state
                        )
                    )
                    {
                        num_states_in_collection++;
                        /* It's a new state - put it in the queue. */
                        queue[queue_len++] = next_state;

                        if (queue_len == queue_max_len)
                        {
                            queue = realloc(
                                queue,
                                sizeof(queue[0]) * (queue_max_len += 64)
                            );
                        }
                    }
                }
            }
        }

        if (no_cards)
        {
            solver->final_state = state;

            solver->iterations_num = iterations_num;
            solver->num_states_in_collection = num_states_in_collection;

            free(queue);

            return BLACK_HOLE_SOLVER__SUCCESS;
        }
        else
        {
            if (iterations_num == max_iters_limit)
            {
                solver->iterations_num = iterations_num;
                solver->num_states_in_collection = num_states_in_collection;

                free(queue);

                return BLACK_HOLE_SOLVER__OUT_OF_ITERS;
            }
        }
    }

    solver->iterations_num = iterations_num;
    solver->num_states_in_collection = num_states_in_collection;

    free(queue);

    return BLACK_HOLE_SOLVER__NOT_SOLVABLE;
}

extern int DLLEXPORT black_hole_solver_free(
    black_hole_solver_instance_t * instance_proto
)
{
    bhs_solver_t * solver;

    solver = (bhs_solver_t *)instance_proto;

    bh_solve_hash_free(&(solver->positions));

    free(solver);

    return BLACK_HOLE_SOLVER__SUCCESS;
}

static int suit_char_to_index(char suit)
{
    switch (suit)
    {
        case 'H':
            return 0;
        case 'C':
            return 1;
        case 'D':
            return 2;
        case 'S':
            return 3;
        default:
            return -1;
    }
}

DLLEXPORT extern int black_hole_solver_get_next_move(
    black_hole_solver_instance_t * instance_proto,
    int * col_idx_ptr,
    int * card_rank_ptr,
    int * card_suit_ptr /*  H=0, C=1, D=2, S=3 */
)
{
    bhs_solver_t * solver;

    solver = (bhs_solver_t *)instance_proto;

    if (! solver->states_in_solution)
    {
        bhs_state_key_value_pair_t * states;
        bhs_state_key_value_pair_t * key_ptr;
        bhs_state_key_value_pair_t temp_state;

        int i, num_states, max_num_states;

        num_states = 0;
        max_num_states = 53;

        states = malloc(sizeof(states[0]) * max_num_states);

        states[num_states] = (solver->final_state);

        while (memcmp(
            &(states[num_states].key),
            &(solver->init_state.key),
            sizeof(states[num_states].key)
        ))
        {
            if (num_states == max_num_states)
            {
                states =
                    realloc(
                        states,
                        sizeof(states[0]) * (max_num_states += 16)
                    );
            }

            key_ptr = (bhs_state_key_value_pair_t *)&(states[num_states].value.parent_state);
            /* Look up the next state in the positions associative array. */
            bh_solve_hash_get(
                &(solver->positions),
                key_ptr,
                states+(++num_states)
            );
        }

        num_states++;

        /* Reverse the list in place. */
        for (i = 0 ; i < (num_states >> 1) ; i++)
        {
            temp_state = states[i];
            states[i] = states[num_states-1-i];
            states[num_states-1-i] = temp_state;
        }

        solver->states_in_solution = states;
        solver->num_states_in_solution = num_states;
        solver->current_state_in_solution_idx = 0;
    }

    if (solver->current_state_in_solution_idx == solver->num_states_in_solution-1)
    {
        *col_idx_ptr = *card_rank_ptr = *card_suit_ptr = -1;
        return BLACK_HOLE_SOLVER__END;
    }

    {
        bhs_state_key_value_pair_t next_state;
        int height;

        next_state = solver->states_in_solution[
            ++solver->current_state_in_solution_idx
            ];

        *col_idx_ptr = next_state.value.col_idx;
        height =
        (
        (
            (next_state.key.data[(*col_idx_ptr)>>2]
                >>
            (((*col_idx_ptr)&0x3) << 1)) & 0x3
        )
        );

        (*card_rank_ptr) = solver->board_values[*col_idx_ptr][height]+1;
        (*card_suit_ptr) = suit_char_to_index(solver->initial_board_card_strings[*col_idx_ptr][height][1]);

        return BLACK_HOLE_SOLVER__SUCCESS;
    }
}

DLLEXPORT extern long black_hole_solver_get_num_states_in_collection(
    black_hole_solver_instance_t * instance_proto
)
{
    return ((bhs_solver_t *)instance_proto)->num_states_in_collection;
}

DLLEXPORT extern long black_hole_solver_get_iterations_num(
    black_hole_solver_instance_t * instance_proto
)
{
    return ((bhs_solver_t *)instance_proto)->iterations_num;
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.