summaryrefslogtreecommitdiff
path: root/2020/rust/day09/src/main.rs
blob: d62f0d43d23898cb65d4a25cf4f3ea7ae3383a8e (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
use anyhow::Result;
use getopts::Options;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

const DEFAULT_PREAMBLE: usize = 25;

fn usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [options] INPUT", program);
    print!("{}", opts.usage(&brief));
}

fn parse_args() -> (usize, Vec<String>) {
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();

    let mut opts = Options::new();
    opts.optopt("p", "preamble", "set preamble length", "25");
    opts.optflag("h", "help", "print this help menu");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };
    if matches.opt_present("h") {
        usage(&program, opts);
        std::process::exit(0);
    }
    let preamble = match matches.opt_str("p") {
        Some(p) => p.parse().expect("Could not parse preamble"),
        None => DEFAULT_PREAMBLE,
    };
    let free = if !matches.free.is_empty() {
        matches.free
    } else {
        usage(&program, opts);
        std::process::exit(1);
    };

    (preamble, free)
}

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

    let values = reader.lines()
        .map(|v| v?.parse::<usize>().map_err(anyhow::Error::new)).collect();

    values
}

fn is_valid_xmas(data: &[usize]) -> bool {
    let last = data[data.len()-1];
    for first in 0..data.len()-2 {
        for second in first+1..data.len()-1 {
            let sum = data[first] + data[second];
            if sum == last && data[first] != data[second] {
                return true;
            }
        }
    }

    false
}

fn find_sum(needle: usize, data: &[usize]) -> Option<&[usize]> {
    for first in 0..data.len()-1 {
        for len in 2..data.len()-first {
            let slice = data.get(first..first+len).unwrap();
            let sum: usize = slice.iter().sum();
            if sum == needle {
                return Some(slice);
            }
        }
    }

    None
}

fn part1(input: &[usize], preamble: usize) -> Option<usize> {
    for index in 0..(input.len()-preamble) {
        if ! is_valid_xmas(&input[index..(index+preamble+1)]) {
            return Some(input[index+preamble]);
        }
    }

    None
}

fn part2(input: &[usize], preamble: usize) -> Option<usize> {
    for index in 0..(input.len()-preamble) {
        if ! is_valid_xmas(&input[index..(index+preamble+1)]) {
            if let Some(found) = find_sum(input[index+preamble], input) {
                return Some(found.iter().min().unwrap() + found.iter().max().unwrap());
            }
        }
    }

    None
}

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

    let (preamble, args) = parse_args();
    let filename = match args.get(0) {
        Some(f) => f,
        None => {
            eprintln!("Missing input filename");
            std::process::exit(1);
        },
    };
    match read_input(filename) {
        Ok(input) => {
            if preamble > input.len() {
                eprintln!("A preamble of {} is not possible with an input of {} elements",
                    preamble, input.len());
                std::process::exit(1);
            }
            if do_part_1 {
                match part1(&input, preamble) {
                    Some(solution) => println!("Part1: {}", solution),
                    None => {
                        eprintln!("Part1, no solution found");
                        std::process::exit(1);
                    }
                };
            }
            if do_part_2 {
                match part2(&input, preamble) {
                    Some(solution) => println!("Part2: {}", solution),
                    None => {
                        eprintln!("Part2, no solution found");
                        std::process::exit(1);
                    }
                };
            }
        },
        Err(err) => eprintln!("Could not read input: {}", err),
    }
}