Source

LM-Solve Source / lib / Games / LMSolve / Base.pm

  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
package Games::LMSolve::Base;

use strict;

use Getopt::Long;

use vars qw($VERSION);

$VERSION = '0.7.8';

use Exporter;

use vars qw(@ISA @EXPORT_OK);

@ISA=qw(Exporter);

@EXPORT_OK=qw(%cell_dirs);

no warnings qw(recursion);

use vars qw(%cell_dirs);

%cell_dirs = 
    (
        'N' => [0,-1],
        'NW' => [-1,-1],
        'NE' => [1,-1],
        'S' => [0,1],
        'SE' => [1,1],
        'SW' => [-1,1],
        'E' => [1,0],
        'W' => [-1,0],
    );

=head1 NAME

Games::LMSolve::Base - base class for puzzle solvers.

=head1 SYNOPSIS

    package MyPuzzle::Solver;
    
    @ISA = qw(Games::LMSolve::Base);

    # Override these methods:

    sub input_board { ... }
    sub pack_state { ... }
    sub unpack_state { ... }
    sub display_state { ... }
    sub check_if_final_state { ... }
    sub enumerate_moves { ... }
    sub perform_move { ... }

    # Optionally: 
    sub render_move { ... }
    sub check_if_unsolvable { ... }

    package main;

    my $self = MyPuzzle::Solver->new();

    $self->solve_file($filename);

=head1 DESCRIPTION
    
This class implements a generic solver for single player games. In order
to use it, one must inherit from it and implement some abstract methods.
Afterwards, its interface functions can be invoked to actually solve
the game.

=head1 Methods to Override

=cut
    

sub new
{
    my $class = shift;

    my $self = {};

    bless $self, $class;

    $self->initialize(@_);

    return $self;    
}

sub initialize
{
    my $self = shift;

    $self->{'state_collection'} = { };
    $self->{'cmd_line'} = { };

    $self->{'num_iters'} = 0;

    return 0;
}

