4
$\begingroup$

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

$\endgroup$
2
$\begingroup$
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

$\endgroup$
  • $\begingroup$ Thank you !! Would you mind to explain this part : Length @ # > 1 &][[-1, 1]]]. I am not familiar with this style of programming. $\endgroup$ – james Sep 6 '18 at 9:38
  • $\begingroup$ First@Position[list, 5] $\endgroup$ – rmw Sep 6 '18 at 9:41
  • $\begingroup$ @james, i updated with new method. The older one with Select was not general enough. $\endgroup$ – kglr Sep 6 '18 at 10:29
  • $\begingroup$ 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. $\endgroup$ – james Sep 6 '18 at 12:58
  • $\begingroup$ @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. ... $\endgroup$ – kglr Sep 7 '18 at 8:13
2
$\begingroup$

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.

$\endgroup$

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.