Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Created November 20, 2020 20:02
Show Gist options
  • Save Gerst20051/6da3cf7adb93ae558ba583cae1cdff8f to your computer and use it in GitHub Desktop.
Save Gerst20051/6da3cf7adb93ae558ba583cae1cdff8f to your computer and use it in GitHub Desktop.
Can Find Zero
const digits = [3, 7, 0, 2, 8, 3, 7, 6];
const digits_empty = [];
function canFindZero(values, startIndex, checkedIndexes) {
checkedIndexes.push(startIndex);
if (values[startIndex] === 0) {
return true;
}
const leftIndex = startIndex - values[startIndex];
const leftIndexValue = values[leftIndex];
if (leftIndexValue && !checkedIndexes.includes(leftIndex)) {
checkedIndexes.push(leftIndex);
const canFindZeroLeft = canFindZero(values, leftIndexValue, checkedIndexes);
if (canFindZeroLeft) {
return true;
}
}
const rightIndex = startIndex + values[startIndex];
const rightIndexValue = values[rightIndex];
if (rightIndexValue && !checkedIndexes.includes(rightIndex)) {
checkedIndexes.push(rightIndex);
const canFindZeroRight = canFindZero(values, rightIndexValue, checkedIndexes);
if (canFindZeroRight) {
return true;
}
}
return false;
}
console.log(canFindZero(digits, 0, []) === true);
console.log(canFindZero(digits, 4, []) === false);
console.log(canFindZero(digits_empty, 0, []) === false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment