-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-24.rs
128 lines (118 loc) · 3.07 KB
/
day-24.rs
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
use std::{collections::HashSet, mem::swap};
const INPUT: &str = include_str!("day-24.input");
fn main() {
let input: Vec<_> = INPUT
.lines()
.map(|line| {
let mut it = line.chars();
let mut directions = vec![];
while let Some(ch) = it.next() {
directions.push(match ch {
'e' => Direction::East,
'w' => Direction::West,
's' => match it.next().unwrap() {
'e' => Direction::SouthEast,
'w' => Direction::SouthWest,
_ => panic!(),
},
'n' => match it.next().unwrap() {
'e' => Direction::NorthEast,
'w' => Direction::NorthWest,
_ => panic!(),
},
_ => panic!(),
});
}
directions
})
.collect();
let mut set = HashSet::new();
for line in input.iter() {
let pos = line.iter().fold((0, 0), |pos, &dir| {
let delta = dir.delta();
(pos.0 + delta.0, pos.1 + delta.1)
});
if !set.insert(pos) {
set.remove(&pos);
}
}
println!("part 1: {}", set.len());
for _ in 0..100 {
step(&mut set);
}
println!("part 2: {}", set.len());
}
fn step(set: &mut HashSet<(isize, isize)>) {
let mut next = HashSet::new();
for &(x, y) in set.iter() {
match neighbor_coords(x, y)
.map(|(x, y)| {
if neighbor_coords(x, y)
.map(|c| set.get(&c).is_some() as usize)
.sum::<usize>()
== 2
{
next.insert((x, y));
}
set.get(&(x, y)).is_some() as usize
})
.sum()
{
1 | 2 => {
next.insert((x, y));
}
_ => (),
}
}
swap(set, &mut next);
}
fn neighbor_coords(x: isize, y: isize) -> impl Iterator<Item = (isize, isize)> {
[
Direction::East,
Direction::SouthEast,
Direction::SouthWest,
Direction::West,
Direction::NorthWest,
Direction::NorthEast,
]
.iter()
.map(move |dir| {
let delta = dir.delta();
(x + delta.0, y + delta.1)
})
}
#[derive(Clone, Copy)]
enum Direction {
East,
SouthEast,
SouthWest,
West,
NorthWest,
NorthEast,
}
impl Direction {
/*
. .
/ \ / \
|-1 | 1 |
|-1 |-1 |
/ \ / \ / \
|-2 | 0 | 2 |
| 0 | 0 | 0 |
\ / \ / \ /
|-1 | 1 |
| 1 | 1 |
\ / \ /
' '
*/
fn delta(self) -> (isize, isize) {
match self {
Direction::East => (2, 0),
Direction::SouthEast => (1, 1),
Direction::SouthWest => (-1, 1),
Direction::West => (-2, 0),
Direction::NorthWest => (-1, -1),
Direction::NorthEast => (1, -1),
}
}
}