Algorithm-Search
view release on metacpan or search on metacpan
#!/usr/bin/perl
#Copyright 2008 Arthur S Goldstein
#Games Magazine, July 2008 page 54
use Test::More tests => 6;
package easy_as_one_two_three;
#our $xx = 0;
sub new {return bless {count => 0}}
sub set_rules {
my $self = shift;
my $parameters = shift;
$self->{max_row} = $parameters->{max_row};
$self->{max_column} = $parameters->{max_column};
$self->{start} = $parameters->{start};
$self->{position} = $parameters->{start};
$self->{final} = $parameters->{final};
$self->{not_allowed} = $parameters->{not_allowed};
$self->{not_allowed_count} = 0;
$self->{final_count} = 0;
for my $i (0..$self->{max_row}) {
for my $j (0..$self->{max_column}) {
if ($self->{not_allowed}->[$i]->[$j]) {
$self->{not_allowed_count}++;
}
else {
$self->{final_count}++;
}
}
}
$self->{final_count} -= 1; #start
}
sub move {
my $self = shift;
my $direction = shift;
my $length = ++$self->{count} % 3;
if ($length == 0) {$length = 3};
my $row = $self->{position}->[0];
my $column = $self->{position}->[1];
if ($direction eq 'U' || $direction eq 'UL' || $direction eq 'UR') {
if ($row - $length < 0) {return}
else {$row -= $length}
}
if ($direction eq 'D' || $direction eq 'DL' || $direction eq 'DR') {
if ($row + $length > $self->{max_row}) {return}
else {$row += $length}
}
if ($direction eq 'L' || $direction eq 'DL' || $direction eq 'UL') {
if ($column - $length < 0) {return}
else {$column -= $length}
}
if ($direction eq 'R' || $direction eq 'DR' || $direction eq 'UR') {
if ($column + $length > $self->{max_column}) {return}
else {$column += $length}
}
if ($self->{value}->[$row]->[$column]) {
return;
}
if (($self->{start}->[0]== $row) && ($self->{start}->[1] == $column)) {
return;
}
if ($self->{not_allowed}->[$row]->[$column]) {
return;
}
$self->{position} = [$row, $column];
if (($self->{final}->[0]== $row) && ($self->{final}->[1] == $column)) {
if ($self->{final_count} == $self->{count}) {return 1}
return;
}
else {
$self->{value}->[$row]->[$column] = $self->{count};
}
return 1;
}
sub copy {
my $self = shift;
my $copy = $self->new;
$copy->{max_row} = $self->{max_row};
$copy->{max_column} = $self->{max_column};
$copy->{start} = $self->{start};
$copy->{final} = $self->{final};
$copy->{final_count} = $self->{final_count};
$copy->{count} = $self->{count};
$copy->{position} = $self->{position};
$copy->{not_allowed} = $self->{not_allowed};
$copy->{not_allowed_count} = $self->{not_allowed_count};
for my $i (0..$self->{max_row}) {
for my $j (0..$self->{max_column}) {
$copy->{value}->[$i]->[$j] = $self->{value}->[$i]->[$j];
}
}
return $copy;
}
sub is_solution {
my $self = shift;
if (($self->{position}->[0] == $self->{final}->[0])
&& ($self->{position}->[1] == $self->{final}->[1])) {
return 1;
}
return 0;
}
sub next_moves {
my $self = shift;
( run in 0.572 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )