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