summaryrefslogtreecommitdiff
path: root/2020/rust/day05/src/main.rs
blob: 4d6072ad6212ccd9d86a8931e47efaf873e8e6d0 (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
use anyhow::{anyhow, Result};
use std::env::args;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::ops::RangeInclusive;
use std::path::Path;
use thiserror::Error;

#[derive(Error, Debug)]
enum BinarySpaceError {
    #[error("Space is not fully reduced")]
    NotReduced,
}

struct BinarySpace {
    start: usize,
    end: usize,
}

impl BinarySpace {
    fn new(range: RangeInclusive<usize>) -> BinarySpace
    // FIXME It would be nice with a cleaner interface. The intention was to use something like the
    //       RangeBounds trait, but it seems to require support of Unbounded ranges, which this
    //       BinarySpace will not be able to work with.
    {
        BinarySpace {
            start: *range.start(),
            end: *range.end(),
        }
    }

    fn size(&self) -> usize {
        self.end - self.start
    }

    fn split(&mut self, op: char) {
        let size = self.size() + 1;
        let half = size / 2;
        match op {
            'F' | 'L' => self.end -= half,
            'B' | 'R' => self.start += half,
            c => panic!("Invalid op to BinarySpace.split(): {}", c),
        }
    }

    fn value(&self) -> std::result::Result<usize, BinarySpaceError> {
        if self.start == self.end {
            Ok(self.start)
        } else {
            Err(BinarySpaceError::NotReduced)
        }
    }
}

fn read_input<T: AsRef<Path>>(filename: T) -> std::io::Result<Vec<String>> {
    let f = File::open(filename)?;
    let reader = BufReader::new(f);

    reader.lines().collect()
}

fn parse_boarding_passes(input: &[String]) -> Result<Vec<usize>> {
    input.iter().map(|ops| {
        let mut row = BinarySpace::new(0..=127);
        let mut col = BinarySpace::new(0..=7);
        for op in ops.clone().drain(..) {
            match op {
                'F' | 'B' => row.split(op),
                'L' | 'R' => col.split(op),
                _ => return Err(anyhow!("Invalid op encountered")),
            }
        }

        Ok(row.value()? * 8 + col.value()?)
    }).collect()
}

fn part1(input: &[usize]) -> Option<usize> {
    input.iter().max().copied()
}

fn part2(input: &[usize]) -> Option<usize> {
    let mut ret = None;

    for seat in 1..(128*8) {
        if (input.contains(&seat),
            input.contains(&(seat-1)),
            input.contains(&(seat+1))
        ) == (false, true, true) {
            match ret {
                None => ret = Some(seat),
                Some(_) => return None, /* No more than one solution allowed */
            }
        }
    }

    ret
}

fn main() {
    let (do_part_1, do_part_2) = aoc::do_parts();

    let filename = match args().nth(1) {
        Some(f) => f,
        None => {
            eprintln!("Missing input filename");
            std::process::exit(1);
        },
    };
    match read_input(filename) {
        Ok(input) => {
            match parse_boarding_passes(&input) {
                Ok(seat_ids) => {
                    if do_part_1 {
                        match part1(&seat_ids) {
                            Some(solution) =>
                                println!("Part1, highest seat ID found to be: {}", solution),
                            None => eprintln!("Part1, no soluton found"),
                        }
                    }
                    if do_part_2 {
                        match part2(&seat_ids) {
                            Some(solution) =>
                                println!("Part2, seat {} is lacking a boarding pass", solution),
                            None => eprintln!("Part2, no soluton found"),
                        }
                    }
                },
                Err(err) => eprintln!("Could not parse input: {}", err),
            }

        },
        Err(err) => eprintln!("Could not read input: {}", err),
    }
}