Improve column swapping logic to handle empty matrices and prevent overlapping swaps

This commit is contained in:
Palash Tyagi 2025-05-03 00:25:45 +01:00
parent 34cff9f05e
commit 20727a2b91

View File

@ -149,19 +149,24 @@ impl<T: Clone> Matrix<T> {
self.cols self.cols
); );
if c1 == c2 { if c1 == c2 {
// Indices are equal; no operation required
return; return;
} }
// Iterate over each row to swap corresponding elements if self.rows == 0 {
for r in 0..self.rows { self.data.swap(c1, c2);
// Compute the one-dimensional index for (row r, column c1) return;
let idx1 = c1 * self.rows + r; }
// Compute the one-dimensional index for (row r, column c2)
let idx2 = c2 * self.rows + r;
// Exchange the two elements in the internal data buffer let (start1, end1) = (c1 * self.rows, (c1 + 1) * self.rows);
self.data.swap(idx1, idx2); let (start2, end2) = (c2 * self.rows, (c2 + 1) * self.rows);
if (start1 < start2 && end1 > start2) || (start2 < start1 && end2 > start1) {
panic!("Cannot swap overlapping columns");
}
// element-wise swap
for r in 0..self.rows {
self.data.swap(start1 + r, start2 + r);
} }
} }