It didn't take me long to realise (after I had seen your analysis) that rand(n), when int'd, gives me values 0..(n-1). I should have spotted that earlier.

It took me a lot longer to understand why it required a changed from rand($_-1) to rand($_+1) rather rand($_) to effect the desired results.

Maybe others spotted this right away, but incase anyone who reads this doesn't get it, I'll give my explanation and risk correction.

I had thought that what was required for the shuffle to work was to swap the last element with a random choice of the preceeding elements, then the second from last with its preceeding elements and so on.

It took me while to realise that you have to allow the last element to also have the possibility of 'swapping with itself' otherwise you exclude 1/n of the possible outcomes. Omitting this possibility for all of the passes (in your testcase) gives 3! possible outcomes rather than 4!.

But that led me to wondering why my original code only resulted in 2 outcomes!

It took me a while longer to see this resulted from the combination of the int'd rand and the loop starting at 1 not zero. Meaning that whilst n-1 swaps are performed, 2 of these swaps are always the same. Ie. no randomness involved.

So, one swap with a choice of two, and 2 swaps with no choice = 2 possible outcomes.

All that said, the most significants thing to come out of this (for me) are

Thankyou for both.


In reply to Re: Re: Fisher-Yates shuffle? by BrowserUk
in thread Fisher-Yates shuffle? by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.