Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   random generator for unique numbers (http://www.go4expert.com/forums/random-generator-unique-t14394/)

Arielis 6Oct2008 18:03

random generator for unique numbers
I have an issue ,trying to build a unique number generator.
Specifiacally, the generator is this

                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()) {

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!

oogabooga 6Oct2008 22:59

Re: random generator for unique numbers
Presumably you mean something like this:

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.

Arielis 7Oct2008 18:37

Re: random generator for unique numbers

All times are GMT +5.5. The time now is 13:47.