5
$\begingroup$
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.

$\endgroup$

1 Answer 1

5
$\begingroup$

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}

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.