Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare elements in an array for duplicates

Tags:

java

arrays

I am trying to generate a 5 digit int array in Java and am having trouble on where to start. None of the numbers in the array can be duplicates. I can generate random numbers for it fine but just cant figure out how to compare the numbers to each other and replace any duplicates.

like image 627
John Avatar asked Jun 18 '09 07:06

John


2 Answers

You can use a java.util.Set instead of an array as it is guaranteed to have only unique elements.

like image 85
Rahul Avatar answered Oct 02 '22 20:10

Rahul


If I understand you correctly, you want a random 5 digit number, with no digit repeated?

If so, one way is to shuffle a list of the digits 0-9, then pick the first 5 elements.

EDIT

Integer[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Random random = new Random();

public Integer[] generateId() {
    List<Integer> id = Arrays.asList(digits);
    Collections.shuffle(id, random);
    return id.subList(0, 5).toArray(new Integer[0]);
}
like image 21
Jonathan Maddison Avatar answered Oct 02 '22 19:10

Jonathan Maddison