Advertisement
Guest User

Untitled

a guest
Dec 9th, 2022
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.86 KB | None | 0 0
  1.  
  2. #[derive(Debug, Clone)]
  3. struct Position {
  4.     x: i32,
  5.     y: i32,
  6. }
  7.  
  8. impl Position {
  9.     fn new() -> Position {
  10.         Position { x: 0, y: 0 }
  11.     }
  12.     fn dist(first: &Position, second: &Position) -> i32 {
  13.         let x_dist = (first.x - second.x).abs();
  14.         let y_dist = (first.y - second.y).abs();
  15.  
  16.         x_dist + y_dist
  17.     }
  18.  
  19.     fn follow(&mut self, position: &Position) {
  20.         let x = self.x;
  21.         let y = self.y;
  22.         let distance = Position::dist(self, position);
  23.         if distance > 1 {
  24.             if x == position.x || distance > 2 {
  25.                 self.y += if y > position.y { -1 } else { 1 };
  26.             }
  27.             if y == position.y || distance > 2 {
  28.                 self.x += if x > position.x { -1 } else { 1 };
  29.             }
  30.         }
  31.     }
  32. }
  33.  
  34. fn main() {
  35.     let content = read_file_content("input.txt");
  36.     let mut knots = vec![Position::new(); 10];
  37.     let head_knot = 9;
  38.  
  39.     let mut moves = HashSet::new();
  40.  
  41.     let mut commands = HashMap::new();
  42.     commands.insert("R", (1, 0));
  43.     commands.insert("L", (-1, 0));
  44.     commands.insert("U", (0, 1));
  45.     commands.insert("D", (0, -1));
  46.  
  47.     for command_order in content.lines() {
  48.         let parts = command_order.split(' ').collect::<Vec<_>>();
  49.         let (x_move, y_move) = commands.get(parts[0]).unwrap();
  50.         let repeat = parts[1].parse::<u32>().unwrap();
  51.  
  52.         for _ in 0..repeat {
  53.             knots[head_knot].x += x_move;
  54.             knots[head_knot].y += y_move;
  55.  
  56.             for i in (0..9).rev() {
  57.                 let knot = &knots[i + 1].clone();
  58.                 knots[i].follow(knot);
  59.             }
  60.  
  61.             let last = knots.first().unwrap();
  62.             println!("{:?}", (last.x, last.y));
  63.             moves.insert((last.x, last.y));
  64.         }
  65.     }
  66.  
  67.     println!("Number of unique moves is {}.", moves.len());
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement