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