0

I've working my way through codewars, and I've come across mazerunner (https://www.codewars.com/kata/maze-runner/train/javascript) I've been stumped for about 2 days!

function mazeRunner(maze, directions) {

//find start value  

var x = 0; //x position of the start point
var y = 0; //y position of the start point

for (var j = 0 ; j < maze.length ; j++){
if (maze[j].indexOf(2) != -1){
  x = j;
  y = maze[j].indexOf(2)
}
      } // end of starting position forloop

console.log(x + ', ' + y)


  for (var turn = 0 ; turn < directions.length ; turn++){


if (directions[turn] == "N"){
 x -= 1;
}
if (directions[turn] == "S"){
 x += 1;
}
if (directions[turn] == "E"){
 y += 1;
}
if (directions[turn] == "W"){
 y -= 1;
}

 if (maze[x][y] === 1){
 return 'Dead';
 }else if (maze[x][y] === 3){
 return 'Finish';
 }

if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}

}

return 'Lost';

}

When I run this, it works on most of the scenarios, however on the last one I get the following error

TypeError: Cannot read property '3' of undefined
at mazeRunner
at /home/codewarrior/index.js:87:19
at /home/codewarrior/index.js:155:5
at Object.handleError

Any help would be appreciated! I'm pulling my hair out over this one!

1 Answer 1

2

The problem of your solution is that after the move, you just check the value of maze[x][y]

In the test that fails, maze[x] will be at some point undefined (moves south for a while). I guess at that same point y would be 3, hence the error Cannot read property '3' of undefined

To avoid that, you should move up the code where you test for undefined, before trying to access the coordinates:

// move this as first check
if (maze[x] === undefined || maze[y] === undefined){
  return 'Dead';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! That worked a treat! Thanks! That makes sense and has worked!! I've been scratching my head for days! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.