Algorithm-Combinatorics
view release on metacpan or search on metacpan
Combinatorics.pm view on Meta::CPAN
#
# Note that the public contract is that responds to next(), no
# iterator class name is documented.
package Algorithm::Combinatorics::Iterator;
sub new {
my ($class, $coderef, $first_seq) = @_;
if (defined $first_seq) {
return bless [$coderef, $first_seq], $class;
} else {
return bless $coderef, 'Algorithm::Combinatorics::JustCoderef';
}
}
sub next {
my ($self) = @_;
$_[0] = $self->[0];
bless $_[0], 'Algorithm::Combinatorics::JustCoderef';
return $self->[1];
}
package Algorithm::Combinatorics::JustCoderef;
sub next {
my ($self) = @_;
return $self->();
}
1;
__END__
=head1 NAME
Algorithm::Combinatorics - Efficient generation of combinatorial sequences
=head1 SYNOPSIS
use Algorithm::Combinatorics qw(permutations);
my @data = qw(a b c);
# scalar context gives an iterator
my $iter = permutations(\@data);
while (my $p = $iter->next) {
# ...
}
# list context slurps
my @all_permutations = permutations(\@data);
=head1 VERSION
This documentation refers to Algorithm::Combinatorics version 0.26.
=head1 DESCRIPTION
Algorithm::Combinatorics is an efficient generator of combinatorial sequences. Algorithms are selected from the literature (work in progress, see L</REFERENCES>). Iterators do not use recursion, nor stacks, and are written in C.
Tuples are generated in lexicographic order, except in C<subsets()>.
=head1 SUBROUTINES
Algorithm::Combinatorics provides these subroutines:
permutations(\@data)
circular_permutations(\@data)
derangements(\@data)
complete_permutations(\@data)
variations(\@data, $k)
variations_with_repetition(\@data, $k)
tuples(\@data, $k)
tuples_with_repetition(\@data, $k)
combinations(\@data, $k)
combinations_with_repetition(\@data, $k)
partitions(\@data[, $k])
subsets(\@data[, $k])
All of them are context-sensitive:
=over 4
=item *
In scalar context subroutines return an iterator that responds to the C<next()> method. Using this object you can iterate over the sequence of tuples one by one this way:
my $iter = combinations(\@data, $k);
while (my $c = $iter->next) {
# ...
}
The C<next()> method returns an arrayref to the next tuple, if any, or C<undef> if the
sequence is exhausted.
Memory usage is minimal, no recursion and no stacks are involved.
=item *
In list context subroutines slurp the entire set of tuples. This behaviour is offered
for convenience, but take into account that the resulting array may be really huge:
my @all_combinations = combinations(\@data, $k);
=back
=head2 permutations(\@data)
The permutations of C<@data> are all its reorderings. For example, the permutations of C<@data = (1, 2, 3)> are:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
The number of permutations of C<n> elements is:
( run in 0.801 second using v1.01-cache-2.11-cpan-df04353d9ac )