Skip to content

Commit 719d6a0

Browse files
committed
feat(09/2024): solve first part
1 parent 9133a21 commit 719d6a0

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
| [Day 6: Guard Gallivant](src/solutions/year2024/day06.rs) | ⭐⭐ | 8.738 | 3375.211 |
2020
| [Day 7: Bridge Repair](src/solutions/year2024/day07.rs) | ⭐⭐ | 1.198 | 219.754 |
2121
| [Day 8: Resonant Collinearity](src/solutions/year2024/day08.rs) | ⭐⭐ | 0.883 | 1.238 |
22+
| [Day 9: Disk Fragmenter](src/solutions/year2024/day09.rs) || 387.168 | - |
2223

2324
# 2023
2425

src/solutions/year2024/day09.rs

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,22 @@ use std::str::FromStr;
66
pub struct Day09;
77

88
impl Solution for Day09 {
9-
fn part_one(&self, _input: &str) -> String {
10-
String::from('0')
9+
fn part_one(&self, input: &str) -> String {
10+
let mut disk_map = DiskMap::from_str(input).unwrap();
11+
12+
loop {
13+
let last_digit_index = disk_map.blocks.iter().rposition(|v| v.is_some()).unwrap();
14+
let first_empty_index = disk_map.blocks.iter().position(|v| v.is_none()).unwrap();
15+
16+
if first_empty_index > last_digit_index {
17+
break;
18+
}
19+
20+
disk_map.blocks[first_empty_index] = Some(disk_map.blocks[last_digit_index].unwrap());
21+
disk_map.blocks[last_digit_index] = None;
22+
}
23+
24+
disk_map.checksum().to_string()
1125
}
1226

1327
fn part_two(&self, _input: &str) -> String {
@@ -19,17 +33,32 @@ struct DiskMap {
1933
blocks: Vec<Option<usize>>,
2034
}
2135

36+
impl DiskMap {
37+
fn checksum(&self) -> usize {
38+
self.blocks
39+
.clone()
40+
.into_iter()
41+
.flatten()
42+
.enumerate()
43+
.fold(0, |acc, (i, id)| acc + i * id)
44+
}
45+
}
46+
2247
impl FromStr for DiskMap {
2348
type Err = String;
2449

2550
fn from_str(s: &str) -> Result<Self, Self::Err> {
2651
let mut current_id = 0;
2752

2853
let test: Vec<Option<usize>> = s
54+
.trim()
2955
.chars()
3056
.enumerate()
3157
.flat_map(|(i, c)| {
32-
let times: usize = c.to_string().parse().unwrap();
58+
let times: usize = c
59+
.to_string()
60+
.parse()
61+
.unwrap_or_else(|_| panic!("cannot parse char to usize: '{}'", c));
3362

3463
let value: Option<usize> = match i % 2 == 0 {
3564
true => {
@@ -71,11 +100,11 @@ mod tests {
71100
use crate::solutions::Solution;
72101
use std::str::FromStr;
73102

74-
const EXAMPLE: &str = r#""#;
103+
const EXAMPLE: &str = "2333133121414131402";
75104

76105
#[test]
77106
fn part_one_example_test() {
78-
assert_eq!("0", Day09.part_one(EXAMPLE));
107+
assert_eq!("1928", Day09.part_one(EXAMPLE));
79108
}
80109

81110
#[test]

0 commit comments

Comments
 (0)