Finding BEGINNING & ENDING positions of sequential sublists from an array

teknokid1's Avatar, Join Date: Nov 2011
Newbie Member
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
. .
. .
. .
. .
0
chorny's Avatar, Join Date: Jun 2010
Go4Expert Member
So, what question do you have?
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
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