rust_dsa/unionfind.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
/// A [disjoint-set data structure](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)
/// backed by a disjoint set forest.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// // First, we create a new structure.
/// let mut uf = UnionFind::new();
///
/// // Then we can insert values.
/// uf.insert(1);
/// uf.insert(2);
/// uf.insert(3);
/// uf.insert(4);
/// uf.insert(5);
///
/// // And union some of the elements.
/// uf.union(&1, &2);
/// uf.union(&2, &4);
/// uf.union(&3, &5);
///
/// // Now, we can query to see if elements are in the same set.
/// assert_eq!(uf.find(&1), uf.find(&2));
/// assert_eq!(uf.find(&2), uf.find(&4));
/// assert_eq!(uf.find(&4), uf.find(&1));
/// assert_eq!(uf.find(&3), uf.find(&5));
/// assert_eq!(uf.find(&5), uf.find(&3));
///
/// assert_ne!(uf.find(&1), uf.find(&3));
/// assert_ne!(uf.find(&5), uf.find(&4));
///
/// // We can also create `UnionFind`s from arrays.
/// let uf = UnionFind::from(["foo", "bar"]);
///
/// assert!(!uf.friends(&"foo", &"bar").unwrap());
///
/// // And iterators.
/// let uf: UnionFind<_> = "string".chars().collect();
///
/// assert!(!uf.friends(&'s', &'t').unwrap());
/// ```
pub struct UnionFind<T> {
map: HashMap<T, usize>,
nodes: Vec<Node>,
}
impl<T> UnionFind<T> {
/// Creates a new [`UnionFind`] structure.
pub fn new() -> UnionFind<T> {
UnionFind {
map: HashMap::new(),
nodes: Vec::new(),
}
}
/// Creates a new [`UnionFind`] structure with the specified capacity.
pub fn with_capacity(capacity: usize) -> UnionFind<T> {
UnionFind {
map: HashMap::with_capacity(capacity),
nodes: Vec::with_capacity(capacity),
}
}
/// Inserts a value into the [`UnionFind`] structure.
///
/// Returns `true` if the [`UnionFind`] structure did not contain `value`
/// and `false` if it did.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf = UnionFind::new();
///
/// uf.insert('a');
/// uf.insert('b');
///
/// assert!(uf.contains(&'a'));
/// assert!(uf.contains(&'b'));
/// ```
pub fn insert(&mut self, value: T) -> bool
where
T: Hash + Eq,
{
let old_len = self.len();
match self.map.entry(value) {
Entry::Occupied(_) => false,
Entry::Vacant(entry) => {
entry.insert(old_len);
self.nodes.push(Node::new(old_len, 0));
true
}
}
}
/// Returns a [`usize`] representing the set that contains `value` or `None` if the
/// [`UnionFind`] structure does not contain `value`.
///
/// This method applies path compression as it searches.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf = UnionFind::from([1, 2, 3]);
/// uf.union(&1, &2);
///
/// assert_eq!(uf.find(&1), uf.find(&2));
/// assert_ne!(uf.find(&1), uf.find(&3));
/// ```
pub fn find(&mut self, value: &T) -> Option<usize>
where
T: Hash + Eq,
{
let start = *self.map.get(value)?;
let mut index = start;
while self.nodes[index].parent != index {
index = self.nodes[index].parent;
}
let mut trace = start;
while trace != index {
let last = trace;
trace = self.nodes[trace].parent;
self.nodes[last].parent = index;
}
Some(index)
}
/// Returns a [`usize`] representing the set that contains `value` or `None` if the
/// [`UnionFind`] structure does not contain `value`.
///
/// This method does not apply path compression as it searches.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf = UnionFind::from([1, 2, 3]);
/// uf.union(&1, &2);
///
/// assert_eq!(uf.static_find(&1), uf.static_find(&2));
/// assert_ne!(uf.static_find(&1), uf.static_find(&3));
/// ```
pub fn static_find(&self, value: &T) -> Option<usize>
where
T: Hash + Eq,
{
let mut index = *self.map.get(value)?;
while self.nodes[index].parent != index {
index = self.nodes[index].parent;
}
Some(index)
}
/// Joins the two sets containing `a` and `b`. Returns `None` if `a` or `b`
/// is not in the [`UnionFind`] structure. Returns `Some(true)` if `a` and `b` were
/// in different sets before the union operation was preformed and `Some(false)` if
/// they were already in the same set.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf = UnionFind::from(['x', 'y', 'z']);
///
/// assert_eq!(uf.union(&'x', &'y'), Some(true));
///
/// // Returns `Some(false)` if we try again.
/// assert_eq!(uf.union(&'x', &'y'), Some(false));
///
/// assert!(uf.friends(&'x', &'y').unwrap());
/// assert!(!uf.friends(&'y', &'z').unwrap());
/// ```
pub fn union(&mut self, a: &T, b: &T) -> Option<bool>
where
T: Hash + Eq,
{
let a_id = self.find(a)?;
let b_id = self.find(b)?;
if a_id != b_id {
// we hash `a` and `b` twice which is kinda dumb...
let a_index = self.map[a];
let b_index = self.map[b];
let a_rank = self.nodes[a_index].rank;
let b_rank = self.nodes[b_index].rank;
match a_rank.cmp(&b_rank) {
Ordering::Less => self.nodes[a_index].parent = b_index,
Ordering::Greater => self.nodes[b_index].parent = a_index,
Ordering::Equal => {
self.nodes[a_index].parent = b_index;
self.nodes[b_index].rank += 1;
}
}
Some(true)
} else {
Some(false)
}
}
/// Returns `Some(true)` if `a` and `b` are members of the same set and `Some(false)`
/// if they are not. If `a` or `b` is not in the [`UnionFind`] structure, `None`
/// is returned.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf = UnionFind::from([1, 2, 3]);
///
/// uf.union(&1, &2);
///
/// assert_eq!(uf.friends(&1, &2), Some(true));
/// assert_eq!(uf.friends(&1, &3), Some(false));
/// assert_eq!(uf.friends(&1, &999), None);
/// ```
pub fn friends(&self, a: &T, b: &T) -> Option<bool>
where
T: Hash + Eq,
{
Some(self.static_find(a)? == self.static_find(b)?)
}
/// Returns `true` if the value is in the [`UnionFind`] structure.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf = UnionFind::new();
///
/// uf.insert('a');
/// uf.insert('b');
///
/// assert!(uf.contains(&'a'));
/// assert!(uf.contains(&'b'));
/// ```
pub fn contains(&self, value: &T) -> bool
where
T: Hash + Eq,
{
self.map.contains_key(value)
}
/// Returns the number of elements in the [`UnionFind`] structure.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf: UnionFind<_> = (0..42).collect();
///
/// assert_eq!(uf.len(), 42);
///
/// uf.clear();
///
/// assert_eq!(uf.len(), 0);
/// ```
pub fn len(&self) -> usize {
self.map.len()
}
/// Returns `true` if the [`UnionFind`] structure is empty.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf: UnionFind<_> = "chars".chars().collect();
///
/// assert!(!uf.is_empty());
///
/// uf.clear();
///
/// assert!(uf.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Clears the [`UnionFind`] structure.
///
/// # Example
/// ```
/// use rust_dsa::UnionFind;
///
/// let mut uf: UnionFind<_> = "chars".chars().collect();
///
/// assert!(!uf.is_empty());
///
/// uf.clear();
///
/// assert!(uf.is_empty());
/// ```
pub fn clear(&mut self) {
self.map.clear();
self.nodes.clear();
}
}
impl<T> Default for UnionFind<T> {
fn default() -> UnionFind<T> {
UnionFind::new()
}
}
impl<T> FromIterator<T> for UnionFind<T>
where
T: Hash + Eq,
{
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> UnionFind<T> {
let iter = iter.into_iter();
let mut uf = UnionFind::with_capacity(iter.size_hint().0);
for value in iter {
uf.insert(value);
}
uf
}
}
impl<T, const N: usize> From<[T; N]> for UnionFind<T>
where
T: Hash + Eq,
{
fn from(array: [T; N]) -> UnionFind<T> {
array.into_iter().collect()
}
}
struct Node {
parent: usize,
rank: usize,
}
impl Node {
fn new(parent: usize, rank: usize) -> Node {
Node { parent, rank }
}
}