summaryrefslogtreecommitdiff
path: root/2019/src/bin/day_7.rs
blob: 9b9177aac348c38e937e1cfcc913ea194f5c3bd7 (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
use aoc2019::*;
use rpds::list;
use rpds::list::List;
use rpds::vector::Vector;
use std::io;
use std::io::prelude::*;
use std::iter;
use std::process;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "Day 7: Amplification Circuit")]
/// Executes an Intcode program on 5 amplifiers, and finds the input that gives the max output
///
/// See https://adventofcode.com/2019/day/7 for details.
struct Opt {
    #[structopt(short = "f", long = "feedback-loop")]
    feedback_loop_mode: bool,
}

fn main() {
    let stdin = io::stdin();
    let opt = Opt::from_args();

    let program: IntcodeProgram = stdin
        .lock()
        .split(b',')
        .map(|x| exit_on_failed_assertion(x, "Error reading input"))
        .map(|x| exit_on_failed_assertion(String::from_utf8(x), "Input was not valid UTF-8"))
        .map(|x| exit_on_failed_assertion(x.trim().parse::<Intcode>(), "Invalid number"))
        .collect::<IntcodeProgram>();

    let result = exit_on_failed_assertion(
        find_max_power(&program, opt.feedback_loop_mode),
        "Program errored",
    );
    println!("{}", result);
}

fn exit_on_failed_assertion<A, E: std::error::Error>(data: Result<A, E>, message: &str) -> A {
    match data {
        Ok(data) => data,
        Err(e) => {
            eprintln!("{}: {}", message, e);
            process::exit(1);
        }
    }
}

fn find_max_power(
    program: &IntcodeProgram,
    feedback_loop_mode: bool,
) -> Result<Intcode, IntcodeProgramError> {
    PhaseSetting::all(feedback_loop_mode)
        .map(|phase| AmplifierArray::new(program, &phase).execute())
        .collect::<Result<Vec<Intcode>, _>>()
        .map(|powers| powers.into_iter().max().unwrap_or(Intcode::from(0)))
}

#[derive(Debug, Clone)]
struct PhaseSetting([Intcode; 5]);

impl PhaseSetting {
    fn all(feedback_loop_mode: bool) -> impl Iterator<Item = PhaseSetting> {
        if feedback_loop_mode {
            PhaseSetting::permute(5, 10)
        } else {
            PhaseSetting::permute(0, 5)
        }
    }

    fn permute(min: i32, max: i32) -> impl Iterator<Item = PhaseSetting> {
        // This is an absolutely atrocious way to do the permutation,
        // but luckily it's only 5 elements long.
        (min..max)
            .flat_map(move |a| {
                (min..max).flat_map(move |b| {
                    (min..max).flat_map(move |c| {
                        (min..max).flat_map(move |d| {
                            (min..max).map(move |e| {
                                PhaseSetting([a.into(), b.into(), c.into(), d.into(), e.into()])
                            })
                        })
                    })
                })
            })
            .filter(move |phase| (min..max).all(|x| phase.0.contains(&x.into())))
    }
}

#[derive(Debug, Clone)]
struct AmplifierArray {
    amplifiers: Vector<IntcodeProgram>,
}

impl AmplifierArray {
    fn new(program: &IntcodeProgram, phase: &PhaseSetting) -> AmplifierArray {
        AmplifierArray {
            amplifiers: (0..5)
                .map(|n| AmplifierArray::new_amp(program, phase, n))
                .collect(),
        }
    }

    fn new_amp(program: &IntcodeProgram, phase: &PhaseSetting, n: usize) -> IntcodeProgram {
        if n == 0 {
            program.with_input(list![phase.0[n].clone(), Intcode::from(0)])
        } else {
            program.with_input(list![phase.0[n].clone()])
        }
    }

    fn execute(&self) -> Result<Intcode, IntcodeProgramError> {
        self.run_to_termination().output_into_result()
    }

    fn run_to_termination(&self) -> AmplifierArray {
        iter::successors(Some(self.clone()), |p| Some(p.next()))
            .find(|p| p.is_terminated())
            .unwrap() // successors doesn't terminate, so this will never be none.
    }

    fn output_into_result(&self) -> Result<Intcode, IntcodeProgramError> {
        self.amplifiers
            .first()
            .and_then(|amp| amp.input.first().cloned())
            .ok_or(IntcodeProgramError::Unknown)
    }

    fn is_terminated(&self) -> bool {
        self.amplifiers.last().map(|amp| amp.halted).unwrap_or(true)
    }

    fn next(&self) -> AmplifierArray {
        self.run_amplifiers().update_inputs()
    }

    fn run_amplifiers(&self) -> AmplifierArray {
        AmplifierArray {
            amplifiers: self
                .amplifiers
                .iter()
                .map(|amp| amp.run_to_termination_or_input())
                .collect(),
        }
    }

    fn update_inputs(&self) -> AmplifierArray {
        AmplifierArray {
            amplifiers: self
                .amplifiers
                .iter()
                .fold(
                    (
                        Vector::new(),
                        self.amplifiers
                            .last()
                            .map(|a| a.output.iter().cloned().collect::<List<Intcode>>())
                            .unwrap_or(List::new()),
                    ),
                    |(amps, piped_input), next_amp| {
                        (
                            amps.push_back(
                                next_amp
                                    .with_additional_input(piped_input)
                                    .with_cleared_output(),
                            ),
                            next_amp.output.iter().cloned().collect::<List<Intcode>>(),
                        )
                    },
                )
                .0,
        }
    }
}