Home > Net >  How to make random non-repeating numbers?
How to make random non-repeating numbers?

Time:05-14

I made a code that could generate random numbers, but my issue is that sometimes it would repeat two or three numbers from time to time.

    int winnum[] = new int[6];
    System.out.print("Lotto winning numbers: ");
    
    for(int i = 0; i < winnum.length; i  ){
        
        winnum[i] = 0   (int)(Math.random() * 42);    
        
        System.out.print(winnum[i]   " ");
      }

here is my code for generating random numbers

CodePudding user response:

A fairly easy way to do this is to re-imagine this a little bit. Instead of 'generate a random number', think about a deck of cards. You don't 'generate random cards' - you generate (well, print) 52 cards in a specific order and then you randomize their order. Now you can draw cards off the top of the deck and they'll be random, but they cannot repeat.

Do the same thing: Make a list, fill it with all 42 numbers, then shuffle the list, then pull the top 6 numbers off of the list. Voila: Random - and without repetition.

var numbers = new ArrayList<Integer>();
for (int i = 0; i < 42; i  ) numbers.add(i);
Collections.shuffle(numbers);
for (int i = 0; i < 6; i  ) {
  System.out.print(list.get(i)   " ");
}

CodePudding user response:

Here is a real quick way using streams.

Random r = new Random();
  • r.ints(n,m) - generate a stream of random values between n and m-1 inclusive
  • distinct - ensure they are unique
  • limit(n) - limit to n
  • toArray - return as an array.
int [] result = r.ints(0,42).distinct().limit(6).toArray();
System.out.println(Arrays.toString(result));

prints something like

[37, 19, 28, 31, 15, 12]

CodePudding user response:

You need to check whether the array contains the newly generated random number. If not, you add it, otherwise, keep generating random numbers until one that's not in the array is generated. To check whether the number is found in the array, you can write the following function that takes the random integer, your array and returns a boolean:

boolean exists = false;

for (int n : winnum) {
  if (n == randomInt) {
    exists = true;
    break;
  }
} return exists;
  • Related