Update: Even with the update below, this code is broken. Wait for this message to disappear before accepting the code.

This is a simple modification to the classic Fisher-Yates shuffle algorithm that produces a derangement. I suppose I should contact the authors of the permutation-related modules on CPAN about this. This produces one random derangement; it is not an algorithm to return an ordered list of derangements.

My simple proof is that, since we set $j to a random number less than $i, the element at position $i will always be swapped out of its location, and can never be swapped back into it because $i decreases each time.

Update: I added to the algorithm because it was producing all possible derangements. For example, (1,2,3,4) has a derangement of (3,4,1,2), but the old algorithm couldn't produce this. The real problem is now it requires twice as much memory. :(

sub derangement { my $list = shift; my $i = @$list; my @swapped; while (--$i) { my $j = int rand ($i+1); redo if $i == $j and !$swapped[$i]; @$list[$i,$j] = @$list[$j,$i]; @swapped[$i,$j] = (1,1); } }

In reply to Derangement of a list by japhy

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.