aoc2022

Advent of Code 2022 solutions in Rust
git clone git://code.mfashby.net:/aoc2022
Log | Files | Refs

day3.rs (1470B)


      1 use std::{collections::{HashSet, HashMap}};
      2 
      3 pub fn run(input: String) {
      4     let scores_table = make_scores_table();
      5     let score = input.lines()
      6         .collect::<Vec<&str>>()
      7         .chunks(3).map(|group| {
      8             let init: Option<HashSet<char>> = None;
      9             let overlapping_chars: Vec<char> = group.into_iter().fold(init, |acc, group_member| {
     10                 let group_member_charset: HashSet<char> = group_member.chars().collect();
     11                 if let Some(acc) = acc {
     12                     let intersected: HashSet<char> = acc.intersection(&group_member_charset).map(|x| {x.clone()}).collect();
     13                     Some(intersected)
     14                 } else {
     15                     Some(group_member_charset)
     16                 }
     17             })
     18         .expect("didn't get any group members??!")
     19         .into_iter().collect();
     20         let ct = overlapping_chars.len();
     21         if ct != 1 {
     22             panic!("Couldn't find exactly one badge for group! found {}, {:?}", ct, group);
     23         }
     24         scores_table[&overlapping_chars[0]]
     25     }).sum::<u32>();
     26 
     27     println!("Day 3: {}", score);
     28 }
     29 
     30 fn make_scores_table() -> HashMap<char, u32> {
     31     let mut scores_table: HashMap<char,u32> = HashMap::new();
     32     let r1 = 'a'..='z';
     33     for (ix, ch) in r1.enumerate() {
     34         scores_table.insert(ch, (ix as u32)+1);
     35     }
     36     let r2 = 'A'..='Z';
     37     for (ix, ch) in r2.enumerate() {
     38         scores_table.insert(ch, (ix as u32)+27);
     39     }
     40     scores_table
     41 }