In Perl, how can I generate all possible combinations of a list?

后端 未结 7 1236
执念已碎
执念已碎 2020-12-16 12:39

I have a file with a list, and a need to make a file that compares each line to the other. for example, my file has this:

AAA  
BBB  
CCC  
DDD  
EEE

I w

7条回答
  •  [愿得一人]
    2020-12-16 13:07

    Take a look at Math::Combinatorics - Perform combinations and permutations on lists

    example copying from the CPAN:

    use Math::Combinatorics;
    
      my @n = qw(a b c);
      my $combinat = Math::Combinatorics->new(count => 2,
                                              data => [@n],
                                             );
    
      print "combinations of 2 from: ".join(" ",@n)."\n";
      print "------------------------".("--" x scalar(@n))."\n";
      while(my @combo = $combinat->next_combination){
        print join(' ', @combo)."\n";
      }
    
      print "\n";
    
      print "permutations of 3 from: ".join(" ",@n)."\n";
      print "------------------------".("--" x scalar(@n))."\n";
      while(my @permu = $combinat->next_permutation){
        print join(' ', @permu)."\n";
      }
    
      output:
    combinations of 2 from: a b c
      ------------------------------
      a b
      a c
      b c
    
      permutations of 3 from: a b c
      ------------------------------
      a b c
      a c b
      b a c
      b c a
      c a b
      c b a
    

提交回复
热议问题