5
$\begingroup$

Possible Duplicate:
How can I remove B -> A from a list if A -> B is in the list?

I'm working toward building a graph and use some code to construct my rules which results in a form as follows:

g = {1 -> 2, 1 -> 3, 2 -> 1, 2 -> 3, 2 -> 4, 3 -> 2, 3 -> 4, 3 -> 1, 4 -> 3, 4 -> 2}

I would like to delete all reverse duplicate entries form the list, i.e. both 1->2 and 2->1 appear in the list. I would like to get rid of one of them and do this for all reverse duplicates in the list g.

$\endgroup$
2
  • $\begingroup$ All: please try a bit harder to find duplicate questions; thank you. $\endgroup$
    – Mr.Wizard
    Commented Jun 27, 2012 at 20:46
  • $\begingroup$ @Tom That case is already covered by my own answer to the previous question. If you feel that this closure was in error feel free to vote to reopen. IMHO the fact that identical answers were posted indicates it is a true duplicate. (ps. please use the @name notification when responding; I didn't see your message until now.) $\endgroup$
    – Mr.Wizard
    Commented Jun 28, 2012 at 7:10

2 Answers 2

4
$\begingroup$

This satisfies your needs

DeleteDuplicates @ (Sort /@ g)
{1 -> 2, 1 -> 3, 2 -> 3, 2 -> 4, 3 -> 4}
$\endgroup$
4
  • 1
    $\begingroup$ Kind of a waste to f @ (stuff) when you can just f[stuff], no? $\endgroup$ Commented Jun 27, 2012 at 16:52
  • $\begingroup$ Well, no unnecessary signs : Sort /@ g // DeleteDuplicates $\endgroup$
    – Artes
    Commented Jun 27, 2012 at 16:57
  • 1
    $\begingroup$ @J.M. I also use this kind of @(...) syntax because of reasons given here. By removing the head you don't have to jump to the end to remove ]. $\endgroup$ Commented Jun 28, 2012 at 8:53
  • $\begingroup$ @István: still bloody ugly for me. To each his own, I suppose. $\endgroup$ Commented Jun 28, 2012 at 14:21
5
$\begingroup$

Union[Sort /@ g] seems to be what you need...

$\endgroup$

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