0

I need to get code that will allow me to remove duplicates of numbers as I have a random number generator which generates number associated to the counter of an array, the array being a 'pack' of cards, so I can't really afford to change the code but I really need to stop duplicates appearing!

Other questions on here require me to change my whole code, which I can't do as it means I have to start over which I really don't have the time for at the moment as I need to begin testing in a week and I still have more code to implement!

    for (int v = 0; v < 30; v++)
    {
        Random rnd = new Random();
        rnd.nextInt(30);

        int i = rnd.nextInt(30);

        System.out.println(i + " " + aCards[i].getCard());
    }

This is what the code above produces, there are clearly duplicates within the list!

TiaC
  • 3
  • 1
  • 4
  • It's a pack of cards. you don't need to generate "random numbers". You pre-populate the array with your cards, then shuffle it (e.g. randomly re-order). Then to play cards, it's just a matter of popping items off the array. – Marc B Nov 30 '15 at 14:36
  • The random generator was part of the requirements, unfortunately! – TiaC Nov 30 '15 at 14:38
  • then do something silly, like having the pre-defined array, and use a random generator to create keys you can slice out of that array. copy that random key to the new array, and keep slicing until there's nothing left of the original. – Marc B Nov 30 '15 at 14:39
  • A fast method to resolve your problem is to add your randomly generated number to a Set, then before picking from cards check if the number already exist in the Set, if true generate a new one. – wadi3 Nov 30 '15 at 14:47
  • You need the RNG to shuffle--you just don't use it to generate random card values, you use it to generate random array indices. The one and only correct way to do that is a proper F-Y shuffle. If your "requirements" are different, then they are wrong, and you need to tell your teacher he's an idiot. More likely, he expects you to use the RNG for indices and not cards, and he just didn't explain it well. – Lee Daniel Crocker Dec 01 '15 at 02:35

0 Answers0