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
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityf = 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
Length @ # > 1 &][[-1, 1]]]
. I am not familiar with this style of programming.
$\endgroup$
Select
was not general enough.
$\endgroup$
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
. ...
$\endgroup$
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.