-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_11.rs
106 lines (88 loc) · 2.33 KB
/
day_11.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
use bitvec::{bitvec, vec::BitVec};
use itertools::Itertools;
use nd_vec::{vector, Vec2};
use common::{solution, Answer};
type Pos = Vec2<usize>;
solution!("Cosmic Expansion", 11);
fn part_a(input: &str) -> Answer {
let mut galaxies = parse(input);
galaxies.expand(2);
galaxies.total_distance().into()
}
fn part_b(input: &str) -> Answer {
let mut galaxies = parse(input);
galaxies.expand(1000000);
galaxies.total_distance().into()
}
struct Galaxies {
galaxies: Vec<Pos>,
rows: BitVec,
cols: BitVec,
}
fn parse(input: &str) -> Galaxies {
let lines = input.lines().collect::<Vec<_>>();
let mut galaxies = Vec::new();
let mut rows = bitvec![0; lines[0].len()];
let mut cols = bitvec![0; lines.len()];
for (y, line) in lines.iter().enumerate() {
for (x, c) in line.chars().enumerate() {
if c == '#' {
galaxies.push(vector!(x, y));
rows.set(y, true);
cols.set(x, true);
}
}
}
Galaxies {
galaxies,
rows,
cols,
}
}
impl Galaxies {
fn expand(&mut self, mut multiplier: usize) {
multiplier -= 1;
for (y, _) in self.rows.iter().enumerate().rev().filter(|x| !x.1.as_ref()) {
for pos in self.galaxies.iter_mut().filter(|pos| pos.y() > y) {
*pos += vector!(0, multiplier)
}
}
for (x, _) in self.cols.iter().enumerate().rev().filter(|x| !x.1.as_ref()) {
for pos in self.galaxies.iter_mut().filter(|pos| pos.x() > x) {
*pos += vector!(multiplier, 0)
}
}
}
fn total_distance(&self) -> usize {
self.galaxies
.iter()
.map(|x| x.num_cast::<isize>().unwrap())
.tuple_combinations()
.map(|(a, b)| a.manhattan_distance(&b) as usize)
.sum()
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 374.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 82000210.into());
}
}