1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
use std::fs;
use std::path::Path;
use std::collections::HashMap;
/* AOC21 Day 8: https://adventofcode.com/2021/day/8 */
fn main() {
let input = Path::new("resources").join("input.txt");
let content = fs::read_to_string(input).expect("Unable to read input file");
println!("Ex1: The result is {}", ex1(&content));
println!("Ex2: The result is {}", ex2(&content));
}
fn ex1(content: &str) -> usize {
content.lines().flat_map(
|l| l.split_once(" | ").expect("Malformed input").1.split_whitespace().map(|d| d.len())
).filter(|&x| x == 2 || x == 3 || x == 4 || x == 7).count()
}
#[inline]
fn parse_pattern(pattern: &str) -> (usize,u8) {
(pattern.len(), pattern.bytes().fold(0, |a, b| a + (1 << (b - b'a'))))
}
fn decode_patterns(patterns: &[(usize,u8)]) -> HashMap<u8,u32> {
let mut map = [0; 10];
patterns.iter().for_each(|(l,e)| {
match l {
2 => map[1] = *e,
3 => map[7] = *e,
4 => map[4] = *e,
7 => map[8] = *e,
_ => {}
}
});
patterns.iter().for_each(|(l,e)| {
match l {
5 if (e & map[1]).count_ones() == 2 => map[3] = *e,
5 if (e & map[4]).count_ones() == 2 => map[2] = *e,
5 => map[5] = *e,
6 if (e & map[4]).count_ones() == 4 => map[9] = *e,
6 if (e & map[1]).count_ones() == 2 => map[0] = *e,
6 => map[6] = *e,
_ => {}
}
});
map.iter().enumerate().fold(HashMap::new(),|mut m, (i,v)| { m.insert(*v, i as u32); m })
}
fn ex2(content: &str) -> u32 {
content.lines().map(|l| {
let (patterns, digits) = l.split_once(" | ").expect("Malformed input");
let patterns = decode_patterns(&patterns.split_whitespace().map(|p| parse_pattern(p)).collect::<Vec<(usize,u8)>>());
digits.split_whitespace().map(|p| patterns.get(&parse_pattern(p).1).unwrap()).fold(0, |a,d| (a*10)+d)
}).sum()
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce";
#[test]
fn example1() {
assert_eq!(26, ex1(INPUT))
}
#[test]
fn example2() {
assert_eq!(61229, ex2(INPUT))
}
}
|