advent-of-code-2025/src/bin/04.rs
2025-12-04 07:54:45 -06:00

143 lines
4.2 KiB
Rust

advent_of_code::solution!(4);
pub fn part_one(input: &str) -> Option<u64> {
let char_grid: Vec<Vec<char>> = input
.split('\n')
.filter(|el| !el.is_empty())
.map(|line| line.chars().collect())
.collect();
let mut num_rolls = 0;
for (i, row) in char_grid.iter().enumerate() {
for (j, c) in row.iter().enumerate() {
let mut num = 0;
if *c == '@' {
if (i + 1) < char_grid.len() && char_grid[i + 1][j] == '@' {
num += 1;
}
if (i + 1) < char_grid.len()
&& (j + 1) < row.len()
&& char_grid[i + 1][j + 1] == '@'
{
num += 1;
}
if (j + 1) < row.len() && char_grid[i][j + 1] == '@' {
num += 1;
}
if (i as i32 - 1) >= 0 && (j + 1) < row.len() && char_grid[i - 1][j + 1] == '@' {
num += 1;
}
if (i as i32 - 1) as i32 >= 0 && char_grid[i - 1][j] == '@' {
num += 1;
}
if (i as i32 - 1) as i32 >= 0
&& (j as i32 - 1) >= 0
&& char_grid[i - 1][j - 1] == '@'
{
num += 1;
}
if (j as i32 - 1) >= 0 && char_grid[i][j - 1] == '@' {
num += 1;
}
if i + 1 < char_grid.len() && (j as i32 - 1) >= 0 && char_grid[i + 1][j - 1] == '@'
{
num += 1;
}
if num < 4 {
num_rolls += 1;
}
}
}
}
Some(num_rolls)
}
pub fn part_two(input: &str) -> Option<u64> {
let mut char_grid: Vec<Vec<char>> = input
.split('\n')
.filter(|el| !el.is_empty())
.map(|line| line.chars().collect())
.collect();
let mut num_rolls = 0;
let mut done = false;
while !done {
done = true;
for (i, row) in char_grid.clone().iter().enumerate() {
for (j, c) in row.clone().iter().enumerate() {
let mut num = 0;
if *c == '@' {
if (i + 1) < char_grid.len() && char_grid[i + 1][j] == '@' {
num += 1;
}
if (i + 1) < char_grid.len()
&& (j + 1) < row.len()
&& char_grid[i + 1][j + 1] == '@'
{
num += 1;
}
if (j + 1) < row.len() && char_grid[i][j + 1] == '@' {
num += 1;
}
if (i as i32 - 1) >= 0 && (j + 1) < row.len() && char_grid[i - 1][j + 1] == '@'
{
num += 1;
}
if (i as i32 - 1) as i32 >= 0 && char_grid[i - 1][j] == '@' {
num += 1;
}
if (i as i32 - 1) as i32 >= 0
&& (j as i32 - 1) >= 0
&& char_grid[i - 1][j - 1] == '@'
{
num += 1;
}
if (j as i32 - 1) >= 0 && char_grid[i][j - 1] == '@' {
num += 1;
}
if i + 1 < char_grid.len()
&& (j as i32 - 1) >= 0
&& char_grid[i + 1][j - 1] == '@'
{
num += 1;
}
if num < 4 {
num_rolls += 1;
char_grid[i][j] = '.';
done = false;
}
}
}
}
}
Some(num_rolls)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(13));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(43));
}
}