Skip to content

Commit

Permalink
Add problem 2319: Check if Matrix Is X-Matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 13, 2024
1 parent 16d50ec commit 0d01016
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1721,6 +1721,7 @@ pub mod problem_2310_sum_of_numbers_with_units_digit_k;
pub mod problem_2315_count_asterisks;
pub mod problem_2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph;
pub mod problem_2317_maximum_xor_after_operations;
pub mod problem_2319_check_if_matrix_is_x_matrix;

#[cfg(test)]
mod test_utilities;
34 changes: 34 additions & 0 deletions src/problem_2319_check_if_matrix_is_x_matrix/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn check_x_matrix(grid: Vec<Vec<i32>>) -> bool {
let n = grid.len();
let n_minus_1 = n - 1;

grid.iter().enumerate().all(|(y, row)| {
let other_x = n_minus_1 - y;

row.iter()
.enumerate()
.all(|(x, &value)| (value != 0) == (x == y || x == other_x))
})
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn check_x_matrix(grid: Vec<Vec<i32>>) -> bool {
Self::check_x_matrix(grid)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
25 changes: 25 additions & 0 deletions src/problem_2319_check_if_matrix_is_x_matrix/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
pub mod iterative;

pub trait Solution {
fn check_x_matrix(grid: Vec<Vec<i32>>) -> bool;
}

#[cfg(test)]
mod tests {
use super::Solution;
use crate::test_utilities::Matrix;

pub fn run<S: Solution>() {
let test_cases = [
(
&[[2, 0, 0, 1], [0, 3, 1, 0], [0, 5, 2, 0], [4, 0, 0, 2]] as &dyn Matrix<_>,
true,
),
(&[[5, 7, 0], [0, 3, 1], [0, 5, 0]], false),
];

for (grid, expected) in test_cases {
assert_eq!(S::check_x_matrix(grid.to_vec()), expected);
}
}
}

0 comments on commit 0d01016

Please sign in to comment.