Given a sequence $(a_1, a_2, \ldots, a_n)$ and a number $m$, I'd like to count the number of subsequences $(a_{i_1},a_{i_2},a_{i_3})$ such that $a_{i_2} < m \leq a_{i_1}, a_{i_3}$.
For example, if the sequence is $(4,2,1,3)$ and $m = 3$, then there are two such subsequences, namely $(4,2,3)$ and $(4,1,3)$.
I solved the problem in two steps: transforming the list into a $0-1$ list using
binary[list_List, m_Integer] :=
Table[If[list[[i]] < m, 0, 1], {i, 1, Length[list]}]
allows us to count the $(1,0,1)$ subsequences several different ways, including
SequenceCount[binary[list, m], {1, ___, 0, ___, 1}, Overlaps -> All]
This seems to work fine, but now I'm trying to eliminate the first transformation and use SequenceCount
with a pattern on the original list directly; however the following does not work as it returns 1 instead of 2:
list = {4, 2, 1, 3}; m = 3;
SequenceCount[list, {x_, ___, y_, ___, z_} /; x >= m && y < m && z >= m, Overlaps -> All]
What is the problem with the second approach? I suspect that the conditional pattern is wrong, but I cannot figure out why. Neither SequenceCases
nor SequencePosition
help.
Bonus question: is there a 'better', more efficient way to do this?