sub die_on_abstract_function
{
    my ($package, $filename, $line, $subroutine, $hasargs,
        $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
    die ("The abstract function $subroutine() was " . 
        "called, while it needs to be overrided by the derived class.\n");
}

=head2 input_board($self, $file_spec);

This method is responsible to read the "board" (the permanent parameters) of 
the puzzle and its initial state. It should place the board in the object's
keys, and return the initial state. (in unpacked format).

Note that $file_spec can be either a filename (if it's a string) or a reference
to a filehandle, or a refernce to the text of the board. input_board() should
handle all cases.

=cut

sub input_board
{
    return &die_on_abstract_function();
}

=head2 pack_state($self, $state_vector)

This function accepts a state in unpacked form and should return it in packed
format. A state in unpacked form can be any perl scalar (as complex as you 
like). A state in packed form must be a string.

=cut

# A function that accepts the expanded state (as an array ref)
# and returns an atom that represents it.
sub pack_state
{
    return &die_on_abstract_function();
}

=head2 unpack_state($self, $packed_state)

This function accepts a state in a packed form and should return it in its
expanded form.

=cut

# A function that accepts an atom that represents a state 
# and returns an array ref that represents it.
sub unpack_state
{
    return &die_on_abstract_function();
}

=head2 display_state($self, $packed_state)

Accepts a packed state and should return the user-readable string 
representation of the state.

=cut

# Accept an atom that represents a state and output a 
# user-readable string that describes it.
sub display_state
{
    return &die_on_abstract_function();
}

=head2 check_if_final_state($self, $state_vector)

This function should return 1 if the expanded state $state_vector is 
a final state, and the game is over.

=cut

sub check_if_final_state
{
    return &die_on_abstract_function();
}

=head2 enumerate_moves($self, $state_vector)

This function accepts an expanded state and should return an array of moves
that can be performed on this state.

=cut

# This function enumerates the moves accessible to the state.
# If it returns a move, it still does not mean that this move is a valid 
# one. I.e: it is possible that it is illegal to perform it.
sub enumerate_moves
{
    return &die_on_abstract_function();
}

=head2 perform_move($self, $state_vector, $move)

This method accepts an expanded state and a move. It should try to peform
the move on the state. If it is successful, it should return the new
state. Else, it should return undef, to indicate that the move cannot
be performed.

=cut

# This function accepts a state and a move. It tries to perform the
# move on the state. If it is succesful, it returns the new state.
#
# Else, it returns undef to indicate that the move is not possible.
sub perform_move
{
    return &die_on_abstract_function();
}

=head2 check_if_unsolvable($self, $state_vector) (optional over-riding)

This method returns the verdict if C<$state_vector> cannot be solved. This
method defaults to returning 0, and it is usually safe to keep it that way.

=cut

# This function checks if a state it receives as an argument is a
# dead-end one.
sub check_if_unsolvable
{
    return 0;
}

=head2 render_move($self, $move) (optional overriding)

This function returns the user-readable stringified represtantion of a
move.

=cut

# This is a function that should be overrided in case
# rendering the move into a string is non-trivial.
sub render_move
{
    my $self = shift;

    my $move = shift;

    return $move;
}

=head1 API

=cut

sub solve_brfs_or_dfs
{
    my $self = shift;
    my $state_collection = $self->{'state_collection'};
    my $initial_state = shift;
    my $is_dfs = shift;
    my %args = @_;
    
    my $run_time_display = $self->{'cmd_line'}->{'rt_states_display'};
    my $rtd_callback = $self->{'run_time_display_callback'};
    my $max_iters = $args{'max_iters'} || (-1);
    my $not_check_iters = ($max_iters < 0);
    
    my (@queue, $state, $coords, $depth, @moves, $new_state);

    push @queue, $initial_state;

    my $num_iters = $self->{'num_iters'};
    my @ret;

    while (scalar(@queue) && 
           (
               $not_check_iters || 
               ($max_iters > $num_iters)
           )
          )
    {
        if ($is_dfs)
        {
            $state = pop(@queue);
        }
        else
        {
            $state = shift(@queue);
        }
        $coords = $self->unpack_state($state);
        $depth = $state_collection->{$state}->{'d'};

        $num_iters++;

        # Output the current state to the screen, assuming this option
        # is set.
        if ($run_time_display)
        {
            $rtd_callback->(
                $self,
                'depth' => $depth,
                'state' => $coords,
                'move' => $state_collection->{$state}->{'m'},
                'num_iters' => $num_iters,
            );
            # print ((" " x $depth) . join(",", @$coords) . " M=" . $self->render_move($state_collection->{$state}->{'m'}) ."\n");
        }
        
        if ($self->check_if_unsolvable($coords))
        {
            next;
        }

        if ($self->check_if_final_state($coords))
        {
            @ret = ("solved", $state);
            goto Return;
        }
        
        @moves = $self->enumerate_moves($coords);

        foreach my $m (@moves)
        {
            my $new_coords = $self->perform_move($coords, $m);
            # Check if this move leads nowhere and if so - skip to the next move.
            if (!defined($new_coords))
            {
                next;
            }
            
            $new_state = $self->pack_state($new_coords);
            if (! exists($state_collection->{$new_state}))
            {
                $state_collection->{$new_state} = 
                    {
                        'p' => $state, 
                        'm' => $m, 
                        'd' => ($depth+1)
                    };
                push @queue, $new_state;
            }
        }
    }

    @ret = ("unsolved", undef);
    
    Return:

    $self->{'num_iters'} = $num_iters;

    return @ret;
}

sub run_length_encoding
{
    my @moves = @_;
    my @ret = ();

    my $prev_m = shift(@moves);
    my $count = 1;
    my $m;
    while ($m = shift(@moves))
    {
        if ($m eq $prev_m)
        {
            $count++;            
        }
        else
        {
            push @ret, [ $prev_m, $count];
            $prev_m = $m;
            $count = 1;
        }
    }
    push @ret, [$prev_m, $count];

    return @ret;    
}

my %scan_functions =
(
    'dfs' => sub {
        my $self = shift;
        my $initial_state = shift;

        return $self->solve_brfs_or_dfs($initial_state, 1, @_);
    },
    'brfs' => sub {
        my $self = shift;
        my $initial_state = shift;

        return $self->solve_brfs_or_dfs($initial_state, 0, @_);
    },
);


sub solve_state
{
    my $self = shift;
    
    my $initial_coords = shift;
    
    my $state = $self->pack_state($initial_coords);
    $self->{'state_collection'}->{$state} = {'p' => undef, 'd' => 0};

    return 
        $scan_functions{$self->{'cmd_line'}->{'scan'}}->(
            $self,
            $state,
            @_
        );
}

sub solve_file
{
    my $self = shift;
    
    my $filename = shift;

    my $initial_coords = $self->input_board($filename);

    return $self->solve_state($initial_coords);
}

sub display_solution
{
    my $self = shift;

    my @ret = @_;

    my $state_collection = $self->{'state_collection'};

    my $output_states = $self->{'cmd_line'}->{'output_states'};
    my $to_rle = $self->{'cmd_line'}->{'to_rle'};

    my $echo_state = 
        sub {
            my $state = shift;
            return $output_states ? 
                ($self->display_state($state) . ": Move = ") :
                "";
        };    

    print $ret[0], "\n";

    if ($ret[0] eq "solved")
    {
        my $key = $ret[1];
        my $s = $state_collection->{$key};
        my @moves = ();
        my @states = ($key);

        while ($s->{'p'})
        {
            push @moves, $s->{'m'};
            $key = $s->{'p'};
            $s = $state_collection->{$key};
            push @states, $key;
        }
        @moves = reverse(@moves);
        @states = reverse(@states);
        if ($to_rle)
        {
            my @moves_rle = &run_length_encoding(@moves);
            my ($m, $sum);

            $sum = 0;
            foreach $m (@moves_rle)
            {            
                print $echo_state->($states[$sum]) . $self->render_move($m->[0]) . " * " . $m->[1] . "\n";
                $sum += $m->[1];
            }
        }
        else
        {
            my ($a);
            for($a=0;$a<scalar(@moves);$a++)
            {
                print $echo_state->($states[$a]) . $self->render_move($moves[$a]) . "\n";
            }            
        }
        if ($output_states)
        {
            print $self->display_state($states[$a]), "\n";
        }
    }
}

sub _default_rtd_callback
{
    my $self = shift;

    my %args = @_;
    print ((" " x $args{depth}) . join(",", @{$args{state}}) . " M=" . $self->render_move($args{move}) ."\n");
}

sub main
{
    my $self = shift;

    # This is a flag that specifies whether to present the moves in Run-Length
    # Encoding.
    my $to_rle = 1;
    my $output_states = 0;
    my $scan = "brfs";
    my $run_time_states_display = 0;

    #my $p = Getopt::Long::Parser->new();
    if (! GetOptions('rle!' => \$to_rle, 
        'output-states!' => \$output_states,
        'method=s' => \$scan,
        'rtd!' => \$run_time_states_display,
        ))
    {
        die "Incorrect options passed!\n"
    }

    if (!exists($scan_functions{$scan}))
    {
        die "Unknown scan \"$scan\"!\n";
    }

    $self->{'cmd_line'}->{'to_rle'} = $to_rle;
    $self->{'cmd_line'}->{'output_states'} = $output_states;
    $self->{'cmd_line'}->{'scan'} = $scan;
    $self->set_run_time_states_display($run_time_states_display && \&_default_rtd_callback);

    my $filename = shift(@ARGV) || "board.txt";

    my @ret = $self->solve_file($filename);

    $self->display_solution(@ret);
}

sub set_run_time_states_display
{
    my $self = shift;
    my $states_display = shift;

    if (! $states_display)
    {
        $self->{'cmd_line'}->{'rt_states_display'} = undef;
    }
    else
    {
        $self->{'cmd_line'}->{'rt_states_display'} = 1;
        $self->{'run_time_display_callback'} = $states_display;
    }

    return 0;
}


1;
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.