in reply to Re^2: Algorithm to convert combinations to bitstring
in thread Algorithm to convert combinations to bitstring
1 use List::AllUtils qw/sum/; 2 use Bit::Vector; 3 4 my $k = 2; 5 6 my @letters = split '',"ABCDE"; 7 my $n = scalar(@letters); 8 9 my $vec = Bit::Vector->new($n); 10 11 while(!$vec->increment){ 12 my $i = $vec->to_Bin; # current bitstring 13 my $s = sum(split '',$i); # sum up to find out how many bits a +re lit 14 15 next unless ($s == $k); # just the ones with $k bits lit 16 17 18 my $str = # convert bitstring to string 19 join '', 20 map { $letters[$_] } 21 grep { $vec->contains($_); } 22 0..$n-1 ; 23 24 print "$s $i $str\n"; 25 };
The seen and set_seen routines are incorporated in the check at line 15.
The output for this is:
2 00011 AB 2 00101 AC 2 00110 BC 2 01001 AD 2 01010 BD 2 01100 CD 2 10001 AE 2 10010 BE 2 10100 CE 2 11000 DE
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: Algorithm to convert combinations to bitstring
by Limbic~Region (Chancellor) on Jan 01, 2010 at 19:49 UTC | |
by spx2 (Deacon) on Jan 10, 2010 at 14:57 UTC | |
by Limbic~Region (Chancellor) on Jan 10, 2010 at 15:26 UTC |