I am generating 4 character pin numbers for children to use in schools. The pins have to be stored as 4 character strings in a database. This is the method I am using to generate the pins:
public void generatePin() {
String pin;
Random r = new Random();
for (int i = 0; i < createdStudents.size(); i++) {
int rand = r.nextInt((3998 - 1) + 1) + 1;
if (rand < 10) {
pin = "000" + rand;
} else if (rand < 100) {
pin = "00" + rand;
} else if (rand < 1000) {
pin = "0" + rand;
} else {
pin = "" + rand;
}
createdStudents.get(i).setPin(pin);
}
}
My question is:
If I slightly alter the above method, adding each pin to an ArrayList of String type as I go, what is the most efficient way to 'search' through that List and make sure that 2 students in the one school don't end up with the same pin?
(Note: there will never be more than 1,200 students per school)
Edit:
I ended up doing the following:
public void generatePin() {
List<String> pins = new ArrayList<String>();
String pin;
Random r = new Random();
for (int i = 0; i < createdStudents.size(); i++) {
int rand = r.nextInt((9999 - 1) + 1) + 1;
if (rand < 10) {
pin = "000" + rand;
} else if (rand < 100) {
pin = "00" + rand;
} else if (rand < 1000) {
pin = "0" + rand;
} else {
pin = "" + rand;
}
if (!pins.contains(pin)) {
createdStudents.get(i).setPin(pin);
pins.add(pin);
} else {
i--;
}
}
}
Creating an ArrayList to store the pins, checking if the pin exists in the ArrayList after each generation. If it doesn't, assign it to a student. If it does, decrement the loop counter in order to go back to the just referenced index in the list and generate a new pin. This will continue until a unique pin is generated, where it will be assigned to a student.