const nextDirMap = {
north: { left: "west", right: "east", straight: "north" },
south: { left: "east", right: "west", straight: "south" },
east: { left: "north", right: "south", straight: "east" },
west: { left: "south", right: "north", straight: "west" },
};
function getNextPos(grid, currPos, currDir, move) {
const nextDir = nextDirMap[currDir][move];
const [r, c] = currPos;
const maxRowLength = grid.length;
const maxColLength = grid[0].length;
switch (nextDir) {
case "north": {
if (r <= 0) {
throw "Unable to move";
}
return { val: grid[r - 1][c], pos: [r - 1, c], dir: "north" };
}
case "south": {
if (r >= maxRowLength) {
throw "Unable to move";
}
return { val: grid[r + 1][c], pos: [r + 1, c], dir: "south" };
}
case "east": {
if (c >= maxColLength) {
throw "Unable to move";
}
return { val: grid[r][c + 1], pos: [r, c + 1], dir: "east" };
}
case "west": {
if (c <= 0) {
throw "Unable to move";
}
return { val: grid[r][c - 1], pos: [r, c - 1], dir: "west" };
}
}
}
function solution(grid, initPos, initDir, moves) {
let currPos = initPos;
let currDir = initDir;
let currVal;
moves.forEach((move) => {
let { val, pos, dir } = getNextPos(grid, currPos, currDir, move);
currDir = dir;
currPos = pos;
currVal = val;
});
return currVal;
}
const res = solution(
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
],
[0, 0],
"east",
["straight", "right", "left"]
);
console.log(res); // 7