From 7901645c55f6f309f5386be5fbe8357036b69bcd Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Tue, 10 Dec 2024 17:30:41 +0100 Subject: [PATCH] day 8: part 1: rust --- 2024/days/08/part1/Cargo.toml | 6 ++++ 2024/days/08/part1/src/main.rs | 66 ++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 2024/days/08/part1/Cargo.toml create mode 100644 2024/days/08/part1/src/main.rs diff --git a/2024/days/08/part1/Cargo.toml b/2024/days/08/part1/Cargo.toml new file mode 100644 index 0000000..d85b608 --- /dev/null +++ b/2024/days/08/part1/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "part1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/days/08/part1/src/main.rs b/2024/days/08/part1/src/main.rs new file mode 100644 index 0000000..71a66f1 --- /dev/null +++ b/2024/days/08/part1/src/main.rs @@ -0,0 +1,66 @@ +use std::collections::BTreeSet; + +fn get_antinode(x1: usize, y1: usize, x2: usize, y2: usize) -> (isize, isize) { + let dx = x1 as isize - x2 as isize; + let dy: isize = y1 as isize - y2 as isize; + (x1 as isize + dx, y1 as isize + dy) +} + +fn is_in_bound(x: isize, y: isize, height: usize, width: usize) -> bool { + return x >= 0 && y >= 0 && y < height as isize && x < width as isize; +} + + +fn find_antinodes(map: &Vec>) -> BTreeSet<(usize, usize)> { + let mut antinodes: BTreeSet<(usize, usize)> = BTreeSet::new(); + let height = map.len(); + let width = map[0].len(); + for y1 in 0..map.len() { + for x1 in 0..map[y1].len() { + if map[y1][x1] != '.' { + let antenna = map[y1][x1]; + for y2 in 0..map.len() { + for x2 in 0..map[y2].len() { + if !(x1 == x2 || y1 == y2) { + if map[y2][x2] == antenna { + let antinode = get_antinode(x1, y1, x2, y2); + if is_in_bound(antinode.0, antinode.1, height, width) { + let x = antinode.0 as usize; + let y = antinode.1 as usize; + antinodes.insert((x, y)); + } + } + } + } + } + } + } + } + antinodes +} + +fn main() { + // Read the antenna location map + let mut map: Vec> = Vec::new(); + for line in std::io::stdin().lines() { + let line = line.unwrap(); + let mut map_row: Vec = Vec::new(); + for letter in line.chars() { + map_row.push(letter); + } + map.push(map_row); + } + // Find antinodes + let antinodes = find_antinodes(&map); + // for y in 0..map.len() { + // print!("\n"); + // for x in 0..map[y].len() { + // if antinodes.contains(&(x, y)) { + // print!("{}", '#'); + // } else { + // print!("{}", map[y][x]); + // } + // } + // } + println!("{}", antinodes.len()); +}