day9: use part 2 'inodes' table to speed up part 1

This commit is contained in:
Keenan Tims 2024-12-08 23:51:51 -08:00
parent 2bc751dd0d
commit b08c8fbd80
Signed by: ktims
GPG Key ID: 11230674D69038D4

View File

@ -115,42 +115,21 @@ impl DiskMap {
fn problem1<T: BufRead>(input: Lines<T>) -> u64 { fn problem1<T: BufRead>(input: Lines<T>) -> u64 {
let mut map = DiskMap::from(input); let mut map = DiskMap::from(input);
let mut i = map.map.len() - 1; for file in map.files.iter().rev() {
while i != 0 {
// find start index of 'file'
if map.map[i] == Unit::Free {
i -= 1;
continue;
};
let mut len = 1;
while i >= 1 && map.map[i] == map.map[i - 1] {
i -= 1;
len += 1;
}
let file_id = match map.map[i] {
Unit::File(id) => id,
_ => panic!(),
};
let frees = map let frees = map
.map .map
.iter() .iter()
.enumerate() .enumerate()
.take(i + len + 1) .take(file.pos + file.len as usize + 1)
.filter(|(_i, u)| **u == Unit::Free || **u == Unit::File(file_id)) .filter(|(_i, u)| **u == Unit::Free || **u == Unit::File(file.id))
.map(|(i, _u)| i) .map(|(i, _u)| i)
.take(len) .take(file.len as usize)
.collect_vec(); .collect_vec();
if frees[0] >= i { if frees[0] >= file.pos {
if i > 0 {
i -= 1;
}
continue; continue;
} }
for j in 0..len { for j in 0..file.len as usize {
map.map.swap(frees[j], i + j); map.map.swap(frees[j], file.pos + j);
}
if i > 0 {
i -= 1;
} }
} }
map.checksum() map.checksum()