Add 2024 Day 09
This commit is contained in:
parent
59cfa274c0
commit
65ba60d18c
5 changed files with 233 additions and 0 deletions
13
2024/day09_disk-fragmenter/Cargo.toml
Normal file
13
2024/day09_disk-fragmenter/Cargo.toml
Normal file
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "day09_disk-fragmenter"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
[dev-dependencies]
|
||||
# criterion = "0.5.1"
|
||||
|
||||
[[bench]]
|
||||
name = "test_benchmark"
|
||||
harness = false
|
96
2024/day09_disk-fragmenter/challenge.md
Normal file
96
2024/day09_disk-fragmenter/challenge.md
Normal file
|
@ -0,0 +1,96 @@
|
|||
Another push of the button leaves you in the familiar hallways of some friendly [amphipods](/2021/day/23)! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.
|
||||
|
||||
While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.
|
||||
|
||||
He shows you the *disk map* (your puzzle input) he's already generated. For example:
|
||||
|
||||
```
|
||||
2333133121414131402
|
||||
```
|
||||
|
||||
The disk map uses a dense format to represent the layout of *files* and *free space* on the disk. The digits alternate between indicating the length of a file and the length of free space.
|
||||
|
||||
So, a disk map like `12345` would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like `90909` would represent three nine-block files in a row (with no free space between them).
|
||||
|
||||
Each file on disk also has an *ID number* based on the order of the files as they appear *before* they are rearranged, starting with ID `0`. So, the disk map `12345` has three files: a one-block file with ID `0`, a three-block file with ID `1`, and a five-block file with ID `2`. Using one character for each block where digits are the file ID and `.` is free space, the disk map `12345` represents these individual blocks:
|
||||
|
||||
```
|
||||
0..111....22222
|
||||
```
|
||||
|
||||
The first example above, `2333133121414131402`, represents these individual blocks:
|
||||
|
||||
```
|
||||
00...111...2...333.44.5555.6666.777.888899
|
||||
```
|
||||
|
||||
The amphipod would like to *move file blocks one at a time* from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map `12345`, the process looks like this:
|
||||
|
||||
```
|
||||
0..111....22222
|
||||
02.111....2222.
|
||||
022111....222..
|
||||
0221112...22...
|
||||
02211122..2....
|
||||
022111222......
|
||||
|
||||
```
|
||||
|
||||
The first example requires a few more steps:
|
||||
|
||||
```
|
||||
00...111...2...333.44.5555.6666.777.888899
|
||||
009..111...2...333.44.5555.6666.777.88889.
|
||||
0099.111...2...333.44.5555.6666.777.8888..
|
||||
00998111...2...333.44.5555.6666.777.888...
|
||||
009981118..2...333.44.5555.6666.777.88....
|
||||
0099811188.2...333.44.5555.6666.777.8.....
|
||||
009981118882...333.44.5555.6666.777.......
|
||||
0099811188827..333.44.5555.6666.77........
|
||||
00998111888277.333.44.5555.6666.7.........
|
||||
009981118882777333.44.5555.6666...........
|
||||
009981118882777333644.5555.666............
|
||||
00998111888277733364465555.66.............
|
||||
0099811188827773336446555566..............
|
||||
|
||||
```
|
||||
|
||||
The final step of this file-compacting process is to update the *filesystem checksum*. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position `0`. If a block contains free space, skip it instead.
|
||||
|
||||
Continuing the first example, the first few blocks' position multiplied by its file ID number are `0 * 0 = 0`, `1 * 0 = 0`, `2 * 9 = 18`, `3 * 9 = 27`, `4 * 8 = 32`, and so on. In this example, the checksum is the sum of these, `*1928*`.
|
||||
|
||||
Compact the amphipod's hard drive using the process he requested. *What is the resulting filesystem checksum?* (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)
|
||||
|
||||
Your puzzle answer was `6607511583593`.
|
||||
|
||||
\--- Part Two ---
|
||||
----------
|
||||
|
||||
Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that [file system fragmentation](https://en.wikipedia.org/wiki/File_system_fragmentation) was a bad idea?
|
||||
|
||||
The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving *whole files* instead.
|
||||
|
||||
This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of *decreasing file ID number* starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move.
|
||||
|
||||
The first example from above now proceeds differently:
|
||||
|
||||
```
|
||||
00...111...2...333.44.5555.6666.777.888899
|
||||
0099.111...2...333.44.5555.6666.777.8888..
|
||||
0099.1117772...333.44.5555.6666.....8888..
|
||||
0099.111777244.333....5555.6666.....8888..
|
||||
00992111777.44.333....5555.6666.....8888..
|
||||
|
||||
```
|
||||
|
||||
The process of updating the filesystem checksum is the same; now, this example's checksum would be `*2858*`.
|
||||
|
||||
Start over, now compacting the amphipod's hard drive using this new method instead. *What is the resulting filesystem checksum?*
|
||||
|
||||
Your puzzle answer was `6636608781232`.
|
||||
|
||||
Both parts of this puzzle are complete! They provide two gold stars: \*\*
|
||||
|
||||
At this point, you should [return to your Advent calendar](/2024) and try another puzzle.
|
||||
|
||||
If you still want to see it, you can [get your puzzle input](9/input).
|
122
2024/day09_disk-fragmenter/src/lib.rs
Normal file
122
2024/day09_disk-fragmenter/src/lib.rs
Normal file
|
@ -0,0 +1,122 @@
|
|||
use core::fmt::Display;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
ParseCharError(char),
|
||||
}
|
||||
|
||||
impl Display for ParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::ParseCharError(e) => write!(f, "Unable to parse {e} into a digit."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Id=usize;
|
||||
type Size=u8;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Filesystem {
|
||||
// All the FS blocks. `None` for empty blocks, `Some(file_id, file_size)` for files.
|
||||
blocks: Vec<Option<(Id, Size)>>,
|
||||
// List of the empty blocks in order. Format: (first_block_idx, size)
|
||||
free: Vec<(usize, Size)>,
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Filesystem {
|
||||
type Error=ParseError;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
let mut file = true;
|
||||
let mut id = 0;
|
||||
let mut blocks = Vec::new();
|
||||
let mut free = Vec::new();
|
||||
for c in value.chars() {
|
||||
if !c.is_ascii_digit() {
|
||||
return Err(Self::Error::ParseCharError(c));
|
||||
}
|
||||
let size = c as Size - b'0';
|
||||
let entry = if file { Some((id, size)) } else { None };
|
||||
file = if file {
|
||||
id += 1;
|
||||
false
|
||||
} else {
|
||||
if size != 0 {
|
||||
free.push((blocks.len(), size));
|
||||
}
|
||||
true
|
||||
};
|
||||
(0..size).for_each(|_| blocks.push(entry));
|
||||
|
||||
}
|
||||
Ok(Self { blocks, free, })
|
||||
}
|
||||
}
|
||||
|
||||
impl Filesystem {
|
||||
fn compress(&mut self) {
|
||||
while let Some(empty) = self.blocks.iter().position(|b| b.is_none()) {
|
||||
let last = self.blocks.pop().unwrap();
|
||||
if last.is_some() {
|
||||
self.blocks[empty] = last;
|
||||
}
|
||||
self.free = Vec::new();
|
||||
}
|
||||
}
|
||||
|
||||
fn compress_unfragmented(&mut self) {
|
||||
for id in (0..=self.blocks.iter().rfind(|file| file.is_some()).unwrap_or(&Some((0, 0))).unwrap().0).rev() {
|
||||
let old_idx = self.blocks.iter().position(|file| file.is_some() && file.unwrap().0 == id).unwrap();
|
||||
let file_size = self.blocks[old_idx].unwrap().1;
|
||||
if let Some(free_entry) = self.free.iter_mut().find(|(_block_id, free_size)| *free_size >= file_size) {
|
||||
let new_idx = free_entry.0;
|
||||
if new_idx < old_idx {
|
||||
free_entry.0 += file_size as usize;
|
||||
free_entry.1 -= file_size;
|
||||
(0..file_size as usize).for_each(|offset| {
|
||||
self.blocks[old_idx + offset] = None;
|
||||
self.blocks[new_idx + offset] = Some((id, file_size));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fn checksum(&self) -> usize {
|
||||
self.blocks.iter().enumerate().map(|(idx, file)| idx * file.unwrap_or((0, 0)).0).sum()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(input: &str) -> Result<(usize, usize), ParseError> {
|
||||
let mut fs1 = Filesystem::try_from(input)?;
|
||||
let mut fs2 = fs1.clone();
|
||||
fs1.compress();
|
||||
fs2.compress_unfragmented();
|
||||
let first = fs1.checksum();
|
||||
let second = fs2.checksum();
|
||||
Ok((first, second))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs::read_to_string;
|
||||
|
||||
fn read_file(name: &str) -> String {
|
||||
read_to_string(name).expect(&format!("Unable to read file: {name}")[..]).trim().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sample() {
|
||||
let sample_input = read_file("tests/sample_input");
|
||||
assert_eq!(run(&sample_input), Ok((1928, 2858)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_challenge() {
|
||||
let challenge_input = read_file("tests/challenge_input");
|
||||
assert_eq!(run(&challenge_input), Ok((6607511583593, 6636608781232)));
|
||||
}
|
||||
}
|
1
2024/day09_disk-fragmenter/tests/challenge_input
Normal file
1
2024/day09_disk-fragmenter/tests/challenge_input
Normal file
File diff suppressed because one or more lines are too long
1
2024/day09_disk-fragmenter/tests/sample_input
Normal file
1
2024/day09_disk-fragmenter/tests/sample_input
Normal file
|
@ -0,0 +1 @@
|
|||
2333133121414131402
|
Loading…
Add table
Add a link
Reference in a new issue