Skip to content

Commit

Permalink
Add day9 part1 - working
Browse files Browse the repository at this point in the history
  • Loading branch information
qselle committed Dec 16, 2024
1 parent 5d31475 commit 7df8d44
Showing 1 changed file with 53 additions and 35 deletions.
88 changes: 53 additions & 35 deletions src/day9.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,61 +28,79 @@ pub fn input_generator(input: &str) -> Vec<Disk> {

#[aoc(day9, part1)]
pub fn part1(input: &[Disk]) -> usize {
for i in input {
match i {
Disk::File { id, blocks } => {
print!("{}", id.to_string().repeat(*blocks));
}
Disk::Free { blocks } => {
print!("{}", ".".repeat(*blocks));
}
}
}
println!();

let mut i = 0;
let mut input = input.to_vec();
let mut results: Vec<usize> = Vec::new();

loop {
if i > input.len() {
break;
}
// for j in &input {
// match j {
// Disk::File { id, blocks } => {
// print!("{}", id.to_string().repeat(*blocks));
// }
// Disk::Free { blocks } => {
// print!("{}", ".".repeat(*blocks));
// }
// }
// }
// println!();

match input[i] {
Disk::File { id, blocks } => results.extend(std::iter::repeat(id).take(blocks)),
Disk::File { id: _, blocks: _ } => {
i += 1;
}
Disk::Free {
blocks: free_blocks,
} => loop {
} => {
if let Some(last) = input.pop() {
match last {
Disk::Free { blocks } => continue,
Disk::File { id: _, blocks } => {
if blocks == *free_blocks {
results.push(last);
Disk::Free { blocks: _ } => continue,
Disk::File { id, blocks } => match blocks.cmp(&free_blocks) {
std::cmp::Ordering::Equal => {
input[i] = last;
i += 1;
}
std::cmp::Ordering::Less => {
input.insert(i, last);
input[i + 1] = Disk::Free {
blocks: free_blocks - blocks,
};
i += 1;
}
std::cmp::Ordering::Greater => {
input[i] = Disk::File {
id,
blocks: free_blocks,
};
input.push(Disk::File {
id,
blocks: blocks - free_blocks,
});
i += 1;
}
}
},
}
} else {
break;
}
},
}
}
if i >= input.len() {
break;
}
}

for i in results {
let mut res = 0;
let mut pos = 0;
for i in input {
match i {
Disk::File { id, blocks } => {
print!("{}", id.to_string().repeat(blocks));
}
Disk::Free { blocks } => {
print!("{}", ".".repeat(blocks));
for _ in 0..blocks {
res += pos * id;
pos += 1;
}
}
_ => unreachable!(),
}
}
println!();

0
res
}

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

#[test]
fn test_part1() {
assert_eq!(1, part1(&input_generator(INPUT)))
assert_eq!(1928, part1(&input_generator(INPUT)))
}

// #[test]
Expand Down

0 comments on commit 7df8d44

Please sign in to comment.