intersection method

Graph<V, E> intersection(
  1. Graph<V, E> other, {
  2. bool edgeCompare(
    1. V source,
    2. V target,
    3. E a,
    4. E b,
    )?,
  3. E edgeMerge(
    1. V source,
    2. V target,
    3. E a,
    4. E b,
    )?,
})

Returns the intersection of this graph and other. This is a graph with the nodes and edges present in both graphs. edgeMerge specifies how parallel edges are merged, if unspecified the last one is used.

Implementation

Graph<V, E> intersection(Graph<V, E> other,
    {bool Function(V source, V target, E a, E b)? edgeCompare,
    E Function(V source, V target, E a, E b)? edgeMerge}) {
  final result = copy(empty: true);
  // Create all the vertices present in both graphs.
  for (final vertex in vertices) {
    if (other.vertices.contains(vertex)) {
      result.addVertex(vertex);
    }
  }
  // Create all edges that have vertices present in the result, and edges
  // in both graphs.
  for (final edge in edges) {
    final otherEdge = other.getEdge(edge.source, edge.target);
    if (otherEdge != null &&
        (edgeCompare == null ||
            edgeCompare(
                edge.source, edge.target, edge.value, otherEdge.value))) {
      final value = edgeMerge == null
          ? otherEdge.value
          : edgeMerge(edge.source, edge.target, edge.value, otherEdge.value);
      result.addEdge(edge.source, edge.target, value: value);
    }
  }
  return result;
}