samedi 30 mai 2020

Does the order of the comparisons matter when using OR operators in IF statements?

I'm trying to get a better understanding of conditions within IF statements. When I change the order of the conditions I receive a TypeError of undefined.

I receive a TypeError: Cannot read property 'length' of undefined when the order is changed to:

if (col === maze[row].length || row < 0 || col < 0 || row === maze.length) {
    return
  }

Does the order of the comparisons matter when using OR operators in IF statements?

Working code base:

const maze = [
  [' ', ' ', ' ', '*', ' ', ' ', ' '],
  ['*', '*', ' ', '*', ' ', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', ' '],
  [' ', '*', '*', '*', '*', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', 'e'],
];

const solve = (maze, row = 0, col = 0, path = "") => {

  if (col === maze[row].length || row < 0 || col < 0 || row === maze.length) {
    return
  }

  // Base case
  if (maze[row][col] === "e") {
    return console.log(`Solved at (${row}, ${col})! Path to exit: ${path}`)

    // General case
  } else if (maze[row][col] === "*") {
    return
  }

  // Marker
  maze[row][col] = "*"

  // Right
  solve(maze, row, col + 1, path.concat("R"))

  // Down
  solve(maze, row + 1, col, path.concat("D"))

  // Left
  solve(maze, row, col - 1, path.concat("L"))

  // Up
  solve(maze, row - 1, col, path.concat("U"))

  // Remove marker
  maze[row][col] = " "
}

console.log(solve(maze));

Aucun commentaire:

Enregistrer un commentaire