[Algorithm] Tower Hopper Problem

时间:2022-10-05 14:01:24

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

[Algorithm] Tower Hopper Problem

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 = ;
if (data[current] === ) {
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 > ; i--) {
console.log(current, i, data[i+current])
/**
0 4 2
0 3 0
0 2 0
0 1 2
*/
max = Math.max(current + i + data[i + current], max);
} return max;
} let current = ;
while (true) {
if (current >= data.length) {
return true;
} if (data[current] === ) {
return false;
} current = helper(current, data);
}
} const data = [, , , , , ];
console.log(isHopperable(data));// true