2016-09-17 36 views
0

我想讓我的程序隨機生成1和0,但它應該看起來像是在隊列中。 1代表一個人,0代表沒有人。它應該產生像這樣的0 0 0 0 1 1 1 1 1 1這樣的隨機1和0,如果這條線在左邊,反之亦然,如果它在右邊,不是這樣的1 1 1 0 0 1 0 0 1 1隨機生成1和0作爲隊列

public void randPeople(){ 
    int person1 = rand.nextInt((1 - 0) + 1) + 0; 
    int person2 = rand.nextInt((1 - 0) + 1) + 0; 
    int person3 = rand.nextInt((1 - 0) + 1) + 0; 
    int person4 = rand.nextInt((1 - 0) + 1) + 0; 
    int person5 = rand.nextInt((1 - 0) + 1) + 0; 
    int person6 = rand.nextInt((1 - 0) + 1) + 0; 
    int person7 = rand.nextInt((1 - 0) + 1) + 0; 
    int person8 = rand.nextInt((1 - 0) + 1) + 0; 
    int person9 = rand.nextInt((1 - 0) + 1) + 0; 
    int person10 = rand.nextInt((1 - 0) + 1) + 0; 

    EntryFloor1.setText(Integer.toString(person1) + " " + Integer.toString(person2) + " " + 
          Integer.toString(person3) + " " + Integer.toString(person4) + " " + 
          Integer.toString(person5) + " " + Integer.toString(person6) + " " + 
          Integer.toString(person7) + " " + Integer.toString(person8) + " " + 
          Integer.toString(person9) + " " + Integer.toString(person10)); 
} 
+0

問:是不是'rand.nextInt(8)'三個零和/或1的隊列(作爲一個例子)? – paulsm4

+0

@ paulsm4我試過了,但它在第一個數字上有一個除1或0以外的數字 – Temmie

+0

Dude:重點是......二進制「數字」......相當於一串*位數*。如果將0或1存儲在「int」數組中,則只能在每個元素中使用* 32 BITS *中的* ONE *。 – paulsm4

回答

1

實現了一個簡單的隨機函數來生成0和1

int[] queue = new int[10]; 
    Random r = new Random(); 
    int rand = r.nextInt(queue.length); 
    int r1 = 1 - rand % 2; 
    int r2 = rand % 2; 
    for (int i = 0; i < queue.length; i++) { 
     if (i <= rand) { 
      queue[i] = r1; 
     } else { 
      queue[i] = r2; 
     } 
    } 
    System.out.println("Queue " + Arrays.toString(queue)); 

輸出

Queue [1, 1, 1, 0, 0, 0, 0, 0, 0, 0] 

隨着Java8發生器

final int size = 10; 
    final Random random = new Random(); 
    boolean order = random.nextBoolean(); 
    Object[] arr = IntStream.generate(() -> random.nextInt(size) % 2).limit(size).boxed().sorted((i1, i2) -> order ? i1 - i2 : i2 - i1).toArray(); 
    System.out.println("Arrays " + Arrays.toString(arr)); 

輸出

Arrays [1, 1, 1, 1, 1, 0, 0, 0, 0, 0] 
+0

謝謝!有用! – Temmie

+0

歡迎,您可以進一步優化它,通過不設置零,因爲該數組將被初始化爲零 – Saravana

+0

我建議任何時候明確設置爲可讀性的零。 –

0

試試這個:

Random r = new Random(); 

    boolean b = r.nextBoolean(); // left or right 
    int l = r.nextInt(11); // breakpoint to change from 0 to 1 or other way 
    System.out.println(b + " " + l); 
    int person[] = new int[10]; 
    for (int i = 0; i < 10; i++) { 
     if (b) { 
      if (i < l) 
       person[i] = 1; 
      else 
       person[i] = 0; 

     } else { 
      if (i < l) 
       person[i] = 0; 
      else 
       person[i] = 1; 
     } 
    } 
    System.out.println(Arrays.toString(person));