1. Member
Join Date
Oct 2010
Posts
24
Rep Power
0

## Random int

Hi guys, been looking online and can;t seem to find how to do what I want. I'm basically looking through methods but want to create a random number. I know how to limit its top end but not sure how to limit both:

For example a random number between 14-40.

Any help is appreciated!

2. Originally Posted by drucey
Hi guys, been looking online and can;t seem to find how to do what I want. I'm basically looking through methods but want to create a random number. I know how to limit its top end but not sure how to limit both:

For example a random number between 14-40.

Any help is appreciated!
Think of it: you want a pseudo random number in the range 14-40; in your mind subtract 14 from both numbers: 0-26. If you can generate a pseudo random number in that range you can generate one in the original range: simply add 14 to it.

kind regards,

Jos

3. just add the lower end to the number. If you want to do 14-40, you do the random from 0 - 26, then add 14.

4. Member
Join Date
Oct 2010
Posts
24
Rep Power
0
Oh ok thanks. I did think of that just thought there may be a way to dictate the lower parameter!

Thanx Guys

5. Originally Posted by drucey
Oh ok thanks. I did think of that just thought there may be a way to dictate the lower parameter!
There is, and Jos and sunde887 show you how. ;)

6. Member
Join Date
Oct 2010
Posts
24
Rep Power
0
Thanks, got it.

One more quick thing - the random generator is throwing out random numbers. What if i didnt want it to pick the same number? I have created the array etc, and want an if statement to say if its equal to ANYTHING in the array?

Thanks guys

7. Originally Posted by drucey
Thanks, got it.

One more quick thing - the random generator is throwing out random numbers. What if i didnt want it to pick the same number? I have created the array etc, and want an if statement to say if its equal to ANYTHING in the array?
There are two approaches to solve this little problem:

1) remember the numbers that were already genetated; if such a number is generated again, retry.

2) generate all possible numbers in some order and store them in a Collection (without repetition, the order doesn't mind) and call the Collections.shuffle( ... ) method.

kind regards,

Jos

8. 1) remember the numbers that were already genetated; if such a number is generated again, retry.
Remember that if you use this method to use an efficient data structure for lookups, like a HashMap or something. If you use an ArrayList or the like with the .contains() method, this will get really slow really quick. Hashed structures have a constant time lookup, so they are quite fast for this type of thing!

#### Posting Permissions

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