summaryrefslogtreecommitdiff
path: root/2021/rust/day08/src/main.rs
blob: 0eeb904a64c1b2893089b576ed3bdf2a62d20574 (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use {
    anyhow::{
        anyhow,
        Context,
        Result,
    },
    std::{
        collections::HashSet,
        env::args,
        fs::File,
        hash::{
            Hash,
            Hasher,
        },
        io::{
            BufRead,
            BufReader,
        },
        path::Path,
        str::FromStr,
    },
    thiserror::Error,
};

#[derive(Error, Debug)]
enum SegmentError {
    #[error("Invalid segment character")]
    Invalid(char),
}

type SegmentResult<T> = std::result::Result<T, SegmentError>;

#[derive(Clone,Debug,Eq,Hash,Ord,PartialEq,PartialOrd)]
enum Segment { A, B, C, D, E, F, G, }

#[derive(Clone,Debug,Eq)]
struct Digit {
    inner: HashSet<Segment>,
}

// https://stackoverflow.com/q/36562419/hashset-as-key-for-other-hashset
impl Hash for Digit {
    fn hash<H>(&self, state: &mut H) where H: Hasher {
        let mut a: Vec<&Segment> = self.inner.iter().collect();
        a.sort();
        for s in a.iter() {
            s.hash(state);
        }
    }

}

impl PartialEq for Digit {
    fn eq(&self, other: &Digit) -> bool {
        self.inner == other.inner
    }
}

impl FromStr for Digit {
    type Err = SegmentError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let inner = s.chars().map(|c| match c {
            'a' => Ok(Segment::A),
            'b' => Ok(Segment::B),
            'c' => Ok(Segment::C),
            'd' => Ok(Segment::D),
            'e' => Ok(Segment::E),
            'f' => Ok(Segment::F),
            'g' => Ok(Segment::G),
            _ => Err(SegmentError::Invalid(c)),
        }).collect::<SegmentResult<HashSet<Segment>>>()?;
        Ok(Self {
            inner,
        })
    }
}

#[derive(Debug)]
struct Signals {
    input: Vec<Digit>,
    output: Vec<Digit>,
}

fn read_signals<T: AsRef<Path>>(filename: T) -> Result<Vec<Signals>> {
    let reader = BufReader::new(File::open(filename)?);

    reader.lines().map(
        |row| {
            let r = row?;
            let (left, right) = r.split_once('|')
                .ok_or_else(|| anyhow!("Missing separator: {}", r))?;
            let input = left.split_whitespace().map(|n| n.parse()
                .map_err(|err| anyhow!("{}", err))).collect::<Result<Vec<Digit>>>()?;
            let output = right.split_whitespace().map(|n| n.parse()
                .map_err(|err| anyhow!("{}", err))).collect::<Result<Vec<Digit>>>()?;
            Ok(Signals {input, output})
        }
    ).collect()
}

fn part1<'a, I: IntoIterator<Item = &'a Signals>>(signals: I) -> Result<usize> {
    //  aaaa    ....    aaaa    aaaa    ....
    // b    c  .    c  .    c  .    c  b    c
    // b    c  .    c  .    c  .    c  b    c
    //  ....    ....    dddd    dddd    dddd
    // e    f  .    f  e    .  .    f  .    f
    // e    f  .    f  e    .  .    f  .    f
    //  gggg    ....    gggg    gggg    ....
    // 
    //   5:      6:      7:      8:      9:
    //  aaaa    aaaa    aaaa    aaaa    aaaa
    // b    .  b    .  .    c  b    c  b    c
    // b    .  b    .  .    c  b    c  b    c
    //  dddd    dddd    ....    dddd    dddd
    // .    f  e    f  .    f  e    f  .    f
    // .    f  e    f  .    f  e    f  .    f
    //  gggg    gggg    ....    gggg    gggg
    //                   0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    let segment_count = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6];
    let count = signals.into_iter().map(|s| {
        let c: usize = s.output.iter().map(|d| {
            match d.inner.len() {
                v if v == segment_count[1] ||
                    v == segment_count[4] ||
                    v == segment_count[7] ||
                    v == segment_count[8] => 1,
                _ => 0,
            }
        }).sum();
        c
    }).sum();

    Ok(count)
}

