public static void main(String[] args) { // 设置随机数个数,最小数为0(分割随机数本身)最大不能大于随机数 // 这个长度为设定的长度减一,如获取5个随机数,将len设置为4 int len = 2; // 要拆分的数 int sources = 486; Random random = new Random(); // 先获取到随机数分割的个数,提升效率 List<Double> r = new ArrayList<>(); for (int i = 0; i < len; i++) { double v = random.nextDouble(); r.add(v); } // 从小到大排序,便于后续获取随机数 r.sort(new Comparator<Double>() { @Override public int compare(Double o1, Double o2) { return o1 < o2 ? -1 : 1; } }); // 用上边的随机数,来取得len份拆分之后的数 List<Integer> out = new ArrayList<>(); // 记录前一个随机数 int last = 0; for (int i = 0; i < len; i++) { int c = (int) (r.get(i) * sources); int i1 = c - last; out.add(i1); last = c; } // 最后一个随机数 out.add(sources - last); }
将一个数A随机分为N个(N个数之和为A)
猜你喜欢
转载自blog.csdn.net/wdz985721191/article/details/90606300
今日推荐
周排行