Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/forums/perl/)
-   -   Finding BEGINNING & ENDING positions of sequential sublists from an array (http://www.go4expert.com/forums/finding-beginning-positions-sequential-t27122/)

teknokid1 9Nov2011 20:05

Finding BEGINNING & ENDING positions of sequential sublists from an array
 
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
. .
. .
. .
. .

chorny 11Nov2011 05:45

Re: Finding BEGINNING & ENDING positions of sequential sublists from an array
 
So, what question do you have?

pradeep 25Nov2011 11:17

Re: Finding BEGINNING & ENDING positions of sequential sublists from an array
 
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



All times are GMT +5.5. The time now is 05:17.