# Delete parts of a linear array

I think this question has not been answered. Suppose I generate a random linear array with only two entries -1 or +1. From this array I want to delete all sequences that alternate such as {-1,1,-1,1,-1,1} or {1,-1,1,-1,1,-1} and similar longer sub-sequences but not shorter ones (which I want to retain) e.g. I want to retain sub-sequences such as {-1,1,-1,1} and {1,-1} etc. I know how to delete a particular sub-sequence but I don't know how to delete all sub-sequences that are longer than 4 alternating signs.

f[k_] := 2 RandomInteger[] - 1

RanList[m_] := Array[f, m]

DeleteCases[RanList[100], {-1, 1, -1, 1, -1, 1}] (* for example *)

• Sounds like a job for SequenceReplace[]: SequenceReplace[RanList[100], {-1, 1, -1, 1, -1, 1} -> Nothing]. Apr 27, 2020 at 12:34

SeedRandom[123]
rl = RanList[100]

 {-1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1,
-1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1,
-1, -1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1,
1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1,
1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1}

SequenceReplace[pat : {Repeated[PatternSequence[-1, 1], {4, Infinity}] |
Repeated[PatternSequence[1, -1], {4, Infinity}]} :>
Sequence @@ ( Style[#, Red] & /@ pat)]@rl


SequenceReplace[{Repeated[PatternSequence[-1, 1], {4, Infinity}] |
Repeated[PatternSequence[1, -1], {4, Infinity}]} -> Nothing]@rl

  {-1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1,
-1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, -1,
-1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1,
1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1,
-1, 1, -1, -1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1}