在java中创建随机对象

sar*_*nem 2 java random math percentage

我有一个数组,我想用随机对象填充它,但每个对象的特定百分比.例如,我有矩形,圆形和圆柱形.我希望Rectangle是数组长度的40%,Circle和Cylinder各占30%.有任何想法吗?

这段代码有40%的可能性来生成Rectangle等.

 public static void main(String[] args){
     n = UserInput.getInteger();
     Shape[] array = new Shape[n];


            for (int i=0;i<array.length;i++){
            double rnd = Math.random();

            if (rnd<=0.4) {
            array[i] = new Rectangle();
        }


            else if (rnd>0.4 && rnd<=0.7){
            array[i] = new Circle();
        }

            else {
            array[i] = new Cylinder();
      }  
Run Code Online (Sandbox Code Playgroud)

ars*_*jii 6

你可以做一些事情

for each v in array,
    x = rand()  // number between 0 and 1, see Math.random()
    if 0 < x < 0.40, then set v to Rectangle;  // 40% chance of this
    if 0.40 < x < 0.70, then set v to Circle;  // 30% chance of this
    otherwise set v to Cylcinder               // 30% chance of this
Run Code Online (Sandbox Code Playgroud)

当然,这不会确保准确的比率,而只是确定某些预期比率.例如,如果您希望阵列由40%的矩形组成,则可以使用矩形填充40%(30%使用圆圈,30%使用圆柱体),然后使用

Collections.shuffle(Arrays.asList(array))
Run Code Online (Sandbox Code Playgroud)