Mathematica Asked by Literal on January 28, 2021
Is there any way to simplify the following pattern:
{p___, {a___, x_, x_, b___}, q___} :> {p, {a, x, b}, q}
Ie. where I remove duplicated elements within sublists?
Edit: Just to be clear, I have the feeling p and q could be removed here, but well I’m not certain 🙂
Thanks
Several demonstrative examples:
list = {{1, 2, 3}, {1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}};
list /. {p___, {a___, x_, x_, b___}, q___} :> {p, {a, x, b}, q}
(* {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 3, 3, 5}} *)
list /. {a___, x_, x_, b___} :> {a, x, b}
(* {{1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}} *)
Replace[list, {a___, x_, x_, b___} :> {a, x, b}, {1}]
(* {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 3, 5}} *)
I think the last one is what you are looking for.
If you want to delete many sequential duplicates with patterns you can use
Replace[list, {a___, Repeated[x_, {2, ∞}], b___} :> {a, x, b}, {1}]
Correct answer by ybeltukov on January 28, 2021
If I don't missunderstand your question this could be a good candidat for ReplaceRepeated
list = {1, 1, 2, 3, 3, 3, 1, 1, 7};
list //. {head___, x_, x_, tail___} :> {head, x, tail}
{1, 2, 3, 1, 7}
To scrutinise @ ybeltukov's excellent answer and your nice but ambiguous question
matrix = {{1, 2, 3}, {1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}};
matrix //. {head___, x_, x_, tail___} :> {head, x, tail}
{{1, 2, 3}, {1, 3, 5}}
Answered by eldo on January 28, 2021
Another option to consider is to only (repeatedly) replace if the repeated item is an atom:
rule = {a___, x_?AtomQ, x_, b___} :> {a, x, b}
In action:
{{1, 2, 3}, {1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}} //. rule
{{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 3, 5}}
Answered by wxffles on January 28, 2021
Map ReplaceAll
at Level
1:
# /. {a___, x_, x_, b___} :> {a, x, b} & /@ list
(* {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 3, 5}} *)
Map
DeleteDuplicates
at Level
1:
DeleteDuplicates /@ list
(* {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 3, 5}} *)
Alternative methods to ReplaceRepeated
to get {{1, 2, 3}, {1, 3, 5}}
:
FixedPoint[# /. {a___, x_, x_, b___} :> {a, x, b} &, list]
(* {{1, 2, 3}, {1, 3, 5}} *)
Map[DeleteDuplicates, list, {0, 1}]
(* {{1, 2, 3}, {1, 3, 5}} *)
And to get {{1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}}
:
Map[# /. {a___, x_, x_, b___} :> {a, x, b} &, list, {0}]
(* {{1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}} *)
or
Map[DeleteDuplicates, list, {0}]
(* {{1, 2, 3}, {1, 2, 2, 3}, {1, 3, 3, 5}} *)
Answered by kglr on January 28, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP