Skip to content
Advertisement

How to find the next position in a 2D array based on the current position? [closed]

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

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

Note the solution assumes that you’ve a valid grid (same no. of columns for all rows) and it has at least one row.

Advertisement