## Monday, March 19, 2007

### Random number revisited(without using the rand() function)

Like I mention earlier,nothing is random in a computer.Only the nature is random,hence considering which "things" of nature do we have in the computer,in my opinion it is time.Well some may say that time is not a "random thing" because we know what time is it now,some hours later and so on.But my point in this case is that we need to have a random number and suppose that we keep track of the number of seconds that have elapsed after a specific time and each time we need a random number, then we can consider the number of seconds that have elapsed after the specific time we stated.The number that we would get would be different each time(of course that could be calculated if we are keeping track at the time we want the random number.The previous algorithm I've posted is modified a bit(just replacing the ran() function).See below the blue part is the added one and the green one is the one that is being removed from the previous version.

int generate_unique_random(){
static int b=0,a=20,myarray[20];
int index,temp,y;

time_t seconds;

if(b==0){
for(y=0;y<20;y++)
myarray[y]=y+1;}

//srand(time(NULL));
//index=rand()%a+b;

seconds = time (NULL);
index=(seconds)%a+b;

temp = myarray[index];
myarray[index]=myarray[b];
myarray[b]=temp;

b++;
a--;
return temp;
}

#### 1 comment:

Anonymous said...

yo adarsh, nice. :)
though i still don't agree with this method as O(1).. since you have to fill up the array using the for (1-n) times.
:p