Solve day 9
This commit is contained in:
parent
695e0b6fb8
commit
529619261e
3 changed files with 93 additions and 0 deletions
1
input/09-0.in
Normal file
1
input/09-0.in
Normal file
|
|
@ -0,0 +1 @@
|
|||
2333133121414131402
|
||||
1
input/09-1.in
Normal file
1
input/09-1.in
Normal file
File diff suppressed because one or more lines are too long
91
src/bin/09.rs
Normal file
91
src/bin/09.rs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
use itertools::Itertools;
|
||||
|
||||
fn main() {
|
||||
let text = std::fs::read_to_string("input/09-1.in").unwrap();
|
||||
|
||||
let mut map = text
|
||||
.trim()
|
||||
.chars()
|
||||
.map(|c| c.to_digit(10).unwrap() as usize)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
dbg!(map.len());
|
||||
|
||||
let mut sum = 0;
|
||||
let mut i = 0;
|
||||
let mut pos = 0;
|
||||
while i < map.len() {
|
||||
sum += (0..map[i]).map(|c| (c + pos) * i / 2).sum::<usize>();
|
||||
|
||||
pos += map[i];
|
||||
|
||||
// println!("{pos} {sum}");
|
||||
while i < (map.len() - 1) && map[i + 1] > 0 {
|
||||
while map[map.len() - 1] == 0 {
|
||||
map.pop();
|
||||
map.pop();
|
||||
}
|
||||
|
||||
let l = map.len() - 1;
|
||||
if i < l {
|
||||
map[l] -= 1;
|
||||
|
||||
sum += (l / 2) * pos;
|
||||
// println!("{i} {pos} {sum} {map:?}");
|
||||
map[i + 1] -= 1;
|
||||
}
|
||||
pos += 1;
|
||||
// println!("{pos} {sum}");
|
||||
}
|
||||
|
||||
i += 2;
|
||||
}
|
||||
|
||||
println!("{}", sum);
|
||||
|
||||
let mut pos = 0;
|
||||
let mut map = text
|
||||
.trim()
|
||||
.chars()
|
||||
.map(|c| c.to_digit(10).unwrap() as usize)
|
||||
.map(|d| {
|
||||
let r = (d, pos);
|
||||
pos += d;
|
||||
r
|
||||
})
|
||||
.enumerate()
|
||||
.filter_map(|(i, d)| if i % 2 == 0 { Some(d) } else { None })
|
||||
.enumerate()
|
||||
.map(|(i, (d, pos))| (i, d, pos))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// println!("{map:?}");
|
||||
|
||||
let mut i = map.len() - 1;
|
||||
let mut id = i;
|
||||
while id > 0 {
|
||||
while i > 0 && map[i].0 != id {
|
||||
i -= 1;
|
||||
}
|
||||
|
||||
let size = map[i].1;
|
||||
if let Some((l, _)) = map[0..i]
|
||||
.iter()
|
||||
.zip(map[1..].iter())
|
||||
.find_position(|(left, right)| size <= right.2 - (left.1 + left.2))
|
||||
{
|
||||
let (_, len, _) = map.remove(i);
|
||||
map.insert(l + 1, (id, len, map[l].1 + map[l].2))
|
||||
}
|
||||
|
||||
// println!("{map:?}");
|
||||
id -= 1;
|
||||
}
|
||||
|
||||
let t = map
|
||||
.iter()
|
||||
.flat_map(|&(id, c, pos)| (0..c).map(move |i| (pos + i) * id))
|
||||
.sum::<usize>();
|
||||
|
||||
println!("{t}");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue