How to get all possible combinations of neighboring elements in the following order using Perl?

For example, I have an array

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

How to get the following combinations:

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

If so, what is the name for this kind of combination (or permutation)?

Thanks, as always!

+3
source share
3 answers

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;

Conclusion:

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

Personally, I find a "C style" loop for a loop that uses gbacon that often unnecessarily complicates the code. And, as a rule, you can replace it with a "range-style" for a loop that is easier to complete.

#!/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;
+7
source

:

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;
+1

Source: https://habr.com/ru/post/1764340/


All Articles