Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of PaulDance

PaulDance's solution

to Custom Set in the Rust Track

Published at Sep 17 2020 · 0 comments
Instructions
Test suite
Solution

Create a custom set type.

Sometimes it is necessary to define a custom data structure of some type, like a set. In this exercise you will define your own set. How it works internally doesn't matter, as long as it behaves like a set of unique elements.

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ cargo test

All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

If you wish to run all ignored tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specific test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

cargo fmt

To see, if your solution contains some common ineffective use cases, inside the solution directory use

cargo clippy --all-targets

Submitting the solution

Generally you should submit all files in which you implemented your solution (src/lib.rs in most cases). If you are using any external crates, please consider submitting the Cargo.toml file. This will make the review process faster and clearer.

Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

custom-set.rs

use custom_set::*;

#[test]
fn sets_with_no_elements_are_empty() {
    let set: CustomSet<()> = CustomSet::new(&[]);
    assert!(set.is_empty());
}

#[test]
#[ignore]
fn sets_with_elements_are_not_empty() {
    let set = CustomSet::new(&[1]);
    assert!(!set.is_empty());
}

#[test]
#[ignore]
fn nothing_is_contained_in_an_empty_set() {
    let set = CustomSet::new(&[]);
    assert!(!set.contains(&1));
}

#[test]
#[ignore]
fn true_when_the_element_is_in_the_set() {
    let set = CustomSet::new(&[1, 2, 3]);
    assert!(set.contains(&1));
}

#[test]
#[ignore]
fn false_when_the_element_is_not_in_the_set() {
    let set = CustomSet::new(&[1, 2, 3]);
    assert!(!set.contains(&4));
}

#[test]
#[ignore]
fn empty_sets_are_subsets_of_each_other() {
    let set1: CustomSet<()> = CustomSet::new(&[]);
    let set2: CustomSet<()> = CustomSet::new(&[]);
    assert!(set1.is_subset(&set2));
    assert!(set2.is_subset(&set1));
}

#[test]
#[ignore]
fn empty_set_is_subset_of_non_empty_set() {
    let set1 = CustomSet::new(&[]);
    let set2 = CustomSet::new(&[1]);
    assert!(set1.is_subset(&set2));
}

#[test]
#[ignore]
fn non_empty_set_is_not_subset_of_empty_set() {
    let set1 = CustomSet::new(&[1]);
    let set2 = CustomSet::new(&[]);
    assert!(!set1.is_subset(&set2));
}

#[test]
#[ignore]
fn sets_with_same_elements_are_subsets() {
    let set1 = CustomSet::new(&[1, 2, 3]);
    let set2 = CustomSet::new(&[1, 2, 3]);
    assert!(set1.is_subset(&set2));
    assert!(set2.is_subset(&set1));
}

#[test]
#[ignore]
fn set_contained_in_other_set_is_a_subset() {
    let set1 = CustomSet::new(&[1, 2, 3]);
    let set2 = CustomSet::new(&[4, 1, 2, 3]);
    assert!(set1.is_subset(&set2));
}

#[test]
#[ignore]
fn set_not_contained_in_other_set_is_not_a_subset_one() {
    let set1 = CustomSet::new(&[1, 2, 3]);
    let set2 = CustomSet::new(&[4, 1, 3]);
    assert!(!set1.is_subset(&set2));
}

