js控制隨機數生成概率代碼實例


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM