I will agree that there's a distinct difference between "trivial" and "not too difficult" that applies to converting between iterators and recursive solutions. However, jd and I found it easier to write recursive solutions, so there's a trade-off in difficulty: It might be easier en toto to come up with a recursive one and then convert it to an iterator.
Not even understanding jdporter's algorithm, I converted it to be iterative (or perhaps more precisely, lazily evaluated). I made the derange function print only the first 15 results, for convenient testing of large inputs.
sub _derange_iter {
my ($cb, $todo, @v) = @_;
@$todo or return do { $cb->( @v ); sub {} }; # this line was wrong b
+efore
my %seen;
@seen{@v} = ();
my ( $range, @todo ) = @$todo;
my @sub_iter = map {
my $my_ = $_;
sub { _derange_iter ( $cb, \@todo, @v, $my_ ) }
} grep { ! exists $seen{$_} } @$range;
return sub {} unless (@sub_iter);
# 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;
}
}
sub derange(&@)
{
my $cb = shift;
my $iter = _derange_iter( $cb,
[ map { my $x = $_; [ grep { $_ ne $x } @_ ] } @_ ] );
for (1..15) {
$iter->();
}
}
derange { print "@_\n" } @ARGV;
Caution: Contents may have been coded under pressure.
|