aoc/2024/4/src/main.rs

106 lines
4.0 KiB
Rust

use std::fs;
use std::io;
fn check_for_xmas(x: usize, y: usize, array: &Vec<Vec<char>>, total: &mut u32) {
//print!("X");
//let mut first: i32 = 1;
//let mut second: i32 = 1;
// Check if the next position is within bounds
for first in -1..2 {
for second in -1..2 {
let mut next_x: usize = x+1;
let mut next_y: usize = y+1;
next_x = (next_x as isize + first) as usize;
next_y = (next_y as isize + second) as usize;
if next_x <= array[y].len() && next_y <= array.len() && next_x >= 1 && next_y >= 1 {
//println!(" M:({}, {})", (next_y as isize -1), (next_x as isize -1));
if array[next_y-1][next_x-1] == 'M' {
//print!("--M--");
next_x = (next_x as isize + first) as usize;
next_y = (next_y as isize + second) as usize;
if next_x <= array[y].len() && next_y <= array.len() && next_x >= 1 && next_y >= 1 {
//println!(" A:({}, {})", (next_y as isize -1), (next_x as isize -1));
if array[next_y-1][next_x-1] == 'A' {
//print!("--A--");
next_x = (next_x as isize + first) as usize;
next_y = (next_y as isize + second) as usize;
if next_x <= array[y].len() && next_y <= array.len() && next_x >= 1 && next_y >= 1 {
//println!(" S:({}, {})", (next_y as isize -1), (next_x as isize -1));
if array[next_y-1][next_x-1] == 'S' {
//print!("--S--");
*total = *total + 1;
//println!("New total: {}",total);
}
}
}
}
}
}
}
}
}
fn check_for_x_mas(x: usize, y: usize, array: &Vec<Vec<char>>, total2: &mut u32) {
if x >= 1 && x <= array[y].len()-2 && y >= 1 && y <= array.len()-2 {
let tl = array[y-1][x+1];
let tr = array[y-1][x-1];
let bl = array[y+1][x+1];
let br = array[y+1][x-1];
let mut m_count = 0;
let mut s_count = 0;
let diagonals = vec![tl, tr, bl, br];
for &ch in &diagonals {
if ch == 'M' {
m_count += 1;
} else if ch == 'S' {
s_count += 1;
}
}
if m_count != 2 || s_count != 2 {
println!("nope (wrong number of S's or M's)");
return ();
}
else if br == 'A' || br == 'X' || tr == 'A' || tr == 'X' || tl == 'A' || tl == 'X' || bl == 'A' || bl == 'X' {
println!("nope (X or A detected)");
return ();
}
else if (br == 'M' && tl == 'M') || (tr == 'M' && bl == 'M') {
println!("note (diagonally opposite characters)");
return ();
}
else {
*total2 = *total2 + 1;
}
}
}
fn main() -> io::Result<()> {
let mut total: u32 = 0;
let mut total2: u32 = 0;
let file_contents = fs::read_to_string("medium.txt")?;
let array: Vec<Vec<char>> = file_contents
.lines()
.map(|line| line.chars().collect())
.collect();
//println!("{}", file_contents);
for line in 0..array.len() {
for character in 0..array[line].len() {
if array[line][character] == 'X' {
//println!("X:({}, {})", line, character);
check_for_xmas(character, line, &array, &mut total);
//println!("");
}
else if array[line][character] == 'A' {
println!("A:({},{})",line,character);
check_for_x_mas(character, line, &array, &mut total2);
}
}
}
println!("Part 1 total is: {}\n Part 2 total is: {}",total,total2);
Ok(())
}