Possible Duplicate:
Finding a subsequence in a list
Question
The position of {3, 5} is the list
{1, 3, 4, 3, 5, 5, 1}
is 3. How can such a position be found fast when dealing with large lists?
Attempt
This is what I could think of:
list = Table[RandomInteger[3], {200}]
ToString[FromDigits[%]]
StringPosition[%, "123"][[1, All]]
Out put example:
{1, 3, 2, 3, 1, 2, 2, 0, 0, 1, 0, 2, 3, 0, 2, 1, 2, 2, 3, 3, 1, 0, 1,
3, 1, 1, 0, 3, 1, 3, 2, 2, 2, 1, 2, 0, 2, 0, 2, 2, 3, 1, 3, 1, 1, 1,
1, 3, 3, 1, 3, 1, 0, 2, 3, 1, 0, 3, 2, 3, 0, 1, 1, 3, 3, 3, 2, 1, 3,
0, 1, 0, 1, 0, 3, 1, 1, 2, 0, 0, 2, 0, 1, 3, 1, 2, 0, 2, 0, 2, 2, 2,
2, 2, 3, 1, 0, 3, 1, 2, 0, 3, 3, 2, 3, 1, 2, 3, 0, 0, 1, 2, 1, 2, 3,
2, 0, 1, 3, 1, 1, 1, 3, 2, 3, 3, 2, 0, 2, 3, 0, 3, 0, 3, 3, 2, 3, 2,
3, 1, 0, 1, 3, 0, 1, 1, 2, 2, 1, 2, 3, 3, 2, 3, 0, 2, 0, 3, 3, 2, 2,
0, 2, 3, 3, 2, 2, 0, 2, 2, 2, 3, 1, 3, 2, 0, 2, 0, 3, 3, 1, 0, 1, 2,
1, 2, 0, 0, 1, 0, 1, 0, 0, 2, 0, 3, 2, 1, 2, 2}
"132312200102302122331013110313222120202231311113313102310323011333213
0101031120020131202022222310312033231230012123201311132332023030332323
1013011221233230203322023322022231320203310121200101002032122"
{106, 108}
My solution does not work if the numbers in the list exceed 9 because there is no distinction between {..., 1, 2,...} and {...., 12, ....}. I also run into trouble if the sequence happens to start with 0.
I can fix this, but I doubt whether it is worth spending time on. There is likely a method that is faster in principle.
Answer
This isn't particularly fast, but I like it for simplicity:
seqpos[a_List, seq_List] :=
ReplaceList[a, {x___, Sequence @@ seq, ___} :> 1 + Length[{x}]]
seqpos[{1, 2, 3, 4, 2, 3}, {2, 3}]
(* {2,5} *)
Comments
Post a Comment