summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorReiner Herrmann <reiner@reiner-h.de>2024-12-08 13:54:34 +0100
committerReiner Herrmann <reiner@reiner-h.de>2024-12-08 13:54:34 +0100
commitb7a788abb919e200d8c6bf44fe23191d636563f4 (patch)
tree3e9025de80183074970f1eca5a1b2a617fb24163 /src
parent8c3ae3b47613a3c245f9c87382b012a7be986fb6 (diff)
day8 solution 1
Diffstat (limited to 'src')
-rw-r--r--src/bin/day8.rs86
1 files changed, 86 insertions, 0 deletions
diff --git a/src/bin/day8.rs b/src/bin/day8.rs
new file mode 100644
index 0000000..ab8595f
--- /dev/null
+++ b/src/bin/day8.rs
@@ -0,0 +1,86 @@
+use std::collections::{HashMap, HashSet};
+
+static DAY: u8 = 8;
+
+fn main() {
+ let input = advent::read_lines(DAY);
+ println!("{DAY}a: {}", Map::new(&input).count_antinodes());
+ println!("{DAY}b: {}", 0);
+}
+
+#[derive(Eq, PartialEq, Hash)]
+struct Position {
+ x: isize,
+ y: isize,
+}
+
+impl Position {
+ fn add_position(&self, other: &Position) -> Position {
+ Position { x: self.x + (self.x - other.x), y: self.y + (self.y - other.y) }
+ }
+}
+
+struct Map {
+ antennas: HashMap<Position, char>,
+ dimensions: Position,
+}
+
+impl Map {
+ fn new(input: &[String]) -> Map {
+ let mut antennas = HashMap::new();
+
+ for (y, line) in input.iter().enumerate() {
+ for (x, c) in line.chars().enumerate() {
+ if c != '.' {
+ let pos = Position { x: x as isize, y: y as isize };
+ antennas.insert(pos, c);
+ }
+ }
+ }
+ let dimensions = Position { x: input[0].len() as isize, y: input.len() as isize };
+ Map { antennas, dimensions }
+ }
+
+ fn inside_map(&self, pos: &Position) -> bool {
+ pos.x >= 0 && pos.y >= 0 && pos.x < self.dimensions.x && pos.y < self.dimensions.y
+ }
+
+ fn count_antinodes(&self) -> usize {
+ let mut antinodes = HashSet::new();
+
+ for (pos1, antenna) in &self.antennas {
+ for (pos2, _) in self.antennas.iter().filter(|&(_, a)| a == antenna).filter(|&(p, _)| p != pos1) {
+ let antinode_pos = pos1.add_position(pos2);
+ if self.inside_map(&antinode_pos) {
+ antinodes.insert(antinode_pos);
+ }
+ }
+ }
+
+ antinodes.len()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test() {
+ let input = [
+ "............",
+ "........0...",
+ ".....0......",
+ ".......0....",
+ "....0.......",
+ "......A.....",
+ "............",
+ "............",
+ "........A...",
+ ".........A..",
+ "............",
+ "............",
+ ].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
+ assert_eq!(Map::new(&input).count_antinodes(), 14);
+ }
+}