Finish day 5

This commit is contained in:
Savanni D'Gerinel 2022-12-11 00:46:28 -05:00
parent 0f7b59af46
commit 72426e9163
1 changed files with 44 additions and 1 deletions

View File

@ -16,7 +16,8 @@ pub fn part1() -> String {
}
pub fn part2() -> String {
unimplemented!()
let (stacks, commands) = input(INPUT);
tops(run_commands_multicrate(stacks, commands))
}
fn run_commands(stacks: Stacks<char>, commands: Vec<Command>) -> Stacks<char> {
@ -25,6 +26,12 @@ fn run_commands(stacks: Stacks<char>, commands: Vec<Command>) -> Stacks<char> {
.fold(stacks, |stacks, command| stacks.run_command(command))
}
fn run_commands_multicrate(stacks: Stacks<char>, commands: Vec<Command>) -> Stacks<char> {
commands.into_iter().fold(stacks, |stacks, command| {
stacks.run_command_multicrate(command)
})
}
fn tops(stacks: Stacks<char>) -> String {
stacks
.0
@ -125,6 +132,25 @@ impl<T: Clone + Copy> Stacks<T> {
});
self
}
fn run_command_multicrate(mut self, cmd: Command) -> Self {
let Command {
count,
source,
dest,
} = cmd;
let mut stack = Vec::new();
(0..count).for_each(|_| {
let val = self.0[(source - 1) as usize].pop().unwrap();
stack.push(val);
});
while stack.len() > 0 {
self.0[(dest - 1) as usize].push(stack.pop().unwrap());
}
self
}
}
fn input(data: &str) -> (Stacks<char>, Vec<Command>) {
@ -263,6 +289,23 @@ move 1 from 1 to 2";
});
}
#[test]
fn it_can_follow_multicrate_commands() {
with_input(|(stacks, commands)| {
let stacks = stacks.run_command_multicrate(commands[0].clone());
assert_eq!(stacks.0[0].0, vec!['Z', 'N', 'D']);
assert_eq!(stacks.0[1].0, vec!['M', 'C']);
assert_eq!(stacks.0[2].0, vec!['P']);
});
with_input(|(stacks, commands)| {
let stacks = run_commands_multicrate(stacks, commands);
assert_eq!(stacks.0[0].0, vec!['M']);
assert_eq!(stacks.0[1].0, vec!['C']);
assert_eq!(stacks.0[2].0, vec!['P', 'Z', 'N', 'D']);
});
}
#[test]
fn it_can_find_tops() {
with_input(|(stacks, commands)| {