Advertisement
JonathanGupton

Advent of Code 2022 - Day 3

Dec 3rd, 2022
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.60 KB | None | 0 0
  1. use std::collections::HashSet;
  2.  
  3. fn score_char(letter: &char) -> u32 {
  4.     let i = *letter as u32;
  5.     if i >= 97 {
  6.         i - 96
  7.     } else {
  8.         i - 38
  9.     }
  10. }
  11.  
  12. pub fn part_one(input: &str) -> Option<u32> {
  13.     let mut priorities: u32 = 0;
  14.     for line in input.lines() {
  15.         let pivot = line.len() / 2;
  16.         let compartment_a: HashSet<char> = HashSet::from_iter(line[0..pivot].chars());
  17.         for c in line[pivot..].chars() {
  18.             if compartment_a.contains(&c) {
  19.                 priorities += score_char(&c);
  20.                 break;
  21.             }
  22.         }
  23.     }
  24.     Some(priorities)
  25. }
  26.  
  27. pub fn part_two(input: &str) -> Option<u32> {
  28.     let mut priorities: u32 = 0;
  29.     let mut set1: HashSet<char> = HashSet::with_capacity(50);
  30.     let mut set2: HashSet<char> = HashSet::with_capacity(50);
  31.     let mut set3: HashSet<char> = HashSet::with_capacity(50);
  32.     let mut set4: HashSet<char> = HashSet::with_capacity(50);
  33.  
  34.     for lines in input.lines().collect::<Vec<&str>>().chunks_exact_mut(3) {
  35.         let mut l = lines.iter_mut();
  36.         for c in l.next().unwrap().chars() {
  37.             set1.insert(c);
  38.         }
  39.         for c in l.next().unwrap().chars() {
  40.             set2.insert(c);
  41.         }
  42.         for c in l.next().unwrap().chars() {
  43.             set3.insert(c);
  44.         }
  45.         for c in set1.intersection(&set2) {
  46.             set4.insert(*c);
  47.         }
  48.         priorities += score_char(set3.intersection(&set4).next().unwrap());
  49.  
  50.         set1.clear();
  51.         set2.clear();
  52.         set3.clear();
  53.         set4.clear();
  54.     }
  55.  
  56.  
  57.     Some(priorities)
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement