1

I have the following code generating 5-digit random numbers and adding them to an ArrayList. These numbers however must be unique ids.

for(int i = 0; i < myArr.length; i++) {
    int id = (int) (Math.round(Math.random() * 89999) + 10000);
    idArr.add(id);
}

I'm trying to work out how I could check to see if the number was already in the array before adding it but I can't get my head around the best way to do this.

4 Answers 4

3

Don't use an (Array)List, use a Set:

Set<Integer> set = ...;
while (set.size() < myArr.length) {
  set.add(yourRandomNumber);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Minor comment: the OP was asking for "unique 5-digit numbers", not "5 unique numbers". The number 5 there should be myArr.length.
1

Use an ArrayList instead of an array. That way you would just need to use ArrayList#contains(obj) method to test whether the id is already in the ArrayList or not.

Or, you can just work with a HashSet, which will work faster with its HashSet#contains() method.

1 Comment

Thanks Rohit - the contains method was exactly what I needed
1

You can create a Set of the numbers. E.g.:

Set<Integer> intSet = new HashSet<Integer>();
while(intSet.size() < myArr.length) {
    intSet.add(getNextRandomInt());
}

Then yo can do anything with that Set.

So, if you need an array, just call:

Integer[] intArray = intSet.toArray(new Integer[myArr.length]);

or, if you need an ArrayList or int[] array:

// ArrayList:
List<Integer> ints = new ArrayList<Integer>();
ints.addAll(intSet);

// int[] array:
int[] intArray = new int[myArr.length];
for( int i = 0; i<intArray.length; ++i) {
    intArray[i] = int.get(i);
}

Comments

0

Anything which involves looping until you find enough unique random numbers is never guaranteed to complete. It's possible, if extremely unlikely, that the random number generator will never output enough unique numbers in a reasonable amount of time.

(I know this will never happen in practice, but it's a theoretical possibility.)

A safe alternative is to choose one random number, and then increment it in a loop until you have enough numbers.

int n = new Random().nextInt(89999 - myArr.length) + 10000;
for (int i = 0; i < myArr.length; i++) {
    idArr.add(n++);
}

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.