A poor miner is trapped in a mine and you have to help him to get out! The mine is completely dark so you have to tell him where to go.
Implement a method solve(cave_map, miner, exit)
that has to return the path the miner must take to reach the exit as an array of moves: ['up', 'down', 'right', 'left']
. Those are the only four possible moves as the miner cannot move diagonally.
cave_map
is a 2-dimensional array of Boolean values, representing squares. false
for walls, true
for open space. It will never be larger than 5 x 5. It is laid out as an array of columns. All columns will always be the same size, though not necessarily the same size as rows (in other words, maps can be rectangular). The map will never contain any loop, so there will always be only one possible path. The map may contain dead-ends though.
miner
is the position of the miner at the start, as an object made of two zero-based integer properties, x
and y
. For example (0,0)
would be the top-left corner.
exit
is the position of the exit, in the same format as miner.
Note that the miner can't go outside the map, as it is a tunnel.
Let's take a pretty basic example :
cave_map = [[true, false], [true, true]]; solve(cave_map, (0,0), (1,1)); // Should return ['right', 'down']
Challenge maps:
A simple map. (2x2)
cave_map = [[true, false],
[true, true]];
miner = (0,0)
exit = (1,0)
A linear map. (1x4)
cave_map = [[true], [true], [true], [true]];
miner = (0,0)
exit = (3,0)
Walk around an obstacle (3x3)
cave_map = [[true, true, true],
[false, false, true],
[true, true, true]];
miner = (0,0)
exit = (2,0)
Change directions several times (5x5)
cave_map = [[true, true, false, false, false],
[false, true, true, false, false],
[false, false, true, true, false],
[false, false, false, true, true],
[false, false, false, false, true]];
miner = (0,0)
exit = (4,4)
Good luck!
Today's challenge is edited from damned3's kata on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (3)
stackblitz.com/edit/typescript-vmdbzm
Here's my solution, in Haskell. It uses the A* path-finding algorithm using Manhattan/taxi-cab distance as the heuristic.
I don't think using a list is the best data-structure for holding the open and closed sets. It isn't great for searching for a minimum and removing elements from the middle. I might revisit this and look for a better solution, but for this challenge, it's fast enough.
There are also some things in my solution that I'm not entirely happy about. For one,
getRequiredMove
isn't a complete function but I didn't like my other ideas on how to put get the Move in the Tile, so I stuck with this.Here's a solution in TypeScript.
You can see it in the Playground
Some tests at the end.