Re: Efficient way of comparing items in an array
- From: rwan@xxxxxxxxxxxxxxxxxxx (Raymond Wan)
- Date: Thu, 30 Oct 2008 16:52:41 +0900
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
.
- References:
- Curly braces and the logic of PERL
- From: Brian
- Re: Curly braces and the logic of PERL
- From: "Octavian Rasnita"
- Re: Curly braces and the logic of PERL
- From: "Jenda Krynicky"
- Re: Curly braces and the logic of PERL
- From: Jack Gates
- Re: Curly braces and the logic of PERL
- From: Rob Dixon
- Re: Curly braces and the logic of PERL
- From: "Mr. Shawn H. Corey"
- Re: Curly braces and the logic of PERL
- From: Rob Dixon
- Re: Curly braces and the logic of PERL
- From: Mr. Shawn H. Corey
- Re: Curly braces and the logic of PERL
- From: Rob Dixon
- Re: Curly braces and the logic of PERL
- From: "Mr. Shawn H. Corey"
- Re: Curly braces and the logic of PERL
- From: "Chas. Owens"
- Efficient way of comparing items in an array
- From: "Dave Tang"
- Re: Efficient way of comparing items in an array
- From: Dave Tang
- Curly braces and the logic of PERL
- Prev by Date: RE: Reading from multiple sockets.
- Next by Date: Hi all
- Previous by thread: Re: Efficient way of comparing items in an array
- Next by thread: Re: Curly braces and the logic of PERL
- Index(es):
Relevant Pages
|