Hey guys Im tryin to randomize a pointer but i have to write afunction to do it.
ID: 3619028 • Letter: H
Question
Hey guys Im tryin to randomize a pointer but i have to write afunction to do it. This is my function: void randomizeInts(int* ptr, int num, int seed); The parameters are: An int* (int pointer) pointing thethe memory to initialize, An int representing the number ofint values to randomize, An int representing the seed to usewith the srand function. this is what I got so far:void ranInts(int* ptr, int num, int seed) { int i; /* Seed the C Std. Lib. random number generator*/ if (seed == 0) { srand(time(0)); } else { srand(seed); } /* Initialize pointer for no garbage */ for (i=0;i < num;i++) { ptr[i] = 0; } /* Populate pointer with numbers */ for (i=0;i < num;i++) { ptr[i] = rand(); } }
Do i have the right idea? Can anyone please help meout? void randomizeInts(int* ptr, int num, int seed); The parameters are: An int* (int pointer) pointing thethe memory to initialize, An int representing the number ofint values to randomize, An int representing the seed to usewith the srand function. this is what I got so far:
void ranInts(int* ptr, int num, int seed) { int i; /* Seed the C Std. Lib. random number generator*/ if (seed == 0) { srand(time(0)); } else { srand(seed); } /* Initialize pointer for no garbage */ for (i=0;i < num;i++) { ptr[i] = 0; } /* Populate pointer with numbers */ for (i=0;i < num;i++) { ptr[i] = rand(); } }
Do i have the right idea? Can anyone please help meout? void ranInts(int* ptr, int num, int seed) { int i; /* Seed the C Std. Lib. random number generator*/ if (seed == 0) { srand(time(0)); } else { srand(seed); } /* Initialize pointer for no garbage */ for (i=0;i < num;i++) { ptr[i] = 0; } /* Populate pointer with numbers */ for (i=0;i < num;i++) { ptr[i] = rand(); } }
Do i have the right idea? Can anyone please help meout?
Explanation / Answer
the function of ur's serves the purpose . Absolute randomnessis not possible with computers . There is some deterministicapproach involved in it . i suggest some improvements : 1. dynamically allocate the array before calling thefunction. 2. use % mod operator to restrict the range of numbers eg : to haverandom numbers between 0 and 9. use int next_random_int = (rand()%10) 3. for better randomness use "Multiply-With-Carry"generator of G. Marsagliaunsigned intx = 88 ; // take some +ve numberother than zero
unsigned int y = 96 ;// take some +ve number other thanzero unsigned intget_random()
{
x = 36969 * (x & 65535) + (x >>16);
y = 18000 * (y & 65535) + (y >>16);
return (x<< 16) + y;
}
4. make a call to above function to haverandom numbers . Use % mod operator to restrict range. hopethis helps ram