0

I'm in the process of creating a program that generates 50 random numbers between 1-999, but I can't figure out how to stop duplicates from showing up in the program. Any help would be appreciated.

public class Random50 //Name of my class
{
  public static void main(String[] args)
  {
    int[] randomArray; //Declares a new array of integers

    randomArray = new int[51];  

    Random rand = new Random(); 
    for (int i = 1; i < randomArray.length; i++) 
      {
        int n = rand.nextInt(1000);
        randomArray[i] = n;
      }

    for (int i = 1; i < randomArray.length; i++) 4
      {
        System.out.printf("Number " + i + ": " + "%03d\n", randomArray[i]);
      }  
  }
}
Ben Parry
  • 133
  • 1
  • 4
  • 19
  • 2
    A random number is by definition random. So there is no way tell the next nextInt call to generate a number that has not been generated yet. One naive approach (which would work) would be to create a Set and until its size is not 50 loop to add another random number. Since your range ([0-999]) is large enough compared to the size of the data you want to generate, that would be ok. One other way would be to generate the 1000 values into a Set and pick 50 from them (and you remove one each time you pick it from the set). – Alexis C. Dec 09 '14 at 22:39
  • 2
    You could check for a duplicate and retry if there is one. Or you could generate a sequence of numbers 1-999 and shuffle. Then take the first 50. – Fred Larson Dec 09 '14 at 22:40
  • [This](http://stackoverflow.com/a/4040014/2296705) answer is worth checking out. – Philip Liberato Dec 09 '14 at 22:43

1 Answers1

0

Simply do the following.

if (!randomArray[i].contains(n)) {
    int n = rand.nextInt(1000);
    randomArray[i] = n;
} else {
    continue;
}

This block proofs the following: - Has the array the n element in it? if no: add it - if yes: skip this pass of the array. BTW: It would be better to increment the index of the array here AFTER the first condition is true and not for every pass. So rather something like this:

public class Random50 //Name of my class
{
  public static void main(String[] args)
  {
    ArrayList<Integer> randomArray; //Declares a new array of integers

    randomArray = new ArrayList<Integer>();  

    Random rand = new Random();
    int i = 1; 
    for (; i < 51;) 
      {
       if (!randomArray[i].contains(n)) {
           int n = rand.nextInt(1000);
           randomArray[i] = n;
           i++;
       } else {
           continue;
       }
      }

    for (int i = 1; i < randomArray.length; i++) 4
      {
        System.out.printf("Number " + i + ": " + "%03d\n", randomArray[i]);
      }  
      }
    }
X-Fate
  • 323
  • 4
  • 13