refactors to avoid duplication

This commit is contained in:
JasterV 2021-12-02 13:11:30 +01:00
parent 2cf6b3eb50
commit aa8e3dadc4
2 changed files with 24 additions and 46 deletions

View file

@ -10,22 +10,32 @@ static INPUT_PATH: &str = "input.txt";
fn main() -> Result<()> {
// First puzzle
let submarine_v1 = SubmarineV1::new();
let submarine_v1 = SubmarineV1 { xcord: 0, depth: 0 };
let submarine_v2 = SubmarineV2 {
xcord: 0,
depth: 0,
aim: 0,
};
let commands = read_commands(INPUT_PATH)?;
let submarine_v1 = apply_commands(submarine_v1, &commands);
println!("First puzzle: {}", submarine_v1.position_x_depth());
// Second puzzle
let submarine_v2 = SubmarineV2::new();
let submarine_v2 = apply_commands(submarine_v2, &commands);
println!("First puzzle: {}", submarine_v1.position_x_depth());
println!("Second puzzle: {}", submarine_v2.position_x_depth());
Ok(())
}
fn apply_commands(submarine: impl Submarine, commands: &[Command]) -> impl Submarine {
commands
.iter()
.copied()
.fold(submarine, |submarine, command| submarine.exec(command))
fn apply_commands<T: Submarine>(submarine: T, commands: &[Command]) -> T {
commands.iter().copied().fold(submarine, move_submarine)
}
fn move_submarine<T: Submarine>(submarine: T, command: Command) -> T {
match command {
Command::Forward(unit) => submarine.forward(unit),
Command::Down(unit) => submarine.down(unit),
Command::Up(unit) => submarine.up(unit),
}
}
fn read_commands(file_path: &str) -> Result<Vec<Command>> {

View file

@ -1,7 +1,7 @@
use super::Command;
pub trait Submarine {
fn exec(&self, command: Command) -> Self;
fn forward(self, unit: i32) -> Self;
fn down(self, unit: i32) -> Self;
fn up(self, unit: i32) -> Self;
fn position(&self) -> i32;
fn depth(&self) -> i32;
fn position_x_depth(&self) -> i32 {
@ -15,11 +15,7 @@ pub struct SubmarineV1 {
pub depth: i32,
}
impl SubmarineV1 {
pub fn new() -> Self {
Self { xcord: 0, depth: 0 }
}
impl Submarine for SubmarineV1 {
fn forward(self, unit: i32) -> Self {
SubmarineV1 {
xcord: self.xcord + unit,
@ -40,16 +36,6 @@ impl SubmarineV1 {
depth: self.depth - unit,
}
}
}
impl Submarine for SubmarineV1 {
fn exec(&self, command: Command) -> Self {
match command {
Command::Forward(unit) => self.forward(unit),
Command::Down(unit) => self.down(unit),
Command::Up(unit) => self.up(unit),
}
}
fn position(&self) -> i32 {
self.xcord
@ -67,15 +53,7 @@ pub struct SubmarineV2 {
pub aim: i32,
}
impl SubmarineV2 {
pub fn new() -> Self {
Self {
xcord: 0,
depth: 0,
aim: 0,
}
}
impl Submarine for SubmarineV2 {
fn forward(self, unit: i32) -> Self {
SubmarineV2 {
xcord: self.xcord + unit,
@ -99,16 +77,6 @@ impl SubmarineV2 {
aim: self.aim - unit,
}
}
}
impl Submarine for SubmarineV2 {
fn exec(&self, command: Command) -> Self {
match command {
Command::Forward(unit) => self.forward(unit),
Command::Down(unit) => self.down(unit),
Command::Up(unit) => self.up(unit),
}
}
fn position(&self) -> i32 {
self.xcord