Skip to content

Graph - AbstractGraph<T>(fromGraph graph: AbstractGraph<T>) drops unlinked vertices #645

Open
@barrypress

Description

@barrypress

Brief Intro

The method AbstractGraph(fromGraph graph: AbstractGraph) in Graph.swift does not produce a complete copy of the source graph.

More Details

Currently the method looks like this (lines 14-21, ):

  public required init(fromGraph graph: AbstractGraph<T>) {
    for edge in graph.edges {
      let from = createVertex(edge.from.data)
      let to = createVertex(edge.to.data)

      addDirectedEdge(from, to: to, withWeight: edge.weight)
    }
  }

Because it only generates vertices in the new graph linked to an edge, it drops all unlinked vertices (including the case where there's only one vertex in the graph, for which it produces an empty graph). It's simple to change that, of course:

    public required init(fromGraph graph: AbstractGraph<T>) {
        for vertex in graph.vertices {
            let _ = self.createVertex(vertex.data)
        }

        for edge in graph.edges {
          let from = createVertex(edge.from.data)
          let to = createVertex(edge.to.data)

          addDirectedEdge(from, to: to, withWeight: edge.weight)
        }
    }

I've hesitated to write a pull request, though, because it's so obvious a difference that I wondered if the behavior to drop those vertices is intentional. The issue matters because without the change there's no way in the existing API to perform a deep copy other than to write the above method under a different name.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions