2
$\begingroup$

I have a list of directed edges for a graph and I want to replace all edges that match a certain pattern. The edges should be replaced by a number. It ends up in a edge weighting list for a graph. All edges that go to "window" should have the same weight. Therefore the replacement. I tried this:

ReplaceList[{"a" \[DirectedEdge] "window", 
  "window" \[DirectedEdge] "door"}, 
 y_ \[DirectedEdge] x_ /; x == "window" -> 2]

The pattern matching does not work in this case. The goal is to replace only edges were "window" is the receiving vertex. Is there a way to do it in similar fashion to above trial? Can the pattern matching made to work in ReplaceList?

$\endgroup$
4
$\begingroup$

You can use Replace with level specification All:

Replace[{"a" \[DirectedEdge] "window", "window" \[DirectedEdge] "door"}, 
 y_ \[DirectedEdge] x_ /; x == "window" -> 2, All]

or, shorter,

Replace[{"a" \[DirectedEdge] "window", "window" \[DirectedEdge] "door"},
   _ \[DirectedEdge] "window" ->  2, All]

and

Replace[{"a" \[DirectedEdge] "window", "window" \[DirectedEdge] "door"}, 
 DirectedEdge[_, "window"] -> 2, All]

to get

 {2, "window" \[DirectedEdge] "door"}

Note: As commented by @Szabolcs, DirectedEdge may have three arguments in version 12.1. So if the input list contains tagged edges we can use the replacement rule

DirectedEdge[_, "window", ___] -> 2
$\endgroup$
1
  • 1
    $\begingroup$ DirectedEdge may have a 3rd argument in 12.1 (EdgeTaggedGraph) $\endgroup$
    – Szabolcs
    Apr 15 '20 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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