[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--) {
      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 = 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
复制代码

 

posted @   Zhentiw  阅读(435)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-03-11 [HTML5] Text Alternatives
2018-03-11 [HTML5] Semantics for accessibility
2016-03-11 [RxJS] Logging a Stream with do()
2016-03-11 [RxJS] Handling a Complete Stream with Reduce
2016-03-11 [RxJS] Completing a Stream with TakeWhile
2016-03-11 [RxJS] Adding Conditional Logic with Filter
2016-03-11 [RxJS] Combining Streams with CombineLatest
点击右上角即可分享
微信分享提示