Sort_by { rand } not working

Lloyd L. wrote:

Yes, that is fairly simple to understand. But it is equivalent to
sort_by {rand} in that it does not actually change the array that is
passed in.

Actually, it was different. The sort_by {rand} gives the same sequence
of shuffling every time you run it. Mine is different every time. I
get a bang out of the declaration you have. That is a nice touch. I
also like your use of until temp.empty? That is very Ruby-ish to me.
:slight_smile:

Thanks. Wanna see a better version of this algorithm? Check out a sample
chapter from Hal F.'s book–he does it a little more elegantly (
http://www.informit.com/articles/article.aspx?p=26943&rl=1 ). And I was
very much mistaken in what I said–your code /does/ change the array
that is passed in, but it zeros it (not randomizes). You could add a
line ar.replace(arr) to mitigate that, or make a copy (ar.dup) and
operate on that instead, depending on whether you expect the method to
perturb the array that is passed in.

And by the way, sort_by {rand} does return a different result every
time. If it doesn’t, I would assume you’re installation of ruby is old
(or broken?) and doesn’t initialize a new random seed (srand) each time
it is started. Or maybe this is how ruby behaves on Windows? I’m not
quite sure.

Dan

Dan Z. wrote:

Lloyd L. wrote:

dang it! I knew that I should have been thinking more ruby and less
pascal. This may look more rubyish:

def arr_rand(ar)
arr = []
while ar.length > 0 {arr << ar.delete_at(rand(ar.length))}
arr
end

Yes, that is fairly simple to understand. But it is equivalent to
sort_by {rand} in that it does not actually change the array that is
passed in.

Actually, it was different. The sort_by {rand} gives the same sequence
of shuffling every time you run it. Mine is different every time. I
get a bang out of the declaration you have. That is a nice touch. I
also like your use of until temp.empty? That is very Ruby-ish to me.
:slight_smile: