2

我有一个数组,我想用 Random 对象填充它,但每个对象都有特定的百分比。例如,我有矩形、圆形和圆柱体。我希望 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();
      }  
4

2 回答 2

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))
于 2013-06-24T13:50:27.217 回答
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;
}
于 2013-06-24T14:48:00.160 回答