Skip to content

Instantly share code, notes, and snippets.

@romelperez
Last active July 29, 2022 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romelperez/2be443a41cd84fd7216d1742ff8033ce to your computer and use it in GitHub Desktop.
Save romelperez/2be443a41cd84fd7216d1742ff8033ce to your computer and use it in GitHub Desktop.
function checkGameIndex (checkedIndexesCache, list, index) {
const offset = list[index];
const is0 = list[index] === 0;
const is0ToLeft = list[index - offset] === 0;
const is0ToRight = list[index + offset] === 0;
if (is0 || is0ToLeft || is0ToRight) {
return true;
}
checkedIndexesCache[index] = true;
const rightIndex = index + offset;
const canMoveToRight = rightIndex <= list.length - 1;
if (
canMoveToRight &&
!checkedIndexesCache[rightIndex] &&
checkGameIndex(checkedIndexesCache, list, rightIndex)
) {
return true;
}
const leftIndex = index - offset;
const canMoveToLeft = leftIndex >= 0;
if (
canMoveToLeft &&
!checkedIndexesCache[leftIndex] &&
checkGameIndex(checkedIndexesCache, list, leftIndex)
) {
return true;
}
return false;
}
function runGame (list, index) {
if (!list.length) {
return false;
}
// A cache to check for already reviewed indexes.
// This is to prevent to check on the same indexes more than once.
const checkedIndexesCache = {};
return checkGameIndex(checkedIndexesCache, list, index);
}
console.log(0, runGame([], 2) === false);
console.log(1, runGame([4,9,2,100,0], 2) === true);
console.log(2, runGame([0,9], 1) === false);
console.log(3, runGame([1,1,0], 0) === true);
console.log(4, runGame([2,6,3,2,0,1,4], 0) === true);
console.log(5, runGame([2,6,3,2,0,1,4], 3) === true);
console.log(6, runGame([2,6,3,2,0,1,4], 1) === false);
console.log(7, runGame([2,6,3,2,0,2,4], 5) === false);
console.log(8, runGame([1, 4, 1, 1, 9, 0], 2) === true);
console.log(9, runGame([4,9,0,100,0], 2) === true);
console.log(10, runGame([1, 1, 2, 2, 1, 2, 0, 2, 1, 2, 2, 1], 5) === false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment