Random Number Algorithm

• 04-06-2011, 12:00 AM
javauserjava
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??

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..

• 04-06-2011, 12:14 AM
Junky
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.
• 04-06-2011, 12:15 AM
Junky
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.
• 04-06-2011, 12:21 AM
Fubarable
Yep. You should do what Java does -- use the results from the most recent calculation to create a seed for the next calculation.
• 04-06-2011, 12:28 AM
javauserjava