Java生成有概率随机数(可自定义随机数长度及概率)
2018-02-11 15:16
429 查看
由于项目工作需求,需要一种随机数生成的法,可自定义概率和长度。遍观网上各大平台,无法找到满足需求的方法,于是动手自己写了一个实现类。手拙,望批评建议。
2、测试的主函数
1、自定义MathRandom类实现
import java.util.ArrayList; import java.util.List; public class MathRandom { private List<Double> probability;//随机数生成的概率列表 private int high;//随机数的范围(0-high) public MathRandom(int block) { this.probability = new ArrayList<Double>(block); this.high = block; } /* * 初始化概率表,判断概率之和是否为1 */ public boolean init(List<Double> prob) { double count= 0 ; for(double i : prob) count = count + i; if(count == 1) { for(int i = 0 ;i< prob.size();i++) this.probability.add(prob.get(i)); return true; } else return false; } /* * 生成随机数,范围(0-high) */ public int random() { if(this.high<=0) return -1; else { double randomNumber = Math.random(); double count = 0; int out = -1 ; for(int i = 0;i< this.high ; i++) { count =count + this.probability.get(i); if(randomNumber <= count) { out = i; break; } else { continue; } } return out; } } /* * 获取(0-high)之间的概率 */ public double getProbability(int k) { return probability.get(k); } public int getHigh() { return high; } }
2、测试的主函数
/* * 测试主函数 */ public static void main(String[] args) { MathRandom cMathRandom = new MathRandom(4); ArrayList<Double> cArrayList = new ArrayList<Double>(4); cArrayList.add(0.5); cArrayList.add(0.3); cArrayList.add(0.15); cArrayList.add(0.05); cMathRandom.init(cArrayList);//初始化随机数概率 int[] count = new int[4] ; for(int i = 0 ; i < 10000 ; i ++) { int k = cMathRandom.random(); switch (k) { case 0: count[0]++; break; case 1: count[1]++; break; case 2: count[2]++; break; case 3: count[3]++; break; default: break; } } int num = 0 ; for(int j = 0 ; j < 4 ; j ++) { System.out.println("随机数 "+j+" \t设定的概率:"+cArrayList.get(j)+"\t 对应的数量:"+count[j] ); num+=count[j]; } System.out.println("所有随机数数量之和:"+num); }
3、总结
具体测试可以将测试主函数放入类里直接运行,也可以单独拿出测试,看个人喜好。由于第一次写此类博客,如有不足之处,希望多家批评建议,谢谢。相关文章推荐
- JAVA 根据设置的概率生成随机数的方法
- 编写一个Java程序,创建制定长度的int型数组,并生成100以内的随机数为数组的每个元素赋值
- JAVA 生成随机数,并根据概率、比率
- JAVA 生成随机数并根据后台概率灵活生成的实例代码
- JAVA 生成随机数,并根据概率、比率
- 【java】0到n中生成m个等概率随机数
- Java生成指定长度的随机数
- JAVA 根据设置的概率生成随机数
- 编写一个JAVA程序,创建指定长度的 int 型数组,并生成 100 以内随机数为数组中的每个元素赋值,然后输出数组
- 按概率生成随机数Java版本
- Java改变生成随机数的平均值(改变生成随机数的概率)
- JAVA 根据设置的概率生成随机数
- Java生成规定长度生成条数的随机数代码
- JAVA 生成随机数,并根据后台概率灵活生成
- java,url长链接生成短链接,短链接生成器,自定义字符串,对字符串md5混合KEY加密,根据短链接获得key值,不重复的随机数,不重复的随机字符串
- java生成随机数字和字母组合(自定义长度)
- java生成一定位数的随机数
- Java 生成指定范围的随机数
- [置顶] 【JAVA】生成一个32位的随机数。防止重复,保留唯一性
- java 文件压缩 base64加解密 生成指定随机数 时间换算 获取系统 获取mac等小结