2
$\begingroup$

There is a list of UndirectedEdge:

list = {1 <-> 2, 2 <-> 3, 4 <-> 5}

How to change it to:

{101 <-> 102, 102 <-> 103,  104 <-> 105}

?


I tried :

list /. UndirectedEdge[x_, y_] /; x :> x + 100;
list /. x_ <-> y_ /; x + 100 <-> y + 100;
list /. x_UndirectedEdge /; First[x] <-> Last[x]
list /. x_UndirectedEdge /; x :> First[x] <-> Last[x];

but they are not working correctly.

$\endgroup$
2
  • 3
    $\begingroup$ You nearly had it! You're second attempt is very close, you have the correct pattern to match x_ \[UndirectedEdge] y_, and the correct replacement x + 100 \[UndirectedEdge] y + 100 the only minor mistake is that you used Condition, \;, which should be RuleDelayed, :>. Therefore try: list /. x_ \[UndirectedEdge] y_ :> x + 100 \[UndirectedEdge] y + 100; $\endgroup$ Oct 26, 2016 at 7:52
  • $\begingroup$ list /. x_Integer :> 100 + x $\endgroup$
    – kglr
    Oct 26, 2016 at 20:20

2 Answers 2

2
$\begingroup$

In such cases Casesis your friend ;-). You can use it to identify and modify arguments in the following way:

Cases[list, 
 UndirectedEdge[x_, y_] :> UndirectedEdge[100 + x, 100 + y]]
(*{101 <-> 102, 102 <-> 103, 104 <-> 105}*)
$\endgroup$
2
$\begingroup$
list = {1 <-> 2, 2 <-> 3,  4 <-> 5};

list /. x_Integer :> 100 + x
Map[100 + # &, list, {-1}]
Replace[list, x_ :> 100 + x, {2}]
MapAt[100 + # &, list, {{All, 1}, {All, 2}}]
UndirectedEdge @@@ (100 + {##} & @@@ list)
EdgeList @ VertexReplace[list, v_ :> 100 + v]

all give

{101 <-> 102, 102 <-> 103, 104 <-> 105}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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