Re: Efficient way of comparing items in an array



On Thu, 30 Oct 2008 16:04:31 +1000, Dave Tang <d.tang@xxxxxxxxxxxxx> 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/

.



Relevant Pages

  • Re: Sorting numbers based on value into arrays
    ... If the sorted array numbers are unique then the below example should be really close. ... Let me know if this is close enough for your purpose. ... Prev by Date: ...
    (comp.lang.labview)
  • Re: array "sort()" question, weird php behavior ?
    ... Mmmhhh according to me true => 1. ... I didn't mention it but rather than make a var_dump on the sorted array, ... Arnaud ... Prev by Date: ...
    (comp.lang.php)
  • rotated sorted list search
    ... An element in a sorted array can be found in Otime via binary ... But suppose I rotate the sorted array at some pivot unknown to ... Prev by Date: ...
    (comp.programming)
  • Change link text
    ... Is there a good cross-browser way of ... achieving this? ... Is HTMLAnchorElement a good place to start? ... Prev by Date: ...
    (comp.lang.javascript)
  • Trigger
    ... StockCode, Warehouse, TrnYear, TrnMonth, EntryDate, TrnQty and Movement Type ... How would I go about achieving this? ... I'm not sure what BOL is telling me. ... Prev by Date: ...
    (microsoft.public.sqlserver.mseq)