5
$\begingroup$

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 *)
$\endgroup$
1
  • 1
    $\begingroup$ Sounds like a job for SequenceReplace[]: SequenceReplace[RanList[100], {-1, 1, -1, 1, -1, 1} -> Nothing]. $\endgroup$ Apr 27, 2020 at 12:34

1 Answer 1

6
$\begingroup$
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

enter image description here

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}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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