I was trying to write my own code to perform the pseudo random traversal of a set and ran into a situation where the skip value generated could be a multiple of the prime therefore causing the algorithm to always "randomly" generate 0s.
The following is pseudo-ish code that I wrote.
Display All
The question is what did I miss which occasionally can cause the random traversal to keep generating 0s. Thanks for your help and wonderful book!
The following is pseudo-ish code that I wrote.
Source Code
- int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
- int members = rand() % 25 + 5;
- int prime;
- //find the smallest prime number greater than members
- for (int i = 0; i < primes.length; i++) {
- if (primes[i] > members) {
- prime = primes[i];
- break;
- }
- }
- //randomly generate 3 non-zero coefficients
- int coefficients[3];
- for (int i = 0; i < coefficients.length; i++) {
- coefficients[i] = rand() % 5 + 1; //5 was arbitrarily chosen
- }
- //generate the skip value
- int skip = coefficients[0] * members * members + coefficients[1] * members + coefficients[2];
- //randomly traverse the set
- //if skip is a multiple of prime then this always generates 0
- int nextMember = 0;
- for (int i = 0; i < members; i++) {
- cout << nextMember << endl;
- do {
- nextMember += skip;
- nextMember %= prime;
- } while (nextMember >= members);
- }
The question is what did I miss which occasionally can cause the random traversal to keep generating 0s. Thanks for your help and wonderful book!
The post was edited 3 times, last by ssrun ().