1
0
Fork 0

day(05): refactor

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-12-05 11:31:44 +01:00
parent 95df0a175e
commit 4bbb98661c
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -42,7 +42,6 @@ impl FromStr for Ship {
let (stacks_str, moves_str) = (split_s[0], split_s[1]); let (stacks_str, moves_str) = (split_s[0], split_s[1]);
let mut stacks: Vec<Vec<char>> = Vec::new(); let mut stacks: Vec<Vec<char>> = Vec::new();
stacks_str stacks_str
.lines() .lines()
.rev() .rev()
@ -69,22 +68,7 @@ impl FromStr for Ship {
type Input = Ship; type Input = Ship;
type Output = String; type Output = String;
fn part_1(input: &Input) -> Output { fn stacks_to_string(stacks: &[Vec<char>]) -> String {
let Ship(stacks, moves) = input;
let mut stacks = stacks.clone();
moves.iter().for_each(|m| {
for _ in 0..m.count {
if stacks[m.from - 1].is_empty() {
break;
}
let popped = stacks[m.from - 1].pop().unwrap();
stacks[m.to - 1].push(popped);
}
});
stacks.iter().fold(String::new(), |acc, stack| { stacks.iter().fold(String::new(), |acc, stack| {
if let Some(c) = stack.last() { if let Some(c) = stack.last() {
acc + &c.to_string() acc + &c.to_string()
@ -94,24 +78,30 @@ fn part_1(input: &Input) -> Output {
}) })
} }
fn part_2(input: &Input) -> Output { fn move_crates(input: &Input, one_by_one: bool) -> Output {
let Ship(stacks, moves) = input; let Ship(stacks, moves) = input;
let mut stacks = stacks.clone(); let mut stacks = stacks.clone();
moves.iter().for_each(|m| { moves.iter().for_each(|m| {
let size = stacks[m.from - 1].len(); let size = stacks[m.from - 1].len();
let mut s = stacks[m.from - 1].split_off(max(0, size - m.count)); let mut s = stacks[m.from - 1].split_off(max(0, size - m.count));
if one_by_one {
s.reverse();
}
stacks[m.to - 1].append(&mut s); stacks[m.to - 1].append(&mut s);
}); });
stacks.iter().fold(String::new(), |acc, stack| { stacks_to_string(&stacks)
if let Some(c) = stack.last() {
acc + &c.to_string()
} else {
acc
} }
})
fn part_1(input: &Input) -> Output {
move_crates(input, true)
}
fn part_2(input: &Input) -> Output {
move_crates(input, false)
} }
fn parse_input(pathname: &str) -> Input { fn parse_input(pathname: &str) -> Input {