0

As the title says I'm trying to get my code to not generate the same number twice in a set array. EX: (comp is an array defined as int[] comp = new int[20];)

Random ran = new Random();
for(int i = 0; i < comp.length; i++)
{
    comp[i] = ran.nextInt(80)+1;
    for(int j = 0; j < comp.length; j++)
    {
        if(comp[i] == comp[j])
            comp[i] = ran.nextInt(80)+1;
    }
    System.out.println(comp[i]);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What is your question? – npinti Mar 13 '15 at 12:01
  • If the set of possible random numbers is small enough, create an array with all numbers possible. Then pick one entry at random, insert it into the result and remove it from the array. That way each number can only be drawn once. – Sirko Mar 13 '15 at 12:02
  • You can test for the same number like this `Arrays.asList(comp).contains(yourInt)` – Zlopez Mar 13 '15 at 12:05
  • Lots of ideas [here](http://stackoverflow.com/questions/1051949/map-incrementing-integer-range-to-six-digit-base-26-max-but-unpredictably) – OldCurmudgeon Mar 13 '15 at 12:09

0 Answers0