Skip to content

Commit

Permalink
Add problem 2352: Equal Row and Column Pairs
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 5, 2024
1 parent 56c38c9 commit 3fe4e71
Show file tree
Hide file tree
Showing 3 changed files with 76 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 @@ -1743,6 +1743,7 @@ pub mod problem_2347_best_poker_hand;
pub mod problem_2348_number_of_zero_filled_subarrays;
pub mod problem_2349_design_a_number_container_system;
pub mod problem_2351_first_letter_to_appear_twice;
pub mod problem_2352_equal_row_and_column_pairs;

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

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

use std::collections::hash_map::Entry;
use std::collections::HashMap;

impl Solution {
pub fn equal_pairs(grid: Vec<Vec<i32>>) -> i32 {
let mut counts = HashMap::new();

for row in &grid {
match counts.entry(&**row) {
Entry::Occupied(occupied_entry) => *occupied_entry.into_mut() += 1,
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(1);
}
}
}

let mut result = 0;
let n = grid.len();
let mut buffer = Vec::with_capacity(n);

for x in 0..n {
buffer.extend(grid.iter().map(|row| row[x]));

if let Some(count) = counts.get(&*buffer) {
result += count;
}

buffer.clear();
}

result
}
}

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

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

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

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

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

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

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

0 comments on commit 3fe4e71

Please sign in to comment.