Skip to content

Commit 7df8d44

Browse files
committed
Add day9 part1 - working
1 parent 5d31475 commit 7df8d44

File tree

1 file changed

+53
-35
lines changed

1 file changed

+53
-35
lines changed

src/day9.rs

Lines changed: 53 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -28,61 +28,79 @@ pub fn input_generator(input: &str) -> Vec<Disk> {
2828

2929
#[aoc(day9, part1)]
3030
pub fn part1(input: &[Disk]) -> usize {
31-
for i in input {
32-
match i {
33-
Disk::File { id, blocks } => {
34-
print!("{}", id.to_string().repeat(*blocks));
35-
}
36-
Disk::Free { blocks } => {
37-
print!("{}", ".".repeat(*blocks));
38-
}
39-
}
40-
}
41-
println!();
42-
4331
let mut i = 0;
4432
let mut input = input.to_vec();
45-
let mut results: Vec<usize> = Vec::new();
4633

4734
loop {
48-
if i > input.len() {
49-
break;
50-
}
35+
// for j in &input {
36+
// match j {
37+
// Disk::File { id, blocks } => {
38+
// print!("{}", id.to_string().repeat(*blocks));
39+
// }
40+
// Disk::Free { blocks } => {
41+
// print!("{}", ".".repeat(*blocks));
42+
// }
43+
// }
44+
// }
45+
// println!();
5146

5247
match input[i] {
53-
Disk::File { id, blocks } => results.extend(std::iter::repeat(id).take(blocks)),
48+
Disk::File { id: _, blocks: _ } => {
49+
i += 1;
50+
}
5451
Disk::Free {
5552
blocks: free_blocks,
56-
} => loop {
53+
} => {
5754
if let Some(last) = input.pop() {
5855
match last {
59-
Disk::Free { blocks } => continue,
60-
Disk::File { id: _, blocks } => {
61-
if blocks == *free_blocks {
62-
results.push(last);
56+
Disk::Free { blocks: _ } => continue,
57+
Disk::File { id, blocks } => match blocks.cmp(&free_blocks) {
58+
std::cmp::Ordering::Equal => {
59+
input[i] = last;
60+
i += 1;
61+
}
62+
std::cmp::Ordering::Less => {
63+
input.insert(i, last);
64+
input[i + 1] = Disk::Free {
65+
blocks: free_blocks - blocks,
66+
};
67+
i += 1;
68+
}
69+
std::cmp::Ordering::Greater => {
70+
input[i] = Disk::File {
71+
id,
72+
blocks: free_blocks,
73+
};
74+
input.push(Disk::File {
75+
id,
76+
blocks: blocks - free_blocks,
77+
});
78+
i += 1;
6379
}
64-
}
80+
},
6581
}
66-
} else {
67-
break;
6882
}
69-
},
83+
}
84+
}
85+
if i >= input.len() {
86+
break;
7087
}
7188
}
7289

73-
for i in results {
90+
let mut res = 0;
91+
let mut pos = 0;
92+
for i in input {
7493
match i {
7594
Disk::File { id, blocks } => {
76-
print!("{}", id.to_string().repeat(blocks));
77-
}
78-
Disk::Free { blocks } => {
79-
print!("{}", ".".repeat(blocks));
95+
for _ in 0..blocks {
96+
res += pos * id;
97+
pos += 1;
98+
}
8099
}
100+
_ => unreachable!(),
81101
}
82102
}
83-
println!();
84-
85-
0
103+
res
86104
}
87105

88106
// #[aoc(day9, part2)]
@@ -99,7 +117,7 @@ mod tests {
99117

100118
#[test]
101119
fn test_part1() {
102-
assert_eq!(1, part1(&input_generator(INPUT)))
120+
assert_eq!(1928, part1(&input_generator(INPUT)))
103121
}
104122

105123
// #[test]

0 commit comments

Comments
 (0)