I have a large ordered list of lists of integers like this


and I would like to filter out the nested list based on two conditions. The conditions are two types of shorter nested lists

  • pairs of consecutive numbers that are not allowed anywhere in the nested list
  • pairs of consecutive numbers that must occur somewhere in the list



The output in this case would be

  • $\begingroup$ why do you need both notallowed and also allowed? Would not just using notallowed be enought to remove those unwanted? $\endgroup$
    – Nasser
    Feb 19 '18 at 23:45
  • $\begingroup$ No because allowed must be there all present. I can remove all notallowed but that does not guarantee there are all alowed (can be {3,4} but not {5,6}). $\endgroup$ Feb 20 '18 at 0:01
  • $\begingroup$ For your use case, what would the maximum integer be? Are the allowed and disallowed sets always pairs of consecutive numbers? Are your sublists always ordered? $\endgroup$
    – Carl Woll
    Feb 20 '18 at 0:54

You can use SequencePosition -- if it returns a nonempty list, then the given sublist is present:

 // Select[Length@SequencePosition[#, Alternatives @@ notallowed, 1] == 0 &]
 // Select@Function[list, 
       Length@SequencePosition[list, #, 1] > 0 & /@ allowed // Apply@And]
{{3, 4, 5, 6, 7, 9}, {3, 4, 5, 6, 11, 12}}
  • $\begingroup$ This is brilliant. Thank you. $\endgroup$ Feb 20 '18 at 2:34

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.