Updated. Cleaner version, without (too much) poking inside other modules guts. + I always wanted to use the PadWalker for something real.
use strict; use warnings; use feature 'say'; use PadWalker qw/ closed_over set_closed_over /; use Algorithm::Combinatorics qw/ combinations_with_repetition /; my @data = qw( a b c ); my $state; { say "\tDay one, hard work ahead..."; my $iter = combinations_with_repetition( \@data, 3 ); say @{ $iter-> next } for 1 .. 5; say "\tEnough work for one day!"; $state = closed_over( $iter ); } { say "\tDay 2, back to work..."; my $iter = combinations_with_repetition( \@data, 3 ); $iter-> next; # init set_closed_over( $iter, $state ); say "\tDeadline! Exhaust the iterator!"; while ( my $c = $iter-> next ) { say @$c } } __END__ >perl comb.pl Day one, hard work ahead... aaa aab aac abb abc Enough work for one day! Day 2, back to work... Deadline! Exhaust the iterator! acc bbb bbc bcc ccc
We need the line with "init" comment because first call to iterator is special.
a not very clean hack would be:
use strict; use warnings; use feature 'say'; use Algorithm::Combinatorics qw( combinations_with_repetition ); package Algorithm::Combinatorics { no warnings 'redefine'; sub main::combinations_with_repetition { my ($data, $k, $ref) = @_; __check_params($data, $k); return __contextualize(__null_iter()) if $k < 0; return __contextualize(__once_iter()) if $k == 0; my @indices = $ref ? @$ref : (0) x $k; my $iter = Algorithm::Combinatorics::Iterator->new(sub { __next_combination_with_repetition(\@indices, @$data-1) == -1 +? undef : [ @{$data}[@indices] ]; }, [ @{$data}[@indices] ]); my $x = __contextualize($iter); # Note: scalar context forced return [ $x, \@indices ] # + interface changed } } my @data = qw( a b c ); my ( $iter, $secret ) = @{ combinations_with_repetition( \@data, 3 )}; say @{ $iter-> next } for 1..5; my ( $iter_2 ) = @{ combinations_with_repetition( \@data, 3, $secret )}; say '**********'; $iter_2-> next; # skip 1 while ( my $p = $iter_2-> next ) { say @$p } __END__ aaa aab aac abb abc ********** acc bbb bbc bcc ccc
In reply to Re: Looking for combinatorics with state (Updated)
by vr
in thread Looking for combinatorics with state
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |