Day05 part 2

This commit is contained in:
max.nuding 2022-12-05 09:01:04 +01:00
parent f73bc65d9f
commit 8a2f37c67f
Failed to extract signature

View File

@ -4,54 +4,61 @@ pub fn run() {
let input = read("05"); let input = read("05");
let lines = input.split_once("\n\n").unwrap(); let lines = input.split_once("\n\n").unwrap();
let stackslines = lines.0.lines().collect::<Vec<_>>(); let mut stacks: Vec<Vec<char>> = lines
let mut stacks = std::collections::HashMap::new(); .0
for l in stackslines { .lines()
.fold(vec![], |mut agg, l| {
let length = l.len(); let length = l.len();
let mut idx = 0; let mut idx = 0;
while idx <= length { while idx <= length {
let charnum = 1 + idx * 4; if let Some(s1) = l.chars().nth(1 + idx * 4) {
if let Some(s1) = l.chars().nth(charnum) {
if !s1.is_whitespace() && !s1.is_numeric() { if !s1.is_whitespace() && !s1.is_numeric() {
let e = stacks.entry(idx + 1).or_insert(vec![]); while idx >= agg.len() {
e.push(s1); agg.push(vec![]);
}
agg.get_mut(idx).unwrap().push(s1);
} }
} }
idx += 1; idx += 1;
} }
} agg
let k = stacks.keys().max().unwrap(); });
for i in 1..=*k { stacks.iter_mut().for_each(|s|s.reverse());
stacks.entry(i).and_modify(|s| s.reverse());
}
let re = regex::Regex::new(r"move (\d+) from (\d+) to (\d+)").unwrap(); 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 instructions = lines.1.lines()
.filter(|l| !l.is_empty())
.map(|l| {
let capt = re.captures(l).unwrap(); let capt = re.captures(l).unwrap();
let count: usize = capt[1].parse().unwrap(); (capt[1].parse::<usize>().unwrap(),
let from: usize = capt[2].parse().unwrap(); capt[2].parse::<usize>().unwrap() - 1,
let to: usize = capt[3].parse().unwrap(); capt[3].parse::<usize>().unwrap() - 1)
for _i in 0..count { }).collect::<Vec<_>>();
let fr = stacks.get_mut(&from).unwrap();
let c = fr.pop().unwrap();
stacks.entry(to).and_modify(|s| s.push(c));
}
}
#[cfg(feature = "part1")] #[cfg(feature = "part1")]
{ {
let mut keys = stacks.keys().copied().collect::<Vec<_>>(); let mut stacks = stacks.clone();
keys.sort(); instructions.iter().for_each(|(count, from, to)| {
let chars = keys for _i in 0..*count {
.iter() let c2 = stacks.get_mut(*from).unwrap().pop().unwrap();
.map(|s| stacks.get(s).unwrap().last().unwrap()) stacks.get_mut(*to).unwrap().push(c2);
}
});
let chars = stacks.iter().map(|s|s.last().unwrap())
.collect::<String>(); .collect::<String>();
println!("Day 5, Part 01: {}", chars); println!("Day 5, Part 01: {}", chars);
} }
#[cfg(feature = "part2")] #[cfg(feature = "part2")]
{ {
let count = 1; instructions.iter().for_each(|(count, from, to)| {
println!("Day 5, Part 02: {}", count); 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::<String>();
println!("Day 5, Part 02: {}", chars);
} }
} }