qzazwxsx

Untitled

Dec 8th, 2023
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.04 KB | Source Code | 0 0
  1. use crate::{Solution, SolutionPair};
  2. use std::collections::HashMap;
  3. use num::integer::lcm;
  4.  
  5. ///////////////////////////////////////////////////////////////////////////////
  6.  
  7. pub fn solve(input: std::str::Lines<'_>) -> SolutionPair {
  8.  
  9.    let sol2: u64 = 0;
  10.  
  11.    let mut lines = input.clone();
  12.  
  13.    let instructions = lines.next().unwrap();
  14.    lines.next();
  15.    let mut map: HashMap<&str, (&str, &str)> = HashMap::new();
  16.  
  17.  
  18.    for line in lines {
  19.        let parts: Vec<&str> = line.split(" = ").collect();
  20.        let key = parts[0];
  21.        let values = parts[1].trim_matches(|c| c == '(' || c == ')').split(',').collect::<Vec<&str>>();
  22.        
  23.        if values.len() == 2 {
  24.            map.insert(key, (values[0].trim(), values[1].trim()));
  25.        }
  26.    }
  27.  
  28.    let mut count: u64 = 0;
  29.    let mut curr_element = "AAA";
  30.    while curr_element != "ZZZ" {
  31.        let idx = count as usize % instructions.len();
  32.        let instruction = instructions.as_bytes()[idx];
  33.        if instruction == b'L' {
  34.            curr_element = map[curr_element].0;
  35.        }
  36.        if instruction == b'R' {
  37.            curr_element = map[curr_element].1;
  38.        }
  39.        count += 1;
  40.    }
  41.  
  42.    let mut counts2: Vec<u64> = Vec::new();
  43.    let all_curr_elements: Vec<&str> = map
  44.        .keys().
  45.        filter(|&&i| i.ends_with("A"))
  46.        .cloned()
  47.        .collect();
  48.  
  49.    for el in all_curr_elements {
  50.        let mut curr_elem = el;
  51.        let mut curr_count: u64 = 0;
  52.  
  53.        while !curr_elem.ends_with("Z") {
  54.            let idx = curr_count as usize % instructions.len();
  55.            let instruction = instructions.as_bytes()[idx];
  56.            if instruction == b'L' {
  57.                curr_elem = map[curr_elem].0;
  58.            }
  59.            if instruction == b'R' {
  60.                curr_elem = map[curr_elem].1;
  61.            }
  62.            curr_count += 1;
  63.        }
  64.        counts2.push(curr_count);
  65.    }
  66.  
  67.    let sol2 = counts2.into_iter().fold(1, |acc, x| lcm(acc, x));
  68.  
  69.    (Solution::from(count), Solution::from(sol2))
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment