dsa_rust/associative/
hash_set.rs

1#![allow(clippy::uninlined_format_args)] // Cant inline all args in print
2
3/*! A set structure based on this library's HashMap
4
5# About
6This structure provides common binary set operations (as `self` and `other`), mostly as an excuse to explore implementing custom iterators.
7- [Union](crate::associative::hash_set::HashSet::union): Returns an iterator over references to all elements that appear in either `self` or `other` as a set-theoretic [union](https://en.wikipedia.org/wiki/Union_(set_theory)).
8- [Extend](crate::associative::hash_set::HashSet::extend): Mutates `self` to contain all unique elements in both `self` and `other`. This is a mutating version of `union()`.
9- [Intersection](crate::associative::hash_set::HashSet::intersection): Returns an iterator over references to elements that appear in both `self` and `other` as a set-theoretic [intersection](https://en.wikipedia.org/wiki/Intersection_(set_theory)).
10- [Retain All](crate::associative::hash_set::HashSet::retain_all): Mutates `self` such that self only keeps elements that are also in `other`. This function could also appropriately be called "intersect", but that was too close to the non-mutating version of this function called "intersection".
11- [Difference](crate::associative::hash_set::HashSet::difference): Returns an iterator over references to elements that are present in `self` but not in `other` as a set-theoretic asymmetric difference or [relative complement](https://en.wikipedia.org/wiki/Complement_(set_theory)). This operation is asymmetric: interchanging self and other generally produces different results.
12- [Unique](crate::associative::hash_set::HashSet::unique): Returns an iterator over references to elements that are present in exactly one of the two sets as a set-theoretic [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference). This operation is symmetric: interchanging self and other yields the same result.
13
14# Design
15The structure is based on this library's (open-addressing) [hash map](crate::associative::probing_hash_table). Each entry is stored as `(T, ())`, and because of the underlying implementation, `T` must be [Hash], [PartialEq], and [Eq].
16
17# Example
18
19```rust
20use dsa_rust::associative::hash_set::HashSet;
21
22    //Creates a couple new hash sets
23    let mut set1 = HashSet::<u8>::new();
24    // [0, 1, 2, 3]
25    for n in 0..=3 {
26        set1.put(n);
27    }
28
29    let mut set2 = HashSet::<u8>::new();
30    // [2, 3, 4, 5]
31    for n in 2..=5 {
32        set2.put(n);
33    }
34
35    // Creates a list of all elements in both self and other
36    let mut union: Vec<u8> = Vec::new();
37    for e in set1.union(&set2) {
38        union.push(*e);
39    }
40    assert_eq!(union.len(), 6);
41    assert!(union.contains(&0));
42    assert!(union.contains(&1));
43    assert!(union.contains(&2));
44    assert!(union.contains(&3));
45    assert!(union.contains(&4));
46    assert!(union.contains(&5));
47
48    // Converts the union() observer operation to a producer operaiton
49    let mut new: Vec<_> = set1.union(&set2).copied().collect();
50    new.sort(); // None of the sets guarantee comparative ordering
51    assert_eq!(new, vec!(0, 1, 2, 3, 4, 5));
52
53    // Creates a list of elements only present in both sets
54    let mut intersection: Vec<u8> = Vec::new();
55    for e in set1.intersection(&set2) {
56        intersection.push(*e);
57    }
58    assert_eq!(intersection.len(), 2);
59    assert!(intersection.contains(&2));
60    assert!(intersection.contains(&3));
61
62    // Creates a list of elements from self not present in other
63    let mut difference: Vec<u8> = Vec::new();
64    for e in set1.difference(&set2) {
65        difference.push(*e);
66    }
67    assert_eq!(difference.len(), 2);
68    assert!(difference.contains(&0));
69    assert!(difference.contains(&1));
70
71    // Proves that difference() is asymmetric
72    let mut difference: Vec<u8> = Vec::new();
73    for e in set2.difference(&set1) {
74        difference.push(*e);
75    }
76    assert_eq!(difference.len(), 2);
77    assert!(difference.contains(&4));
78    assert!(difference.contains(&5));
79
80    // Creates a list of elements present in either the first or
81    // second one set, but not both
82    let mut unique: Vec<u8> = Vec::new();
83    for e in set1.unique(&set2) {
84        unique.push(*e);
85    }
86    assert_eq!(unique.len(), 4);
87    assert!(unique.contains(&0));
88    assert!(unique.contains(&1));
89    assert!(unique.contains(&4));
90    assert!(unique.contains(&5));
91
92    // Illustrates that unique() is symmetric
93    let mut unique: Vec<u8> = Vec::new();
94    for e in set2.unique(&set1) {
95        unique.push(*e);
96    }
97    assert_eq!(unique.len(), 4);
98    assert!(unique.contains(&0));
99    assert!(unique.contains(&1));
100    assert!(unique.contains(&4));
101    assert!(unique.contains(&5));
102```
103
104*/
105
106use crate::associative::probing_hash_table;
107
108use std::fmt::Debug;
109use std::hash::Hash;
110
111pub struct HashSet<T> {
112    map: probing_hash_table::HashMap<T, ()>,
113}
114impl<T> Default for HashSet<T>
115where
116    T: Clone + Default + Debug + Hash + Eq + PartialEq,
117{
118    fn default() -> Self {
119        Self::new()
120    }
121}
122impl<T> HashSet<T>
123where
124    T: Clone + Default + Debug + Hash + Eq + PartialEq,
125{
126    // Basic operations
127    ///////////////////
128
129    /// Constructor for an empty set with a default capacity of 2
130    /// because everyone deserves a friend.
131    pub fn new() -> Self {
132        let new_capacity = 2;
133        Self {
134            map: probing_hash_table::HashMap::<T, ()>::new_with_capacity(new_capacity),
135        }
136    }
137
138    /// Constructor for an empty set with a given capacity.
139    pub fn new_with_capacity(size: usize) -> Self {
140        Self {
141            map: probing_hash_table::HashMap::<T, ()>::new_with_capacity(size),
142        }
143    }
144
145    /// Returns the number of elements in the set.
146    pub fn size(&self) -> usize {
147        self.map.len()
148    }
149
150    /// Returns true if the set is either empty or contains only empty slots and deleted entries.
151    pub fn is_empty(&self) -> bool {
152        self.map.is_empty()
153    }
154
155    /// Adds an item to the set.
156    pub fn put(&mut self, elem: T) {
157        self.map.put(elem, ());
158    }
159
160    /// Removes an item from the set.
161    pub fn remove(&mut self, elem: T) -> Option<T> {
162        if let Some(val) = self.map.remove(&elem) {
163            return Some(val.key().clone());
164        }
165        None
166    }
167
168    /// Returns true if the set contains the referenced element.
169    pub fn contains<Q>(&self, elem: &Q) -> bool
170    where
171        T: std::borrow::Borrow<Q>,
172        Q: Debug + Hash + Eq + ?Sized,
173    {
174        self.map.contains(elem) // Uses the HashMap's contains() function
175    }
176
177    // Union operations
178    ///////////////////
179
180    /// Returns an iterator over references to all elements that appear
181    /// in either `self` or `other` as a set-theoretic
182    /// [union](https://en.wikipedia.org/wiki/Union_(set_theory)).
183    pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T> {
184        Union::build(&self.map, &other.map)
185    }
186
187    /// A mutating version of `union()` that consumes `other` to add
188    /// all of its elements to `self`.
189    pub fn extend(&mut self, other: Self) {
190        let other_iter = other.map.into_iter();
191        for key in other_iter {
192            if !self.map.contains(&key.0) {
193                self.put(key.0)
194            }
195        }
196    }
197
198    //Intersection operations
199    /////////////////////////
200
201    /// Returns an iterator over references to elements that appear
202    /// in both `self` and `other` as a set-theoretic
203    /// [intersection](https://en.wikipedia.org/wiki/Intersection_(set_theory)).
204    pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> {
205        let (longer, shorter) = if self.map.len() >= other.map.len() {
206            (&self.map, &other.map)
207        } else {
208            (&other.map, &self.map)
209        };
210        Intersection {
211            lhs: longer,
212            rhs_iter: shorter.keys(),
213        }
214    }
215
216    /// Mutates `self` such that `self` only keeps elements that are also in `other`.
217    /// Different from the function `retain` which takes a closure to only retain elements
218    /// according to the predicate.
219    ///
220    /// NOTE: This function could also appropriately be called "intersect", but that was
221    /// too close to the non-mutating version of this function called "intersection".
222    // O(m*n)
223    pub fn retain_all(&mut self, other: &Self) {
224        // Collect keys to remove
225        let keys_to_remove: Vec<_> = self
226            .map
227            .keys()
228            .filter(|k| !other.map.contains(k))
229            .cloned() // collect owned keys if necessary
230            .collect();
231
232        // Remove them safely
233        for key in keys_to_remove {
234            self.map.remove(&key);
235        }
236    }
237
238    // Subtraction operations
239    /////////////////////////
240
241    /// Returns an iterator over references to elements that are present
242    /// in `self` but not in `other` as a set-theoretic asymmetric difference
243    /// or [relative complement](https://en.wikipedia.org/wiki/Complement_(set_theory)).
244    /// This operation is asymmetric: interchanging self and other
245    /// generally produces different results.
246    pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T> {
247        //let (longer, shorter) = if self.map.len() <= other.map.len() {
248        //    (&self.map, &other.map)
249        //} else {
250        //    (&other.map, &self.map)
251        //};
252        //Diff::new(longer, shorter)
253        Difference {
254            lhs_iter: self.map.keys(),
255            rhs: &other.map,
256        }
257    }
258
259    /// Returns an iterator over references to elements that are present
260    /// in exactly one of the two sets as a set-theoretic [symmetric
261    /// difference](https://en.wikipedia.org/wiki/Symmetric_difference).
262    /// This operation is symmetric: interchanging `self` and `other`
263    /// yields the same result.
264    pub fn unique<'a>(&'a self, other: &'a Self) -> Unique<'a, T> {
265        Unique::new(&self.map, &other.map)
266    }
267
268    // Filter operations
269    ////////////////////
270
271    // Mutates `S` to only contain values that adhere to the given predicate (lambda)
272    //pub fn retain(&mut self, |predicate|) {}
273}
274
275pub struct Union<'a, K> {
276    // Used "raw" for its "free" operations
277    lhs: &'a probing_hash_table::HashMap<K, ()>,
278    // Create explicit iterators outside of the next() implementation
279    lhs_iter: probing_hash_table::Keys<'a, K, ()>,
280    rhs_iter: probing_hash_table::Keys<'a, K, ()>,
281}
282impl<'a, K> Union<'a, K> {
283    // Constructor that takes map references to create iterators outside of the next()
284    // implementation
285    fn build(
286        lhs: &'a probing_hash_table::HashMap<K, ()>,
287        rhs: &'a probing_hash_table::HashMap<K, ()>,
288    ) -> Union<'a, K>
289    where
290        K: Debug + Eq + Hash + PartialEq,
291    {
292        Union {
293            lhs_iter: lhs.keys(),
294            rhs_iter: rhs.keys(),
295            lhs,
296        }
297    }
298}
299impl<'a, K> Iterator for Union<'a, K>
300where
301    K: Debug + Eq + Hash,
302{
303    type Item = &'a K;
304
305    fn next(&mut self) -> Option<Self::Item> {
306        // Yield elements from lhs iterator
307        if let Some(key) = self.lhs_iter.next() {
308            return Some(key);
309        }
310
311        // Then yield only unique elements from the rhs iterator
312        self.rhs_iter.by_ref().find(|&key| !self.lhs.contains(key))
313        //while let Some(key) = self.rhs_iter.next() {
314        //    if !self.lhs.contains(key) {
315        //        return Some(key);
316        //    }
317        //}
318        //None
319    }
320}
321
322pub struct Intersection<'a, K> {
323    rhs_iter: probing_hash_table::Keys<'a, K, ()>,
324    lhs: &'a probing_hash_table::HashMap<K, ()>, // needed to skip duplicates from rhs
325}
326impl<'a, K> Iterator for Intersection<'a, K>
327where
328    K: Debug + Eq + Hash,
329{
330    type Item = &'a K;
331
332    fn next(&mut self) -> Option<Self::Item> {
333        // Yield only elements from both sets
334        self.rhs_iter.by_ref().find(|&key| self.lhs.contains(key))
335    }
336}
337
338pub struct Difference<'a, K> {
339    lhs_iter: probing_hash_table::Keys<'a, K, ()>,
340    rhs: &'a probing_hash_table::HashMap<K, ()>, // optional if needed
341}
342impl<'a, K> Iterator for Difference<'a, K>
343where
344    K: Debug + Eq + Hash,
345{
346    type Item = &'a K;
347
348    // Yield only elements from self not contained in other
349    fn next(&mut self) -> Option<Self::Item> {
350        self.lhs_iter.find(|&k| !self.rhs.contains(k))
351    }
352}
353
354pub struct Unique<'a, K> {
355    lhs_iter: probing_hash_table::Keys<'a, K, ()>,
356    rhs_iter: probing_hash_table::Keys<'a, K, ()>,
357    lhs: &'a probing_hash_table::HashMap<K, ()>,
358    rhs: &'a probing_hash_table::HashMap<K, ()>,
359}
360impl<'a, K> Unique<'a, K>
361where
362    K: Debug + Eq + Hash,
363{
364    pub fn new(
365        lhs: &'a probing_hash_table::HashMap<K, ()>,
366        rhs: &'a probing_hash_table::HashMap<K, ()>,
367    ) -> Self {
368        Self {
369            lhs,
370            rhs,
371            lhs_iter: lhs.keys(),
372            rhs_iter: rhs.keys(),
373        }
374    }
375}
376impl<'a, K> Iterator for Unique<'a, K>
377where
378    K: Debug + Eq + Hash,
379{
380    type Item = &'a K;
381
382    // Yield only elements not contained across both sets
383    fn next(&mut self) -> Option<Self::Item> {
384        // First yield from rhs elements not in lhs
385        if let Some(key) = self.rhs_iter.find(|&k| !self.lhs.contains(k)) {
386            return Some(key);
387        }
388
389        // Then reverse the operation to yield lhs elements not in rhs
390        self.lhs_iter.find(|&k| !self.rhs.contains(k))
391    }
392}
393
394// Unit tests
395/////////////
396
397#[test]
398// Basic function test
399fn hash_set_test() {
400    //Creates a new hash map
401    let mut set = HashSet::<&str>::new();
402    assert_eq!(set.size(), 0);
403    assert_eq!(set.map.len(), 0);
404
405    set.put("Peter");
406    set.put("Brain");
407    set.put("Bobson");
408    set.put("Peter"); // Oopsiedoodle, a duplicate!
409    set.put("Dichael");
410
411    assert_eq!(set.size(), 4);
412    assert_eq!(set.map.len(), 4);
413    assert!(!set.is_empty());
414    assert!(set.contains(&"Peter"));
415    assert!(set.contains(&"Brain"));
416    assert!(set.contains(&"Bobson"));
417    assert!(set.contains(&"Dichael"));
418}
419
420#[test]
421// Covers union() and extend()
422fn union() {
423    //Creates a new hash map
424    let mut set1 = HashSet::<&str>::new();
425    set1.put("Peter"); // +1
426    set1.put("Brain"); // +1
427    set1.put("Bobson"); // +1
428    set1.put("Dichael"); // +1
429
430    let mut set2 = HashSet::<&str>::new();
431    set2.put("Remus"); // +1
432    set2.put("Romulus"); // +1
433    set2.put("Bobson");
434    set2.put("Peter");
435
436    let mut union: Vec<&str> = Vec::new();
437    for e in set1.union(&set2) {
438        union.push(*e);
439    }
440    assert_eq!(union.len(), 6);
441    eprintln!("{:#?}", union);
442    // contains takes &T, which is &&str for the type
443    assert!(union.contains(&"Peter"));
444    assert!(union.contains(&"Brain"));
445    assert!(union.contains(&"Bobson"));
446    assert!(union.contains(&"Dichael"));
447
448    // Consumes set2 and extends set1
449    assert_eq!(set1.size(), 4);
450    set1.extend(set2);
451    assert_eq!(set1.size(), 6);
452    assert!(set1.contains("Peter"));
453    assert!(set1.contains("Brain"));
454    assert!(set1.contains("Bobson"));
455    assert!(set1.contains("Dichael"));
456    assert!(set1.contains("Remus"));
457    assert!(set1.contains("Romulus"));
458
459    //panic!("MANUAL TEST FAILURE");
460}
461
462#[test]
463// Covers intersection() and retain_all()
464fn intersection() {
465    //Creates a couple new hash sets
466    let mut set1 = HashSet::<&str>::new();
467    set1.put("Peter");
468    set1.put("Brain");
469    set1.put("Bobson");
470    set1.put("Dichael");
471
472    let mut set2 = HashSet::<&str>::new();
473    set2.put("Remus");
474    set2.put("Romulus");
475    set2.put("Bobson");
476    set2.put("Glank");
477    set2.put("Flock");
478    set2.put("Peter");
479
480    // Creates a vec of borrowed keys contained only in both sets
481    let mut intersection: Vec<&str> = Vec::new();
482    for e in set1.intersection(&set2) {
483        intersection.push(*e);
484    }
485    eprintln!("{:#?}", intersection);
486    assert_eq!(intersection.len(), 2);
487    assert!(intersection.contains(&"Peter"));
488    assert!(intersection.contains(&"Bobson"));
489
490    // Mutates self to contain only keys ALSO contained in other
491    eprintln!("{:#?}", set1.map);
492    assert_eq!(set1.size(), 4);
493    assert!(set1.contains(&"Peter"));
494    assert!(set1.contains(&"Brain"));
495    assert!(set1.contains(&"Bobson"));
496    assert!(set1.contains(&"Dichael"));
497    set1.retain_all(&set2); // Removes two entries
498    eprintln!("{:#?}", set1.map);
499    assert_eq!(set1.size(), 2);
500    assert!(set1.contains(&"Peter"));
501    assert!(set1.contains(&"Bobson"));
502
503    //panic!("MANUAL TEST FAILURE");
504}
505
506#[test]
507// Covers difference() and unique()
508fn difference() {
509    //Creates a couple new hash sets
510    let mut set1 = HashSet::<&str>::new();
511    set1.put("Peter");
512    set1.put("Brain"); // +1
513    set1.put("Bobson");
514    set1.put("Dichael"); // +1
515
516    let mut set2 = HashSet::<&str>::new();
517    set2.put("Remus"); // +1
518    set2.put("Romulus"); // +1
519    set2.put("Bobson");
520    set2.put("Flock"); // +1
521    set2.put("Peter");
522
523    // Creates a vec of borrowed keys contained only in both sets
524    let mut difference: Vec<&str> = Vec::new();
525    for e in set1.difference(&set2) {
526        difference.push(*e);
527    }
528    eprintln!("{:#?}", difference);
529    assert_eq!(difference.len(), 2);
530    assert!(difference.contains(&"Brain"));
531    assert!(difference.contains(&"Dichael"));
532
533    // Proves that difference() is positionally dependent
534    let mut difference: Vec<&str> = Vec::new();
535    for e in set2.difference(&set1) {
536        difference.push(*e);
537    }
538    eprintln!("{:#?}", difference);
539    assert_eq!(difference.len(), 3);
540    assert!(difference.contains(&"Remus"));
541    assert!(difference.contains(&"Romulus"));
542    assert!(difference.contains(&"Flock"));
543
544    // Creates a vec of borrowed keys contained only in both sets
545    let mut unique: Vec<&str> = Vec::new();
546    for e in set1.unique(&set2) {
547        unique.push(*e);
548    }
549    eprintln!("{:#?}", unique);
550    assert_eq!(unique.len(), 5);
551    assert!(unique.contains(&"Brain"));
552    assert!(unique.contains(&"Dichael"));
553    assert!(unique.contains(&"Remus"));
554    assert!(unique.contains(&"Romulus"));
555    assert!(unique.contains(&"Flock"));
556
557    //panic!("MANUAL TEST FAILURE");
558}
559
560#[test]
561// Tests converting an observer to a producer
562fn observer_to_producer() {
563    // Tests with u8
564    ////////////////
565
566    //Creates a couple new hash sets
567    let mut set1 = HashSet::<u8>::new();
568    // [0, 1, 2, 3]
569    for n in 0..=3 {
570        set1.put(n);
571    }
572
573    let mut set2 = HashSet::<u8>::new();
574    // [2, 3, 4, 5]
575    for n in 2..=5 {
576        set2.put(n);
577    }
578
579    // Creates a list of all elements in both self and other
580    let mut union: Vec<u8> = Vec::new();
581    for e in set1.union(&set2) {
582        union.push(*e); // e is of type &u8
583    }
584    assert_eq!(union.len(), 6);
585    assert!(union.contains(&0)); // contains() requires &T
586    assert!(union.contains(&1));
587    assert!(union.contains(&2));
588    assert!(union.contains(&3));
589    assert!(union.contains(&4));
590    assert!(union.contains(&5));
591
592    let mut new: Vec<_> = set1.union(&set2).copied().collect();
593    new.sort();
594    assert_eq!(new, vec!(0, 1, 2, 3, 4, 5));
595
596    // Tests with char
597    //////////////////
598
599    //Creates a couple new hash sets
600    let mut set1 = HashSet::<char>::new();
601    // [0, 1, 2, 3]
602    for n in ['a', 'b', 'c', 'd'] {
603        set1.put(n);
604    }
605
606    let mut set2 = HashSet::<char>::new();
607    // [2, 3, 4, 5]
608    for n in ['c', 'd', 'e', 'f'] {
609        set2.put(n);
610    }
611
612    let mut new: Vec<_> = set1.union(&set2).copied().collect();
613    new.sort();
614    assert_eq!(new, vec!('a', 'b', 'c', 'd', 'e', 'f'));
615
616    // Tests with String
617    //////////////////
618
619    //Creates a couple new hash sets
620    let mut set1 = HashSet::<String>::new();
621    // [0, 1, 2, 3]
622    for n in [
623        "a".to_string(),
624        "b".to_string(),
625        "c".to_string(),
626        "d".to_string(),
627    ] {
628        set1.put(n);
629    }
630
631    let mut set2 = HashSet::<String>::new();
632    // [2, 3, 4, 5]
633    for n in [
634        "d".to_string(),
635        "d".to_string(),
636        "e".to_string(),
637        "f".to_string(),
638    ] {
639        set2.put(n);
640    }
641
642    // Uses cloned() because String is Clone, but not Copy
643    //let mut new: Vec<_> = set1.union(&set2).cloned().collect();
644    // Uses them references
645    let mut new: Vec<_> = set1.union(&set2).collect();
646    new.sort();
647    assert_eq!(
648        new,
649        vec!(
650            //"a".to_string(),
651            //"b".to_string(),
652            //"c".to_string(),
653            //"d".to_string(),
654            //"e".to_string(),
655            //"f".to_string(),
656            "a", "b", "c", "d", "e", "f",
657        )
658    );
659}