Finding BEGINNING & ENDING positions of sequential sublists from an array

Discussion in 'Perl' started by teknokid1, Nov 9, 2011.

  1. teknokid1

    teknokid1 New Member

    Joined:
    Nov 9, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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
    . .
    . .
    . .
    . .
     
  2. chorny

    chorny New Member

    Joined:
    Jun 6, 2010
    Messages:
    20
    Likes Received:
    2
    Trophy Points:
    0
    Home Page:
    http://chorny.net
    So, what question do you have?
     
  3. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Code:
    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: Nov 25, 2011

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice