1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#[cfg(feature = "impl_from")]
mod from;
mod iter;
mod std_ops;

use std::ops::Deref;

/// A 2-Dimensional, non-resisable container.
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd)]
pub struct Matrix<T> {
    rows: usize,
    cols: usize,
    data: Vec<T>,
}

impl<T> Matrix<T> {
    /// Constructs a new, non-empty Matrix<T> where cells are set to `T::default`.  
    /// Use `Matrix::from_iter` if you want to set the matrix from an iterator.
    ///
    /// # Panics
    /// Panics if either `rows` or `cols` are equal to `0`
    ///
    /// # Examples
    /// ```
    /// let mut mat: Matrix<i32> = Matrix::new(3, 6);
    /// ```
    pub fn new(rows: usize, cols: usize) -> Matrix<T>
    where
        T: Default,
    {
        Matrix::from_iter(rows, cols, (0..).map(|_| T::default()))
    }

    /// Constructs a new, non-empty Matrix<T> where cells are set from an iterator.  
    /// The matrix cells are set row by row.  
    /// The iterator can be infinite, this method only consume `rows * cols`
    /// values from the iterator.
    ///
    /// # Panics
    /// Panics if either `rows` or `cols` are equal to `0`.  
    /// Panics if the iterator does not have `rows * cols` values
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    ///
    /// assert_eq!(mat.get(0, 0).unwrap(), 0);
    /// assert_eq!(mat.get(0, 1).unwrap(), 1);
    /// assert_eq!(mat.get(1, 0).unwrap(), 6);
    /// ```
    pub fn from_iter(rows: usize, cols: usize, data: impl IntoIterator<Item = T>) -> Matrix<T> {
        assert!(rows > 0 && cols > 0);

        Matrix {
            rows,
            cols,
            data: {
                let data: Vec<_> = data.into_iter().take(rows * cols).collect();
                assert_eq!(data.len(), rows * cols);
                data
            },
        }
    }

    /// Returns the number of rows in the matrix.
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    ///
    /// assert_eq!(mat.rows(), 3);
    /// ```
    pub fn rows(&self) -> usize {
        self.rows
    }

    /// Returns the number of columns in the matrix.
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    ///
    /// assert_eq!(mat.cols(), 6);
    /// ```
    pub fn cols(&self) -> usize {
        self.cols
    }

    /// Try to get a reference to the value at given row & column.  
    /// Returns `None` if `row` or `col` is outside of the matrix.
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    ///
    /// assert_eq!(mat.get(0, 0).unwrap(), 0);
    /// assert_eq!(mat.get(2, 5).unwrap(), 17);
    ///
    /// assert!(mat.get(10, 2).is_err());
    /// ```
    pub fn get(&self, row: usize, col: usize) -> Option<&T> {
        if row < self.rows && col < self.cols {
            Some(&self.data[col + row * self.cols])
        } else {
            None
        }
    }

    /// Try to get a mutable reference to the cell at given row & column.  
    /// Returns `None` if `row` or `col` is outside of the matrix.
    ///
    /// # Examples
    /// ```
    /// let mut mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    /// assert_eq!(mat.get(0, 0).unwrap(), 0);
    ///
    /// let cell = mat.get_mut(0, 0).unwrap();
    /// *cell = 5;
    ///
    /// assert_eq!(mat.get(0, 0).unwrap(), 5);
    /// ```
    pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut T> {
        if row < self.rows && col < self.cols {
            Some(&mut self.data[col + row * self.cols])
        } else {
            None
        }
    }

    /// Try to set the cell at given row & column to the given value.  
    /// Returns `false` if `row` or `col` is outside of the matrix.  
    /// Returns `true` if the cell has been modified.
    ///
    /// # Examples
    /// ```
    /// let mut mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    /// assert_eq!(mat.get(0, 0).unwrap(), 0);
    ///
    /// mat.set(0, 0, 5);
    /// assert_eq!(mat.get(0, 0).unwrap(), 5);
    /// ```
    pub fn set(&mut self, row: usize, col: usize, value: T) -> bool {
        if let Some(cell) = self.get_mut(row, col) {
            *cell = value;
            true
        } else {
            false
        }
    }

    /// Try to get an iterator of all cells of the requested row.  
    /// Returns `None` if given row is outside of the matrix.
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    ///
    /// assert_eq!(mat.get_row(1).unwrap(), vec![6, 7, 8, 9, 10, 11]);
    ///
    /// assert!(mat.get_row(5).is_err());
    /// ```
    pub fn get_row(&self, row: usize) -> Option<impl Iterator<Item = &T>> {
        if row < self.rows {
            Some((0..self.cols).map(move |col| self.get(row, col).unwrap()))
        } else {
            None
        }
    }

    /// Try to get an iterator of all cells of the requested column.  
    /// Returns `None` if given row is outside of the matrix.
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    ///
    /// assert_eq!(mat.get_col(1).unwrap(), vec![1, 7, 13]);
    ///
    /// assert!(mat.get_col(10).is_err());
    /// ```
    pub fn get_col(&self, col: usize) -> Option<impl Iterator<Item = &T>> {
        if col < self.cols {
            Some((0..self.rows).map(move |row| self.get(row, col).unwrap()))
        } else {
            None
        }
    }

    /// Take a *M*x*N* Matrix and construct the transposed *N*x*M* Matrix.
    ///
    /// # Examples
    /// ```
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    /// let mat_t = mat.transpose();
    ///
    /// assert_eq!(mat.rows(), mat_t.cols());
    /// assert_eq!(mat.cols(), mat_t.rows());
    ///
    /// assert_eq!(mat.get(0, 0).unwrap(), mat_t.get(0, 0).unwrap());
    /// assert_eq!(mat.get(1, 2).unwrap(), mat_t.get(2, 1).unwrap());
    /// ```
    pub fn transpose(&self) -> Matrix<T>
    where
        T: Clone,
    {
        Matrix {
            rows: self.cols,
            cols: self.rows,
            data: {
                let mut data = Vec::with_capacity(self.cols * self.rows);
                for row in 0..self.rows {
                    for val in self.get_row(row).unwrap() {
                        data.push(val.clone());
                    }
                }
                data
            },
        }
    }

    /// Apply a function to all cells of the matrix.  
    /// Cells are provided as immutable references to the function,
    /// if you want to modify the cells, use `apply_mut`.
    ///
    /// # Examples
    /// ```
    /// // Get the sum of all cells
    /// let mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    /// let mut sum = 0;
    /// mat.apply(|n| sum += *n);
    ///
    /// assert_eq!(sum, 153);
    /// ```
    pub fn apply<F: FnMut(&T)>(&self, mut func: F) {
        self.data.iter().for_each(|n| func(n));
    }

    /// Apply a function to all cells of the matrix.  
    /// Cells are provided as mutable references to the function,
    /// and can therefore be modified.
    ///
    /// # Examples
    /// ```
    /// // Modify all cells with a function
    /// let mut mat: Matrix<usize> = Matrix::new(3, 6, 0..);
    /// mat.apply_mut(|n| n *= 2);
    ///
    /// assert_eq!(mat.get(0, 0).unwrap(), 0);
    /// assert_eq!(mat.get(0, 1).unwrap(), 2);
    /// assert_eq!(mat.get(0, 2).unwrap(), 4);
    /// ```
    pub fn apply_mut<F: FnMut(&mut T)>(&mut self, mut func: F) {
        self.data.iter_mut().for_each(|n| func(n));
    }
}

impl<T> Deref for Matrix<T> {
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}