hi,
I want to generate k different random numbers between 1 to n. (k<n).
One of the appraoch is calling random function again and again. and
checking wheter new generated number had already been generated. but
its complexity is O(n^2).....Is there any better mthod?
To give a proper answer, I think your question
needs to be more focused:
(1) What's the (approx) largest n you'll encounter?
(2) Given that n, what's the (approx) largest k?
(3) Do you want the combination elements in
sorted order? Or do you want one of its k! permutations,
each equally likely?
The Floyd's algorithm posted by Ben Bacarisse may be
to be good enough for you but does suffer two disadvantages:
(a) it uses O(k^2) time, assuming the test "t in S"
takes O(|S|) time.
(b) the elements end up in *neither* sorted order, *nor*
as a uniformly-distributed permutation.
The "Fisher-Yates" shuffle avoids both these problems, but at
the cost of needing O(n) storage.
So ... O(n) storage *or* O(k^2) time? Is there a way to avoid
*both* of these undesireables? I know of a way which requires
you to generate a subset of Pascal's triangle: that would be
O(k*n) storage but at least it would be read-only storage!
James Dow Allen