On Thu, 30 Oct 2008 16:04:31 +1000, Dave Tang <[EMAIL PROTECTED]> wrote:

Hi everybody,

I am working with a sorted array (sorted from smallest to largest), containing coordinates as such:

13645692
13645693
13645694
13645695
13645696
13645697
13645698
13645699
13645700
13645701
13645702
13645703
13645704
13645705
13645706
13645707
13645708
13645709
13645710
13645711

If each element has a difference of 1 from the next element, I would like to connect them and for this example the output will be:

13645692 - 13645711

However sometimes the elements are not separated by 1 as such:

13645692
13645693
13645694
13645709
13645710
13645711

For this example the output would be:

13645692 - 13645694
13645709 - 13645711

I have written the following code but I wish I could think of a much better way of achieving my output. Any tips and suggestions will be greatly appreciated! Thanks in advance.

my $prev = 'NULL';
my $first = '';
for (my $i = 0; $i < scalar(@array); ++$i){
    if ($prev eq 'NULL'){
       $prev = $array[$i];
       $first = $array[$i];
    }
    else {
       if ($prev == $array[$i] + 1){
          $prev = $array[$i];
       }
       else {
          print "$first - $prev\n";
          $prev = $array[$i];
          $first = $array[$i];
       }
    }
}
print "$first - $prev\n";

__END__

Dave



Oops I mean (I wrote the code in my email) and sorry for the double post.

my $prev = 'NULL';
my $first = '';
for (my $i = 0; $i < scalar(@array); ++$i){
    if ($prev eq 'NULL'){
       $prev = $array[$i];
       $first = $array[$i];
    }
    else {
       if ($array[$i] == $prev + 1){
          $prev = $array[$i];
       }
       else {
          print "$first - $prev\n";
          $prev = $array[$i];
          $first = $array[$i];
       }
    }
}
print "$first - $prev\n";

 __END__

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to