Created
August 23, 2019 10:16
-
-
Save kaskichandrakant/5ce58376f168e858a103278a7a2953e8 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
let ground = [ | |
[1, 1, 0, 0, 0], | |
[0, 1, 0, 0, 0], | |
[0, 1, 1, 1, 2], | |
[0, 1, 1, 0, 0], | |
[0, 0, 0, 0, 0], | |
] | |
const initialPosition = [0, 0] | |
let pathIsInTrace = (trace, pos) => { | |
return trace.find(function (element) { | |
return element[0] == pos[0] && element[1] == pos[1] | |
}) | |
} | |
let findNeighbours = function (ground, pos) { | |
const xLength = ground[0].length; | |
const yLength = ground.length; | |
const directions = [[0, -1], [0, 1], [-1, 0], [1, 0]] | |
const allNeighbours = directions.map(direction => { | |
return [pos[0] + direction[0], pos[1] + direction[1]] | |
}) | |
const validNeighbours = allNeighbours.filter(neighbour => { | |
return (neighbour[0] >= 0 && neighbour[1] >= 0) && (neighbour[0] < xLength && neighbour[1] <= yLength) | |
}) | |
return validNeighbours; | |
} | |
let availablePaths = (ground, neighbours) => { | |
return neighbours.filter((neighbour) => { | |
return ground[neighbour[0]][neighbour[1]] !== 0; | |
}) | |
} | |
const hasReachedDestination = (ground, pos) => { | |
return ground[pos[0]][pos[1]] === 2; | |
} | |
const hasReachedEnd = (paths) => { | |
return paths.length === 0 | |
} | |
const findPath = function (ground, currentPosition, trace) { | |
let neighbours = findNeighbours(ground, currentPosition) | |
trace.push(currentPosition) | |
let openPaths = availablePaths(ground, neighbours) | |
let newPaths = openPaths.filter((path) => !pathIsInTrace(trace, path)) | |
if (hasReachedDestination(ground, currentPosition)) { | |
console.log(trace, "DESTINATION") | |
} | |
if (hasReachedEnd(newPaths)) { | |
console.log(trace, "END") | |
} | |
newPaths.forEach(path => { | |
return findPath(ground, path, trace) | |
}) | |
} | |
console.log(findPath(ground, [0, 0], [])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment