1. Member
Join Date
Mar 2011
Posts
27
Rep Power
0

## Random Number Algorithm

Hi everyone,

I have faced a problem with the following code which should create a random number .. could you please take a look on it??

Java Code:
``` Calendar CURRENTDATE = Calendar.getInstance ();
int CURRENTTIME = CURRENTDATE.get (Calendar.MILLISECOND);

int CURRENT9 = 50;
int RANDNUMBER = 560;
int NUM = CURRENTTIME + CURRENT9;
int SIDOUT = (RANDNUMBER / CURRENT9) + NUM;
int PIDOUT = (RANDNUMBER / NUM) + NUM;

PIDOUT = RANDNUMBER + PIDOUT;
SIDOUT = RANDNUMBER + SIDOUT;
SIDOUT = PIDOUT + SIDOUT;
PIDOUT = SIDOUT + PIDOUT;
int PID = PIDOUT / CURRENT9;
int PIDOUT1 = PIDOUT % CURRENT9;
int SID = SIDOUT / PID;
int SIDOUT1 = SIDOUT % PID;```

this algorithm should give me a new number in each line for example ,

102232
213093
213302
109032

but unfortunately it gave me results same as the following which is not correct

1233
1233
1233
4323
4323
5334
5334

finally, I know I can use the random class in Java but the problem is I have to use this algorithm and I have to fix it..

2. Create a SSCCE (google it). If you do that you might realise what the problem is yourself. It also gives a better understanding of the purpose of the code.

One thing I will mention is that you use Calendar class to get time and date. A common misconception is that a Calendar object is like a clock and keeps updating itself. It doesn't. It is simply a snapshot in time and will always have the same value.

3. Now that I think about it, you probably call a method several times. If those calls occur within a fraction of a second then they will all get the same timestamp and therefore generate the same "random" number.

4. Yep. You should do what Java does -- use the results from the most recent calculation to create a seed for the next calculation.

5. Member
Join Date
Mar 2011
Posts
27
Rep Power
0

But unfortunately I do not know how to do it exactly,, I know it seems strange but that what I can say,,

6. As Fubar mentioned you can use the number generated to calculate the next number. Make your RANDNUMBER variable an instance variable. At the end of the calculation set RANDNUMBER equal to the generated number. This isn't optimal but it should help to generate some different values.

#### Posting Permissions

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