day 8: part 1: rust

This commit is contained in:
Samuel Ortion 2024-12-10 17:30:41 +01:00
parent 4619aaf4ed
commit 7901645c55
Signed by: sortion
GPG Key ID: 9B02406F8C4FB765
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "part1"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -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<Vec<char>>) -> 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<char>> = Vec::new();
for line in std::io::stdin().lines() {
let line = line.unwrap();
let mut map_row: Vec<char> = 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());
}