in reply to How to get the index of smallest whole number in an array?
G'day sohamsg90,
Welcome to the Monastery.
I'm not really trying to nitpick; however, simply saying you wanted the index of the smallest "non-negative integer", would have precluded the need to provide a definition of what you meant by "whole numbers" — which, incidentally, differs from what is generally understood by that term (e.g. -5 is a whole number; -0.5 isn't) — and made the whole thing less confusing. I had to read it twice to make sure I understood what you were getting at.
You've added two negative integers to your test data: that's good. However, you don't have any non-integer values to test: that's less good.
The following one-liner includes fractional test values and code to handle them.
$ perl -E 'my @x = qw{3 4 71 1 -598 -100293 0.5 -0.5}; say +(sort { $a +->[1] <=> $b->[1] } map $x[$_] >= 0 && $x[$_] == int $x[$_] ? [ $_ => + $x[$_] ] : (), 0 .. $#x)[0][0]' 3
Well, that was my actual test. Here it is again, in a somewhat more readable format.
$ perl -E ' my @x = qw{3 4 71 1 -598 -100293 0.5 -0.5}; say +( sort { $a->[1] <=> $b->[1] } map $x[$_] >= 0 && $x[$_] == int $x[$_] ? [ $_ => $x[$_] ] : (), 0 .. $#x )[0][0] ' 3
I also tested this with the first element of @x changed from 3 to 0.3, and also changed to -0.3. The result was the same for all three runs.
You'll note that the general approach is similar to some other solutions already posted.
— Ken
|
|---|