0

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

2
  • You need the check each value against each other, therefore you need a second for-each inside the one which generates the random numbers Commented May 13, 2022 at 19:02
  • Java generating non-repeating random numbers Commented May 13, 2022 at 19:28

3 Answers 3

4

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) + " ");
}
Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.