3
$\begingroup$

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}.

$\endgroup$
  • $\begingroup$ related: 95912 $\endgroup$ – Kuba Jan 28 '17 at 22:02
6
$\begingroup$
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

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – xanadu Jan 28 '17 at 23:23
  • 1
    $\begingroup$ @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. $\endgroup$ – kglr Jan 28 '17 at 23:53

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.