Consider if you would the case where we have some list of elements:
list0 = {54, 4, 7, 9, 3, 54, 4, 20, 2, 456, 2, 3};
And we have some target list:
targetList = {2, 3, 4, 7};
We'd like to scan from left to right through list0
and chop off an RHS tail at the moment all elements in targetList
have appeared. With the example given we would have:
list0chopped = {54, 4, 7, 9, 3, 54, 4, 20, 2};
As an output.
Is there a simple way to do this?
Answer
I propose:
truncate[a_List, b_List] :=
a ~Take~ Max @ Lookup[PositionIndex[a][[All, 1]], b, 0]
For maximum performance replace PositionIndex
with cleanPosIdx
from Why is the new PositionIndex horribly slow?
I'll add comparative timings later if I get the chance.
Comments
Post a Comment