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

Time:01-15

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

}

}

CodePudding user response:

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.

CodePudding user response:

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.

I'm a beginner too so don't expect too much but on what I understand, this is the solution I came up to.

  •  Tags:  
  • Related