Skip to content

Commit

Permalink
Add problem 2013: Detect Squares
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Aug 4, 2024
1 parent 610cd5a commit d28af3f
Show file tree
Hide file tree
Showing 3 changed files with 672 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 @@ -1487,6 +1487,7 @@ pub mod problem_2007_find_original_array_from_doubled_array;
pub mod problem_2008_maximum_earnings_from_taxi;
pub mod problem_2011_final_value_of_variable_after_performing_operations;
pub mod problem_2012_sum_of_beauty_in_the_array;
pub mod problem_2013_detect_squares;
pub mod problem_2016_maximum_difference_between_increasing_elements;
pub mod problem_2017_grid_game;
pub mod problem_2018_check_if_word_can_be_placed_in_crossword;
Expand Down
85 changes: 85 additions & 0 deletions src/problem_2013_detect_squares/hash_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// ------------------------------------------------------ snip ------------------------------------------------------ //

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

pub struct DetectSquares {
points: HashMap<u16, HashMap<u16, u16>>,
}

impl DetectSquares {
fn new() -> Self {
Self { points: HashMap::new() }
}

fn add(&mut self, point: Vec<i32>) {
let [x, y]: [_; 2] = point.try_into().ok().unwrap();
let x = x as u16;
let y = y as u16;

match self.points.entry(x) {
Entry::Occupied(entry) => match entry.into_mut().entry(y) {
Entry::Occupied(entry) => *entry.into_mut() += 1,
Entry::Vacant(entry) => {
entry.insert(1);
}
},
Entry::Vacant(entry) => {
entry.insert(HashMap::from([(y, 1)]));
}
}
}

fn count(&self, point: Vec<i32>) -> i32 {
let [x_0, y_0]: [_; 2] = point.try_into().ok().unwrap();
let x_0 = x_0 as u16;
let y_0 = y_0 as u16;
let mut result = 0;

if let Some(column_0) = self.points.get(&x_0) {
for (&y_1, &count_0) in column_0 {
if y_0 == y_1 {
continue;
}

let d = y_1.wrapping_sub(y_0);

for x_1 in [x_0.wrapping_sub(d), x_0.wrapping_add(d)] {
if let Some(column_1) = self.points.get(&x_1) {
if let Some(&count_1) = column_1.get(&y_0) {
if let Some(&count_2) = column_1.get(&y_1) {
result += u32::from(count_0) * u32::from(count_1) * u32::from(count_2);
}
}
}
}
}
}

result as _
}
}

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

impl super::DetectSquares for DetectSquares {
fn new() -> Self {
Self::new()
}

fn add(&mut self, point: Vec<i32>) {
self.add(point);
}

fn count(&self, point: Vec<i32>) -> i32 {
self.count(point)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::DetectSquares>();
}
}
Loading

0 comments on commit d28af3f

Please sign in to comment.