在java中创建随机对象

时间:2013-06-24 13:46:42

标签: java math random percentage

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

这段代码有40%的可能性来生成矩形等。

 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();
      }  

2 个答案:

答案 0 :(得分: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

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

Collections.shuffle(Arrays.asList(array))

答案 1 :(得分:1)

我认为你可以这样做:

import java.awt.Rectangle;
import java.awt.Shape;

public Shape[] ArrayRandomizer(int size) {
    List<Shape> list = new ArrayList<Shape>();
    if (size < 10 && size%10 != 0) {
        return null; // array must be divided by 10 without modulo
    }
    else {
        Random random = new Random();
        Shape[] result = new Shape[size];
        for (int r=0; r<4*(size/10); r++) {
            Shape rectangle = new Rectangle(random.nextInt(), random.nextInt(), random.nextInt(), random.nextInt()); // standart awt constructor
            list.add(rectangle);
        }
        for (int cir=0; cir<3*(size/10); cir++) {
            Shape circle = new Circle(random.nextInt(), random.nextInt(), random.nextInt()); // your constructor of circle like Circle(int x, int y, int radius)
            list.add(circle);
        }
        for (int cil=0; cil<3*(size/10); cil++) {
            Shape cilinder = new Cilinder(random.nextInt(), random.nextInt(), random.nextInt(), random.nextInt()); // your constructor of cilinder like Cilinder (int x, int y, int radius, int height)
            list.add(cilinder);
        }
    }
    Shape[] result = list.toArray(new Shape[list.size()]);

    return  result;
}