1
0
Fork 0

day(09): refactor

• Implement ‹new› for ‹Instruction›
• Pass ‹visited› instead of returning and consuming

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-12-09 12:20:29 +01:00
parent d7d3a8f889
commit f1c4785890
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -45,6 +45,13 @@ struct Instruction {
steps: i32,
}
impl Instruction {
#[cfg(test)]
fn new(direction: Direction, steps: i32) -> Self {
Self { direction, steps }
}
}
impl FromStr for Instruction {
type Err = Report;
@ -98,16 +105,14 @@ impl State {
State { knots }
}
fn execute(&self, i: &Instruction) -> (BTreeSet<Position>, State) {
let mut visited = BTreeSet::new();
fn execute(&self, visited: &mut BTreeSet<Position>, i: &Instruction) -> State {
// debug!("\n{}", self.show(6, 5));
let mut state: State = self.clone();
for _ in 0..i.steps {
state = state.execute_step(&mut visited, &i.direction);
state = state.execute_step(visited, &i.direction);
}
(visited, state)
state
}
// fn show(&self, width: i32, height: i32) -> String {
@ -136,10 +141,7 @@ fn execute(knots: i32, input: &Input) -> Output {
let mut visited = BTreeSet::<Position>::new();
input.iter().fold(State::new(knots), |state, instruction| {
let (mut v, s) = state.execute(instruction);
visited.append(&mut v);
s
state.execute(&mut visited, instruction)
});
visited.len()
@ -173,38 +175,14 @@ mod day_09_extended {
#[test]
fn test_part_2_bigger_sample() {
let input = vec![
Instruction {
direction: Direction::Right,
steps: 5,
},
Instruction {
direction: Direction::Up,
steps: 8,
},
Instruction {
direction: Direction::Left,
steps: 8,
},
Instruction {
direction: Direction::Down,
steps: 3,
},
Instruction {
direction: Direction::Right,
steps: 17,
},
Instruction {
direction: Direction::Down,
steps: 10,
},
Instruction {
direction: Direction::Left,
steps: 25,
},
Instruction {
direction: Direction::Up,
steps: 20,
},
Instruction::new(Direction::Right, 5),
Instruction::new(Direction::Up, 8),
Instruction::new(Direction::Left, 8),
Instruction::new(Direction::Down, 3),
Instruction::new(Direction::Right, 17),
Instruction::new(Direction::Down, 10),
Instruction::new(Direction::Left, 25),
Instruction::new(Direction::Up, 20),
];
assert_eq!(Day09::part_2(&input), 36);