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


In reply to Re: How to get the index of smallest whole number in an array? by kcott
in thread How to get the index of smallest whole number in an array? by sohamsg90

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.