I have the need to collect values from the rows of rectangular arrays of arbitrary precision integers, given a target element value and allowed "distance" (positions +/- within the row from found targets).
E.g., given a target array of
ar={{6, 10, 6, 5, 7}, {10, 2, 2, 0, 7}, {0, 6, 3, 7, 5}, {2, 8, 6, 9, 1}, {8, 8, 5, 0, 8}}
and a target value of 5
, with an allowed "distance" of 2
, the result should be
{10, 6, 5, 7, 3, 7, 5, 8, 8, 5, 0, 8}
Result must be order-preserving, i.e., as if the array were "read" left to right, top to bottom.
I'm using this:
nearEles[array_, ele_, dist_, posOnly_: False] :=
With[{r = Range[-dist, dist], d = Dimensions[array][[2]]},
If[posOnly, #, Extract[array, #]] &[SparseArray[
Map[IntegerDigits[BitOr @@ (BitShiftLeft[FromDigits[#, 2], r]), 2, d] &,
SparseArray[BitXor[1, Unitize[array- ele]]]]]["NonzeroPositions"]]];
so in the above example, called as nearEles[ar,5,2]
gets me what I need.
On actual data (typically 1K X 1K to 4K X 2K array size), performs pretty well.
Any ideas for a more efficient (and perhaps less ungainly) method?