[Algorithm] Tower Hopper Problem

By given an array of number, each number indicate the number of step you can move to next index:

For example index = 0, value is 4, means at most you can reach index = 4, value is 2.  You can also choose take only 1 step, reach index = 1, value is 2. If in the end you can jump out of the array (values sum up larger than the length of array), then return true, if not able, then return false. If you get stuch with index which values is zero, then basiclly means you cannot reach outside of the array.

function isHopperable(data) {
  function helper(current, data) {
    let max = 0;
    if (data[current] === 0) {
      return current;
    }

    // We keep checking what is the max reach for us
    // for the given index value
    //[4,2,0,0,2,0]: for example index = 0;
    // max would be 
    // case1: choose 1 step: 0 + 1 + 2 = 3
    // case2: choose 2 step: 0 + 2 + 0 = 2
    // case3: choose 3 step: 0 + 3 + 0 = 3
    // case4: choose 4 step: 0 + 4 + 2 = 6
    // WE will choose case 4, since 6 is max reach we can get

    for (let i = data[current]; i > 0; i--) {
      max = Math.max(data[current] + current, max);
    }

    return max;
  }

  let current = 0;
  while (true) {
    if (current >= data.length) {
      return true;
    }

    if (data[current] === 0) {
      return false;
    }

    current = helper(current, data);
  }
}

const data = [4, 2, 0, 0, 2, 0];
console.log(isHopperable(data));// true

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10513572.html