Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(Debug, Clone)]
- struct Position {
- x: i32,
- y: i32,
- }
- impl Position {
- fn new() -> Position {
- Position { x: 0, y: 0 }
- }
- fn dist(first: &Position, second: &Position) -> i32 {
- let x_dist = (first.x - second.x).abs();
- let y_dist = (first.y - second.y).abs();
- x_dist + y_dist
- }
- fn follow(&mut self, position: &Position) {
- let x = self.x;
- let y = self.y;
- let distance = Position::dist(self, position);
- if distance > 1 {
- if x == position.x || distance > 2 {
- self.y += if y > position.y { -1 } else { 1 };
- }
- if y == position.y || distance > 2 {
- self.x += if x > position.x { -1 } else { 1 };
- }
- }
- }
- }
- fn main() {
- let content = read_file_content("input.txt");
- let mut knots = vec![Position::new(); 10];
- let head_knot = 9;
- let mut moves = HashSet::new();
- let mut commands = HashMap::new();
- commands.insert("R", (1, 0));
- commands.insert("L", (-1, 0));
- commands.insert("U", (0, 1));
- commands.insert("D", (0, -1));
- for command_order in content.lines() {
- let parts = command_order.split(' ').collect::<Vec<_>>();
- let (x_move, y_move) = commands.get(parts[0]).unwrap();
- let repeat = parts[1].parse::<u32>().unwrap();
- for _ in 0..repeat {
- knots[head_knot].x += x_move;
- knots[head_knot].y += y_move;
- for i in (0..9).rev() {
- let knot = &knots[i + 1].clone();
- knots[i].follow(knot);
- }
- let last = knots.first().unwrap();
- println!("{:?}", (last.x, last.y));
- moves.insert((last.x, last.y));
- }
- }
- println!("Number of unique moves is {}.", moves.len());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement