forked from manwar/perlweeklychallenge-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch-2.raku
executable file
·133 lines (102 loc) · 2.68 KB
/
ch-2.raku
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
#!/usr/bin/raku
class Position {
has Int $.row is rw;
has Int $.col is rw;
method new( $row, $col ) {
self.bless(:$row, :$col);
}
method Str {
('a'.ord + $!col).chr ~ (8 - $!row).Str;
}
}
multi sub infix:<==>(Position $a, Position $b) returns Bool {
return $a.row == $b.row && $a.col == $b.col;
}
sub estimatedCost(Position $position, Position $goal) {
return 1;
}
sub stepCost(Position $position) {
return 1;
}
sub tryMove(Position $position, Position $delta) {
my $dest = $position.clone;
$dest.row += $delta.row;
$dest.col += $delta.col;
return ($dest.row >= 0 && $dest.row < 8 && $dest.col >= 0 && $dest.col < 8)
?? $dest
!! Nil;
}
sub possibleMoves(Position $position, Position $target) {
state @deltas = [
Position.new(-2, -1),
Position.new(-2, 1),
Position.new(-1, 2),
Position.new(1, 2),
Position.new(2, 1),
Position.new(2, -1),
Position.new(-1, -2),
Position.new(1, -2)
];
my @moves;
for @deltas -> $delta {
my $move = tryMove($position, $delta);
if $move {
@moves.push($move);
}
}
@moves = @moves.sort({
estimatedCost($^a, $target) < estimatedCost($^b, $target);
});
return @moves;
}
sub search(Position @path, Position $target, Int $cost, Int $bound) {
my $current = @path[*-1];
my $estimate = $cost + estimatedCost($current, $target);
if $estimate > $bound {
return $estimate;
}
if $current == $target {
return -∞;
}
my $min = ∞;
for possibleMoves($current, $target) -> $move {
if $move ⊄ @path {
@path.push($move);
my $t = search(@path, $target, $cost + stepCost($move), $bound);
if $t == -∞ {
return -∞;
}
if $t < $min {
$min = $t;
}
@path.pop;
}
}
return $min;
}
sub makePath(Position $current, Position $target) {
my Position @path = [ $current ];
my $bound = estimatedCost($current, $target);
loop {
my $t = search(@path, $target, 0, $bound);
if $t ~~ -∞ {
last;
}
# Can't solve; this shouldn't happen.
if $t ~~ ∞ {
last;
}
$bound = $t;
}
return @path;
}
sub MAIN(
Str $s where $s.chars == 2 ,
Str $e where $e.chars == 2
) {
my ($sc, $sr) = $s.comb;
my ($ec, $er) = $e.comb;
my $start = Position.new('8'.ord - $sr.ord, $sc.ord - 'a'.ord );
my $end = Position.new('8'.ord - $er.ord, $ec.ord - 'a'.ord);
say makePath($start, $end).elems - 1;
}