开发者

How do I get all the possible combinations of neighboring items in a subsequent order using Perl?

For example, I have an array

开发者_如何转开发
my @arr = qw(0 1 2 3 4);

How do I get the following combinations:

0
01
012
0123
01234
1
12
123
1234
2
23
234
3
34
4

If any, what's the name for this kind of combination (or permutation)?

Thanks like always!


Personally I find the "C style" for loop that gbacon uses often complicates code unnecessarily. And it's usually possible to replace it with the "range-style" for loop that is easier to follow.

#!/usr/bin/perl

use strict;
use warnings;

my @arr = qw(0 1 2 3 4);

my @result;
for my $i (0 .. $#arr) {
  for my $j ($i .. $#arr) {
    push @result => [ @arr[$i .. $j] ];
  }
}

print @$_, "\n" for @result;


Use array slices:

#! /usr/bin/perl

use warnings;
use strict;

my @arr = qw(0 1 2 3 4);

my @result;
for (my $i = 0; $i < @arr; $i++) {
  for (my $j = $i; $j < @arr; $j++) {
    push @result => [ @arr[$i .. $j] ];
  }
}

print @$_, "\n" for @result;

Output:

0
01
012
0123
01234
1
12
123
1234
2
23
234
3
34
4


Here's a way to divide up the problem into more discrete components:

use strict;
use warnings;

sub consec_subseq_leading {
    # (1, 2, 3) ==> ( [1], [1, 2], [1, 2, 3] )
    return map [ @_[0 .. $_] ], 0 .. $#_;
}

sub consec_subseq {
    # (1, 2, 3) ==> ( F(1, 2, 3), F(2, 3), F(3) )
    # where F = consec_subseq_leading
    my $j = $#_;
    return map consec_subseq_leading( @_[$_ .. $j] ), 0 .. $j;
}

my @cs = consec_subseq(0 .. 4);
print "@$_\n" for @cs;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