随机“分裂"Java中的整数值 [英] Random "splitting up" of integer value in Java

查看:37
本文介绍了随机“分裂"Java中的整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有趣的问题,希望有人知道如何在 Java 中做到这一点.我有一个固定的整数值 x,我想用整数 x1、x2、...、xn 的总和来表示使得以下内容成立:

Interesting question, hope someone has an idea how to do this in Java. I have a fixed integer value x, that I want to represent by a sum of integers x1, x2, ...,xn such that the following holds:

x = x1 + x2 + ... + xn;

例如,假设 n=3 且 x=10

For example, lets assume n=3 and x= 10

10 = 5 + 3 + 2;

问题是,x1,x2, ... xn 份额应该是均匀分布的,每次我想将 x 的值拆分"为不同的份额时,它们应该是不同的.

The thing is, the x1,x2, ... xn shares should be uniformely distributed, and everytime I want to "split" the value x into the different shares, they should be different.

有人知道怎么做吗?

谢谢,帕特里克

推荐答案

这是可行的,想法是采用最大上限为 x - (n -i) 的随机数,即第一个元素必须上限为 8 以避免下一个数字成为零.我假设需要正数,其总和为 x.

This works, the idea is to take random numbers with maximum cap x - (n -i) i.e first element must be capped to 8 to avoid next numbers becoming zero. I am assuming positive numbers are required whose sum is x.

Random random = new Random(System.currentTimeMillis());        
for (int i = 0; i < n -1; i++) {
   int j = random.nextInt(x - (n -i)) + 1;
   System.out.println(j);
   x -= j;
}
System.out.println(x);

这篇关于随机“分裂"Java中的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