4个边长为70的正方形并排放在一个344×70的容器里,第一个正方形距离长方形左侧10,第二个正方形距离第一个12,第三个距离第二个20,第四个距离第三个12,第四个距离长方形右边10,求一算法,给定一个正方形位置就能获得其距离长方形左侧的距离。举个例子,就比如给你“0”,需要的结果就是“10”,给你“3”,需要的结果就是“264”,在此先谢过各位了

解决方案 »

  1.   

    这确实没什么规律滴,非要算法就只好这样纸鸟——y = 82*x + (x>1)*8 + 10;验证:<script tyep=text/javascript>
    Array.prototype.map = function( fun ) {
          var arr = [];
          for (var i = 0; i < this.length; i ++) {
               arr.push( fun.call(this[i], i) );
          }
          return arr
    }
    alert([0, 1, 2, 3].map(function() {
          return this * 82 + (this > 1) * 8 + 10;
    }))
    </script>
      

  2.   

    这样合理些。y = x*82 + (x&2)*4 + 10;验证:Array.prototype.map = function( fun ) {
          var arr = [];
          for (var i = 0; i < this.length; i ++) {
               arr.push( fun.call(this[i], i) );
          }
          return arr
    }alert([0, 1, 2, 3].map(function() {
          return this * 82  + (this & 2) * 4 + 10
    }))
      

  3.   

    当然是有规律的function foo(n) {
      var dict = [10, 12, 20, 12];
      var width = 70;
      if(n >= dict.length) n = dict.length - 1;
      var t = width * n;
      while(n >= 0) t += dict[n--];
      return t;
    }document.write(foo(0)+'<br>');//10
    document.write(foo(1)+'<br>');//92
    document.write(foo(2)+'<br>');//182
    document.write(foo(3)+'<br>');//264