An array that outputs number 1-5 in random, 1-5 must be output only 2 times without repeating

Viewed 63

The code does output 1 - 5 but is there a way to make each number print only twice. (from 1-5 only) Sample Output,

It does change and is random but outputs more than twice

public class Main {

public static void main(String[] args) {
    
int num;    

int[] random = new int[5]; //this code generates numbers 1–5 

int[] array = new int[11]; //array size

for(int x = 0; x < random.length; x++)

random[x] = x; //store the index as a value

for(int x = 0; x < random.length; x++) {

num = (int)(Math.random()*5);

while(random[num] == -1)

num = (int)(Math.random()*5); 

if(random[num] != -1)

array[x] = random[num]; 

random[num] = -1; 

}

for(int x = 0; x < array.length; x++)

array[x] = array[x] + 1;

for(int x = 1; x < array.length; x++)


System.out.println("A["+x+"]: "+ array[x]);

}

}
2 Answers

What's the purpose of the random array? It just complicates things. Instead, generate a random number, and check if it is already used twice. If yes, generate another one, if no put it into the array. Repeat until the array is full. Another approach would be to initialize the array with 2 copies of the numbers 1-5 and to do a random permutation.

Just create a variable that records the random records then inside the method or function use if else statement to check the random recorded value to the current value then set up again a variable that provides the limitation to your code.

Related