2

私は配列を持っていて、それを Random オブジェクトで埋めたいのですが、各オブジェクトの特定の割合で。たとえば、長方形、円、円柱があります。Rectangle を配列の長さの 40% にし、Circle と Cylinder をそれぞれ 30% にします。何か案は?

このコードは、Rectangle などを生成する可能性が 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();
      }  
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 に答える