-1

I am creating a program that generates a random bingo card every time you play. I cannot figure out how to not get duplicate random numbers. I am always getting at least 2 of the same numbers. I have tried many different ways but this is what i've ended up with and it still duplicates. Please help!

  for (int p = 0; p < b.length; p++) { //loop that assigns random
        number
                        b[p] = (int) (Math.random() * 14 + 1);
                        do {
                            b[1] = (int) (Math.random() * 14 + 1);
                        } while (b[1] == b[0]);
                        do {
                            b[2] = (int) (Math.random() * 14 + 1);
                        } while (b[2] == b[1] || b[2] == b[0]);
                        do {
                            b[3] = (int) (Math.random() * 14 + 1);
                        } while (b[3] == b[0] || b[3] == b[1] || b[3] == b[2]);
                        do {
                            b[4] = (int) (Math.random() * 14 + 1);
                        } while (b[4] == b[0] || b[4] == b[1] || b[4] == b[2] || b[4] == b[3]);

                    }
Curiosa Globunznik
  • 3,129
  • 1
  • 16
  • 24
  • 3
    Why not generate the list of numbers for the range, shuffle them, then pick some? – ChiefTwoPencils Nov 21 '19 at 17:37
  • `Math.random()` generates `double`s. Are you sure you aren't running into a rounding error, since you're casting each value to `int`? – spork Nov 21 '19 at 17:55

2 Answers2

2

Assuming you are allowed to import:

import java.util.ArrayList;
import java.util.Collections;

Just create a "deck" of cards in order - then randomize the order. Remove an item from the list so you cant pick (or pop) it more than once.

        ArrayList<Integer> cards = new ArrayList<Integer>();

        // create a list in order
        for (int i = 1; i < 14; i++) {
            cards.add(i);
        }

        Collections.shuffle(cards); // randomize

        for (int i = 1; i < 14; i++) {
            cards.remove(i-1); // pop
            // do something with the card
        }
sleepToken
  • 1,866
  • 1
  • 14
  • 23
  • Thank you.. I am still very much a beginner so I appreciate the help. – Joshua Saikali Nov 23 '19 at 02:54
  • @JoshuaSaikali not a probelm. In the future, if an answer works for you, please accept it. It let's others know the problem is solved not to mention helps out the answer-er (me) – sleepToken Nov 23 '19 at 14:12
0

If you just need random doubles, you can instantiate a Random outside your loop and keep using the same instance with random.nextDouble() to get pseudorandom numbers.

Random random = new Random();
for (int p = 0; p < b.length; p++) {
   b[p] = (int) (random.nextDouble() * 14 + 1);
   do {
      b[1] = (int) (random.nextDouble() * 14 + 1);
   } while (b[1] == b[0]);
...
}
spork
  • 1,185
  • 1
  • 11
  • 17