#[test]
#[ignore]
fn empty_sets_are_disjoint_with_each_other() {
    let set1: CustomSet<()> = CustomSet::new(&[]);
    let set2: CustomSet<()> = CustomSet::new(&[]);
    assert!(set1.is_disjoint(&set2));
    assert!(set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn empty_set_disjoint_with_non_empty_set() {
    let set1 = CustomSet::new(&[]);
    let set2 = CustomSet::new(&[1]);
    assert!(set1.is_disjoint(&set2));
}

#[test]
#[ignore]
fn non_empty_set_disjoint_with_empty_set() {
    let set1 = CustomSet::new(&[1]);
    let set2 = CustomSet::new(&[]);
    assert!(set1.is_disjoint(&set2));
}

#[test]
#[ignore]
fn sets_with_one_element_in_common_are_not_disjoint() {
    let set1 = CustomSet::new(&[1, 2]);
    let set2 = CustomSet::new(&[2, 3]);
    assert!(!set1.is_disjoint(&set2));
    assert!(!set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn sets_with_no_elements_in_common_are_disjoint() {
    let set1 = CustomSet::new(&[1, 2]);
    let set2 = CustomSet::new(&[3, 4]);
    assert!(set1.is_disjoint(&set2));
    assert!(set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn empty_sets_are_equal() {
    let set1: CustomSet<()> = CustomSet::new(&[]);
    let set2: CustomSet<()> = CustomSet::new(&[]);
    assert_eq!(set1, set2);
}

#[test]
#[ignore]
fn empty_set_is_not_equal_to_a_non_empty_set() {
    let set1 = CustomSet::new(&[]);
    let set2 = CustomSet::new(&[1, 2, 3]);
    assert_ne!(set1, set2);
}

#[test]
#[ignore]
fn non_empty_set_is_not_equal_to_an_empty_set() {
    let set1 = CustomSet::new(&[1, 2, 3]);
    let set2 = CustomSet::new(&[]);
    assert_ne!(set1, set2);
}

#[test]
#[ignore]
fn sets_with_the_same_elements_are_equal() {
    let set1 = CustomSet::new(&[1, 2]);
    let set2 = CustomSet::new(&[2, 1]);
    assert_eq!(set1, set2);
}

#[test]
#[ignore]
fn sets_with_different_elements_are_not_equal() {
    let set1 = CustomSet::new(&[1, 2, 3]);
    let set2 = CustomSet::new(&[2, 1, 4]);
    assert_ne!(set1, set2);
}

#[test]
#[ignore]
fn add_to_empty_set() {
    let mut set = CustomSet::new(&[]);
    set.add(3);
    assert_eq!(set, CustomSet::new(&[3]));
}

#[test]
#[ignore]
fn add_to_non_empty_set() {
    let mut set = CustomSet::new(&[1, 2, 4]);
    set.add(3);
    assert_eq!(set, CustomSet::new(&[1, 2, 3, 4]));
}

#[test]
#[ignore]
fn add_existing_element() {
    let mut set = CustomSet::new(&[1, 2, 3]);
    set.add(3);
    assert_eq!(set, CustomSet::new(&[1, 2, 3]));
}

#[test]
#[ignore]
fn intersecting_empty_sets_return_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(&[]);
    let set2: CustomSet<()> = CustomSet::new(&[]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn intersecting_empty_set_with_non_empty_returns_empty_set() {
    let set1 = CustomSet::new(&[]);
    let set2 = CustomSet::new(&[3, 2, 5]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn intersecting_non_empty_set_with_empty_returns_empty_set() {
    let set1 = CustomSet::new(&[1, 2, 3, 4]);
    let set2 = CustomSet::new(&[]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn intersection_of_two_sets_with_no_shared_elements_is_an_empty_set() {
    let set1 = CustomSet::new(&[1, 2, 3]);
    let set2 = CustomSet::new(&[4, 5, 6]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(&[]));
    assert_eq!(set2.intersection(&set1), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn intersection_of_two_sets_with_shared_elements_is_a_set_of_the_shared_elements() {
    let set1 = CustomSet::new(&[1, 2, 3, 4]);
    let set2 = CustomSet::new(&[3, 2, 5]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(&[2, 3]));
    assert_eq!(set2.intersection(&set1), CustomSet::new(&[2, 3]));
}

#[test]
#[ignore]
fn difference_of_two_empty_sets_is_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(&[]);
    let set2: CustomSet<()> = CustomSet::new(&[]);
    assert_eq!(set1.difference(&set2), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn difference_of_an_empty_and_non_empty_set_is_an_empty_set() {
    let set1 = CustomSet::new(&[]);
    let set2 = CustomSet::new(&[3, 2, 5]);
    assert_eq!(set1.difference(&set2), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn difference_of_a_non_empty_set_and_empty_set_is_the_non_empty_set() {
    let set1 = CustomSet::new(&[1, 2, 3, 4]);
    let set2 = CustomSet::new(&[]);
    assert_eq!(set1.difference(&set2), CustomSet::new(&[1, 2, 3, 4]));
}

#[test]
#[ignore]
fn difference_of_two_non_empty_sets_is_elements_only_in_first_set_one() {
    let set1 = CustomSet::new(&[3, 2, 1]);
    let set2 = CustomSet::new(&[2, 4]);
    assert_eq!(set1.difference(&set2), CustomSet::new(&[1, 3]));
}

#[test]
#[ignore]
fn union_of_two_empty_sets_is_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(&[]);
    let set2: CustomSet<()> = CustomSet::new(&[]);
    assert_eq!(set1.union(&set2), CustomSet::new(&[]));
}

#[test]
#[ignore]
fn union_of_empty_set_and_non_empty_set_is_all_elements() {
    let set1 = CustomSet::new(&[]);
    let set2 = CustomSet::new(&[2]);
    assert_eq!(set1.union(&set2), CustomSet::new(&[2]));
}

#[test]
#[ignore]
fn union_of_non_empty_set_and_empty_set_is_the_non_empty_set() {
    let set1 = CustomSet::new(&[1, 3]);
    let set2 = CustomSet::new(&[]);
    assert_eq!(set1.union(&set2), CustomSet::new(&[1, 3]));
}

#[test]
#[ignore]
fn union_of_non_empty_sets_contains_all_unique_elements() {
    let set1 = CustomSet::new(&[1, 3]);
    let set2 = CustomSet::new(&[2, 3]);
    assert_eq!(set1.union(&set2), CustomSet::new(&[3, 2, 1]));
}

Cargo.toml

[package]
edition = "2018"
name = "custom-set"
version = "1.0.1"

src/lib.rs

//! Basically a HashSet re-implementation. There are a few untested functionalities that were
//! added for completion's sake.

use std::collections::{hash_map::DefaultHasher, VecDeque};
use std::hash::{Hash, Hasher};
use std::iter::FromIterator;

/// A collection behaving like a set with faster access using hashing.
#[derive(Debug, Clone)]
pub struct CustomSet<T: Hash> {
    /// The map storing the set values.
    ///
    /// Its indices are the result of hashing its elements modulo its length. `VecDeque` is used in
    /// order to have a faster re-hashing operation.
    map: Vec<VecDeque<T>>,
    /// The number of elements currently stored in the set.
    len: usize,
    /// The maximum number of elements the set can receive before extending and re-hashing.
    capacity: usize,
}

impl<T: Hash + PartialEq + Clone> CustomSet<T> {
    /// The minimum and default capacity of a set if not specified.
    const DEFAULT_CAPACITY: usize = 5;
    /// The amount by which the capacity of a set grows when filled up.
    const ADDED_CAPACITY: usize = 10;
    /// The ratio of the map size to the collection capacity.
    const SIZE_CAP_RATIO: f64 = 0.3;

    /// Builds a new set by cloning the elements from the given `input` slice.
    pub fn new(input: &[T]) -> Self {
        let mut set = Self::with_capacity(input.len());
        set.extend(input.iter().map(|x| x.clone()));
        set
    }

    /// Builds a new empty set with the default capacity.
    pub fn new_empty() -> Self {
        Self::with_capacity(Self::DEFAULT_CAPACITY)
    }

    /// Builds a new empty set with the given `capacity`.
    pub fn with_capacity(capacity: usize) -> Self {
        let capacity = capacity.max(Self::DEFAULT_CAPACITY);
        let map_size = (capacity as f64 * Self::SIZE_CAP_RATIO).round() as usize;
        let mut map = Vec::with_capacity(map_size);
        map.resize(map_size, VecDeque::new());

        Self {
            map,
            capacity,
            len: 0,
        }
    }

    /// Returns the number of elements in the set.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` iff the set contains no element.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Adds an element to the set if does not contain it already.
    pub fn add(&mut self, element: T) {
        // Extend and re-hash if capacity is reached.
        if self.len == self.capacity {
            let add_map_size =
                (Self::ADDED_CAPACITY as f64 * Self::SIZE_CAP_RATIO).round() as usize;
            self.map.extend((0..add_map_size).map(|_| VecDeque::new()));
            self.capacity += add_map_size;
            self.rehash();
        }

        let index = self.index_of(&element);

        // Push if not already stored.
        if !self.map[index].contains(&element) {
            self.map[index].push_back(element);
            self.len += 1;
        }
    }

    /// Removes the given element from the set if it is present, does nothing otherwise.
    pub fn remove(&mut self, element: &T) {
        let i = self.index_of(element);

        if let Some(j) = self.map[i].iter().position(|x| x == element) {
            self.map[i].swap_remove_back(j);
        }
    }

    /// Returns `true` iff the given `element` is present in the set.
    pub fn contains(&self, element: &T) -> bool {
        self.map[self.index_of(element)]
            .iter()
            .any(|x| x == element)
    }

    /// Returns `true` iff all the elements of the set are contained in `other`.
    pub fn is_subset(&self, other: &Self) -> bool {
        self.iter().all(|x| other.contains(x))
    }

    /// Returns `true` iff the set and `other` contain no element in common.
    pub fn is_disjoint(&self, other: &Self) -> bool {
        !(self.iter().any(|x| other.contains(x)) || other.iter().any(|x| self.contains(x)))
    }

    /// Returns a new set by cloning all the elements contained in both `self` and `other`.
    pub fn intersection(&self, other: &Self) -> Self {
        self.iter()
            .filter(|x| other.contains(x))
            .map(|x| x.clone())
            .collect()
    }

    /// Returns a new set by cloning all the elements contained in `self` but not in `other`.
    pub fn difference(&self, other: &Self) -> Self {
        self.iter()
            .filter(|x| !other.contains(x))
            .map(|x| x.clone())
            .collect()
    }

    /// Returns a new set by cloning all the elements contained in either `self` or `other`.
    pub fn union(&self, other: &Self) -> Self {
        let mut set = self.clone();
        set.extend(other.iter().map(|x| x.clone()));
        set
    }

    /// Returns an iterator on the set's elements by reference.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.map.iter().flat_map(|dq| dq.iter())
    }

    /// Consumes the set and returns an iterator on the set's elements by value.
    pub fn into_iter(self) -> impl IntoIterator<Item = T> {
        self.map.into_iter().flat_map(|dq| dq.into_iter())
    }

    /// Re-hashes all the elements of the set in order to put them in their correct place.
    fn rehash(&mut self) {
        for i in 0..self.map.len() {
            for _ in 0..self.map[i].len() {
                if let Some(element) = self.map[i].pop_front() {
                    let index = self.index_of(&element);
                    self.map[index].push_back(element);
                }
            }
        }
    }

    /// Returns the index of the map to use in order to access the deque where is stored the given
    /// `element` by hashing it.
    fn index_of(&self, element: &T) -> usize {
        let mut hasher = DefaultHasher::new();
        element.hash(&mut hasher);
        hasher.finish() as usize % self.map.len()
    }
}

impl<T: Hash + PartialEq + Clone> PartialEq for CustomSet<T> {
    /// Returns `true` iff both sets are subsets of each other.
    fn eq(&self, other: &Self) -> bool {
        self.is_subset(other) && other.is_subset(self)
    }
}

impl<T: Hash + PartialEq + Clone> FromIterator<T> for CustomSet<T> {
    /// Builds a new set by consuming all the elements of the given `iter`.
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut set = Self::new_empty();
        set.extend(iter);
        set
    }
}

impl<T: Hash + PartialEq + Clone> Extend<T> for CustomSet<T> {
    /// Extends the set by consuming and adding to it all the elements of the given `iter`.
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for x in iter {
            self.add(x);
        }
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?