-
July 26th, 2005, 03:58 AM
#1
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!!!
-
July 26th, 2005, 07:15 AM
#2
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!!!!!!
-
July 26th, 2005, 02:38 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|