aoc/year2017/day04.rs
1//! # High-Entropy Passphrases
2//!
3//! ## Part One
4//!
5//! We use a [`FastSet`] to detect duplicates. Sorting the words in each line
6//! then checking for duplicates in adjacent values also works but is slower.
7//!
8//! ## Part Two
9//!
10//! To detect anagrams we first convert each word into a histogram of its letter frequency values.
11//! As the cardinality is at most 26 we can use a fixed size array to represent the set.
12//!
13//! Then a [`FastSet`] is used to detect duplicates. Sorting the letters in each word so that
14//! anagrams become the same also works but is slower.
15use crate::util::hash::*;
16
17type Input<'a> = Vec<&'a str>;
18
19pub fn parse(input: &str) -> Input<'_> {
20 input.lines().collect()
21}
22
23pub fn part1(input: &Input<'_>) -> usize {
24 let mut seen = FastSet::new();
25 input
26 .iter()
27 .filter(|line| {
28 seen.clear();
29 line.split_ascii_whitespace().all(|token| seen.insert(token.as_bytes()))
30 })
31 .count()
32}
33
34pub fn part2(input: &Input<'_>) -> usize {
35 // Calculate the frequency of each letter as anagrams will have the same values.
36 fn convert(token: &str) -> [u8; 26] {
37 let mut freq = [0; 26];
38 for b in token.bytes() {
39 freq[(b - b'a') as usize] += 1;
40 }
41 freq
42 }
43
44 let mut seen = FastSet::new();
45 input
46 .iter()
47 .filter(|line| {
48 seen.clear();
49 line.split_ascii_whitespace().all(|token| seen.insert(convert(token)))
50 })
51 .count()
52}