Created
May 9, 2017 12:18
-
-
Save petar-dambovaliev/f43e38c266d75738cf1060f2807d3781 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
/* | |
You will be given a 2D array of the maze and an array of directions. | |
Your task is to follow the directions given. | |
If you reach the end point before all your moves have gone, you should return Finish. | |
If you hit any walls or go outside the maze border, you should return Dead. | |
If you find yourself still in the maze after using all the moves, you should return Lost. | |
maze = [[1,1,1,1,1,1,1], | |
[1,0,0,0,0,0,3], | |
[1,0,1,0,1,0,1], | |
[0,0,1,0,0,0,1], | |
[1,0,1,0,1,0,1], | |
[1,0,0,0,0,0,1], | |
[1,2,1,0,1,0,1]] | |
0 = Safe place to walk | |
1 = Wall | |
2 = Start Point | |
3 = Finish Point | |
direction = ["N","N","N","N","N","E","E","E","E","E"] == "Finish" | |
RULES | |
1. The Maze array will always be square i.e. N x N but its size and content will alter from test to test. | |
2. The start and finish positions will change for the final tests. | |
3. The directions array will always be in upper case and will be in the format of N = North, E = East, W = West and S = South. | |
*/ | |
class Maze | |
{ | |
private $matrix; | |
private $moves; | |
private $current; | |
private $start = 2; | |
private $finish = 3; | |
private $wall = 1; | |
private $size; | |
private $directions = [ | |
'N' => [-1, 0], | |
'E' => [0, 1], | |
'S' => [1, 0], | |
'W' => [0, -1] | |
]; | |
private $msg = [ | |
'finish' => 'Finish', | |
'dead' => 'Dead', | |
'lost' => 'Lost' | |
]; | |
function __construct(array $matrix, array $moves) | |
{ | |
$this->matrix = $matrix; | |
$this->moves = $moves; | |
$this->size = count($matrix) - 1; | |
$this->setStart(); | |
} | |
public function analyzeMoves() | |
{ | |
foreach($this->moves as $k=>$move) { | |
$movedTo = $this->move($move); | |
if ($movedTo == $this->wall) { | |
return $this->msg['dead']; | |
} | |
if ($movedTo == $this->finish && $k <= | |
count($this->moves) | |
) { | |
return $this->msg['finish']; | |
} | |
} | |
return $this->msg['lost']; | |
} | |
private function move(string $dir) | |
{ | |
$n = $this->current[0] += ($this->directions[$dir][0]); | |
$m = $this->current[1] += ($this->directions[$dir][1]); | |
if ($n < 0|| | |
$m < 0 || | |
$n > $this->size || | |
$m > $this->size | |
) { | |
return $this->wall; | |
} | |
return $this->matrix[$this->current[0]][$this->current[1]]; | |
} | |
private function setStart() | |
{ | |
foreach ($this->matrix as $k=>$lane) { | |
if (($start = array_search($this->start, $lane)) !== false) { | |
return $this->current = [$k, $start]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment