https://leetcode.com/problems/path-crossing/
I am working on this leetcode problem and I think I'm close, but I can't figure out why it isn't working. In my IF statement it doesn't seem like i is incrementing. So once it goes through the loop again, it just returns true and exits loop. Once this is working I intend to into one single conditional so it's not so long, but I want to make it work first haha. Any insight?
var isPathCrossing = function (path) {
const points = {};
const directions = path.split('').map((d) => {
return d;
});
let x = 0;
let y = 0;
let i = 0;
while (i <= directions.length) {
const coordinate = `${x}, ${y}`;
if (directions[i] == 'N') {
y++;
if (!Object.values(points).includes(coordinate)) {
points[i] = coordinate;
i++;
} else {
return true;
}
}
if (directions[i] == 'W') {
x--;
if (!Object.values(points).includes(coordinate)) {
points[i] = coordinate;
i++;
} else {
return true;
}
}
if (directions[i] == 'S') {
y--;
if (!Object.values(points).includes(coordinate)) {
points[i] = coordinate;
i++;
} else {
return true;
}
}
if (directions[i] == 'E') {
x++;
if (!Object.values(points).includes(coordinate)) {
points[i] = coordinate;
i++;
} else {
return true;
}
}
}
return false;
};
console.log(isPathCrossing('NNNNN'));
console.log(isPathCrossing('NES'));
console.log(isPathCrossing('NESWNEENW'));
(i <= directions.length) refactored to (i < directions.length), as would not want to traverse more than length.{ '0': '0, 1', '1': '1, 1', '2': '1, 0', '3': '0, 0' } generated for input "NESWW". Using a set would be more appropriate. (Commented alongside your implementation).var isPathCrossing = function (path) {
// const points = new Set();
const points = {};
const directions = path.split('').map((d) => { return d; });
let x = 0;
let y = 0;
let i = 0;
const initCoord = `${x}, ${y}`;
points[-1] = initCoord;
// points.add(initCoord);
while (i < directions.length) {
if (directions[i] == 'N') { y++; }
else if (directions[i] == 'W') { x--; }
else if (directions[i] == 'S') { y--; }
else if (directions[i] == 'E') { x++; }
const coordinate = `${x}, ${y}`;
// console.log(coordinate);
// console.log(points);
if (!Object.values(points).includes(coordinate)) {
points[i] = coordinate;
i++;
} else {
return true;
}
// if (!points.has(coordinate)) {
// points.add(coordinate);
// i++;
// } else {
// return true;
// }
}
return false;
};