Advertisement
hakonhagland

powerset

Aug 16th, 2021
1,375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.77 KB | None | 0 0
  1. use feature qw(state);
  2. use strict;
  3. use warnings;
  4.  
  5. sub powerset($$&@) {
  6.     my $bitmask = shift;
  7.     my $limit = shift;
  8.     my $callback = shift;
  9.     my $bytes = @_/8;
  10.     {
  11.         my @indices = grep vec($$bitmask, $_, 1), 0..$#_;
  12.         return if $callback->( $limit, @_[@indices] );
  13.         ++vec($$bitmask, $_, 8) and last for 0 .. $bytes;
  14.         redo if @indices != @_;
  15.     }
  16. }
  17.  
  18. my $bitmask = '';
  19. my @seq = 1..21;
  20. my $callback = sub {
  21.     state $counter = 0;
  22.     my $limit = shift;
  23.     if (++$counter > $limit) {
  24.         $counter = 0;
  25.         print "limit reached\n";
  26.         return 1;
  27.     }
  28.     print "[@_]\n";
  29.     return 0;
  30. };
  31.  
  32. my $limit = 6;
  33. powerset \$bitmask, $limit, \&{$callback}, @seq;
  34. powerset \$bitmask, $limit, \&{$callback}, @seq;
  35.  
  36.  
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement