blob: 885a99be4b5e0dfbf1cadbc170c9d7e41964bca5 (
plain) (
blame)
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
|
#![allow(dead_code)]
#![allow(unused_variables)]
use advent_of_code::prelude::*;
pub fn parse(fh: File) -> Result<Grid<bool>> {
Ok(parse::grid(parse::raw_lines(fh), |c, _, _| c == b'#'))
}
pub fn part1(mut map: Grid<bool>) -> Result<i64> {
let mut expand_rows = vec![];
for row in map.each_row() {
if map[row].iter().all(|b| !b) {
expand_rows.push(row);
}
}
let mut expand_cols = vec![];
for col in map.each_col() {
if map.each_row().map(|row| map[row][col]).all(|b| !b) {
expand_cols.push(col);
}
}
for row in expand_rows.into_iter().rev() {
map.insert_row(row);
}
for col in expand_cols.into_iter().rev() {
map.insert_col(col);
}
let galaxies: HashSet<(Row, Col)> = map
.indexed_cells()
.filter_map(|(pos, galaxy)| if *galaxy { Some(pos) } else { None })
.collect();
let mut total = 0;
for a in &galaxies {
for b in &galaxies {
total += a.0.abs_diff(b.0).0 + a.1.abs_diff(b.1).0
}
}
Ok((total / 2).try_into().unwrap())
}
pub fn part2(map: Grid<bool>) -> Result<i64> {
let mut expand_rows = vec![];
for row in map.each_row() {
if map[row].iter().all(|b| !b) {
expand_rows.push(row);
}
}
let mut expand_cols = vec![];
for col in map.each_col() {
if map.each_row().map(|row| map[row][col]).all(|b| !b) {
expand_cols.push(col);
}
}
let galaxies: HashSet<(Row, Col)> = map
.indexed_cells()
.filter_map(|(pos, galaxy)| if *galaxy { Some(pos) } else { None })
.collect();
let mut total = 0;
for a in &galaxies {
for b in &galaxies {
let expanded_rows = expand_rows
.iter()
.filter(|row| (a.0.min(b.0)..a.0.max(b.0)).contains(row))
.count();
let expanded_cols = expand_cols
.iter()
.filter(|col| (a.1.min(b.1)..a.1.max(b.1)).contains(col))
.count();
total += a.0.abs_diff(b.0).0
+ a.1.abs_diff(b.1).0
+ 999999 * (expanded_rows + expanded_cols);
}
}
Ok((total / 2).try_into().unwrap())
}
#[test]
fn test() {
assert_eq!(
part1(parse(parse::data(2023, 11).unwrap()).unwrap()).unwrap(),
10033566
);
assert_eq!(
part2(parse(parse::data(2023, 11).unwrap()).unwrap()).unwrap(),
560822911938
);
}
|