Hi L~R,
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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|