How to generate random numbers from 0-5 twice only. For example the result should be like this 0,0,1,1,2,2,3,3,4,4,5,5 but it should be randomly. The numbers should be used twice only.
CodePudding user response:
This would be a solution:
ArrayList<Integer> numberList = new ArrayList<Integer>(); // Filling a dynamic list with our integers
numberList.add(0);
numberList.add(1);
numberList.add(2);
numberList.add(3);
numberList.add(4);
numberList.add(5);
Random rand = new Random();
while(numberList.size() > 0) // While we have a number inside our list
{
int randomIndex = rand.nextInt(numberList.size()); // get a random index and display the number
int randomNr = numberList.get(randomIndex);
if(numberList.size() != 1)
{
System.out.print(randomNr ", " randomNr ", ");
}
else // if we are at the last element, omit the last comma
{
System.out.print(randomNr ", " randomNr);
}
numberList.remove(randomIndex); // After displaying remove it.
}
CodePudding user response:
You can just generate one number and then copy it.
Example:
You are randomly generate 1, so you will output this number and copy of this number, then you will generate "second" number