| 1 | //! Counter counts recurrent elements of iterables. It is based on [the Python |
| 2 | //! implementation](https://docs.python.org/3/library/collections.html#collections.Counter). |
| 3 | //! |
| 4 | //! The struct [`Counter`](struct.Counter.html) is the entry-point type for this module. |
| 5 | //! |
| 6 | //! # Math Underpinnings |
| 7 | //! |
| 8 | //! Mathematically, a `Counter` implements a hash-based version of a [multiset], |
| 9 | //! or bag. This is simply an extension of the notion of a set to the idea that |
| 10 | //! we care not only about whether an entity exists within the set, but the number |
| 11 | //! of occurrences within the set. Normal set operations such as intersection, |
| 12 | //! union, etc. are of course still supported. |
| 13 | //! |
| 14 | //! [multiset]: https://en.wikipedia.org/wiki/Set_(abstract_data_type)#Multiset |
| 15 | //! |
| 16 | //! # Examples |
| 17 | //! |
| 18 | //! ## Just count an iterable |
| 19 | //! |
| 20 | //! ```rust |
| 21 | //! use counter::Counter; |
| 22 | //! let char_counts = "barefoot".chars().collect::<Counter<_>>(); |
| 23 | //! let counts_counts = char_counts.values().collect::<Counter<_>>(); |
| 24 | //! ``` |
| 25 | //! |
| 26 | //! ## Update a count |
| 27 | //! |
| 28 | //! ```rust |
| 29 | //! # use counter::Counter; |
| 30 | //! let mut counts = "aaa".chars().collect::<Counter<_>>(); |
| 31 | //! counts[&'a'] += 1; |
| 32 | //! counts[&'b'] += 1; |
| 33 | //! ``` |
| 34 | //! |
| 35 | //! ```rust |
| 36 | //! # use counter::Counter; |
| 37 | //! let mut counts = "able babble table babble rabble table able fable scrabble" |
| 38 | //! .split_whitespace().collect::<Counter<_>>(); |
| 39 | //! // add or subtract an iterable of the same type |
| 40 | //! counts += "cain and abel fable table cable".split_whitespace(); |
| 41 | //! // or add or subtract from another Counter of the same type |
| 42 | //! let other_counts = "scrabble cabbie fable babble" |
| 43 | //! .split_whitespace().collect::<Counter<_>>(); |
| 44 | //! let difference = counts - other_counts; |
| 45 | //! ``` |
| 46 | //! |
| 47 | //! ## Extend a `Counter` with another `Counter`: |
| 48 | //! ```rust |
| 49 | //! # use counter::Counter; |
| 50 | //! # use std::collections::HashMap; |
| 51 | //! let mut counter = "abbccc".chars().collect::<Counter<_>>(); |
| 52 | //! let another = "bccddd".chars().collect::<Counter<_>>(); |
| 53 | //! counter.extend(&another); |
| 54 | //! let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter() |
| 55 | //! .cloned().collect::<HashMap<_, _>>(); |
| 56 | //! assert_eq!(counter.into_map(), expect); |
| 57 | //! ``` |
| 58 | //! ## Get items with keys |
| 59 | //! |
| 60 | //! ```rust |
| 61 | //! # use counter::Counter; |
| 62 | //! let counts = "aaa".chars().collect::<Counter<_>>(); |
| 63 | //! assert_eq!(counts[&'a'], 3); |
| 64 | //! assert_eq!(counts[&'b'], 0); |
| 65 | //! ``` |
| 66 | //! |
| 67 | //! ## Get the most common items |
| 68 | //! |
| 69 | //! [`most_common_ordered()`] uses the natural ordering of keys which are [`Ord`]. |
| 70 | //! |
| 71 | //! [`most_common_ordered()`]: Counter::most_common_ordered |
| 72 | //! [`Ord`]: https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html |
| 73 | //! |
| 74 | //! ```rust |
| 75 | //! # use counter::Counter; |
| 76 | //! let by_common = "eaddbbccc".chars().collect::<Counter<_>>().most_common_ordered(); |
| 77 | //! let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)]; |
| 78 | //! assert!(by_common == expected); |
| 79 | //! ``` |
| 80 | //! |
| 81 | //! [`k_most_common_ordered()`] takes an argument `k` of type `usize` and returns the top `k` most |
| 82 | //! common items. This is functionally equivalent to calling `most_common_ordered()` and then |
| 83 | //! truncating the result to length `k`. However, if `k` is smaller than the length of the counter |
| 84 | //! then `k_most_common_ordered()` can be more efficient, often much more so. |
| 85 | //! |
| 86 | //! ```rust |
| 87 | //! # use counter::Counter; |
| 88 | //! let by_common = "eaddbbccc".chars().collect::<Counter<_>>().k_most_common_ordered(2); |
| 89 | //! let expected = vec![('c', 3), ('b', 2)]; |
| 90 | //! assert!(by_common == expected); |
| 91 | //! ``` |
| 92 | //! |
| 93 | //! [`k_most_common_ordered()`]: Counter::k_most_common_ordered |
| 94 | //! [`most_common_ordered()`]: Counter::most_common_ordered |
| 95 | //! |
| 96 | //! ## Get the most common items using your own ordering |
| 97 | //! |
| 98 | //! For example, here we break ties reverse alphabetically. |
| 99 | //! |
| 100 | //! ```rust |
| 101 | //! # use counter::Counter; |
| 102 | //! let counter = "eaddbbccc".chars().collect::<Counter<_>>(); |
| 103 | //! let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a)); |
| 104 | //! let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)]; |
| 105 | //! assert!(by_common == expected); |
| 106 | //! ``` |
| 107 | //! |
| 108 | //! ## Test counters against another |
| 109 | //! |
| 110 | //! Counters are multi-sets and so can be sub- or supersets of each other. |
| 111 | //! |
| 112 | //! A counter is a _subset_ of another if for all its elements, the other |
| 113 | //! counter has an equal or higher count. Test for this with [`is_subset()`]: |
| 114 | //! |
| 115 | //! ```rust |
| 116 | //! # use counter::Counter; |
| 117 | //! let counter = "aaabb".chars().collect::<Counter<_>>(); |
| 118 | //! let superset = "aaabbbc".chars().collect::<Counter<_>>(); |
| 119 | //! let not_a_superset = "aaae".chars().collect::<Counter<_>>(); |
| 120 | //! assert!(counter.is_subset(&superset)); |
| 121 | //! assert!(!counter.is_subset(¬_a_superset)); |
| 122 | //! ``` |
| 123 | //! |
| 124 | //! Testing for a _superset_ is the inverse, [`is_superset()`] is true if the counter can contain another counter in its entirety: |
| 125 | //! |
| 126 | //! ```rust |
| 127 | //! # use counter::Counter; |
| 128 | //! let counter = "aaabbbc".chars().collect::<Counter<_>>(); |
| 129 | //! let subset = "aabbb".chars().collect::<Counter<_>>(); |
| 130 | //! let not_a_subset = "aaae".chars().collect::<Counter<_>>(); |
| 131 | //! assert!(counter.is_superset(&subset)); |
| 132 | //! assert!(!counter.is_superset(¬_a_subset)); |
| 133 | //! ``` |
| 134 | //! |
| 135 | //! These relationships continue to work when [using a _signed_ integer type for the counter][signed]: all values in the subset must be equal or lower to the values in the superset. Negative |
| 136 | //! values are interpreted as 'missing' those values, and the subset would need to miss those |
| 137 | //! same elements, or be short more, to still be a subset: |
| 138 | //! |
| 139 | //! ```rust |
| 140 | //! # use counter::Counter; |
| 141 | //! let mut subset = "aaabb".chars().collect::<Counter<_, i8>>(); |
| 142 | //! subset.insert('e', -2); // short 2 'e's |
| 143 | //! subset.insert('f', -1); // and 1 'f' |
| 144 | //! let mut superset = "aaaabbb".chars().collect::<Counter<_, i8>>(); |
| 145 | //! superset.insert('e', -1); // short 1 'e' |
| 146 | //! assert!(subset.is_subset(&superset)); |
| 147 | //! assert!(superset.is_superset(&subset)); |
| 148 | //! ``` |
| 149 | //! |
| 150 | //! [`is_subset()`]: Counter::is_subset |
| 151 | //! [`is_superset()`]: Counter::is_superset |
| 152 | //! [signed]: #use-your-own-type-for-the-count |
| 153 | //! |
| 154 | //! ## Counter intersection and union |
| 155 | //! |
| 156 | //! You can intersect two counters, giving you the minimal counts of their |
| 157 | //! combined elements using the [`&` bitwise and operator][BitAnd], and produce |
| 158 | //! their union with the maximum counts using [`|` bitwise or][BitOr]: |
| 159 | //! |
| 160 | //! ```rust |
| 161 | //! # use counter::Counter; |
| 162 | //! let a = "aaabb".chars().collect::<Counter<_>>(); |
| 163 | //! let b = "aabbbbe".chars().collect::<Counter<_>>(); |
| 164 | //! |
| 165 | //! let intersection = a & b; |
| 166 | //! let expected_intersection = "aabb".chars().collect::<Counter<_>>(); |
| 167 | //! assert_eq!(intersection, expected_intersection); |
| 168 | //! |
| 169 | //! let c = "aaabb".chars().collect::<Counter<_>>(); |
| 170 | //! let d = "aabbbbe".chars().collect::<Counter<_>>(); |
| 171 | //! |
| 172 | //! let union = c | d; |
| 173 | //! let expected_union = "aaabbbbe".chars().collect::<Counter<_>>(); |
| 174 | //! assert_eq!(union, expected_union) |
| 175 | //! ``` |
| 176 | //! |
| 177 | //! The in-place [`&=`] and [`|=`] operations are also supported. |
| 178 | //! |
| 179 | //! [BitAnd]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html |
| 180 | //! [BitOr]: https://doc.rust-lang.org/std/ops/trait.BitOr.html |
| 181 | //! [`&=`]: https://doc.rust-lang.org/std/ops/trait.BitAndAssign.html |
| 182 | //! [`|=`]: https://doc.rust-lang.org/std/ops/trait.BitOrAssign.html |
| 183 | //! |
| 184 | //! ## Treat it like a `HashMap` |
| 185 | //! |
| 186 | //! `Counter<T, N>` implements [`Deref`]`<Target=HashMap<T, N>>` and |
| 187 | //! [`DerefMut`]`<Target=HashMap<T, N>>`, which means that you can perform any operations |
| 188 | //! on it which are valid for a [`HashMap`]. |
| 189 | //! |
| 190 | //! [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html |
| 191 | //! [`Deref`]: https://doc.rust-lang.org/stable/std/ops/trait.Deref.html |
| 192 | //! [`DerefMut`]: https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html |
| 193 | //! |
| 194 | //! ```rust |
| 195 | //! # use counter::Counter; |
| 196 | //! let mut counter = "aa-bb-cc".chars().collect::<Counter<_>>(); |
| 197 | //! counter.remove(&'-'); |
| 198 | //! assert!(counter == "aabbcc".chars().collect::<Counter<_>>()); |
| 199 | //! ``` |
| 200 | //! |
| 201 | //! Note that `Counter<T, N>` itself implements [`Index`]. `Counter::index` returns a reference to |
| 202 | //! a [`Zero::zero`] value for missing keys. |
| 203 | //! |
| 204 | //! [`Index`]: https://doc.rust-lang.org/stable/std/ops/trait.Index.html |
| 205 | //! [`Zero::zero`]: https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero |
| 206 | //! |
| 207 | //! ```rust |
| 208 | //! # use counter::Counter; |
| 209 | //! let counter = "aaa".chars().collect::<Counter<_>>(); |
| 210 | //! assert_eq!(counter[&'b'], 0); |
| 211 | //! // panics |
| 212 | //! // assert_eq!((*counter)[&'b'], 0); |
| 213 | //! ``` |
| 214 | //! |
| 215 | //! # Advanced Usage |
| 216 | //! |
| 217 | //! ## Count any iterable which is `Hash + Eq` |
| 218 | //! |
| 219 | //! You can't use the `most_common*` functions unless `T` is also [`Clone`], but simple counting |
| 220 | //! works fine on a minimal data type. |
| 221 | //! |
| 222 | //! [`Clone`]: https://doc.rust-lang.org/stable/std/clone/trait.Clone.html |
| 223 | //! |
| 224 | //! ```rust |
| 225 | //! # use counter::Counter; |
| 226 | //! #[derive(Debug, Hash, PartialEq, Eq)] |
| 227 | //! struct Inty { |
| 228 | //! i: usize, |
| 229 | //! } |
| 230 | //! |
| 231 | //! impl Inty { |
| 232 | //! pub fn new(i: usize) -> Inty { |
| 233 | //! Inty { i: i } |
| 234 | //! } |
| 235 | //! } |
| 236 | //! |
| 237 | //! // <https://en.wikipedia.org/wiki/867-5309/Jenny> |
| 238 | //! let intys = vec![ |
| 239 | //! Inty::new(8), |
| 240 | //! Inty::new(0), |
| 241 | //! Inty::new(0), |
| 242 | //! Inty::new(8), |
| 243 | //! Inty::new(6), |
| 244 | //! Inty::new(7), |
| 245 | //! Inty::new(5), |
| 246 | //! Inty::new(3), |
| 247 | //! Inty::new(0), |
| 248 | //! Inty::new(9), |
| 249 | //! ]; |
| 250 | //! |
| 251 | //! let inty_counts = intys.iter().collect::<Counter<_>>(); |
| 252 | //! println!("{:?}", inty_counts); |
| 253 | //! // {Inty { i: 8 }: 2, Inty { i: 0 }: 3, Inty { i: 9 }: 1, Inty { i: 3 }: 1, |
| 254 | //! // Inty { i: 7 }: 1, Inty { i: 6 }: 1, Inty { i: 5 }: 1} |
| 255 | //! assert!(inty_counts.get(&Inty { i: 8 }) == Some(&2)); |
| 256 | //! assert!(inty_counts.get(&Inty { i: 0 }) == Some(&3)); |
| 257 | //! assert!(inty_counts.get(&Inty { i: 6 }) == Some(&1)); |
| 258 | //! ``` |
| 259 | //! |
| 260 | //! ## Use your own type for the count |
| 261 | //! |
| 262 | //! Sometimes [`usize`] just isn't enough. If you find yourself overflowing your |
| 263 | //! machine's native size, you can use your own type. Here, we use an [`i8`], but |
| 264 | //! you can use most numeric types, including bignums, as necessary. |
| 265 | //! |
| 266 | //! [`usize`]: https://doc.rust-lang.org/stable/std/primitive.usize.html |
| 267 | //! [`i8`]: https://doc.rust-lang.org/stable/std/primitive.i8.html |
| 268 | //! |
| 269 | //! ```rust |
| 270 | //! # use counter::Counter; |
| 271 | //! # use std::collections::HashMap; |
| 272 | //! let counter: Counter<_, i8> = "abbccc".chars().collect(); |
| 273 | //! let expected: HashMap<char, i8> = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect(); |
| 274 | //! assert!(counter.into_map() == expected); |
| 275 | //! ``` |
| 276 | |
| 277 | #![allow(clippy::must_use_candidate)] |
| 278 | mod impls; |
| 279 | |
| 280 | use num_traits::{One, Zero}; |
| 281 | |
| 282 | use std::collections::{BinaryHeap, HashMap}; |
| 283 | use std::hash::Hash; |
| 284 | use std::iter; |
| 285 | use std::ops::{AddAssign, SubAssign}; |
| 286 | #[cfg(test)] |
| 287 | mod unit_tests; |
| 288 | |
| 289 | type CounterMap<T, N> = HashMap<T, N>; |
| 290 | |
| 291 | #[derive(Clone, PartialEq, Eq, Debug)] |
| 292 | pub struct Counter<T: Hash + Eq, N = usize> { |
| 293 | map: CounterMap<T, N>, |
| 294 | // necessary for `Index::index` since we cannot declare generic `static` variables. |
| 295 | zero: N, |
| 296 | } |
| 297 | |
| 298 | impl<T, N> Counter<T, N> |
| 299 | where |
| 300 | T: Hash + Eq, |
| 301 | { |
| 302 | /// Consumes this counter and returns a [`HashMap`] mapping the items to the counts. |
| 303 | /// |
| 304 | /// [`HashMap`]: https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html |
| 305 | pub fn into_map(self) -> HashMap<T, N> { |
| 306 | self.map |
| 307 | } |
| 308 | |
| 309 | /// Returns the sum of the counts. |
| 310 | /// |
| 311 | /// Use [`len`] to get the number of elements in the counter and use `total` to get the sum of |
| 312 | /// their counts. |
| 313 | /// |
| 314 | /// [`len`]: struct.Counter.html#method.len |
| 315 | /// |
| 316 | /// # Examples |
| 317 | /// |
| 318 | /// ``` |
| 319 | /// # use counter::Counter; |
| 320 | /// let counter = "abracadabra".chars().collect::<Counter<_>>(); |
| 321 | /// assert_eq!(counter.total::<usize>(), 11); |
| 322 | /// assert_eq!(counter.len(), 5); |
| 323 | /// ``` |
| 324 | pub fn total<'a, S>(&'a self) -> S |
| 325 | where |
| 326 | S: iter::Sum<&'a N>, |
| 327 | { |
| 328 | self.map.values().sum() |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | impl<T, N> Counter<T, N> |
| 333 | where |
| 334 | T: Hash + Eq, |
| 335 | N: AddAssign + Zero + One, |
| 336 | { |
| 337 | /// Add the counts of the elements from the given iterable to this counter. |
| 338 | pub fn update<I>(&mut self, iterable: I) |
| 339 | where |
| 340 | I: IntoIterator<Item = T>, |
| 341 | { |
| 342 | for item in iterable { |
| 343 | let entry = self.map.entry(item).or_insert_with(N::zero); |
| 344 | *entry += N::one(); |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | impl<T, N> Counter<T, N> |
| 350 | where |
| 351 | T: Hash + Eq, |
| 352 | N: PartialOrd + SubAssign + Zero + One, |
| 353 | { |
| 354 | /// Remove the counts of the elements from the given iterable to this counter. |
| 355 | /// |
| 356 | /// Non-positive counts are automatically removed. |
| 357 | /// |
| 358 | /// ```rust |
| 359 | /// # use counter::Counter; |
| 360 | /// # use std::collections::HashMap; |
| 361 | /// let mut counter = "abbccc".chars().collect::<Counter<_>>(); |
| 362 | /// counter.subtract("abba".chars()); |
| 363 | /// let expect = [('c', 3)].iter().cloned().collect::<HashMap<_, _>>(); |
| 364 | /// assert_eq!(counter.into_map(), expect); |
| 365 | /// ``` |
| 366 | pub fn subtract<I>(&mut self, iterable: I) |
| 367 | where |
| 368 | I: IntoIterator<Item = T>, |
| 369 | { |
| 370 | for item in iterable { |
| 371 | let mut remove = false; |
| 372 | if let Some(entry) = self.map.get_mut(&item) { |
| 373 | if *entry > N::zero() { |
| 374 | *entry -= N::one(); |
| 375 | } |
| 376 | remove = *entry == N::zero(); |
| 377 | } |
| 378 | if remove { |
| 379 | self.map.remove(&item); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | impl<T, N> Counter<T, N> |
| 386 | where |
| 387 | T: Hash + Eq + Clone, |
| 388 | N: Clone + Ord, |
| 389 | { |
| 390 | /// Create a vector of `(elem, frequency)` pairs, sorted most to least common. |
| 391 | /// |
| 392 | /// ```rust |
| 393 | /// # use counter::Counter; |
| 394 | /// let mc = "pappaopolo".chars().collect::<Counter<_>>().most_common(); |
| 395 | /// let expected = vec![('p', 4), ('o', 3), ('a', 2), ('l', 1)]; |
| 396 | /// assert_eq!(mc, expected); |
| 397 | /// ``` |
| 398 | /// |
| 399 | /// Note that the ordering of duplicates is unstable. |
| 400 | pub fn most_common(&self) -> Vec<(T, N)> { |
| 401 | use std::cmp::Ordering; |
| 402 | self.most_common_tiebreaker(|_a, _b| Ordering::Equal) |
| 403 | } |
| 404 | |
| 405 | /// Create a vector of `(elem, frequency)` pairs, sorted most to least common. |
| 406 | /// |
| 407 | /// In the event that two keys have an equal frequency, use the supplied ordering function |
| 408 | /// to further arrange the results. |
| 409 | /// |
| 410 | /// For example, we can sort reverse-alphabetically: |
| 411 | /// |
| 412 | /// ```rust |
| 413 | /// # use counter::Counter; |
| 414 | /// let counter = "eaddbbccc".chars().collect::<Counter<_>>(); |
| 415 | /// let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a)); |
| 416 | /// let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)]; |
| 417 | /// assert_eq!(by_common, expected); |
| 418 | /// ``` |
| 419 | pub fn most_common_tiebreaker<F>(&self, mut tiebreaker: F) -> Vec<(T, N)> |
| 420 | where |
| 421 | F: FnMut(&T, &T) -> ::std::cmp::Ordering, |
| 422 | { |
| 423 | let mut items = self |
| 424 | .map |
| 425 | .iter() |
| 426 | .map(|(key, count)| (key.clone(), count.clone())) |
| 427 | .collect::<Vec<_>>(); |
| 428 | items.sort_unstable_by(|(a_item, a_count), (b_item, b_count)| { |
| 429 | b_count |
| 430 | .cmp(a_count) |
| 431 | .then_with(|| tiebreaker(a_item, b_item)) |
| 432 | }); |
| 433 | items |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | impl<T, N> Counter<T, N> |
| 438 | where |
| 439 | T: Hash + Eq + Clone + Ord, |
| 440 | N: Clone + Ord, |
| 441 | { |
| 442 | /// Create a vector of `(elem, frequency)` pairs, sorted most to least common. |
| 443 | /// |
| 444 | /// In the event that two keys have an equal frequency, use the natural ordering of the keys |
| 445 | /// to further sort the results. |
| 446 | /// |
| 447 | /// # Examples |
| 448 | /// |
| 449 | /// ```rust |
| 450 | /// # use counter::Counter; |
| 451 | /// let mc = "abracadabra".chars().collect::<Counter<_>>().most_common_ordered(); |
| 452 | /// let expect = vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]; |
| 453 | /// assert_eq!(mc, expect); |
| 454 | /// ``` |
| 455 | /// |
| 456 | /// # Time complexity |
| 457 | /// |
| 458 | /// *O*(*n* \* log *n*), where *n* is the number of items in the counter. If all you want is |
| 459 | /// the top *k* items and *k* < *n* then it can be more efficient to use |
| 460 | /// [`k_most_common_ordered`]. |
| 461 | /// |
| 462 | /// [`k_most_common_ordered`]: Counter::k_most_common_ordered |
| 463 | pub fn most_common_ordered(&self) -> Vec<(T, N)> { |
| 464 | self.most_common_tiebreaker(Ord::cmp) |
| 465 | } |
| 466 | |
| 467 | /// Returns the `k` most common items in decreasing order of their counts. |
| 468 | /// |
| 469 | /// The returned vector is the same as would be obtained by calling `most_common_ordered` and |
| 470 | /// then truncating the result to length `k`. In particular, items with the same count are |
| 471 | /// sorted in *increasing* order of their keys. Further, if `k` is greater than the length of |
| 472 | /// the counter then the returned vector will have length equal to that of the counter, not |
| 473 | /// `k`. |
| 474 | /// |
| 475 | /// # Examples |
| 476 | /// |
| 477 | /// ```rust |
| 478 | /// # use counter::Counter; |
| 479 | /// let counter: Counter<_> = "abracadabra".chars().collect(); |
| 480 | /// let top3 = counter.k_most_common_ordered(3); |
| 481 | /// assert_eq!(top3, vec![('a', 5), ('b', 2), ('r', 2)]); |
| 482 | /// ``` |
| 483 | /// |
| 484 | /// # Time complexity |
| 485 | /// |
| 486 | /// This method can be much more efficient than [`most_common_ordered`] when *k* is much |
| 487 | /// smaller than the length of the counter *n*. When *k* = 1 the algorithm is equivalent |
| 488 | /// to finding the minimum (or maximum) of *n* items, which requires *n* \- 1 comparisons. For |
| 489 | /// a fixed value of *k* > 1, the number of comparisons scales with *n* as *n* \+ *O*(log *n*) |
| 490 | /// and the number of swaps scales as *O*(log *n*). As *k* approaches *n*, this algorithm |
| 491 | /// approaches a heapsort of the *n* items, which has complexity *O*(*n* \* log *n*). |
| 492 | /// |
| 493 | /// For values of *k* close to *n* the sorting algorithm used by [`most_common_ordered`] will |
| 494 | /// generally be faster than the heapsort used by this method by a small constant factor. |
| 495 | /// Exactly where the crossover point occurs will depend on several factors. For small *k* |
| 496 | /// choose this method. If *k* is a substantial fraction of *n*, it may be that |
| 497 | /// [`most_common_ordered`] is faster. If performance matters in your application then it may |
| 498 | /// be worth experimenting to see which of the two methods is faster. |
| 499 | /// |
| 500 | /// [`most_common_ordered`]: Counter::most_common_ordered |
| 501 | #[allow(clippy::missing_panics_doc)] // current implementation does not panic |
| 502 | pub fn k_most_common_ordered(&self, k: usize) -> Vec<(T, N)> { |
| 503 | use std::cmp::Reverse; |
| 504 | |
| 505 | if k == 0 { |
| 506 | return vec![]; |
| 507 | } |
| 508 | |
| 509 | // The quicksort implementation used by `most_common_ordered()` is generally faster than |
| 510 | // the heapsort used below when sorting the entire counter. |
| 511 | if k >= self.map.len() { |
| 512 | return self.most_common_ordered(); |
| 513 | } |
| 514 | |
| 515 | // Clone the counts as we iterate over the map to eliminate an extra indirection when |
| 516 | // comparing counts. This will be an improvement in the typical case where `N: Copy`. |
| 517 | // Defer cloning the keys until we have selected the top `k` items so that we clone only |
| 518 | // `k` keys instead of all of them. |
| 519 | let mut items = self.map.iter().map(|(t, n)| (Reverse(n.clone()), t)); |
| 520 | |
| 521 | // Step 1. Make a heap out of the first `k` items; this makes O(k) comparisons. |
| 522 | let mut heap: BinaryHeap<_> = items.by_ref().take(k).collect(); |
| 523 | |
| 524 | // Step 2. Successively compare each of the remaining `n - k` items to the top of the heap, |
| 525 | // replacing the root (and subsequently sifting down) whenever the item is less than the |
| 526 | // root. This takes at most n - k + k * (1 + log2(k)) * (H(n) - H(k)) comparisons, where |
| 527 | // H(i) is the ith [harmonic number](https://en.wikipedia.org/wiki/Harmonic_number). For |
| 528 | // fixed `k`, this scales as *n* + *O*(log(*n*)). |
| 529 | items.for_each(|item| { |
| 530 | // If `items` is nonempty at this point then we know the heap contains `k > 0` |
| 531 | // elements. |
| 532 | let mut root = heap.peek_mut().expect("the heap is empty"); |
| 533 | if *root > item { |
| 534 | *root = item; |
| 535 | } |
| 536 | }); |
| 537 | |
| 538 | // Step 3. Sort the items in the heap with the second phases of heapsort. The number of |
| 539 | // comparisons is 2 * k * log2(k) + O(k). |
| 540 | heap.into_sorted_vec() |
| 541 | .into_iter() |
| 542 | .map(|(Reverse(n), t)| (t.clone(), n)) |
| 543 | .collect() |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | impl<T, N> Counter<T, N> |
| 548 | where |
| 549 | T: Hash + Eq, |
| 550 | N: PartialOrd + Zero, |
| 551 | { |
| 552 | /// Test whether this counter is a superset of another counter. |
| 553 | /// This is true if for all elements in this counter and the other, |
| 554 | /// the count in this counter is greater than or equal to the count in the other. |
| 555 | /// |
| 556 | /// `c.is_superset(&d);` -> `c.iter().all(|(x, n)| n >= d[x]) && d.iter().all(|(x, n)| c[x] >= n)` |
| 557 | /// |
| 558 | /// ```rust |
| 559 | /// # use counter::Counter; |
| 560 | /// # use std::collections::HashMap; |
| 561 | /// let c = "aaabbc".chars().collect::<Counter<_>>(); |
| 562 | /// let mut d = "abb".chars().collect::<Counter<_>>(); |
| 563 | /// |
| 564 | /// assert!(c.is_superset(&d)); |
| 565 | /// d[&'e'] = 1; |
| 566 | /// assert!(!c.is_superset(&d)); |
| 567 | /// ``` |
| 568 | pub fn is_superset(&self, other: &Self) -> bool { |
| 569 | // need to test keys from both counters, because if N is signed, counts in `self` |
| 570 | // could be < 0 for elements missing in `other`. For the unsigned case, only elements |
| 571 | // from `other` would need to be tested. |
| 572 | self.keys() |
| 573 | .chain(other.keys()) |
| 574 | .all(|key| self[key] >= other[key]) |
| 575 | } |
| 576 | |
| 577 | /// Test whether this counter is a subset of another counter. |
| 578 | /// This is true if for all elements in this counter and the other, |
| 579 | /// the count in this counter is less than or equal to the count in the other. |
| 580 | /// |
| 581 | /// `c.is_subset(&d);` -> `c.iter().all(|(x, n)| n <= d[x]) && d.iter().all(|(x, n)| c[x] <= n)` |
| 582 | /// |
| 583 | /// ```rust |
| 584 | /// # use counter::Counter; |
| 585 | /// # use std::collections::HashMap; |
| 586 | /// let mut c = "abb".chars().collect::<Counter<_>>(); |
| 587 | /// let mut d = "aaabbc".chars().collect::<Counter<_>>(); |
| 588 | /// |
| 589 | /// assert!(c.is_subset(&d)); |
| 590 | /// c[&'e'] = 1; |
| 591 | /// assert!(!c.is_subset(&d)); |
| 592 | /// ``` |
| 593 | pub fn is_subset(&self, other: &Self) -> bool { |
| 594 | // need to test keys from both counters, because if N is signed, counts in `other` |
| 595 | // could be < 0 for elements missing in `self`. For the unsigned case, only elements |
| 596 | // from `self` would need to be tested. |
| 597 | self.keys() |
| 598 | .chain(other.keys()) |
| 599 | .all(|key| self[key] <= other[key]) |
| 600 | } |
| 601 | } |