#
# This software is Copyright 2005 by Elsevier Inc.  You may use it
# under the terms of the license at http://perl.plover.com/hop/LICENSE.txt .
#



###
### partition-it-optimized
###

## Chapter 5 section 1.2

sub make_partitioner {
  my ($n, $treasures) = @_;
  my @todo = [$n, $treasures, []];
  sub { 
    while (@todo) {
      my $cur = pop @todo;
      my ($target, $pool, $share) = @$cur;

      if ($target == 0) { return $share }
      next if $target < 0 || @$pool == 0;

      my ($first, @rest) = @$pool;        

      push @todo, [$target, \@rest, $share ] if @rest;
      if ($target == $first) {
        return [@$share, $first];
      } elsif ($target > $first && @rest) {
        push @todo, [$target-$first, \@rest, [@$share, $first]],
      }        
    }
    return undef;
  } # end of anonymous iterator function       
} # end of make_partitioner
