From 10b1b09fda6bb7bcffd2f85d1f55fbbe0bc1d892 Mon Sep 17 00:00:00 2001 From: kageru Date: Sun, 15 Dec 2019 11:49:30 +0100 Subject: [PATCH] Add movement to Position2D --- 2019/11/src/main.rs | 28 ++++++++++------------------ 2019/grid/src/lib.rs | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/2019/11/src/main.rs b/2019/11/src/main.rs index 5efbf0b..d102327 100644 --- a/2019/11/src/main.rs +++ b/2019/11/src/main.rs @@ -1,14 +1,7 @@ -use intcode::*; use grid::*; +use intcode::*; use std::collections::HashMap; -enum Direction { - Up, - Down, - Left, - Right, -} - struct Robot { direction: Direction, position: Position2D, @@ -34,14 +27,8 @@ impl Robot { } } - fn mv(&mut self) { - let pos = self.position; - self.position = match self.direction { - Direction::Up => pos + (0, 1).into(), - Direction::Right => pos + (1, 0).into(), - Direction::Left => pos + (-1, 0).into(), - Direction::Down => pos + (0, -1).into(), - } + fn mov(&mut self) { + self.position.mov(&self.direction); } fn paint(&mut self, color: i64) { @@ -64,7 +51,7 @@ fn start_with_input(input: Vec, color: i64) -> Robot { robot.paint(o); let turn_int = pc.run().unwrap(); robot.turn(turn_int); - robot.mv(); + robot.mov(); pc.params.push(robot.current_color()); } robot @@ -76,5 +63,10 @@ fn main() { println!("Part 1: {}", part1_robot.visited.len()); let part2_robot = start_with_input(input, 1); - println!("Part 2:\n{}", draw_ascii(&part2_robot.visited, 0).replace('0', " ").replace('1', "•")); + println!( + "Part 2:\n{}", + draw_ascii(&part2_robot.visited, 0) + .replace('0', " ") + .replace('1', "•") + ); } diff --git a/2019/grid/src/lib.rs b/2019/grid/src/lib.rs index a86bf26..d2722eb 100644 --- a/2019/grid/src/lib.rs +++ b/2019/grid/src/lib.rs @@ -2,6 +2,7 @@ use itertools::join; use std::collections::HashMap; use std::fmt::Display; use std::hash::BuildHasher; +use std::ops::{Add, AddAssign}; #[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)] pub struct Position2D { @@ -9,6 +10,13 @@ pub struct Position2D { pub y: i64, } +pub enum Direction { + Up, + Down, + Left, + Right, +} + struct Boundaries { x_min: i64, x_max: i64, @@ -25,7 +33,10 @@ fn get_boundaries(input: &[&Position2D]) -> Boundaries { Boundaries { x_min, x_max, y_min, y_max } } -pub fn draw_ascii(coordinates: &HashMap, default: T) -> String { +pub fn draw_ascii( + coordinates: &HashMap, + default: T, +) -> String { let b = get_boundaries(&coordinates.keys().collect::>()); join( (b.y_min..=b.y_max).rev().map(|y| { @@ -42,7 +53,25 @@ pub fn draw_ascii(coordinates: &HashMap (0, 1).into(), + Direction::Right => (1, 0).into(), + Direction::Left => (-1, 0).into(), + Direction::Down => (0, -1).into(), + } + } +} + +impl AddAssign for Position2D { + fn add_assign(&mut self, rhs: Position2D) { + *self = *self + rhs; + } +} + +impl Add for Position2D { type Output = Position2D; fn add(self, rhs: Position2D) -> Position2D {