diff --git a/src/sorting/mod.rs b/src/sorting/mod.rs index 9f762e1d590..520d8a85f64 100644 --- a/src/sorting/mod.rs +++ b/src/sorting/mod.rs @@ -79,23 +79,25 @@ use std::cmp; #[cfg(test)] pub fn have_same_elements(a: &[T], b: &[T]) -> bool where - // T: cmp::PartialOrd, - // If HashSet is used - T: cmp::PartialOrd + cmp::Eq + std::hash::Hash, + T: Eq + std::hash::Hash, { - use std::collections::HashSet; + use std::collections::HashMap; - if a.len() == b.len() { - // This is O(n^2) but performs better on smaller data sizes - //b.iter().all(|item| a.contains(item)) + if a.len() != b.len() { + return false; + } - // This is O(n), performs well on larger data sizes - let set_a: HashSet<&T> = a.iter().collect(); - let set_b: HashSet<&T> = b.iter().collect(); - set_a == set_b - } else { - false + let mut counts = HashMap::new(); + for item in a { + *counts.entry(item).or_insert(0usize) += 1; + } + for item in b { + match counts.get_mut(item) { + Some(count) if *count > 0 => *count -= 1, + _ => return false, + } } + true } #[cfg(test)] @@ -116,6 +118,16 @@ where #[cfg(test)] mod tests { + #[test] + fn compares_element_counts() { + use super::have_same_elements; + + assert!(have_same_elements(&[1, 1, 2], &[2, 1, 1])); + assert!(!have_same_elements(&[1, 1, 2], &[1, 2, 2])); + assert!(!have_same_elements(&[1, 1], &[1])); + assert!(!have_same_elements(&[1, 2], &[1, 3])); + } + #[test] fn is_sorted() { use super::*;