From 8a2f37c67fd97ded21347d64fa5e542a6caf53cd Mon Sep 17 00:00:00 2001 From: "max.nuding" Date: Mon, 5 Dec 2022 09:01:04 +0100 Subject: [PATCH] Day05 part 2 --- src/day05/mod.rs | 67 ++++++++++++++++++++++++++---------------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/src/day05/mod.rs b/src/day05/mod.rs index 750e282..a7613e0 100644 --- a/src/day05/mod.rs +++ b/src/day05/mod.rs @@ -4,54 +4,61 @@ pub fn run() { let input = read("05"); let lines = input.split_once("\n\n").unwrap(); - let stackslines = lines.0.lines().collect::>(); - let mut stacks = std::collections::HashMap::new(); - for l in stackslines { + let mut stacks: Vec> = lines + .0 + .lines() + .fold(vec![], |mut agg, l| { let length = l.len(); let mut idx = 0; while idx <= length { - let charnum = 1 + idx * 4; - if let Some(s1) = l.chars().nth(charnum) { + if let Some(s1) = l.chars().nth(1 + idx * 4) { if !s1.is_whitespace() && !s1.is_numeric() { - let e = stacks.entry(idx + 1).or_insert(vec![]); - e.push(s1); + while idx >= agg.len() { + agg.push(vec![]); + } + agg.get_mut(idx).unwrap().push(s1); } } idx += 1; } - } - let k = stacks.keys().max().unwrap(); - for i in 1..=*k { - stacks.entry(i).and_modify(|s| s.reverse()); - } + agg + }); + stacks.iter_mut().for_each(|s|s.reverse()); let re = regex::Regex::new(r"move (\d+) from (\d+) to (\d+)").unwrap(); - for l in lines.1.lines().filter(|l| !l.is_empty()) { - let capt = re.captures(l).unwrap(); - let count: usize = capt[1].parse().unwrap(); - let from: usize = capt[2].parse().unwrap(); - let to: usize = capt[3].parse().unwrap(); - for _i in 0..count { - let fr = stacks.get_mut(&from).unwrap(); - let c = fr.pop().unwrap(); - stacks.entry(to).and_modify(|s| s.push(c)); - } - } + let instructions = lines.1.lines() + .filter(|l| !l.is_empty()) + .map(|l| { + let capt = re.captures(l).unwrap(); + (capt[1].parse::().unwrap(), + capt[2].parse::().unwrap() - 1, + capt[3].parse::().unwrap() - 1) + }).collect::>(); #[cfg(feature = "part1")] { - let mut keys = stacks.keys().copied().collect::>(); - keys.sort(); - let chars = keys - .iter() - .map(|s| stacks.get(s).unwrap().last().unwrap()) + let mut stacks = stacks.clone(); + instructions.iter().for_each(|(count, from, to)| { + for _i in 0..*count { + let c2 = stacks.get_mut(*from).unwrap().pop().unwrap(); + stacks.get_mut(*to).unwrap().push(c2); + } + }); + let chars = stacks.iter().map(|s|s.last().unwrap()) .collect::(); println!("Day 5, Part 01: {}", chars); } #[cfg(feature = "part2")] { - let count = 1; - println!("Day 5, Part 02: {}", count); + instructions.iter().for_each(|(count, from, to)| { + let src = stacks.get_mut(*from).unwrap(); + let range = src.len()-count..; + let mut crates = src.drain(range).collect(); + stacks.get_mut(*to).unwrap().append(&mut crates); + }); + let chars = stacks.iter().map(|s|s.last().unwrap()) + .collect::(); + println!("Day 5, Part 02: {}", chars); } }