From 066f5946e25061d23db5f988061b316eeb043faf Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Wed, 7 Dec 2022 01:06:21 +0300 Subject: 2022, day5: part 2done This felt bad, go over this later --- 2022/day5/part2/Cargo.toml | 10 +++++++ 2022/day5/part2/src/main.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 2022/day5/part2/Cargo.toml create mode 100644 2022/day5/part2/src/main.rs diff --git a/2022/day5/part2/Cargo.toml b/2022/day5/part2/Cargo.toml new file mode 100644 index 0000000..57ffa72 --- /dev/null +++ b/2022/day5/part2/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "part2" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +itertools = "0.10.5" +regex = "1.7.0" diff --git a/2022/day5/part2/src/main.rs b/2022/day5/part2/src/main.rs new file mode 100644 index 0000000..c21f270 --- /dev/null +++ b/2022/day5/part2/src/main.rs @@ -0,0 +1,69 @@ +use itertools::Itertools; +use regex::Regex; +use std::collections::LinkedList; + +fn main() { + let input: &str = include_str!("../../input"); + + let width_finder = Regex::new(r"(?m)^\s1.*(\d)\s$").unwrap(); + let mut width = 0; + + for cap in width_finder.captures_iter(input) { + width = str::parse(&cap[1]).unwrap(); + } + + let mut crate_builder: Vec> = Vec::new(); + + for _ in 0..width { + crate_builder.push(LinkedList::new()); + } + + for line in input.lines() { + let mut idx = 0; + if line.contains("1") { + break; + } + + for part in &line.chars().chunks(4) { + let crt: String = part.collect(); + if !crt.contains("[") { + idx += 1; + } else { + let crate_ = crt.chars().nth(1).unwrap(); + crate_builder[idx].push_back(crate_); + idx += 1; + } + } + } + + let move_parser = Regex::new(r"^move\s(\d+)\sfrom\s(\d)\sto\s(\d)").unwrap(); + + for mv in input.lines().skip_while(|l| !l.contains("move")) { + for cap in move_parser.captures_iter(mv) { + let how_many = str::parse(&cap[1]).unwrap(); + let from: usize = str::parse(&cap[2]).unwrap(); + let to: usize = str::parse(&cap[3]).unwrap(); + + let mut temp: Vec = Vec::new(); + for _ in 0..how_many { + if let Some(box_) = crate_builder[from - 1].pop_front() { + temp.push(box_); + } + } + + temp.reverse(); + + for box_ in temp.iter() { + crate_builder[to - 1].push_front(*box_); + } + } + } + + println!( + "{}", + crate_builder + .iter() + .filter_map(|s| s.front()) + .collect::() + ); +} -- cgit v1.2.3-70-g09d2