1
0
Fork 0

More modular now.

This commit is contained in:
Florent DENEF 2022-12-27 11:16:50 +01:00
parent 3361c4f973
commit 02648af3b3
2 changed files with 29 additions and 24 deletions

View File

@ -35,7 +35,7 @@ fn main() {
}
{
let file_path = "prob5_part1.txt";
let max_part1 = prob5::solve(file_path);
let max_part1 = prob5::solve_part1(file_path);
println!("Solution for problem 5 part 1: {max_part1}");
}
}

View File

@ -96,7 +96,7 @@ fn parse_instruction(i: &str) -> IResult<&str, Instruction> {
)(i)
}
fn parser(content: &str) -> String {
fn parser(content: &str) -> (Vec<VecDeque<char>>, Vec<Instruction>) {
let mut lines = content.lines();
let crate_lines = (&mut lines)
.map_while(|line| {
@ -107,36 +107,41 @@ fn parser(content: &str) -> String {
})
.collect();
let mut crate_columns = transpose_rev(crate_lines);
let crate_columns = {
let mut tmp = transpose_rev(crate_lines);
tmp.iter_mut().for_each(|item| {
item.make_contiguous();
});
tmp
};
assert!(lines.next().unwrap().is_empty());
lines
let instructions = lines
.map(|line| all_consuming(parse_instruction)(line).finish().unwrap().1)
.into_iter()
.for_each(|ins| {
(0..ins.quantity).for_each(|_| {
let tmp = crate_columns
.get_mut(ins.src)
.unwrap_or_else(|| {
panic!("Index {} is out of bound of crate_columns.", ins.src)
})
.pop_front()
.unwrap_or_else(|| panic!("Could not pop front the column {}", ins.src));
crate_columns
.get_mut(ins.dst)
.unwrap_or_else(|| panic!("Index {} is out of bound", ins.dst))
.push_front(tmp);
});
.collect::<Vec<Instruction>>();
(crate_columns, instructions)
}
pub fn solve_part1(file_path: &str) -> String {
let content = std::fs::read_to_string(file_path).unwrap_or_else(|err| panic!("{err}"));
let (mut crate_columns, instructions) = parser(&content);
instructions.iter().for_each(|ins| {
(0..ins.quantity).for_each(|_| {
let tmp = crate_columns
.get_mut(ins.src)
.unwrap_or_else(|| panic!("Index {} is out of bound of crate_columns.", ins.src))
.pop_front()
.unwrap_or_else(|| panic!("Could not pop front the column {}", ins.src));
crate_columns
.get_mut(ins.dst)
.unwrap_or_else(|| panic!("Index {} is out of bound", ins.dst))
.push_front(tmp);
});
});
let mut answer = String::new();
crate_columns
.iter()
.for_each(|item| answer.push(*item.front().unwrap_or_else(|| panic!(""))));
answer
}
pub fn solve(file_path: &str) -> String {
let content = std::fs::read_to_string(file_path).unwrap_or_else(|err| panic!("{err}"));
parser(&content)
}