|
1 | 1 | use super::SparseBinMat; |
2 | | -use crate::SparseBinSlice; |
3 | 2 |
|
4 | 3 | /// An iterator over the coordinates of non trivial elements. |
5 | 4 | /// |
6 | 5 | /// See the [`non_trivial_elements`](SparseBinMat::non_trivial_elements) method. |
7 | 6 | #[derive(Debug, Clone)] |
8 | | -pub struct NonTrivialElements<'a> {} |
| 7 | +pub struct NonTrivialElements<'a> { |
| 8 | + matrix: &'a SparseBinMat, |
| 9 | + row_index: usize, |
| 10 | + column_index: usize, |
| 11 | +} |
9 | 12 |
|
10 | 13 | impl<'a> NonTrivialElements<'a> { |
11 | | - pub(super) fn new(matrix: &'a SparseBinMat) -> Self {} |
| 14 | + pub(super) fn new(matrix: &'a SparseBinMat) -> Self { |
| 15 | + Self { |
| 16 | + matrix, |
| 17 | + row_index: 0, |
| 18 | + column_index: 0, |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + fn next_element(&mut self) -> Option<(usize, usize)> { |
| 23 | + self.matrix |
| 24 | + .row(self.row_index) |
| 25 | + .and_then(|row| row.as_slice().get(self.column_index).cloned()) |
| 26 | + .map(|column| (self.row_index, column)) |
| 27 | + } |
12 | 28 |
|
13 | 29 | fn move_to_next_row(&mut self) { |
14 | | - todo!() |
| 30 | + self.row_index += 1; |
| 31 | + self.column_index = 0; |
| 32 | + } |
| 33 | + |
| 34 | + fn move_to_next_column(&mut self) { |
| 35 | + self.column_index += 1; |
| 36 | + } |
| 37 | + |
| 38 | + fn is_done(&self) -> bool { |
| 39 | + self.row_index >= self.matrix.number_of_rows() |
15 | 40 | } |
16 | 41 | } |
17 | 42 |
|
18 | 43 | impl<'a> Iterator for NonTrivialElements<'a> { |
19 | 44 | type Item = (usize, usize); |
20 | 45 |
|
21 | | - fn next(&mut self) -> Option<Self::Item> {} |
| 46 | + fn next(&mut self) -> Option<Self::Item> { |
| 47 | + println!("({}, {})", self.row_index, self.column_index); |
| 48 | + if self.is_done() { |
| 49 | + None |
| 50 | + } else { |
| 51 | + match self.next_element() { |
| 52 | + Some(element) => { |
| 53 | + self.move_to_next_column(); |
| 54 | + Some(element) |
| 55 | + } |
| 56 | + None => { |
| 57 | + self.move_to_next_row(); |
| 58 | + self.next() |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
22 | 63 | } |
23 | 64 |
|
24 | 65 | #[cfg(test)] |
25 | 66 | mod test { |
26 | 67 | use super::*; |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn non_trivial_elements_of_small_matrix() { |
| 71 | + let matrix = SparseBinMat::new(3, vec![vec![1], vec![0, 2], vec![0, 1, 2]]); |
| 72 | + let mut iter = NonTrivialElements::new(&matrix); |
| 73 | + |
| 74 | + assert_eq!(iter.next(), Some((0, 1))); |
| 75 | + assert_eq!(iter.next(), Some((1, 0))); |
| 76 | + assert_eq!(iter.next(), Some((1, 2))); |
| 77 | + assert_eq!(iter.next(), Some((2, 0))); |
| 78 | + assert_eq!(iter.next(), Some((2, 1))); |
| 79 | + assert_eq!(iter.next(), Some((2, 2))); |
| 80 | + assert_eq!(iter.next(), None); |
| 81 | + } |
27 | 82 | } |
0 commit comments