Robot walk kata has me completely stumped

28 Views Asked by At

You are given an input string that controls the movement of a robot, each character instructing it to move one step north, south, east or west. E.g. "NW" moves the robot one step north and then one step west, or "SE" moves the robot one step south and one step east. Write a function that returns the number of steps that the robot must take to return to its starting point after following all the commands. You should ignore any characters that are not capital N, S, E or W.

For example:

"NE" returns 2 (robot must step south and west to return)

"SWN" returns 1 (robot must step east to return)

"NxWxSxEx" returns 0 (robot is already back at its starting point)

my solution:

function solution(directions) {
    const arr = directions.split("")
    let NS = 0
    let EW = 0
    for(let i of arr){
        if (i == 'N') NS ++; 
        if (i == 'S') NS --; 
        if (i == 'E') EW ++; 
        if (i == 'W') EW --;
    }
    return NS + EW 
}

I get 2/3 passed but when it tries "SWN" it comes back as -1 as opposed to 1. I know I'm missing something pretty obvious but it completely escapes me. Any help would be greatly appreciated

0

There are 0 best solutions below