Skip to content

Improve speed of finding cycles #332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Sources/TSCBasic/GraphAlgorithms.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,13 @@ public func findCycle<T: Hashable>(
) rethrows -> (path: [T], cycle: [T])? {
// Ordered set to hold the current traversed path.
var path = OrderedSet<T>()
var validNodes = Set<T>()

// Function to visit nodes recursively.
// FIXME: Convert to stack.
func visit(_ node: T, _ successors: (T) throws -> [T]) rethrows -> (path: [T], cycle: [T])? {
if validNodes.contains(node) { return nil }

// If this node is already in the current path then we have found a cycle.
if !path.append(node) {
let index = path.firstIndex(of: node)!
Expand All @@ -133,6 +136,7 @@ public func findCycle<T: Hashable>(
// No cycle found for this node, remove it from the path.
let item = path.removeLast()
assert(item == node)
validNodes.insert(node)
return nil
}

Expand Down
17 changes: 17 additions & 0 deletions Tests/TSCBasicTests/GraphAlgorithmsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ class GraphAlgorithmsTests: XCTestCase {
XCTAssertEqual([1, 2], transitiveClosure(1, [1: [2], 2: [1]]))
}

func testLayeredAllToAllGraph() throws {
let count = 100
let items = Array(0...count)
let layers = (0...count).flatMap { layerNumber in
items.map {
(
$0 + 1000 * layerNumber,
layerNumber == count ? [] : items.map {
$0 + 1000 * (layerNumber + 1)
}
)
}
}

XCTAssertNotCycle(findCycle(1, Dictionary(uniqueKeysWithValues: layers)))
}

func testTopologicalSort() throws {
// A trival graph.
XCTAssertEqual([1, 2], try topologicalSort(1, [1: [2]]))
Expand Down