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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |