aboutsummaryrefslogtreecommitdiff
path: root/challenge-118/duane-powell/perl/ch-2.pl
blob: 8ea7b7e4866ab8add2d4034b983494144ed8249c (plain)
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
#!/usr/bin/perl
use warnings;
use strict;
use feature 'say';

=pod
    Problem: 
    https://perlweeklychallenge.org/blog/perl-weekly-challenge-118/ TASK #2

    Approach: 
    Generate all Knight moves, search via stochastic recursion at each ply, prune out obsolete paths. 
   
    Result: 
    This is script reports, in Chess notation, the best path.
    If more than one path exists it returns the first path found. 
=cut

# Slow down so we can watch the Knight move around the board 
my $sleep = shift || 0;

# Knight $N, Treasure $T, Empty $E
my ($N,$T,$E) = ('N','x','0');

# Let's go on a new Adventure!
my $AoK = AdventureOfKnight->new();

# Place Knight and Treasure on the board
$AoK->piece_put($N,1,8);
my $treasure_list = [[1,2],[2,1],[2,2],[2,3],[3,4],[5,6]]; 
#my $treasure_list = [[2,6],[3,4],[4,2],[5,4],[6,6],[7,8],[8,6],[6,5],[4,4],[2,3],[1,1]]; 
#my $treasure_list = [[1,4],[2,4],[3,4],[4,4],[5,4],[6,4],[7,4],[8,4]]; 
$AoK->piece_put($T,$_->[0],$_->[1]) foreach ( @{$treasure_list} );

# Render starting board postion
my $board = $AoK->board_render();
say $board;

# Find the shortest path to all the treasure
$AoK->shortest_path_find();

# Say best solution 
$AoK->best_path_say($board,1);
exit;


package AdventureOfKnight;
# use Data::Dumper; 
sub new {
    my $class = shift;
    my $self = {
        # Current location of Knight
        file => 0,
        rank => 0,

        # Count of treasure items
        treasure_count => 0,

        # Nested array ref indexed by file and rank, 
        # representing the state of the board, $self->{squares}[$f][$r]
        squares => [], 

        # Hash of unique board positions seen, so
        # we can short circuit recursion. 
        board_pos => {},

        # Nested array ref of moves representing current path.
        # A move is a array ref [a,b,c,d,x] where a,b is from square,
        # c,d is target square and x is capture of treasure.
        this_path => [],

        # Best solution found 
        best_path => [],
    };

    # init board to empty squares
    foreach my $r (1..8) {
        foreach my $f (1..8) {
            $self->{squares}[$f][$r] = "$E";
        }
    }

    bless $self, $class;
    return $self;
}
sub shortest_path_find {
    my $self = shift;

    # Note initial board position 
    $self->board_position_visited();

    # Recurse 
    $self->shortest_path_recurse();
}        

sub shortest_path_recurse {
    my $self = shift;

    my @move = $self->knight_moves_get();
    while (@move) {
        # Random, stochastic search 
        my $r = int(rand(scalar @move)); 
        my $move = $move[$r];
        splice @move, $r, 1;

        # Move the knight.
        $self->knight_move($move);

        # Update best path if no treasure remains on a shorter path
        if (not $self->treasure_exists() and $self->this_path_is_shorter()) {
            # copy this_path to best_path, don't forget to deference before copy
            my @this_path = @{$self->{this_path}};
            $self->{best_path} = \@this_path;
        }

        # Render and sleep so we can see the Knight move around
        my $board = $self->board_render();
        $AoK->best_path_say($board);
        sleep $sleep; 

        # Only recurse if: we have not visited this postion before and this path is shorter than best path so far
        $self->shortest_path_recurse() if ( not $self->board_position_visited() and $self->this_path_is_shorter() );

        # Undo Knight move and try another
        $self->knight_move_undo($move);
    }
}
sub treasure_exists {
    my $self = shift;
    return $self->{treasure_count} > 0;
}
sub this_path_is_shorter {
    my $self = shift;
    return (scalar @{$self->{this_path}} < scalar @{$self->{best_path}} or scalar @{$self->{best_path}} == 0);
}
sub treasure_is_here {
    my $self = shift;
    my ($f, $r) = @_;

    return 1 if ( $self->{squares}[$f][$r] eq $T );
    return 0; 
}
sub piece_put {
    my $self  = shift;
    my $piece = shift; 
    my ($f, $r) = @_;

    # A piece can be a Knight $N, Treasure $T or Empty $E.
    # It's $E when we're undo'ing a move
    if ($piece eq $N) {
        # Side effects of placing Knight:
        # Note its location
        $self->{file} = $f;  
        $self->{rank} = $r;  
        if ($self->treasure_is_here($f,$r)) {
            # decrement Treasure if capture
            $self->{treasure_count}--;
        }
    } elsif ($piece eq $T) {
        # Treasure placed if undo'ing a capture
        # or initial Treasure placement
        $self->{treasure_count}++;
    }
    # put piece at file, rank
    $self->{squares}[$f][$r] = $piece;
}
sub knight_moves_get {
    my $self = shift;

    my @move;
    my @capture;

    # Use an offset to calculate all possible Knight moves
    my $offset = [
        [ 2, -1 ], [ 2,  1 ], [ -2, 1 ], [ -2, -1 ],
        [ 1,  2 ], [ 1, -2 ], [ -1, 2 ], [ -1, -2 ],
    ];
    my $a = $self->{file};
    my $b = $self->{rank};
    foreach ( @{ $offset } ) {
        my ($x, $y) = @{$_};
        my ($c, $d) = ($a + $x, $b + $y);

        # Discard move if its off board
        next if (($c < 1 or $c > 8) or ($d < 1 or $d > 8));

        if ($self->treasure_is_here($c,$d)) {
            push @capture, [$a, $b, $c, $d, 1];
        } else {
            push @move, [$a, $b, $c, $d, 0];
        }
    }

    # Focus on captures until we get at least one solution path.
    # This will find a relatively short path quickly but maybe not the shortest.
    # We will use it, though, to prime the pump and prune long dry paths.
    return @capture if (scalar @capture > 0 and scalar @{$self->{best_path}} == 0);

    # Otherwise, return all moves
    return (@capture, @move);

}
sub knight_move {
    my $self = shift;
    my $move = shift; 
    my ($a,$b,$c,$d,$capture) = @{$move};

    # Move Knight to target square [c,d]
    $self->piece_put($N, $c, $d); 
    # Set source square [a,b] to empty 
    $self->piece_put($E, $a, $b); 

    # add move to this path
    push @{ $self->{this_path} }, $move;
}
sub knight_move_undo {
    my $self = shift;
    my $move = shift;

    my ($a,$b,$c,$d,$capture) = @{$move};
    if ( $capture ) {
        # Put treasure back 
        $self->piece_put($T, $c, $d); 
    } else {
        # Set target square to empty
        $self->piece_put($E, $c, $d); 
    }

    # Put knight back on source square 
    $self->piece_put($N, $a, $b); 

    # discard move
    pop @{ $self->{this_path} };
}
sub board_position_visited {
    my $self = shift;

    # Generate unique key to id this board position
    my $key = $self->board_position_key_gen();

    # Note the path length it took to reach this board position
    my $this_path_len = scalar @{$self->{this_path}};

    if ($self->{board_pos}{$key}) {
        # We've been here before but ...
        if ($self->{board_pos}{$key} > $this_path_len) {