Last active
October 6, 2020 04:53
-
-
Save bunsenmcdubbs/316287c1909aa253794155b536a4cff1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type UserID int64 | |
func export(customerID string) map[UserID]UserID { | |
graph := fetchGraph(customerID) | |
for src, _ := range graph { | |
find(graph, src) // Since this function mutates the graph, we don't need to store the results separately | |
} | |
return graph | |
} | |
func fetchGraph(customerID string) map[UserID]UserID { | |
graph := queryUsersDB("SELECT src, dest FROM edges WHERE customer_id = ?", customerID) | |
... | |
return ... | |
} | |
// find returns the set identifier for a given source, mutating the graph with path compression | |
func find(graph map[UserID]UserID, source UserID) UserID { | |
// Find the root, recording all elements in the path along the way | |
path := make([]UserID) | |
current := source | |
for _, ok := graph[current]; ok { | |
path = append(path, current) | |
current = graph[current] | |
} | |
// Path compression - point all elements in path directly to the root | |
if current != source { | |
for _, elem := range path { | |
graph[elem] = current | |
} | |
} | |
// Return root | |
return current | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment