feat: solve day 4

This commit is contained in:
Joshua Smallwood 2025-12-04 07:54:45 -06:00
parent acbd3801ca
commit 98d927cd72
2 changed files with 154 additions and 0 deletions

11
data/examples/04.txt Normal file
View file

@ -0,0 +1,11 @@
..@@.@@@@.
@@@.@.@.@@
@@@@@.@.@@
@.@@@@..@.
@@.@@@@.@@
.@@@@@@@.@
.@.@.@.@@@
@.@@@.@@@@
.@@@@@@@@.
@.@.@@@.@.

143
src/bin/04.rs Normal file
View file

@ -0,0 +1,143 @@
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));
}
}