Advertisement
Guest User

AoC 2021 Day 2

a guest
Dec 2nd, 2021
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.31 KB | None | 0 0
  1. pub struct Day2 {
  2.     input: Vec<(String, i64)>,
  3. }
  4.  
  5. impl Day2 {
  6.     pub async fn new() -> Result<Self, Box<dyn Error>> {
  7.         let content = aoc_input::create_input(2021, 2).await?;
  8.  
  9.         Ok(Day2 {
  10.             input: content
  11.                     .lines()
  12.                     .map(|x| x.split_whitespace().collect::<Vec<&str>>())
  13.                     .map(|x| (x[0].to_string(), x[1].parse::<i64>().unwrap()))
  14.                     .collect(),
  15.         })
  16.     }
  17. }
  18.  
  19. impl Day for Day2 {
  20.     fn part1(&self) -> i64 {
  21.         let mut pos: (i64, i64) = (0, 0);
  22.         for (dir, len) in self.input.iter() {
  23.             match &dir[..] {
  24.                 "forward" => pos.0 += len,
  25.                 "up" => pos.1 -= len,
  26.                 "down" => pos.1 += len,
  27.                 _ => continue,
  28.             }
  29.         }
  30.  
  31.         pos.0 * pos.1
  32.     }
  33.  
  34.     fn part2(&self) -> i64 {
  35.         let mut aim: i64 = 0;
  36.         let mut pos: (i64, i64) = (0, 0);
  37.         for (dir, len) in self.input.iter() {
  38.             match &dir[..] {
  39.                 "forward" => {
  40.                     pos.0 += len;
  41.                     pos.1 += len * aim;
  42.                 },
  43.                 "up" => aim -= len,
  44.                 "down" => aim += len,
  45.                 _ => continue,
  46.             }
  47.         }
  48.  
  49.         pos.0 * pos.1
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement