P: 16

Hi,
I need a piece of code to generate a random number between 0 and 5 (both exclusive) ie., number should be either 1,2,3 or 4. And also I need only two unique random numbers out of the four numbers. ie., out of 1,2,3 and 4 only two numbers should be picked randomly and those two numbers should not be repeated. Any help please....
Regards,
VRK
 
Share this Question
10K+
P: 13,264

Hi,
I need a piece of code to generate a random number between 0 and 5 (both exclusive) ie., number should be either 1,2,3 or 4. And also I need only two unique random numbers out of the four numbers. ie., out of 1,2,3 and 4 only two numbers should be picked randomly and those two numbers should not be repeated. Any help please....
Regards,
VRK
Did you manage to use Math.random() as was suggested here?
 
P: 16

Hi,
I got it....Thanks a lot...
Did you manage to use Math.random() as was suggested here?
  10K+
P: 13,264

Hi,
I got it....Thanks a lot...
All you need is to get the first number, then use a while loop that generates another number until the generated number is different from the first number.
  Expert 2.5K+
P: 3,652

Alternatively, you could use an ArrayList (found in java.util.ArrayList) to build a short list of integers (from 1 to 4, in your case). Then, using a random number generator, generate a number between 0 and the size of your ArrayList, select that Integer from the List, and remove the Integer object. This way, you are guaranteed never to produce the same Integer, as it will be removed after you use it.
For a larger application, this is wonderful, but for 4 possible numbers, it may take too much time, memory space, coding, etc.
 
P: 16

Hi,
Can you give me a piece of code for that. With the earlier method Iam getting even 0 as a random number which is not my requirement. I should get either 1,2 3 or 4.
Alternatively, you could use an ArrayList (found in java.util.ArrayList) to build a short list of integers (from 1 to 4, in your case). Then, using a random number generator, generate a number between 0 and the size of your ArrayList, select that Integer from the List, and remove the Integer object. This way, you are guaranteed never to produce the same Integer, as it will be removed after you use it.
For a larger application, this is wonderful, but for 4 possible numbers, it may take too much time, memory space, coding, etc.
 
P: 16

Hi,
Thanks....I got it.....
Hi,
Can you give me a piece of code for that. With the earlier method Iam getting even 0 as a random number which is not my requirement. I should get either 1,2 3 or 4.
    Question stats  viewed: 2295
 replies: 6
 date asked: Jan 13 '07
