Suppose I have an array with 3 rows and 4 columns const arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
and I give an input like ["straight", "right", "left"]
and the initial position is arr[0][0]
and the initial direction is "east"
.
JavaScript
x
6
1
[
2
[1, 2, 3, 4],
3
[5, 6, 7, 8],
4
[9, 10, 11, 12]
5
]
6
From initial position going "straight"
should give 2
. And then from here going "right"
should give 6
and finally a "left"
from here should give 7
.
How can I achieve this in JavaScript?
Advertisement
Answer
- Create a map that gives the next direction based on the current direction and move.
- Now for every move calculate the next direction and check if it’s a valid move, if it is then return the next value, position & direction and repeat this for every move.
- If the move is invalid at any point this solution throws an error, you can customize the error handling according to your needs.
JavaScript
1
66
66
1
const nextDirMap = {
2
north: { left: "west", right: "east", straight: "north" },
3
south: { left: "east", right: "west", straight: "south" },
4
east: { left: "north", right: "south", straight: "east" },
5
west: { left: "south", right: "north", straight: "west" },
6
};
7
8
function getNextPos(grid, currPos, currDir, move) {
9
const nextDir = nextDirMap[currDir][move];
10
const [r, c] = currPos;
11
const maxRowLength = grid.length;
12
const maxColLength = grid[0].length;
13
14
switch (nextDir) {
15
case "north": {
16
if (r <= 0) {
17
throw "Unable to move";
18
}
19
return { val: grid[r - 1][c], pos: [r - 1, c], dir: "north" };
20
}
21
case "south": {
22
if (r >= maxRowLength) {
23
throw "Unable to move";
24
}
25
return { val: grid[r + 1][c], pos: [r + 1, c], dir: "south" };
26
}
27
case "east": {
28
if (c >= maxColLength) {
29
throw "Unable to move";
30
}
31
return { val: grid[r][c + 1], pos: [r, c + 1], dir: "east" };
32
}
33
case "west": {
34
if (c <= 0) {
35
throw "Unable to move";
36
}
37
return { val: grid[r][c - 1], pos: [r, c - 1], dir: "west" };
38
}
39
}
40
}
41
42
function solution(grid, initPos, initDir, moves) {
43
let currPos = initPos;
44
let currDir = initDir;
45
let currVal;
46
moves.forEach((move) => {
47
let { val, pos, dir } = getNextPos(grid, currPos, currDir, move);
48
currDir = dir;
49
currPos = pos;
50
currVal = val;
51
});
52
return currVal;
53
}
54
55
const res = solution(
56
[
57
[1, 2, 3, 4],
58
[5, 6, 7, 8],
59
[9, 10, 11, 12],
60
],
61
[0, 0],
62
"east",
63
["straight", "right", "left"]
64
);
65
66
console.log(res); // 7
Note the solution assumes that you’ve a valid grid (same no. of columns for all rows) and it has at least one row.