# List Detect Position of Equal Sequence

How can I find the position of the first element (here 5) of the last equal sequence (here 5,5,5) ?

list = {2, 2, 2, 3, 3, 3, 3, 5, 5, 5}


In this case: 8

f = With[{s = Split @ #},
1 + Length @ Flatten @ Drop[s, -(1 + LengthWhile[Reverse@s, Length @ # == 1 &])]] &;
f @ list


8

f @ {7, 7, 4, 5, 6, 7, 7, 7, 7, 7, 8, 9}


6

• Thank you !! Would you mind to explain this part : Length @ # > 1 &][[-1, 1]]]. I am not familiar with this style of programming. Sep 6, 2018 at 9:38
• First@Position[list, 5]
– rmw
Sep 6, 2018 at 9:41
• @james, i updated with new method. The older one with Select was not general enough.
– kglr
Sep 6, 2018 at 10:29
• This is great work !! Thank you very much ! If you have the time, can you just quickly describe in your answer how your method works ? I don't quite understand it. Sep 6, 2018 at 12:58
• @james, the following are intemediate steps : For lst = {7, 7, 4, 5, 6, 7, 7, 7, 7, 7, 8, 9}, (1) s = Split[lst] splits list into parts with same elements, (2)  LengthWhile[Reverse@s, Length @ # == 1 &] gives the number of singleton elements at the end of s. The part we want is the last part that remains after we drop the singleton elements at the end of s (call it p). The number of lst elements that precede p is the sum of the parts in s that precede p in s. ...
– kglr
Sep 7, 2018 at 8:13

SequencePosition is made-to-order for this task, identifying the positions of the first and last element of a designated sequence. And, Repeated[z_, {2, Infinity}] designates any sequence of repeated characters of length two or greater.

g[ll_] := Length@ll + 1 -
SequencePosition[Reverse@ll, {Repeated[z_, {2, Infinity}]}][[1, 2]]

g@{2, 2, 2, 3, 3, 3, 3, 5, 5, 5}
(* 8 *)

g@{7, 7, 4, 5, 6, 7, 7, 7, 7, 7, 8, 9}
(* 6 *)


Alternatively, and a bit more briefly,

h[ll_] := SequencePosition[ll, {Repeated[z_, {2, Infinity}]}, Overlaps -> False][[-1,1]]


which gives the same results.

a = {2, 2, 2, 3, 3, 3, 3, 5, 5, 5};

b = {7, 7, 4, 5, 6, 7, 7, 7, 7, 7, 8, 9};


Using SequencePosition

f = First @ Last @ SequencePosition[#, {x_, x_ ..}, Overlaps -> False] &;

f /@ {a, b}


{8, 6}

a = {2, 2, 2, 3, 3, 3, 3, 5, 5, 5};

b = {7, 7, 4, 5, 6, 7, 7, 7, 7, 7, 8, 9};


Another way to do this using Split and Thread:

 f = First@
Last@Keys[
Cases[Split[
Thread[Range@Length@# -> #] &@#, #2[[2]] - #1[[2]] ==  0 &], {_, __}]] &;

f /@ {a, b}


{8, 6}