If you need to generate many more than 10 distinct random numbers, this solution will be faster because the hash lookup works in constant time, whereas your solution has to iterate over the whole array for each number. For 10 there won't be a big difference.

Also note that for testing it is better to reduce the maximum number so that collision become more likely - I tested it with 12 instead of 1185.

Update: If the maximal number is the same or not much larger than the number of random values you want, this would probably be faster:

If you need to generate many more than 10 distinct random numbers, this solution will be faster because the hash lookup works in constant time, whereas your solution has to iterate over the whole array for each number. For 10 there won't be a big difference.

But do note that the only reason your algorithm guarantees to terminate is because rand uses a pseudo random number generator. Were rand to be truly random, neither algorithm could guarantee to be finished before Perl 6 dominates the world.

Were rand to be truly random, neither algorithm could guarantee to be finished before Perl 6 dominates the world.

Though if you do the math and calculate the probability that either algorithm does not terminate with the given parameters in, let's say, 2 seconds on a modern machine, you'll probably find that the chance of computation errors in the CPU caused by cosmic rays is much higher.

Doing the strict theory only makes sense if the actual machine corresponds to the machine model that the theory assumes.

%seen is a hash. If the key $candidate is not present in the hash, it is added to the hash (that's called "autovivification"), initialized to 1, and undef is returned - the redo is not executed.

On the other hand if the key is already present in the hash, the corresponding value (for example 1) is returned, and incremented by one (for example set to 2). In this case the interesting part is not the incrementing, but that it returns a true value, so the redo is executed.