2013-06-24 98 views
2

我有一個數組,我想用隨機對象填充它,但是使用每個對象的特定百分比。例如,我有矩形,圓形和圓柱形。我希望矩形是陣列長度的40%,圓形和圓柱體各佔30%。有任何想法嗎?在java中創建隨機對象

此代碼將有40%posibility產生矩形等。

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

是的,我有想法,但它需要你的代碼中可以看出 –

+0

這有點曖昧,你想* *確切40%充滿'Rectangle's還是你希望這是預期的價值? – arshajii

+0

陣列長度是否已知? – akaHuman

回答

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)) 
+0

但是,這可能並不意味着恰好40%將是矩形,30%將是圓形並且對於圓柱體是相同的。 – akaHuman

+0

@sleekFish在這方面,問題不明確; OP是否準確地要求40%,或者他希望這是預期的價值? – arshajii

+0

我想要40%。例如在一個數組[10]我想要4個矩形,3個圓形和3個圓柱。 – sarotnem

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; 
} 
+0

您可能想要限制矩形,圓形和圓柱體的座標。如果形狀不在屏幕上,它將不會很好。 OP是否只需要整數座標和大小? –

+0

沒有進入僞隨機數生成的細節)) –

+0

我知道;矩形的非整數大小(甚至邊不平行於軸的整數大小)會導致離散化錯誤。我猜我在查詢中太熱心了。但限制形狀很重要。 'nextInt()'從'Integer.MIN_VALUE'到'Integer.MAX_VALUE'。 –