I may be missing the point here, but it seems to me that there is some ambiguity in what constitutes a generalization of the question, and the answers posted appear to be generalizing in quite different ways and/or answering quite different questions.
This ambiguity stems from the nice sequential ordering of a
and range
, but one interpretation (possibly just mine) of the requirement
"I would like to receive a list, which gathers elementwise all list elements of list a within the range of range
"
can be better illustrated by the following less nice example:
SeedRandom[1]
a = Sort@RandomSample[List /@ Range[20], 10]
range = {{1, #}, {# + 1, 20}} &@ RandomInteger[{Min[a] + 1, Max[a] - 2}]
(* {{1}, {2}, {6}, {8}, {9}, {11}, {13}, {16}, {17}, {19}} *)
(* {{1, 5}, {6, 20}} *)
The "correct" output (again, according to me, and possibly not to the OP) should be
(* {{1, 2}, {6, 8, 9, 11, 13, 16, 17, 19}} *)
which (as far as I can tell) only @Nasser's Map
and @BobHanlon's Pick
provide. (Obviously, this is still "nice" to some extent -- I'm assuming a
is an ordered list of integers, range
is composed of only two intervals, etc..)
Here's an assortment of other functions which provide the "correct" answer:
Pick[Flatten[a], UnitStep[Flatten[a] - range[[2, 1]]], #] & /@ {0, 1}
TakeDrop[#, First@FirstPosition[#, x_ /; x > range[[1, 2]]] - 1] &@ Flatten[a]
GatherBy[Flatten[a], # <= range[[1, 2]] &]
Last@Reap[Scan[Sow[#, # <= range[[1, 2]]] &, Flatten[a]]]
(They also give the right output for the example in the question.)
TakeDrop
might be worth considering?TakeDrop[Flatten@a, 3]
orTakeDrop[Flatten@a, First@range]
$\endgroup$