diff --git a/src/main.rs b/src/main.rs index daf8965..0023e85 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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}"); } } diff --git a/src/prob5.rs b/src/prob5.rs index 8545aee..345d2c9 100644 --- a/src/prob5.rs +++ b/src/prob5.rs @@ -96,7 +96,7 @@ fn parse_instruction(i: &str) -> IResult<&str, Instruction> { )(i) } -fn parser(content: &str) -> String { +fn parser(content: &str) -> (Vec>, Vec) { 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::>(); + (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) -}