Temmie Temmie - 2 months ago 7
Java Question

Randomly generate 1 and 0 as a queue

I want my program to randomly generate 1 and 0 but it should look like it's in a queue. The 1 is represented by a person and 0 means that there's no person. It should generate random 1 and 0 like this

0 0 0 0 1 1 1 1 1 1
, if the line is in the left and vice versa if it's in the right, not like this
1 1 1 0 0 1 0 0 1 1
.

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

Answer

Implemented a simple random function to generate 0s and 1s

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

output

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