Re: DeleteCases

*To*: mathgroup at smc.vnet.net*Subject*: [mg98179] Re: DeleteCases*From*: lshifr at gmail.com*Date*: Wed, 1 Apr 2009 05:58:18 -0500 (EST)*References*: <gqsn69$3qp$1@smc.vnet.net>

On Mar 31, 2:19 am, Filippo Miatto <sottosupr... at gmail.com> wrote: > Dear all, > Given this example list: > > {{0, 0, 1, 1}, {0, 0, 2, 2}, {0, 0, 3, 3}, {1, 1, 0, 0}, {1, 1, 2, 2}, = > {1, 1, 3, 3}, {2, 2, 0, 0}, {2, 2, 1, 1}, {2, 2, 3, 3}, {3, 3, 0, 0}, > {3, 3, 1, 1}, {3, 3, 2, 2}} > > I need the elements {a,a,b,b} and {b,b,a,a} to be the same, i.e. i > want to delete one of the two occurrences from the list. (or all but > one if the condition is more complicated, say {a,b,c,d} and {b,a,c,d} > or {a,b,c,d} and {a,b,d,c}) > How can i do that? Can i use DeleteCases? if so, what conditional > should I use to compare different elements in the list? > I tried without success for all the night.. (it's 6.15AM now!) > Thank you, > > Filippo Hi Filippo, DeleteCases is probably a wrong choice here, since you don't know in advance which elements you want to delete. In[1] = test = {{0, 0, 1, 1}, {0, 0, 2, 2}, {0, 0, 3, 3}, {1, 1, 0, 0}, {1, 1, 2, 2}, {1, 1, 3, 3}, {2, 2, 0, 0}, {2, 2, 1, 1}, {2, 2, 3, 3}, {3, 3, 0, 0}, {3, 3, 1, 1}, {3, 3, 2, 2}}; If you just need to keep a single representative, but do not care about the order (do you get the first, second or whatever of the equivalents), then use Sort to bring them to "normal form", and then Union will remove the duplicates: In[2] = Union[Sort /@ test] Out[2] = {{0, 0, 1, 1}, {0, 0, 2, 2}, {0, 0, 3, 3}, {1, 1, 2, 2}, {1, 1, 3, 3}, {2, 2, 3, 3}} If you want to keep the very first of the equivalents encountered while traversing the list, it's a bit trickier. Here is the implementation which should be efficient enough for even large lists: In[3] = unsortedRepresentatives[x_List] := With[{sorted = Sort /@ x}, Extract[x, Sort[Union[sorted] /. Dispatch[MapIndexed[Rule, sorted]]]]]; It is based on modified <unsortedUnion> operation that I discussed in my book (section on MapIndexed), where this code is explained. In[4] = unsortedRepresentatives[test] Out[4] = {{0, 0, 1, 1}, {0, 0, 2, 2}, {0, 0, 3, 3}, {1, 1, 2, 2}, {1, 1, 3, 3}, {2, 2, 3, 3}} In this case, the result is the same, but you can easily convince yourself that in general the result will be different (take a random permutation of your list for instance). Regards, Leonid