Skip to main content

nekolib/traits/
usize_group_by.rs

1//! イテレータのグルーピング。
2
3/// イテレータのグルーピング。
4///
5/// # See also
6/// [`GroupBy`]
7///
8/// [`GroupBy`]: trait.GroupBy.html
9pub trait UsizeGroupBy<V> {
10    /// # Examples
11    /// ```
12    /// use nekolib::traits::UsizeGroupBy;
13    ///
14    /// let a = vec![1, 4, 3, -5, -6, 0, 2, -2, 3];
15    /// let g = a.iter().copied().usize_group_by(|&ai: &i32| ai.rem_euclid(3) as usize);
16    ///
17    /// assert_eq!(g.len(), 3);
18    /// assert_eq!(g[0], [3, -6, 0, 3]);
19    /// assert_eq!(g[1], [1, 4, -5, -2]);
20    /// assert_eq!(g[2], [2]);
21    /// ```
22    fn usize_group_by(self, index: impl FnMut(&V) -> usize) -> Vec<Vec<V>>;
23}
24
25impl<V, I: Iterator<Item = V>> UsizeGroupBy<V> for I {
26    fn usize_group_by(self, mut index: impl FnMut(&V) -> usize) -> Vec<Vec<V>> {
27        let mut res: Vec<Vec<_>> = vec![];
28        for v in self {
29            let i = index(&v);
30            if i >= res.len() {
31                res.resize_with(i + 1, Default::default);
32            }
33            res[i].push(v);
34        }
35        res
36    }
37}