random generator for unique numbers

Arielis's Avatar, Join Date: Jul 2008
Newbie Member
Hi
I have an issue ,trying to build a unique number generator.
Specifiacally, the generator is this
Code:
                Random randomPerson=new Random(System.nanoTime());
		int no_persons=persons.length;
		
		int cnt=0;
		while(cnt<70) {
			int person=randomPerson.nextInt(no_persons);
			if(function()) {
				cnt++;}
function() returns a boolean whether the random number hasn't used before (and some other operations eg insertion to an array)
When this program is executed, I either take the aprropriate output, or the program stucks (infinite loop). Is there any possibility to fix this infinite loop?

Thanks in advace!
0
oogabooga's Avatar
Ambitious contributor
Presumably you mean something like this:
Code:
bool is_unique( int n) {
    // check array
}

int get_unique_person() {
    Random randomPerson = new Random( System.nanoTime());
    int no_persons = persons.length;
    int max_tries = 70;
    int cnt, person;

    for( cnt = 0; cnt < max_tries; ++cnt) {
        person = randomPerson.nextInt( no_persons);
        if( is_unique( person)) break;  // exit loop if it IS unique
    }
    if( cnt == max_tries) { // No unique number found in max_tries.
        // Deal with it....
    }
    return person;
}
If the range of your random numbers is relatively small, and particularly if you need to use most or all of them, then a better solution might be to create your own class called RndUnique that would contain a shuffled array of the integers in the range and return them one at a time.

Last edited by oogabooga; 6Oct2008 at 23:01.. Reason: fixed scope of "person"
0
Arielis's Avatar, Join Date: Jul 2008
Newbie Member
Thanks!