Skip to content

Instantly share code, notes, and snippets.

@bunsenmcdubbs
Last active October 6, 2020 04:53
Show Gist options
  • Save bunsenmcdubbs/316287c1909aa253794155b536a4cff1 to your computer and use it in GitHub Desktop.
Save bunsenmcdubbs/316287c1909aa253794155b536a4cff1 to your computer and use it in GitHub Desktop.
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