zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    ASCII&Base64
    CentOS自动同步时间
    Java的HashMap
    Java线程同步操作
    Nginx基本配置与应用
    vc中调用Com组件的方法详解
    VC++ try catch (转)
    oracle中exp,imp的使用详解
    jdbc oracle 连接字符串
    标准的开源实现
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10513572.html
Copyright © 2011-2022 走看看