The Union Find data structure.
Inspiration has been gotten from the book Algorithms by Robert Sedgewick and Kevin Wayne.
Representation of Union Find data structure. You can create Union Find of any comparable primitives.
quickUnionPathCompression : UnionFind comparable
There are a number of easy ways to improve the union-find algorithm. Ideally, we would like every node to link directly to the root of its tree, but we do not want to pay the price of changing a large number of links. We can approach the ideal simply by making all the nodes that we do examine directly link to the root.
The amortized cost per operation for this algorithm is known to be logarithmic.
union : comparable -> comparable -> UnionFind comparable -> UnionFind comparable
Add connection between two elements.
"""
unionFind : UnionFind
unionFind =
quickUnionPathCompression
|> union 0 1 -- creates connection between 0 and 1
|> union 1 2 -- creates connection between 1 and 2
|> union 0 2 -- already connected
"""
get : comparable -> UnionFind comparable -> comparable
Given an element, returns the "parent" of the element.
"""
parentOf0 : Int
parentOf0 =
quickUnionPathCompression
|> union 0 1
|> get 0 -- would be equal 1
parentOf2 : Int
parentOf2 =
quickUnionPathCompression
|> union 0 1
|> get 2 -- would be equal 2
"""
find : comparable -> UnionFind comparable -> comparable
Given an element, returns the leader identifying the component to which the element belongs.
"""
leaderOf0 : Int
leaderOf0 =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> find 0 -- would be equal 2
"""
connected : comparable -> comparable -> UnionFind comparable -> Basics.Bool
Given two elements, returns True
when both are in the same component.
"""
elements0and3AreConnected : Bool
elements0and3AreConnected =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> union 3 2
|> connected 0 3 -- would be equal True
elements0and3AreNotConnected : Bool
elements0and3AreNotConnected =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> union 3 4
|> connected 0 3 -- would be equal False
"""
count : UnionFind comparable -> Basics.Int
Returns number of connections.
"""
amountOfConnections : Int
amountOfConnections =
quickUnionPathCompression
|> union 0 1
|> union 1 2
|> union 0 2
|> count -- would be equal 2
"""