Re: Efficient way of comparing items in an array




Hi Dave,


Dave Tang wrote:
On Thu, 30 Oct 2008 16:04:31 +1000, Dave Tang <d.tang@xxxxxxxxxxxxx> wrote:

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.
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__



You have a list of sorted numbers and you're making a single pass through it; you are also looking at each number at most once [excluding the starting end-point which you keep track of]. So, I can't think of a way to make it much faster.

Your first if statement can probably be removed. You only use it once, right? In the very beginning. You might want to set $prev and $first to $array[0], and start the for loop from $i = 1. Or do you have NULLs in your data?

These are co-ordinates in a genome or something? If your data file is so large that you find that your program is too slow, you might want to try a non-scripting language (C or C++). Another more likely problem if your data file is too big is that the slowdown might be due to disk accesses -- and if so, there isn't much I can think of which you can do.

Beyond these thoughts, I can't think of anything else...maybe someone else can?

Ray


.



Relevant Pages

  • Re: Populate from text file
    ... If it's an ordinary text data file just use ... John Nurick [Microsoft Access MVP] ... Please respond in the newgroup and not by email. ... Prev by Date: ...
    (microsoft.public.access.tablesdbdesign)
  • Re: get the first word of a file
    ... >> I have a data file of the format ... cat serves no purpose. ... Prev by Date: ...
    (comp.unix.shell)
  • Re: quicken 2003 restore files
    ... restore your data file? ... > donnie m ... Prev by Date: ...
    (microsoft.public.windowsxp.basics)
  • Using SQL in Word MailMerge
    ... matter the size of the data file. ... Regards ... Dale ... Prev by Date: ...
    (microsoft.public.word.vba.general)
  • How to save mail merge data file on disk or cd?
    ... Instructions as to saving the address file saved in the data file of word ... onto a disk or cd please....Thanks! ... Prev by Date: ...
    (microsoft.public.word.docmanagement)