基本思路:把Math.random()js随机数生成的数看着百分比,然后定义每个整数值取值范围。
具体内容如下,供大家参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | ‘use strict‘ ; export default class GL { /** * 构造函数 * @param {object} opt * @param {number} opt.min 最小整数值 * @param {number} opt.max 最大整数值 * @param {Map} opt.fenpei 自定义概率 */ constructor({ min, max, fenpei = new Map() }) { this .min = min; this .max = max; this .fenpei = fenpei; } /** * 可分配百分比 */ get baifenbi() { return (1 - this .peizhi) / ( this .max - this .min - this .fenpei.size); } /** * 配置 */ get peizhi() { let result = 0; for (let i of this .fenpei.values()) { if ( this .min <= i && i < this .max) result += i; } return result; } /** * 随机数 * @returns {number} [min,max) */ random() { let t = 0, r = Math.random(); for (let i = this .min; i < this .max; i++) { this .fenpei.has(i) ? t += this .fenpei.get(i) : t += this .baifenbi; if (t > r) return i; } return null ; } } let d = new GL({ min: 0, max: 8, fenpei: new Map([ [0, 0.5], // 数值,百分比 [22, 0.4] ]) }); // 测试 let count = Array(10).fill(0); for (let i = 0; i < 10000; i++) { count[d.random()] += 1; } for (let i = 0; i < count.length; i++) { console.log(count[i] / 10000); } |
js控制随机数生成概率代码实例
原文地址:https://www.cnblogs.com/good10000/p/10583345.html