Static2015
V2EX  ›  问与答

生成一个元素服从 0 到 5 均匀分布的随机数组,求好思路

  •  
  •   Static2015 · Jun 1, 2015 · 3107 views
    This topic created in 4026 days ago, the information mentioned may be changed or developed.
    5 replies    2015-06-02 09:59:22 +08:00
    feiyuanqiu
        1
    feiyuanqiu  
       Jun 1, 2015
    Math.round(Math.random()*5)
    feiyuanqiu
        2
    feiyuanqiu  
       Jun 1, 2015
    啊不对,不能四舍五入,这样 0 和 5 的比例只有 0.5
    应该这样:

    function gen(n) {
    var arr = [];
    for (var i = 0; i < n; i++)
    arr.push(Math.floor(Math.random()*6));
    return arr;
    }

    function stat(arr) {
    var stat = {};
    arr.every(function (v) {
    if (!stat[v]) stat[v] = 0;
    return ++stat[v];
    });
    return stat;
    }

    stat(gen(1000));
    nilennoct
        4
    nilennoct  
       Jun 2, 2015
    @feiyuanqiu
    `var stat = [];`
    然后为什么用的every?不用forEach?或者其实可以直接 return arr.map(function() {…}) 吧 囧
    nilennoct
        5
    nilennoct  
       Jun 2, 2015
    @feiyuanqiu 哦没发现stat()其实是统计函数😂
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5424 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 07:37 · PVG 15:37 · LAX 00:37 · JFK 03:37
    ♥ Do have faith in what you're doing.