Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions src/sorting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,23 +79,25 @@ use std::cmp;
#[cfg(test)]
pub fn have_same_elements<T>(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)]
Expand All @@ -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::*;
Expand Down