代码片段: 根据权重产生随机数-WeightRandom.java

package com.springmvcmybatis.Action; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.springmvcmybatis.Entity.WeightCategory; publi...
<pre>package com.springmvcmybatis.Action; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.springmvcmybatis.Entity.WeightCategory; public class WeightRandom { static List<WeightCategory> categorys = new ArrayList<WeightCategory>(); private static Random random = new Random(); public void initData() { WeightCategory wc1 = new WeightCategory("A",15); WeightCategory wc2 = new WeightCategory("B",18); WeightCategory wc3 = new WeightCategory("C",15); WeightCategory wc4 = new WeightCategory("D",20); WeightCategory wc5 = new WeightCategory("E",15); WeightCategory wc6 = new WeightCategory("F",17); categorys.add(wc1); categorys.add(wc2); categorys.add(wc3); categorys.add(wc4); categorys.add(wc5); categorys.add(wc6); } public String Weight() { initData(); Integer weightSum = 0; for (WeightCategory wc : categorys) { weightSum += wc.getWeight(); } if (weightSum <= 0) { System.err.println("Error: weightSum=" + weightSum.toString()); return null; } Integer n = random.nextInt(weightSum); // n in [0, weightSum) Integer m = 0; for (WeightCategory wc : categorys) { if (m <= n && n < m + wc.getWeight()) { System.out.println("随机数是 "+wc.getCategory()); return wc.getCategory(); } m += wc.getWeight(); } return null; } } </pre>
  • 发表于 2018-07-05 11:20
  • 阅读 ( 708 )
  • 分类:代码片段

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除