3
$\begingroup$

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) &]
$\endgroup$
  • $\begingroup$ Bah, DeleteDuplicates[theGraphData, #1 == (#2 /. theRule) &] works. Any other creative ways of doing this? $\endgroup$ – tjm167us Oct 17 '14 at 15:59
  • $\begingroup$ I think that would fail for a data set of: {1--2,3--1,2--1} $\endgroup$ – tjm167us Oct 17 '14 at 16:07
3
$\begingroup$
  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}.

$\endgroup$
2
$\begingroup$

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 &]
$\endgroup$
1
$\begingroup$

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}
$\endgroup$
0
$\begingroup$
Union[theData, SameTest -> (#1 === Reverse@#2 &)]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.