4

Given:

theData = {1 <-> 2, 2 <-> 3, 2 <-> 1}

I would like to remove any duplicates where I define a duplicate to be:

x <-> y == y <-> x

Have tried:

theRule = UndirectedEdge[p1_, p2_] :> UndirectedEdge[p2, p1]
DeleteDuplicates[theData, # == (# /. theRule) &]
Öskå
  • 8,587
  • 4
  • 30
  • 49
tjm167us
  • 993
  • 5
  • 12

4 Answers4

4
  1. Sort the elements of theData:

    DeleteDuplicates[Sort /@ theData]
    
    {1 <-> 2, 2 <-> 3}
    
  2. Use a function ue with Attribute Orderless:

    SetAttributes[ue, Orderless];
    UndirectedEdge @@@ DeleteDuplicates[ue @@@ theData]
    
    {1 <-> 2, 2 <-> 3}
    

    or

    DeleteDuplicates[ue @@@ theData] /. ue -> UndirectedEdge
    
    {1 <-> 2, 2 <-> 3}
    
  3. Temporarily make UndirectedEdge Orderless:

    SetAttributes[UndirectedEdge, Orderless];
    DeleteDuplicates[theData]
    
    {1 <-> 2, 2 <-> 3}
    

    Use ClearAttributes[UndirectedEdge, Orderless] to reset the Attributes of UndirectedEdge back to {Protected, ReadProtected}.

Öskå
  • 8,587
  • 4
  • 30
  • 49
kglr
  • 394,356
  • 18
  • 477
  • 896
2

You can convert your data to a graph and use SimpleGraph to get rid of the duplicates.

EdgeList@SimpleGraph@Graph@theData
{1 <-> 2, 2 <-> 3}
paw
  • 5,650
  • 23
  • 31
2

If you want to delete both true duplicates (i.e. 1<->2 is equal to 1<->2) and those that fulfill your definition of a duplicate you may try

DeleteDuplicatesBy[theData, Sort]

Otherwise you may try

DeleteDuplicates[theData, # === Reverse@#2 &]
C. E.
  • 70,533
  • 6
  • 140
  • 264
0
Union[theData, SameTest -> (#1 === Reverse@#2 &)]
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78