11
$\begingroup$

Is there a pattern that can match repeated elements that appear more than twice in a row?

For the sake of example let's say I want to use pattern matching to delete subsequent duplicate:

l = {1,2,2,3,4};

l/.{b___,x_,x_,r___}->{b,r}

(*{1,3,4}*)

But

l = {1,2,2,2,3,4};

l/.{b___,x_,x_,r___}->{b,r}

(*{1,2,3,4}*)

I can try to use Repeated, but it doesn't seem to work:

l = {1, 2, 2, 2, 3, 4};

l /. {b___, x_, (x_) .., r___} -> {b, r}

(*{1,2,3,4}*)

Am I using it wrong?

$\endgroup$
13
$\begingroup$

Use the Longest pattern command to find the longest repeated sequence that matches the pattern.

l = {1, 2, 2, 2, 3, 4};

l /. {b___, x_, Longest[(x_) ..], r___} :> {b, r}

(*{1, 3, 4}*)
$\endgroup$
3
  • $\begingroup$ That's helpful. However, when I try it on l={1,1,1,2} the result is {1,1,2}, and not {2} as I would expect. $\endgroup$ – Whelp Feb 4 at 14:59
  • 1
    $\begingroup$ l={1,1,1,2} returns {2} when I test it. Are you sure that both the b and r have three blanks? $\endgroup$ – mmeent Feb 4 at 15:02
  • $\begingroup$ My bad, I had missed the "repeated" on the Longest pattern. It does work! $\endgroup$ – Whelp Feb 4 at 15:18
9
$\begingroup$

Another possibility is to use SequenceReplace:

SequenceReplace[{1, 2, 2, 2, 3, 4}, {x_, x_ ..} -> Sequence[]]

{1, 3, 4}

$\endgroup$
9
$\begingroup$

Try the following:

l = {1, 2, 2, 2, 3, 4};
l /. {b___, x_, (x_) .., r___} -> {{b}, {r}}
(* {{1}, {2, 3, 4}} *)

and you see that that r is ill-defined. Therefore we must restrict r:

l //. {b___, Repeated[x_, {2, 10}], Shortest@r___} :> {b, r}
(*{1, 3, 4}*)
$\endgroup$
1
  • $\begingroup$ Very nice debugging trick. I have already given the tick mark, but this would deserve one as well. $\endgroup$ – Whelp Feb 4 at 15:27
6
$\begingroup$

You might also consider using the two-argument form of Repeated for finer control:

{1, 2, 2, 3, 4}  /. {a___, Repeated[x_, {2, ∞}], b___} :> {a, b}
{1, 3, 4}
SequenceReplace[{1, 2, 2, 2, 3, 4}, {Repeated[x_, {2, ∞}]} -> Sequence[]]
{1, 3, 4}
$\endgroup$
5
$\begingroup$

Not pattern matching, but one other way:

Cases[Split@l2, {x_}:>x]

{1, 3, 4}

$\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.