Finding BEGINNING & ENDING positions of sequential sublists from an array

Newbie Member
9Nov2011,20:05   #1
teknokid1's Avatar
I have got an Perl array like:

@array = (1,2,3,4,5,6,1,2,3,4,1,2,1,2,3,4,5,6,7,8,9........ .......)

This numeric sequence will be always sequentially increasing, unless it encounters, The beginning of the new sequentially increasing numeric sequence.
SO in this array we get sequentially increasing many subsists.

There can be n numbers in this array and so can many sequentially increasing subsists.These sublists will always be increasingly sorted.

I want to extract the BEGINING and the ENDING positions of these subsists in the array with respect to array beginning position 0.

(1,2,3,4,5,6) BEG=0 END=5
(1,2,3,4) BEG=6 END=9
(1,2) BEG=10 END=11
(1,2,3,4,5,6,7,8,9) BEG=12 END=20
. .
. .
. .
. .
Go4Expert Member
11Nov2011,05:45   #2
chorny's Avatar
So, what question do you have?
Team Leader
25Nov2011,11:17   #3
pradeep's Avatar
Code: Perl
use strict;
use warnings;

my @array = ( 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9 );

my $subset_start_idx = 0;
for ( my $i = 0 ; $i <= $#array ; $i++ ) {
    my $next_idx = $i + 1;
    if ( ( $next_idx <= $#array && $array[$next_idx] < $array[$i] ) || $next_idx == $#array ) {
        printf( '(%s) Start = %s End = %s%s', join( ',', @array[ $subset_start_idx .. $i ] ), $subset_start_idx, $i, "\n" );
        $subset_start_idx = $next_idx;
    }
}

Output:
Code:
(1,2,3,4,5,6) Start = 0 End = 5
(1,2,3,4) Start = 6 End = 9
(1,2) Start = 10 End = 11
(1,2,3,4,5,6,7,8) Start = 12 End = 19

Last edited by pradeep; 25Nov2011 at 11:20.. Reason: Bug fix