const park = ["SOO", "OOO", "OOO"];
const routes = ["E 2", "S 2", "W 1"];
const result = [2, 1];
const DIR = {
N: [-1, 0],
E: [0, 1],
S: [1, 0],
W: [0, -1],
};
function solution(park, routes) {
var answer = [];
const width = park.length;
const height = park[0].length;
let start = [];
for (let i = 0; i < park.length; i++) {
for (let j = 0; j < park[i].length; j++) {
if (park[i][j] === "S") {
start = [i, j];
routes.forEach((route) => {
route = route.split(" ");
start = search(start, route[0], route[1]);
});
return start;
}
}
}
return start;
function search(start, dir, count) {
const [x, y] = DIR[dir];
let tmp = [...start];
const maxX = count * x;
const maxY = count * y;
if (
tmp[0] + maxX >= width ||
tmp[1] + maxY >= height ||
tmp[0] + maxX < 0 ||
tmp[1] + maxY < 0
) {
return start;
}
for (let i = 0; i < count; i += 1) {
const nextX = tmp[0] + x;
const nextY = tmp[1] + y;
if (park[nextX][nextY] === "X") {
return start;
}
tmp = [nextX, nextY];
}
return tmp;
}
}
const DIR = {
N: [-1, 0],
E: [0, 1],
S: [1, 0],
W: [0, -1],
};
function solution(park, routes) {
const [width, height] = [park.length, park[0].length];
let start = findStart(park);
for (const route of routes) {
const [dir, count] = route.split(" ");
console.log(start);
if (isNotValidPosition(start, dir, count)) {
continue;
}
start = move(start, dir, parseInt(count));
}
return start;
function move(position, dir, count) {
const [x, y] = DIR[dir];
let [curX, curY] = position;
for (let i = 0; i < count; i++) {
const [nextX, nextY] = [curX + x, curY + y];
if (park[nextX][nextY] === "X") {
return position;
}
[curX, curY] = [nextX, nextY];
}
return [curX, curY];
}
function isNotValidPosition(start, dir, count) {
const [x, y] = DIR[dir];
const [maxX, maxY] = [count * x, count * y];
const [currX, currY] = start;
if (
currX + maxX >= width ||
currY + maxY >= height ||
currX + maxX < 0 ||
currY + maxY < 0
) {
return true;
}
return false;
}
}
function findStart(park) {
for (let i = 0; i < park.length; i++) {
for (let j = 0; j < park[i].length; j++) {
if (park[i][j] === "S") {
return [i, j];
}
}
}
}