Day 18 part 1

This commit is contained in:
2023-05-27 01:00:21 +02:00
parent d6c728ccfe
commit 861e31efee
4 changed files with 151 additions and 1 deletions

View File

@@ -1,3 +1,3 @@
fn main() {
aoc_2018::tasks::day17::task1();
aoc_2018::tasks::day18::task1();
}

99
src/tasks/day18.rs Normal file
View File

@@ -0,0 +1,99 @@
use std::collections::HashMap;
use itertools::Itertools;
use crate::utils;
pub fn task1() {
let input = utils::read_file("input/day18.txt");
let initial: HashMap<Pos, char> = input
.lines()
.enumerate()
.flat_map(|(y, line)| {
line.chars()
.enumerate()
.map(|(x, c)| (Pos(x as i32, y as i32), c))
.collect_vec()
})
.collect();
let fin = (0..10).fold(initial, |map, _| {
printmap(&map);
map.keys()
.map(|p| {
let old = map[p];
let new = match old {
'.' => {
if neighbors(&map, *p)
.into_iter()
.filter(|c| *c == '|')
.count()
>= 3
{
'|'
} else {
'.'
}
}
'|' => {
if neighbors(&map, *p)
.into_iter()
.filter(|c| *c == '#')
.count()
>= 3
{
'#'
} else {
'|'
}
}
'#' => {
if neighbors(&map, *p).contains(&'#') && neighbors(&map, *p).contains(&'|')
{
'#'
} else {
'.'
}
}
_ => panic!("unknown type"),
};
(*p, new)
})
.collect()
});
let trees = fin.values().filter(|c| **c == '|').count();
let lumberyards = fin.values().filter(|c| **c == '#').count();
println!("Part 1 - {trees} x {lumberyards} = {}", trees * lumberyards);
}
fn printmap(map: &HashMap<Pos, char>) {
println!();
let (x_min, x_max) = map.keys().map(|p| p.0).minmax().into_option().unwrap();
let (_y_min, y_max) = map.keys().map(|p| p.1).minmax().into_option().unwrap();
for y in 0..=y_max {
for x in x_min..=x_max {
let s = map[&Pos(x, y)];
print!("{s}");
}
print!("\n");
}
}
#[derive(Hash, Eq, PartialEq, Clone, Copy)]
struct Pos(i32, i32);
fn neighbors(map: &HashMap<Pos, char>, p: Pos) -> Vec<char> {
[
Pos(p.0 - 1, p.1 - 1),
Pos(p.0 - 1, p.1),
Pos(p.0 - 1, p.1 + 1),
Pos(p.0, p.1 - 1),
Pos(p.0, p.1 + 1),
Pos(p.0 + 1, p.1 - 1),
Pos(p.0 + 1, p.1),
Pos(p.0 + 1, p.1 + 1),
]
.into_iter()
.flat_map(|pos| map.get(&pos).map(|c| *c))
.collect_vec()
}

View File

@@ -14,6 +14,7 @@ pub mod day13;
pub mod day14;
pub mod day15;
pub mod day17;
pub mod day18;
pub mod day20;
pub mod day22;
pub mod day23;