Algorithm::ChooseSubsets - OO interface to iterate through subsets of a list.


Algorithm-ChooseSubsets documentation  | view source Contained in the Algorithm-ChooseSubsets distribution.

Index


NAME

Top

Algorithm::ChooseSubsets - OO interface to iterate through subsets of a list.

SYNOPSIS

Top

  use Algorithm::ChooseSubsets

  # Choose all subsets of a set
  $i = new Algorithm::ChooseSubsets($n);  
  $i = new Algorithm::ChooseSubsets(\@set);  
  $i = new Algorithm::ChooseSubsets(set=>\@set);

  # Choose subsets of a fixed size $k
  $i = new Algorithm::ChooseSubsets($n,$k);
  $i = new Algorithm::ChooseSubsets(\@set,$k);
  $i = new Algorithm::ChooseSubsets(set=>\@set, size=>$k);

  # Choose subsets of sizes greater than or equal to k
  $i = new Algorithm::ChooseSubsets($n,$k,1);
  $i = new Algorithm::ChooseSubsets(\@set,$k,1);
  $i = new Algorithm::ChooseSubsets(set=>\@set, size=>$k, all=>1);

  while ($x = $i->next) {
    # Do something with @$x
    }

  $i->reset;        # return to the first subset.

DESCRIPTION

Top

    "Subsets" in this context refers to lists with elements taken
from the original list, and in the same order as the elements in the
original list.  After creating the object, subsequent calls to next()
will return the next such list in lexicographic order (where the alphabet
is the original list).

    If K is specified, only subsets of that size will be returned.  If K
is omitted, all subsets will be returned, beginning with the empty set
and ending with the entire set.  If the 'all' flag and a value for 'K' are
specified, subsets of size greater than or equal to K will be returned.

    If a number, N, is used instead of a list, the list is taken to
be [0..N-1].

EXAMPLES

Top

  # Print ab ac ad ae bc bd be cd ce de
  $i = new Algorithm::ChooseSubsets([qw(a b c d e)],2);
  print @$x," " while ($x = $i->next);

  # Print all 2,598,960 possible poker hands.
  $i = new Algorithm::ChooseSubsets (\@cards, 5);
  print @$hand,"\n" while ($hand = $i->next);

  # Print ::0:1:2:01:02:12:012
  $i = new Algorithm::ChooseSubsets(3);
  print ":",@$j while ($j = $i->next);

NOTES

Top

    For a fixed K, next() will return a value N! / (K! * [N-K]!) times.
    For all subsets and a list of size N, it'll return a value 2**N times.

AUTHOR

Top

Brian Duggan <bduggan@matatu.org>

SEE ALSO

Top

perl(1).


Algorithm-ChooseSubsets documentation  | view source Contained in the Algorithm-ChooseSubsets distribution.