Fellow monks,

I found myself in a need to implement a custom subrange from an array (in C++, but a Perl solution should be similar). It's an interesting challenge, and I wonder if there exists a really elegant solution to it:

Input: an array of some length and a pair of numbers that spacify its range. For example you get an array with 4 elementsand the pair is (5, 8) - that is, the 0th array value has a subscript of 5, the last of 8. This range can be descending ! You also receive a subrange that should be extracted from the array.

To formalize, here's the input to your function:

{ arr => \@the_array, arr_range => [from, to], subrange => [subfrom, subto] }

The returned value should be the sub-array of the_array in the range subfrom-subto, in the correct sub-order (ascending or descending). For example you get:

{ arr => [cero, uno, dos, tres], range => [5, 8], subrange => [6, 5] }

You should return: [uno, cero]

You're also required to report if some of the requested subrange elements are out of the array range, i.e. if in the example you'd be asked for subrange (6, 4) it's an error since 4 is not in the array range (5, 8).

This is simple to implement in a straightforward way - 4 cases (range ascending + subrange descending, range descending + subrange descending ...), but I wonder if there's really an elegant solution ?!

Enjoy !

P.S: Naturally, golf answers will be also interesting.


In reply to Code challenge: array subrange by spurperl

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.