# Isolating sequences from a list based on a formula

SeedRandom[4];
alist = RandomInteger[{-4, 4}, 100]


From this list, I can isolate similar neighbors of length two:

SequenceReplace[alist, k : {Repeated[a_, {2}]} :> k]


Or of length two or more:

SequenceReplace[alist, k : {Repeated[a_, {2, ∞}]} :> k]


Question: How do I isolate an additive inverse pattern sequence of even or odd length; e.g., {1,-1, 1, ...} or {4,-4}?

I am having difficulty coming up with a formula for it inside SequenceReplace.

Your help is much appreciated. Thank you.

Use PatternSequence, Condition (/;) and a form of Repeated that allows matching zero or one times:

SeedRandom[6];
With[{alist = RandomInteger[{-2, 2}, 200]},
SequenceReplace[alist,
k : {PatternSequence[a_, b_] .., Repeated[a_, {0, 1}]} /; a == -b :> k]]


{0, -2, {0, 0}, 1, 2, 0, -1, 2, {1, -1, 1, -1}, 2, {1, -1}, 0, {-1, 1}, 0, -1, 2, 2, 1, 1, -2, -1, 0, 1, 2, 0, -2, -2, -2, 0, {-2, 2, -2}, -1, -2, {1, -1, 1}, -2, -1, 0, -1, -1, {2, -2}, 1, 2, -1, -1, -1, -1, -1, {-1, 1}, 2, {-1, 1}, 2, {0, 0}, 2, 0, {-1, 1}, 2, -1, 2, 2, 2, -1, -2, -2, -2, 0, -1, 0, -1, -2, {-1, 1, -1}, -1, {-2, 2}, 0, -2, 1, -2, -1, 2, 1, 0, {-1, 1, -1}, {2, -2}, {-1, 1}, 2, 1, 0, -2, -2, -1, {-1, 1}, 1, -2, 1, 2, 0, -2, -2, {-1, 1, -1, 1}, 2, 0, {2, -2}, -1, -2, 1, 0, 2, -1, -1, -1, -1, -2, 1, {1, -1}, -2, -2, {1, -1, 1, -1}, 0, {2, -2}, 0, -2, -2, -2, -1, 2, 2, {0, 0, 0, 0}, -2, 1, 2, -1, -2, -2, -2, 1, 0, 1, -2, -2, -1, {2, -2}, 1, 0, -2, -1, 2, -1, 2, 1, -2, 0, -2, 0, 1, 2, 0, {-1, 1}, 1, 1, 2, -1, -2, 1, -2, 1}

• I could not have come up with this so I am glad I asked. Thank you very much.
– Syed
Sep 11, 2022 at 8:28
• @Syed Thanks! I simplified my solution a bit, not a big change but nonetheless. Sep 11, 2022 at 9:25