use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone)]
pub struct Classifier<T> {
things: BTreeSet<T>,
sets: Vec<BTreeSet<T>>,
mapping: BTreeMap<T, usize>,
dirty: bool,
sort: bool,
}
impl<T: Ord + Clone> Default for Classifier<T> {
fn default() -> Self {
Self::new(true)
}
}
impl<T: Ord + Clone> Classifier<T> {
pub fn new(sort: bool) -> Self {
Classifier {
things: BTreeSet::new(),
sets: Vec::new(),
mapping: BTreeMap::new(),
dirty: false,
sort,
}
}
pub fn add(&mut self, set_of_things: impl IntoIterator<Item = T>) {
let s: BTreeSet<T> = set_of_things.into_iter().collect();
if s.is_empty() {
return;
}
self.dirty = true;
let (mut intersection, difference): (BTreeSet<T>, BTreeSet<T>) =
s.into_iter().partition(|t| self.things.contains(t));
if !difference.is_empty() {
let index = self.sets.len();
for thing in &difference {
self.things.insert(thing.clone());
self.mapping.insert(thing.clone(), index);
}
self.sets.push(difference);
}
while let Some(first) = intersection.first() {
let Some(&old) = self.mapping.get(first) else {
break;
};
let old_class_intersection: BTreeSet<T> = self.sets[old]
.intersection(&intersection)
.cloned()
.collect();
for thing in &old_class_intersection {
self.sets[old].remove(thing);
intersection.remove(thing);
}
let index = self.sets.len();
for thing in &old_class_intersection {
self.mapping.insert(thing.clone(), index);
}
self.sets.push(old_class_intersection);
}
}
pub fn update<I: IntoIterator<Item = T>>(&mut self, list_of_sets: impl IntoIterator<Item = I>) {
for s in list_of_sets {
self.add(s);
}
}
fn process(&mut self) {
if !self.dirty {
return;
}
let mut sets: Vec<BTreeSet<T>> = std::mem::take(&mut self.sets)
.into_iter()
.filter(|s| !s.is_empty())
.collect();
if self.sort {
sets.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.iter().cmp(b.iter())));
}
self.mapping.clear();
for (i, set) in sets.iter().enumerate() {
for thing in set {
self.mapping.insert(thing.clone(), i);
}
}
self.sets = sets;
self.dirty = false;
}
pub fn get_things(&mut self) -> &BTreeSet<T> {
self.process();
&self.things
}
pub fn get_classes(&mut self) -> &[BTreeSet<T>] {
self.process();
&self.sets
}
pub fn get_mapping(&mut self) -> &BTreeMap<T, usize> {
self.process();
&self.mapping
}
}
pub fn classify<T: Ord + Clone, I: IntoIterator<Item = T>>(
list_of_sets: impl IntoIterator<Item = I>,
sort: bool,
) -> (Vec<BTreeSet<T>>, BTreeMap<T, BTreeSet<T>>) {
let mut classifier = Classifier::new(sort);
classifier.update(list_of_sets);
let classes = classifier.get_classes().to_vec();
let mapping = classifier
.get_mapping()
.iter()
.map(|(thing, &i)| (thing.clone(), classes[i].clone()))
.collect();
(classes, mapping)
}