Skip to main content

aoc/year2018/
day02.rs

1//! # Inventory Management System
2use crate::util::hash::*;
3
4pub fn parse(input: &str) -> Vec<&str> {
5    input.lines().collect()
6}
7
8pub fn part1(input: &[&str]) -> u32 {
9    let (twos, threes) = input.iter().fold((0, 0), |(twos, threes), id| {
10        // Ids are lowercase ASCII only with cardinality of 26.
11        let mut freq = [0; 26];
12
13        for b in id.bytes() {
14            freq[(b - b'a') as usize] += 1;
15        }
16
17        (twos + freq.contains(&2) as u32, threes + freq.contains(&3) as u32)
18    });
19
20    twos * threes
21}
22
23pub fn part2(input: &[&str]) -> String {
24    let width = input[0].len();
25    let mut seen = FastSet::with_capacity(input.len());
26
27    // Use a set to check for duplicates by comparing the prefix and suffix of IDs excluding one
28    // column at a time.
29    for column in 0..width {
30        for &id in input {
31            let pair @ (prefix, suffix) = (&id[..column], &id[column + 1..]);
32            if !seen.insert(pair) {
33                return format!("{prefix}{suffix}");
34            }
35        }
36        seen.clear();
37    }
38
39    unreachable!()
40}