Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
How to find the next position in a 2D array based on the current position?

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".

[
 [1,  2,  3,  4],
 [5,  6,  7,  8],
 [9, 10, 11, 12]
]

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  • 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.

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

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda