Reputation: 840
I tried to find previous threads similar to my question but didn't find.
Consider a function which gets an array and a number. I would like to find the next higher number.
Example:
Input: arr = {2,5,3,8,15,10}, number = 6
Output: 8
because 6 < 8
.
What is the best algorithm to do it in Perl?
Edit: What I tried:
my @arr = (2,5,3,8,15,10);
my $number = 6;
my $next_largest = 10000000;
foreach my $val (@arr) {
if($number < $val && $next_largest > $val) {
$next_largest = $val;
}
}
if(defined($next_largest)) {
print $next_largest."\n";
}
Is there a way without declaring $next_largest = 10000000
? it doesn't look very good and it doesn't handle the case of value higher than this value. Also if I try $next_lergest
without a number, it doesn't work.
By best I meant - best looking (time isn't important so much).
Upvotes: 2
Views: 254
Reputation: 1818
This does it too:
use strict;
use warnings;
my @arr = (2,5,3,8,15,10);
my $number = 6;
my $next_largest = (sort {$a <=> $b} grep {$_ > $number} @arr)[0];
if(defined($next_largest)) {
print $next_largest."\n";
}
Upvotes: 0
Reputation: 234847
You can use $number
as a sentinel value:
my @arr = (2,5,3,8,15,10);
my $number = 6;
my $next_largest = $number;
foreach (@arr) {
if($number < $_ && ($next_largest == $number || $next_largest > $_)) {
$next_largest = $_;
}
}
if($next_largest > $number) {
print $next_largest."\n";
}
This eliminates the arbitrary large value in your code and only prints a result if an element strictly greater than $number
was found.
Note: The answer by @ysth is much more elegant, but mine may be a bit more memory efficient.
Upvotes: 0
Reputation: 98398
use List::Util 'min';
my @arr = (2,5,3,8,15,10);
my $number = 6;
my $next_largest = min grep $_ > $number, @arr;
if(defined($next_largest)) {
print $next_largest."\n";
}
Upvotes: 7
Reputation: 5748
First, sort the array in numerical ascending order. Then loop through elements in array, until a higher number is found.
my $input_number = 6;
my @array = (2, 5, 3, 8, 15, 10);
my @sorted_array = sort { $a <=> $b } @array;
my $found = 0;
my $next_number;
foreach (@sorted_array) {
my $loop_number = $_;
if ($loop_number > $input_number) {
$next_number = $loop_number;
$found = 1;
last;
}
}
if ($found == 1) {
print "next higher number for " + input_number + " is: " + next_number;
} else {
print "no next higher number found";
}
Upvotes: 0