fn find_digits(input: &[Digit]) -> Result<Vec<Option<Digit>>> {
    let segment_count = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6];

    let mut digits: Vec<Option<Digit>> = vec![None; 10];
    let mut unknown = HashSet::new();
    for digit in input.iter() {
        unknown.insert(digit.clone());
    }
    for unique_segments in [1, 4, 7, 8].into_iter() {
        // Digit 1 is found by unique number of segments, as in part 1.
        // The same is true for Digit 4, Digit 7 and Digit 8.
        unknown.clone().into_iter().map(|d| if d.inner.len() == segment_count[unique_segments] {
            unknown.remove(&d);
            digits[unique_segments] = Some(d);
        }).last();
    }
    // Digit 3 is the only five segmented superset of Digit 1 (and Digit 7).
    digits[3] = unknown.clone().into_iter().filter(|d| {
        if d.inner.len() == 5 {
            if let Some(one) = &digits[1] {
                if d.inner.is_superset(&one.inner) {
                    unknown.remove(d);
                    return true;
                }
            }
        }
        false
    }).last();
    // Digit 0 is Digit 8 - (Digit 3 & (Digit 4 - Digit 1)).
    digits[0] = unknown.clone().into_iter().filter(|d| {
        if let (Some(one), Some(three), Some(four), Some(eight)) =
            (&digits[1], &digits[3], &digits[4], &digits[8])
        {
            if d.inner == &eight.inner - &(&three.inner & &(&four.inner - &one.inner)) {
                unknown.remove(d);
                return true
            }
        }
        false
    }).last();
    digits[9] = unknown.clone().into_iter().filter(|d| {
        if d.inner.len() == 6 {
            if let Some(three) = &digits[3] {
                if d.inner.is_superset(&three.inner) {
                    unknown.remove(d);
                    return true
                }
            }
        }
        false
    }).last();
    // Digit 6 is the only remaining six segmented unknown.
    digits[6] = unknown.clone().into_iter().filter(|d| if d.inner.len() == 6 {
        unknown.remove(d);
        true
    } else {
        false
    }).last();
    // Digit 2 is the one with zero overlap with the difference of Digit 4 - Digit 3.
    digits[2] = unknown.clone().into_iter().filter(|d| {
        if let (Some(three), Some(four)) = (&digits[3], &digits[4]) {
            if (&d.inner & &(&four.inner - &three.inner)).is_empty() {
                unknown.remove(d);
                return true
            }
        }
        false
    }).last();
    // Digit 5 is the remaining one.
    digits[5] = unknown.into_iter().next();
    Ok(digits)
}

fn decode_output(output: &[Digit], digits: &[Option<Digit>]) -> Result<usize> {
    output.iter().fold(Ok(0), |acc, d| {
        let mut acc_val = acc.expect("Bug in decode_output()");
        acc_val *= 10;
        (0..=9).filter_map(|n|
            match digits.get(n)? {
                Some(i) if i.inner == d.inner => Some(acc_val + n),
                _ => None,
            }
        ).next().ok_or(anyhow!("No digit matched"))
    })
}

fn part2<'a, I: IntoIterator<Item = &'a Signals>>(signals: I) -> Result<usize> {
    let res: usize = signals.into_iter().map(|signal| {
        let digits = find_digits(&signal.input)?;
        decode_output(&signal.output, &digits)
    }).collect::<Result<Vec<_>>>()?.into_iter().sum();

    Ok(res)
}

fn main() -> Result<()> {
    let ( do_part_1, do_part_2 ) = aoc::do_parts();

    let filename = args().nth(1).ok_or(anyhow!("Missing signals filename"))?;
    let signals = read_signals(filename).context("Could not read signals")?;
    if do_part_1 {
        let solution = part1(&signals).context("No solution for part 1")?;
        println!("Part1, solution found to be: {}", solution);
    }
    if do_part_2 {
        let solution = part2(&signals).context("No solution for part 2")?;
        println!("Part2, solution found to be: {}", solution);
    }
    Ok(())
}