Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Some help with array searching??? 1

Status
Not open for further replies.

BobMCT

IS-IT--Management
Sep 11, 2000
756
US
Gents;

Given an array such as @Array1 = (1, 3, 5, 7, 9);
and a search argument of '4', I am trying to locate the element on @Array1 that is closest to yet less than or equal to the search argument and return the proper index value.

While searching for exact matches using various methods including loops and greps seem to be quite easy, searching for the condition stated above is proving to be frustrating.

Perhaps someone can review my snippet below and advise on a workable method to accomplish this?

===Begin Snippet===

my $index = 0;
my @Array1 = ('1', '3', '5', '7', '9');
my $Argument = "4";
my $Last_Index = 0;

$index=$#Array1;
while($index >= 0) {
if ($Array1[$x] le $Argument) {
last;
}
$Last_Index = $index
$index--;
}

===End Snippet===

Thanks all... [ponder]
 
Is there a particular reason why in the example you've posted you're declaring all your numbers as strings and using string comparison?

Assuming they're all numeric, here are two alternatives (one with an additional module, one without):
Code:
use List::Util qw(max);

my @Array1 = (1, 3, 5, 7, 9);

my ( $largest_under_4 ) = max grep $_ <= 4, @Array1;

print "$largest_under_4\n";

Code:
my @Array1 = (1, 3, 5, 7, 9);

my $largest_under_4 = $Array1[0];
for ( @Array1[1 .. $#Array1] ) {
   if ( $_ <= 4 && $_ > $largest_under_4 ) {
      $largest_under_4 = $_;
   }
}
print "$largest_under_4\n";
 
He was looking for the index...
There are many ways of doing that. This is how I would do it:
Code:
my@Arr=(1,2,4,5,7,9);
my$argument=4;
my$i=-1;for(@Arr){last if$_>$argument;$i++}
if($i<0){
  print"No answer: argument is less than lowest in array\n";
}else{
  print"Answer is:i=$i,v=$Arr[$i]\n";
}
We are of course assuming the array is numeric and sorted in ascending order...

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Thanks, prex1;

You are observant. I used a slightly modified version of your supplied logic and it works exactly as I had been looking for. And, its considerably faster than my supplied solution as it searches low to high and most of my numbers are low.

Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top