CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Random numbers

  1. #1
    Join Date
    Sep 2004
    Location
    New Delhi, India
    Posts
    640

    Unhappy Random numbers

    Hi!
    I want to generate random numbers between 0-80. The no. generated should be unique that is it should not have been used. I have been trying for it but to no avail. Here is what iam doing:

    Code:
    int nRand = 0;
    int n = 0;
    boolean bFlag = true;
    while (bFlag && n <= 80)
    {
    	//Generate a random no
    	nRand = new Random().nextInt(81);
    	
    	if (...//Now check if the no has already been used)
    	{
    		...
    		//perform some work
    
    		bFlag = false;
    	}
    	//Increment n. When n > 80 it will show that all no have been used.
    	++n;
    }
    The problem with the above code is that nextInt doesnt gen a unique no. For instance lets say nextInt gen 20 and 20 is already used then in all other iterations of the while loop nextInt continues to gen 20 , while i want it to generate a unique no (a no which has not been gen before).

    Please help.

    Regards.
    "I rather not play football than wear Nerrazzuri shirt" - Paolo Maldini
    FORZA MILAN!!!

  2. #2
    Join Date
    Jun 2005
    Posts
    33

    Thumbs up Re: Random numbers

    The following class generates random numbers within specified limits

    public class RandomNumberBounds {

    private static void generateRandomNumber() {

    int rawNumber;

    //change these two for ur limit
    int min = 30;
    int max = 256;

    for (int i = 0; i < 500; i++) {
    rawNumber = (int) (Math.random() * (max - min + 1) ) + min;
    System.out.println("Random number : " + rawNumber);
    }

    System.out.println("\n");
    }

    public static void main(String[] args) {
    generateRandomNumber();
    }

    }

    Happy coding!!!!!!

  3. #3
    Join Date
    Sep 2004
    Location
    New Delhi, India
    Posts
    640

    Re: Random numbers

    Thanks mate !
    "I rather not play football than wear Nerrazzuri shirt" - Paolo Maldini
    FORZA MILAN!!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured