Static2015
V2EX  ›  问与答

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

  •  
  •   Static2015 · Jun 1, 2015 · 3519 views
    This topic created in 4202 days ago, the information mentioned may be changed or developed.
    5 replies  •  2015-06-02 09:59:22 +08:00
    feiyuanqiu
    feiyuanqiu
    Jun 1, 2015
    1
    Math.round(Math.random()*5)
    feiyuanqiu
    feiyuanqiu
    Jun 1, 2015
    2
    啊不对,不能四舍五入,这样 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
    nilennoct
    Jun 2, 2015
    4
    @feiyuanqiu
    `var stat = [];`
    然后为什么用的every?不用forEach?或者其实可以直接 return arr.map(function() {…}) 吧 囧
    nilennoct
    nilennoct
    Jun 2, 2015
    5
    @feiyuanqiu 哦没发现stat()其实是统计函数😂
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4561 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 06:13 · PVG 14:13 · LAX 22:13 · JFK 01:13
    ♥ Do have faith in what you're doing.