Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
I've come up with a solution that handles duplicate values properly: that is,
a b b a
generates exactly
b a a b
I wrote it as a recursive sub, and then converted it to be an iterator.
use strict; use warnings; # The recursive one sub derange { # First argument is optional arrayref of original values; if not pro +vided, # build it from arg list my @orig = ref $_[0] ? @{shift(@_)} : @_; if (@_ == 0) { return [] } if (@_ == 1) { return $_[0] eq $orig[0] ? () : [$_[0]]; } # Generate a derangement by extracting each element then mapping it +as the head # to the derangement of the everything else # Swaps that would cause a value to match its corresponding original + value are skipped my %seen; map { if ($orig[$_] ne $_[0] and $orig[0] ne $_[$_] and not $seen{$_[$_] +}++) { my $swap_i = $_; map [$_[$swap_i], @$_] , derange([@orig[1..$#orig]], @_[0..$swap_i-1,$swap_i+1..$#_]); } else { (); } } (0..$#_); } # The iterator version sub derange_iter { # First argument is optional arrayref of original values; if not pro +vided, # build it from arg list my @orig = ref $_[0] ? @{shift(@_)} : @_; # Base cases get assigned to an array, which the iterator shifts thr +ough if (@_ == 0) { my @base_case = ([]); return sub { shift @base_case }; } elsif (@_ == 1) { my @base_case = $_[0] eq $orig[0] ? () : [$_[0]]; return sub { shift @base_case }; } # otherwise.. my %seen; my @list = @_; my @sub_iter = map { if ($orig[$_] ne $list[0] and $orig[0] ne $list[$_] and not $seen{ +$list[$_]}++) { my $swap_i = $_; sub { my $cdr_iter = derange_iter([@orig[1..$#orig]], @list[0..$swap +_i-1,$swap_i+1..$#list]); sub { my $cdr = $cdr_iter->(); if ($cdr) { return [$list[$swap_i], @$cdr] } else { return () } }; } } else { (); } } (0..$#_); # Grab and unwrap an iterator from the list my $iter = (shift @sub_iter)->(); return sub { my $rval; $iter = (shift @sub_iter)->() until ($rval = $iter->() or @sub_iter == 0); return $rval; } } @ARGV or @ARGV = 1..5; my $i = derange_iter(@ARGV); for (1..50) { my $val = $i->() or last; print "@$val\n"; } #print "\nShould be:\n"; #print "@$_\n" for sort {"@$a" cmp "@$b"} derange(@ARGV);
The commented-out code at the end is for verifying that the iterator generates the same output as the recursive version. But don't uncomment it if you want to run on large inputs. The iterator will spit out the first 50 values almost immediately; the recursive version will hang/crash.

Caution: Contents may have been coded under pressure.

In reply to Re: Derangements iterator (handles duplicate values) by Roy Johnson
in thread Derangements iterator by tye

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others avoiding work at the Monastery: (9)
    As of 2018-06-20 09:59 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (116 votes). Check out past polls.