3

I have a list of positive and negative ones {1,1,-1,1,1,-1,1,-1,1,-1,-1,1,1,1,-1} And I want to find and highlight the subsequence of the lists that have the pattern {...,1,1,___,-1,-1,...}. So ideally my output would be {1,1,-1,1,1,-1,1,-1,1,-1,-1,1,1,1,-1}.

xanadu
  • 31
  • 1

1 Answers1

6
list = {1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1};

SequenceCases[list, {a___, Shortest[b : PatternSequence[1, 1, ___, -1, -1]],  c__} :> 
  Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}]][[1]]

Mathematica graphics

Note: the subsequence starting with the first entry also satisfies your pattern, and it can be obtained by removingShortest above or by changing it to Longest:

SequenceCases[list, {a___, b : PatternSequence[1, 1, ___, -1, -1],  c__} :> 
  Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}]][[1]]

Mathematica graphics

kglr
  • 394,356
  • 18
  • 477
  • 896
  • Is there a way to find the first time that pattern occurs? The code is taking a really long time to run with your solution, and I think finding the first occurrence might still give me what I need. – xanadu Jan 28 '17 at 23:23
  • 1
    @xanadu, using the third argument SequenceCases[list, {a___, b : PatternSequence[1, 1, ___, -1, -1], c__} :> Flatten[{a, Style[#, Bold, Red] & /@ {b}, c}], n] gives the first n matches. – kglr Jan 28 '17 at 23:53