random generator code

Ken Moffat kmoffat
Mon May 17 11:59:18 PDT 2004


Ken Moffat wrote:

> Rick Sivernell wrote:
>
>> hi all
>>
>>   has any one got a good random generator c code that you can set the 
>> highes value
>> limit. rand just doe not work for what I need. What I am doing is 
>> passing in an array
>> with it max length, I need to randomly pick a location index and get 
>> its value. Any
>> ideas would be appreciated
>>
>> cheers
>>
>>  
>>
> This may help you. Not great, but ...
>
>
>
>
> static Sint32 seed = 0;
>
> static void initrandom()
> {
>    seed = time(NULL);
> }
>
> static unsigned int getrandom()
> {
>    Sint32 p1 = 1103515245;
>    Sint32 p2 = 12345;
>    seed = (seed*p1+p2) % 2147483647;
>    return (unsigned)seed/3;
> }
>
>
> r = getrandom() % MAX; // #define MAX to size of array
>
>
call initrandom(); first or you'll get the same 'random' number every time.
if the array is a[], then  a[getrandom()%MAX] should print a random 
element<= MAX.

-- 
Ken




More information about the Linux-users mailing list