Last active
July 26, 2020 09:04
-
-
Save AnaTofuZ/6535103fe77f4fb2d80b1ee84748b7fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
my $max_height = shift; | |
my $max_width = shift; | |
# 0 ------------- + | |
# | | |
# | | |
# | | |
# | | |
# | | |
# | | |
# + | |
my $status = { | |
width => 0, | |
height => 0, | |
dx => 1, #右 | |
dy => 1,#下 | |
}; | |
my $counter = 1; | |
while (1) { | |
my $new_status = next_status($status); | |
print "$counter ($new_status->{height}, $new_status->{width})\n"; | |
if (is_goal($new_status->{height}, $new_status->{width}) && $counter != 1) { | |
print "GOAL!\n"; | |
exit 0; | |
} | |
$status = $new_status; | |
$counter++; | |
} | |
sub is_goal { | |
my ($height, $width) = @_; | |
if (($width == 1 ) || $width == $max_width) { | |
return 1 if ($height == 1); #左右の上の角 | |
return 1 if ($height == $max_height); #左右の下の角 | |
} | |
return 0; | |
} | |
sub next_status { | |
my $status = shift; | |
my ($new_height, $new_dy) = new_coordinate($status->{height}, $status->{dy}, $max_height); | |
my ($new_width, $new_dx) = new_coordinate($status->{width}, $status->{dx}, $max_width); | |
my $new_status = { | |
width => $new_width, | |
height => $new_height, | |
dx => $new_dx, | |
dy => $new_dy, | |
}; | |
return $new_status; | |
} | |
sub new_coordinate { | |
my ($coordinate, $d, $max_coordinate) = @_; | |
my $new_coordinate = $coordinate + $d; | |
my $new_d = $d; | |
if ($new_coordinate < 1 ) { #上もしくは左の壁 | |
$new_coordinate += 2; #-1が来ているので2を足して1にする | |
$new_d *= -1; | |
} | |
if ($new_coordinate > $max_coordinate) { #下もしくは右の壁 | |
$new_coordinate -= 2; | |
$new_d *= -1; | |
} | |
return $new_coordinate, $new_d; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment