我被要求执行 perl 程序以在数组中查找值(来自用户输入)。如果匹配“没关系”。如果不匹配,则在 index[0] 到 index[1] ... index[n] 的值范围内进行检查。因此,如果值与两个元素之间的值匹配,那么靠近这些元素的报告可能是 index[0] 或 index[1]。
让你解释。
给定数组:10 15 20 25 30
;
从用户获取值:14(例如)
因此 14 在 10(array[0]) - 15(array[1]) 这两个元素中匹配
Ultimately the check point is do not use more than one
for
loop and never use thewhile
loop. You need to check onefor
loop and many ofif
conditions.
我在这里得到的输出是:
use strict;
use warnings;
my @arr1 = qw(10 15 20 25 30);
my $in = <STDIN>;
chomp($in);
if(grep /$in/, @arr1)
{ } #print "S: $in\n"; }
else
{
for(my $i=0; $i<scalar(@arr1); $i++)
{
my $j = $i + 1;
if($in > $arr1[$i] && $in < $arr1[$j])
{
#print "SN: $arr1[$i]\t$arr1[$j]\n";
my ($inc, $dec) = "0";
my $chk1 = $arr1[$i] + 1;
AGAIN1:
if($in == $chk1)
{ }
else
{ $chk1++; $inc++; goto AGAIN1; }
my $chk2 = $arr1[$j] - 1;
AGAIN2:
if($in == $chk2){ }
else
{ $chk2--; $dec++; goto AGAIN2; }
if($inc > $dec)
{ print "Matched value nearest to $arr1[$j]\n"; }
elsif($inc < $dec)
{ print "Matched value nearest to $arr1[$i]\n"; }
}
}
}
但是我的问题是算法有办法吗?。因此,如果有人可以在这方面提供帮助,我们将不胜感激。
提前致谢。
最佳答案
你似乎下定决心要让它尽可能复杂:-)
您的规范并不完全清楚,但我认为这可以满足您的要求:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my @array = qw[10 15 20 25 30];
chomp(my $in = <STDIN>);
if ($in < $array[0]) {
say "$in is less than first element in the array";
exit;
}
if ($in > $array[-1]) {
say "$in is greater than last element in the array";
exit;
}
for (0 .. $#array) {
if ($in == $array[$_]) {
say "$in is in the array";
exit;
}
if ($in < $array[$_]) {
if ($in - $array[$_ - 1] < $array[$_] - $in) {
say "$in is closest to $array[$_ - 1]";
} else {
say "$in is closest to $array[$_]";
}
exit;
}
}
say "Shouldn't get here!";
关于algorithm - 使用perl查找数组中值的算法 - 绝对面试题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892492/