1
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 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}"); println!("Solution for problem 5 part 1: {max_part1}");
} }
} }

View File

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