in reply to Re: Re: Answer: How can I print all the numbers from 1 to n in random order?
in thread How can I print all the numbers from 1 to n in random order?

Though the books always say that the hash is traversed in a "random" order, you should not take that to mean it is traversed in a TRULY RANDOM order. They just meant you should not write your program such that it will depend on any PARTICULAR order.

A hashtable implementation might decide to visit the values %foo in a key order which looks suspiciously artificial: 0.05, 0.10, 0.15, 0.20, 0.06, 0.11, 0.16, 0.21, etc. You are hoping that the hashtable implementation doesn't actually bear any relationship to the pseudo-random number generator. Well, as seen in a recent security bug-fix, hash functions CAN be tied to random functions. You might end up aligning the two functions and defeating any appearance of unpredictability.

This hashtable technique is interesting, but I wouldn't trust it to return things in a random order.

--
[ e d @ h a l l e y . c c ]

  • Comment on Re: Re: Re: Answer: How can I print all the numbers from 1 to n in random order?
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: Re: Answer: How can I print all the numbers from 1 to n in random order?
by ysth (Canon) on Apr 23, 2004 at 16:30 UTC
    That was my initial thought on looking at this, but it doesn't bear out. It's the values you want in random order; random keys are selected for each value. The fact that values() doesn't return a truly random order based on the keys doesn't matter.

    Update:
    You could bypass all issues of ordering based on hash storage by replacing the values %foo with @foo{sort keys %foo}. Then (assuming a hypothetical keysof() function that returns the key for a value), values would be returned in order of sorted keysof(x), while plain values(%foo) (assuming a hypothetical order() function that returns the index into the keys %foo list of a particular key) is in order of sorted order(keysof(x)). Since keysof(x) is a random number between [0 and 1), order(keysof(x)) is equally random for each x, notwithstanding order()'s lack of randomness wrt its argument.