Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemended swap #54

Merged
merged 1 commit into from
Aug 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1471,6 +1471,32 @@ impl<T> Grid<T> {
col_end_index: self.cols,
}
}

/// Swaps two elements in the Grid.
/// Similar to `Vec::swap()`.
///
/// # Panics
///
/// Panics if either index is out of bounds.
pub fn swap(&mut self, (row_a, col_a): (usize, usize), (row_b, col_b): (usize, usize)) {
assert!(
!(row_a >= self.rows || col_a >= self.cols),
"grid index out of bounds: ({row_a},{col_a}) out of ({},{})",
self.rows,
self.cols
);
assert!(
!(row_b >= self.rows || col_b >= self.cols),
"grid index out of bounds: ({row_b},{col_b}) out of ({},{})",
self.rows,
self.cols
);

let a_idx = self.get_index(row_a, col_a);
let b_idx = self.get_index(row_b, col_b);

self.data.swap(a_idx, b_idx);
}
}

impl<T> Default for Grid<T> {
Expand Down Expand Up @@ -3396,6 +3422,21 @@ mod test {
assert_eq!(r3, 7 + 8 + 9);
}

#[test]
fn swap() {
let mut grid = grid![[1,2][4,5]];
grid.swap((0, 0), (1, 0));
let end_grid = grid![[4,2][1,5]];
assert_eq!(grid, end_grid);
}

#[test]
#[should_panic(expected = "grid index out of bounds: (2,0) out of (2,2)")]
fn swap_out_of_bounds() {
let mut grid = grid![[1,2][4,5]];
grid.swap((0, 0), (2, 0));
}

#[cfg(feature = "serde")]
mod serde_tests {
use super::*;
Expand Down
Loading