Guest User

Untitled

a guest
Jul 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3. use std::iter::FromIterator;
  4. use std::ops::Add;
  5.  
  6. struct Counter<K: Hash + Eq> {
  7. storage: HashMap<K, usize>,
  8. }
  9.  
  10. impl<K: Hash + Eq> Counter<K> {
  11. fn new() -> Self {
  12. Self {
  13. storage: HashMap::new(),
  14. }
  15. }
  16.  
  17. fn with_capacity(capacity: usize) -> Self {
  18. Self {
  19. storage: HashMap::with_capacity(capacity),
  20. }
  21. }
  22.  
  23. fn append(&mut self, key: K) {
  24. *self.storage.entry(key).or_insert(0) += 1
  25. }
  26.  
  27. fn most_common<'a>(&'a self, n: usize) -> Vec<&'a K> {
  28. let mut entries: Vec<_> = self.storage.iter().collect();
  29.  
  30. entries.sort_by(|(_, v1), (_, &v2)| v2.cmp(v1));
  31.  
  32. entries.iter().map(|&(k, _)| k).take(n).collect()
  33. }
  34. }
  35.  
  36. impl<K: Hash + Eq> FromIterator<K> for Counter<K> {
  37. fn from_iter<T: IntoIterator<Item = K>>(iter: T) -> Self {
  38. let iterator = iter.into_iter();
  39. let (min, max) = iterator.size_hint();
  40. let mut counter = Self::with_capacity(max.unwrap_or(min));
  41.  
  42. for key in iterator {
  43. counter.append(key);
  44. }
  45.  
  46. counter
  47. }
  48. }
  49.  
  50.  
  51. impl<K: Hash + Eq> Add<K> for Counter<K> {
  52. type Output = Counter<K>;
  53.  
  54. fn add(&self, other: Counter<K>) -> Counter<K> {
  55. let mut new_counter = Counter::new();
  56. new_counter.merge(&self);
  57.  
  58. for (key, value) in &other {
  59. new_counter.entry(key).or_insert(value);
  60. }
  61.  
  62. new_counter
  63. }
  64. }
  65.  
  66. fn main() {
  67. let collected_counter: Counter<&str> = vec!["test", "test", "test", "hello", "hello", "world"]
  68. .into_iter()
  69. .collect();
  70.  
  71. let mut my_counter: Counter<&str> = Counter::new();
  72. my_counter.append("test");
  73. my_counter.append("test");
  74. my_counter.append("test");
  75. my_counter.append("hello");
  76. my_counter.append("hello");
  77. my_counter.append("world");
  78.  
  79. println!("{:?}", my_counter.most_common(2));
  80.  
  81. let mut my_counter_2: Counter<&str> = Counter::new();
  82. my_counter_2.append("x");
  83. my_counter_2.append("x");
  84. my_counter_2.append("x");
  85. my_counter_2.append("y");
  86.  
  87. println!("{:?}", my_counter_2.most_common(2));
  88.  
  89. println!("{:?}", my_counter + my_counter_2);
  90. }
Add Comment
Please, Sign In to add comment