Skip to content

Commit a764cd5

Browse files
authored
Create 2013-detect-squares.rs
1 parent d9b73e8 commit a764cd5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

rust/2013-detect-squares.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use std::collections::HashMap;
2+
3+
struct DetectSquares {
4+
points: Vec<(i32, i32)>,
5+
counts: HashMap<(i32, i32), i32>
6+
}
7+
8+
impl DetectSquares {
9+
10+
fn new() -> Self {
11+
Self {
12+
points: vec![],
13+
counts: HashMap::new()
14+
}
15+
}
16+
17+
fn add(&mut self, point: Vec<i32>) {
18+
let p = (point[0], point[1]);
19+
self.points.push(p);
20+
*self.counts.entry(p).or_default() += 1;
21+
}
22+
23+
fn count(&self, point: Vec<i32>) -> i32 {
24+
let mut res = 0;
25+
let (px, py) = (point[0], point[1]);
26+
for (x, y) in self.points.iter() {
27+
if (py - y).abs() != (px - x).abs() || *x == px || *y == py {
28+
continue;
29+
}
30+
res += self.counts.get(&(*x, py)).unwrap_or(&0) * self.counts.get(&(px,*y)).unwrap_or(&0);
31+
}
32+
33+
res
34+
}
35+
}

0 commit comments

Comments
 (0)