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

后端 未结 7 1240
执念已碎
执念已碎 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:08

    I benchmarked the following Perl modules:

    1. Math::Combinatorics
    2. Algorithm::Combinatorics
    3. Cmb

    Benchmark consisted of doing what the OP asked, combinations of 2 items, but ramping the set of words up to 10,000 instead of just the original 5 requested (AAA BBB CCC DDD EEE).

    Test script for Math::Combinatorics

    #!/usr/bin/env perl
    use strict; use warnings;
    use Math::Combinatorics;
    my $strings = [qw(AAA BBB CCC DDD EEE) x 2000];
    my $iter = new Math::Combinatorics (count => 2, data => $strings);
    while (my @c = $iter->next_combination) {
        print "@c\n";
    }
    

    This produced ~53,479 combinations per-second.

    Test script for Algorithm::Combinatorics

    #!/usr/bin/env perl
    use strict; use warnings;
    use Algorithm::Combinatorics qw(combinations);
    my $strings = [qw(AAA BBB CCC DDD EEE) x 2000];
    my $iter = combinations($strings, 2);
    while (my $c = $iter->next) {
        print "@$c\n";
    }
    

    This produced ~861,982 combinations per-second.

    Test script for Cmb

    #!/usr/bin/env perl
    use strict; use warnings;
    use Cmb;
    my $strings = [qw(AAA BBB CCC DDD EEE) x 2000];
    my $cmb = new Cmb { size_min => 2, size_max => 2 };
    $cmb->cmb_callback($#$strings + 1, $strings, sub {
        print "@_\n";
        return 0;
    });
    

    This produced ~2,940,882 combinations per-second.

    But if you just need to print the combinations, Cmb can actually do that even faster than the above.

    #!/usr/bin/env perl
    use strict; use warnings;
    use Cmb;
    my $strings = [qw(AAA BBB CCC DDD EEE) x 2000];
    my $cmb = new Cmb { size_min => 2, size_max => 2 };
    $cmb->cmb($#$strings + 1, $strings);
    

    This produced ~3,333,000 combinations per-second.

    Benchmarks were performed using dpv on CentOS Linux release 7.7.1908 (Core) under kernel 3.10.0-1062.1.1.el7.x86_64 x86_64 using Perl 5.16.3 on an Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz

提交回复
热议问题