in reply to Re: Subsets and adjacent values
in thread Subsets and adjacent values
However, it produces one element twice, and I can't figure out why.$ diff -ubB PowerSet.pm.org PowerSet.pm --- PowerSet.pm.org 2008-05-30 11:22:31.000000000 +0200 +++ PowerSet.pm 2008-05-30 12:46:32.000000000 +0200 @@ -9,7 +9,7 @@ use Exporter; use vars qw/$VERSION @ISA @EXPORT_OK/; -$VERSION = '0.05'; +$VERSION = '0.06'; @ISA = ('Exporter'); =head1 NAME @@ -18,8 +18,8 @@ =head1 VERSION -This document describes version 0.05 of Data::PowerSet, released -2008-05-13. +This document describes version 0.06 of Data::PowerSet, released +2008-05-30. =head1 SYNOPSIS @@ -161,6 +161,22 @@ When this attribute is used, the C<next()> method will return a scalar rather than a reference to an array. +=item B<adjacent> + +When this attribute is used, the returned list will contain adjacent +elements only. E.g. + + my $ps = Data::PowerSet->new( {min=>3, adjacent=>1}, 2, 3, 5, 8, 11 + ); + +will produce + + 2, 3, 5, 8, 11 + 2, 3, 5, 8 + 3, 5, 8, 11 + 2, 3, 5 + 3, 5, 8 + 5, 8, 11 + =back =cut @@ -195,6 +211,13 @@ ($args{min}, $args{max}) = ($args{max}, $args{min}) if $args{max} < $args{min}; + + $args{adjacent} = + exists $args{adjacent} + ? $args{adjacent} + : 0 + ; + return bless \%args, $class; } @@ -217,9 +240,18 @@ return undef unless $self->{current} >= 0; my $mask = $self->{current}--; my $offset = 0; + my $last = -1; @set = (); while( $mask ) { + if ($self->{adjacent}) { + if ($mask & 1 && (($offset-1 == $last) || sca +lar(@set) == 0)) { + $last = $offset; + push @set, $self->{data}[$offset]; + } + } else { push @set, $self->{data}[$offset] if $mask & 1; + } + $mask >>= 1; ++$offset; }
|
|---|