|
12 | 12 | use super::MatQ; |
13 | 13 | use crate::{ |
14 | 14 | rational::Q, |
15 | | - traits::{MatrixDimensions, MatrixGetSubmatrix}, |
| 15 | + traits::{MatrixDimensions, MatrixGetEntry, MatrixGetSubmatrix}, |
16 | 16 | }; |
17 | 17 |
|
18 | 18 | impl MatQ { |
@@ -88,6 +88,33 @@ impl MatQ { |
88 | 88 | } |
89 | 89 | max_norm |
90 | 90 | } |
| 91 | + |
| 92 | + /// Outputs the hamming weight of `self`, i.e. it returns the number of |
| 93 | + /// non-zero entries in the matrix. |
| 94 | + /// |
| 95 | + /// # Examples |
| 96 | + /// ``` |
| 97 | + /// use qfall_math::rational::MatQ; |
| 98 | + /// use std::str::FromStr; |
| 99 | + /// |
| 100 | + /// let mat = MatQ::from_str("[[2, 3/2],[2/3, 0]]").unwrap(); |
| 101 | + /// |
| 102 | + /// let hamming_weight = mat.hamming_weight(); |
| 103 | + /// |
| 104 | + /// assert_eq!(3, hamming_weight); |
| 105 | + /// ``` |
| 106 | + pub fn hamming_weight(&self) -> i64 { |
| 107 | + let mut hamming_weight = 0; |
| 108 | + for row in 0..self.get_num_rows() { |
| 109 | + for col in 0..self.get_num_columns() { |
| 110 | + let entry = unsafe { self.get_entry_unchecked(row, col) }; |
| 111 | + if !entry.is_zero() { |
| 112 | + hamming_weight += 1; |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + hamming_weight |
| 117 | + } |
91 | 118 | } |
92 | 119 |
|
93 | 120 | #[cfg(test)] |
@@ -125,3 +152,22 @@ mod test_matrix_norms { |
125 | 152 | assert_eq!(Q::from(5), infty_norm); |
126 | 153 | } |
127 | 154 | } |
| 155 | + |
| 156 | +#[cfg(test)] |
| 157 | +mod test_hamming_weight { |
| 158 | + use super::MatQ; |
| 159 | + use std::str::FromStr; |
| 160 | + |
| 161 | + /// Ensures that the hamming weight is computed correctly. |
| 162 | + #[test] |
| 163 | + fn hamming_weight() { |
| 164 | + let mat0 = MatQ::new(10, 8); |
| 165 | + let mat1 = MatQ::from_str("[[-2/5, 3/4],[2, -5/2],[-2, 0]]").unwrap(); |
| 166 | + |
| 167 | + let hw0 = mat0.hamming_weight(); |
| 168 | + let hw1 = mat1.hamming_weight(); |
| 169 | + |
| 170 | + assert_eq!(0, hw0); |
| 171 | + assert_eq!(5, hw1); |
| 172 | + } |
| 173 | +} |
0 commit comments