After reading this question. I was wondering is it possible using O(1) space can we generate a random permutation of the sequence [1…n] with a uniform distribution using something like double hashing?
I tried this with a small example for the sequence [1,2,3,4,5] and it works. But it fails for scale for larger sets.
int h1(int k) {
return 5 - (k % 7);
}
int h2(int k) {
return (k % 3) + 1;
}
int hash(int k, int i) {
return (h1(k) + i*h2(k)) % size;
}
int main() {
for(int k = 0; k < 10; k++) {
std::cout << "k=" << k << std::endl;
for(int i = 0; i < 5; i++) {
int q = hash(k, i);
if(q < 0) q += 5;
std::cout << q;
}
std::cout << std::endl;
}
}
You can try another approach.
GCD(P, N) == 1whereGCD(P,is greatest common divisor ofN)
PandN(e.g.GCD(70, 42) == 14,GCD(24, 35) == 1).K[i] ::= (P * i) mod N + 1,ifrom1toNK[i]enumerates all numbers between1 and N with no repeats (actually
K[N + 1] == K[1]but that is not a problem because we need only first N numbers).If you can efficiently generate such numbers
Pwith uniform distribution (e.g. with a good random function) with using Euclidean algorithm to calculate GCD in O(log(N)) complexity you’ll get what you want.