-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.rs
110 lines (104 loc) · 2.97 KB
/
14.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
#![feature(test)]
use std::cmp::Ordering;
struct Input {
grid: Vec<Vec<bool>>,
x_offset: usize,
}
fn setup(input: &str) -> Input {
let lines = input
.trim()
.lines()
.map(|line| {
line.split(" -> ")
.map(|p| {
let mut it = p.split(',');
Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?))
})
.collect::<Option<Vec<(usize, usize)>>>()
.unwrap()
})
.collect::<Vec<_>>();
let mut min_x = 500;
let mut max_x = 500;
let mut max_y = 0;
for &(x, y) in lines.iter().flatten() {
min_x = min_x.min(x);
max_x = max_x.max(x);
max_y = max_y.max(y);
}
let mut grid = vec![vec![false; max_x - min_x + 3]; max_y + 2];
let x_offset = min_x - 1;
for line in lines {
let mut it = line.into_iter();
let (mut x, mut y) = it.next().unwrap();
grid[y][x - x_offset] = true;
for (p, q) in it {
let dx = match x.cmp(&p) {
Ordering::Less => 2,
Ordering::Equal => 1,
Ordering::Greater => 0,
};
let dy = match y.cmp(&q) {
Ordering::Less => 2,
Ordering::Equal => 1,
Ordering::Greater => 0,
};
while (x, y) != (p, q) {
x = x + dx - 1;
y = y + dy - 1;
grid[y][x - x_offset] = true;
}
}
}
Input { grid, x_offset }
}
fn part1(input: &Input) -> usize {
let mut grid = input.grid.clone();
let mut out = 0;
loop {
let (mut x, mut y) = (500, 0);
while y < grid.len() - 1 {
if !grid[y + 1][x - input.x_offset] {
y += 1;
} else if !grid[y + 1][x - 1 - input.x_offset] {
x -= 1;
y += 1;
} else if !grid[y + 1][x + 1 - input.x_offset] {
x += 1;
y += 1;
} else {
grid[y][x - input.x_offset] = true;
out += 1;
break;
}
}
if y >= grid.len() - 1 {
break;
}
}
out
}
fn part2(input: &Input) -> usize {
let mut grid = input.grid.clone();
let mut out = 0;
for y in 0..grid.len() {
for x in 500 - y..=500 + y {
if x < input.x_offset
|| x - input.x_offset >= grid[y].len()
|| !grid[y][x - input.x_offset]
{
out += 1;
} else if x > input.x_offset
&& x + 1 < grid[y].len() + input.x_offset
&& grid[y][x - 1 - input.x_offset]
&& grid[y][x - input.x_offset]
&& grid[y][x + 1 - input.x_offset]
&& y + 1 < grid.len()
{
grid[y + 1][x - input.x_offset] = true;
}
}
}
out
}
aoc::main!(2022, 14, ex: 1);