-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathd04.rs
More file actions
144 lines (118 loc) Β· 3.1 KB
/
d04.rs
File metadata and controls
144 lines (118 loc) Β· 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use crate::Day;
pub struct Day04 {}
impl Day for Day04 {
fn year(&self) -> u16 {
2025
}
fn day(&self) -> u8 {
4
}
fn part_one(&self) -> String {
let map = parse_input(&self.read_default_input());
let mut result = 0;
for (x, y) in rolls_positions(&map) {
if count_neighbor_rolls(&map, x, y) < 4 {
result += 1;
}
}
result.to_string()
}
fn part_two(&self) -> String {
let mut map = parse_input(&self.read_default_input());
let mut removed = 0;
loop {
let mut to_be_removed = Vec::<Position>::new();
for (x, y) in rolls_positions(&map) {
if count_neighbor_rolls(&map, x, y) < 4 {
to_be_removed.push((x, y));
}
}
if to_be_removed.is_empty() {
break;
}
for remove_pos in &to_be_removed {
map[remove_pos.1][remove_pos.0] = '.';
removed += 1;
}
}
removed.to_string()
}
}
type Map = Vec<Vec<char>>;
type Position = (usize, usize);
enum Direction {
N,
NE,
E,
SE,
S,
SW,
W,
NW,
}
impl Direction {
fn modifier(&self) -> (i32, i32) {
match self {
Direction::N => (0, -1),
Direction::NE => (1, -1),
Direction::E => (1, 0),
Direction::SE => (1, 1),
Direction::S => (0, 1),
Direction::SW => (-1, 1),
Direction::W => (-1, 0),
Direction::NW => (-1, -1),
}
}
fn all() -> impl Iterator<Item = Direction> {
[
Direction::N,
Direction::NE,
Direction::E,
Direction::SE,
Direction::S,
Direction::SW,
Direction::W,
Direction::NW,
]
.into_iter()
}
}
fn parse_input(input: &str) -> Map {
input
.lines()
.map(|line| line.chars().collect::<Vec<char>>())
.collect::<Vec<Vec<char>>>()
}
fn rolls_positions(map: &Map) -> Vec<Position> {
let mut positions = Vec::new();
for (y, row) in map.iter().enumerate() {
for (x, cell) in row.iter().enumerate() {
if *cell == '@' {
positions.push((x, y));
}
}
}
positions
}
fn count_neighbor_rolls(map: &[Vec<char>], x: usize, y: usize) -> usize {
let mut neighbor_rolls = 0;
let position = (x, y);
for direction in Direction::all() {
let modifier = direction.modifier();
let neighbor_pos = (
position.0 as i32 + modifier.0,
position.1 as i32 + modifier.1,
);
if neighbor_pos.0 < 0 || neighbor_pos.1 < 0 {
continue;
}
if neighbor_pos.0 >= map[0].len() as i32 || neighbor_pos.1 >= map.len() as i32 {
continue;
}
let neighbor_cell = map[neighbor_pos.1 as usize][neighbor_pos.0 as usize];
if neighbor_cell == '@' {
neighbor_rolls += 1;
}
}
neighbor_rolls
}