1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

random generator for unique numbers

Discussion in 'Java' started by Arielis, Oct 6, 2008.

  1. Arielis

    Arielis New Member

    Joined:
    Jul 13, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    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!
     
  2. oogabooga

    oogabooga New Member

    Joined:
    Jan 9, 2008
    Messages:
    115
    Likes Received:
    11
    Trophy Points:
    0
    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: Oct 6, 2008
  3. Arielis

    Arielis New Member

    Joined:
    Jul 13, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0

Share This Page