基本思路:把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);
}
|