From d9848811cd413d50b5753d428f0ac2cb725d3b6d Mon Sep 17 00:00:00 2001 From: Sean Garborg Date: Sun, 7 Dec 2014 21:22:04 -0500 Subject: [PATCH] findIntersections from O(N^2) to O(N) time e.g. for 40k highways, cut time from 21 minutes to 0.18 seconds. Also only returns 'intersections', no 'crossings', which was never documented or used anywhere, wasn't quite right, and would add overhead to the new, lean version. --- src/intersections.jl | 41 +++++++++++++++++++---------------------- test/routes.jl | 2 +- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/src/intersections.jl b/src/intersections.jl index 4cdff27..a87eaa2 100644 --- a/src/intersections.jl +++ b/src/intersections.jl @@ -6,39 +6,36 @@ ### Generate a list of intersections ### function findIntersections(highways::Dict{Int,Highway}) - intersections = Dict{Int,Intersection}() - crossings = Int[] seen = Set{Int}() + intersections = Dict{Int,Intersection}() + + for hwy in values(highways) + n_nodes = length(hwy.nodes) + + for i in 1:n_nodes + node = hwy.nodes[i] - # Highway ends - for (k, highway_k) in highways - n_nodes = length(highway_k.nodes) - for i in 1:max(1, n_nodes - 1):n_nodes - node = highway_k.nodes[i] - hwys = get!(Intersection, intersections, node).highways - push!(hwys, k) + if i == 1 || i == n_nodes || in(node, seen) + get!(Intersection, intersections, node) + else + push!(seen, node) + end end end - # Highway crossings - for (i, highway_i) in highways - for j in keys(highways) - if i > j - for node in intersect(highway_i.nodes, highways[j].nodes) + for (hwy_key, hwy) in highways + n_nodes = length(hwy.nodes) - hwys = get!(Intersection, intersections, node).highways - push!(hwys, i, j) + for i in 1:n_nodes + node = hwy.nodes[i] - if !in(node, seen) - push!(seen, node) - push!(crossings, node) - end - end + if i == 1 || i == n_nodes || haskey(intersections, node) + push!(intersections[node].highways, hwy_key) end end end - return intersections, crossings + return intersections end ### Generate a new list of highways divided up by intersections diff --git a/test/routes.jl b/test/routes.jl index 5b79a38..3efea7b 100644 --- a/test/routes.jl +++ b/test/routes.jl @@ -76,7 +76,7 @@ end @test edges[50].source.index == 22 # Form transportation network from segments -intersections, crossings = findIntersections(hwys) +intersections = findIntersections(hwys) segments = segmentHighways(nodesENU, hwys, intersections, roads, Set(1:8)) segment_network = createGraph(segments, intersections)