Skip to main content

aoc_rust/
lib.rs

1use std::env;
2use std::fmt::Display;
3use std::path::PathBuf;
4use std::process::{Command, Output};
5use std::time::{Duration, Instant};
6
7// ---------------------------------------------------------------------------
8// Macro Exports
9// ---------------------------------------------------------------------------
10
11/// Generates `main` for a day. Expects 'part_one' and 'part_two' functions.
12#[macro_export]
13macro_rules! solution {
14    ($year:expr, $day:expr) => {
15        #[allow(unused_imports)]
16        use $crate::debug;
17
18        fn main() {
19            match $crate::run($year, $day, part_one, part_two) {
20                Err(e) => eprintln!("error: {e}"),
21                Ok(()) => {}
22            };
23        }
24    };
25}
26
27/// 'eprintln!' which does not get compiled into release builds.
28#[macro_export]
29macro_rules! debug {
30    ($($t:tt)*) => {{
31        #[cfg(debug_assertions)]
32        {
33            eprintln!($($t)*);
34        }
35    }};
36}
37
38// ---------------------------------------------------------------------------
39// EntryPoint
40// ---------------------------------------------------------------------------
41
42pub fn run<F1, F2, T1, T2>(year: u16, day: u8, part_one: F1, part_two: F2) -> Result<(), String>
43where
44    F1: Fn(&str) -> Option<T1>,
45    T1: Display,
46    F2: Fn(&str) -> Option<T2>,
47    T2: Display,
48{
49    Cli::parse().command.execute(year, day, part_one, part_two)
50}
51
52// ---------------------------------------------------------------------------
53// CLI
54// ---------------------------------------------------------------------------
55
56struct Cli {
57    command: CliCommand,
58}
59
60enum CliCommand {
61    Run { submit: bool, example: bool },
62    Download {},
63}
64
65const HELP: &str = "\
66Usage: cargo run [--release] --bin <DAY> -- <COMMAND> [OPTIONS]
67
68Commands:
69  run            Run both parts and print the answers
70    --submit     Submit the answer of the highest solved part
71    --example    Use the example input instead of your puzzle input
72  download       Download the puzzle input for the day";
73
74impl Cli {
75    fn parse() -> Self {
76        match Self::try_parse() {
77            Ok(cli) => cli,
78            Err(e) => {
79                println!("{e}");
80                std::process::exit(2);
81            }
82        }
83    }
84
85    fn try_parse() -> Result<Self, String> {
86        let mut args = env::args().skip(1);
87
88        let command = match args.next().as_deref() {
89            Some("run") => {
90                let mut submit = false;
91                let mut example = false;
92
93                if args.any(|a| a == "--submit") {
94                    submit = true;
95                }
96                if args.any(|a| a == "--example") {
97                    example = true;
98                }
99
100                if submit && example {
101                    return Err("--submit can't be used with --example".into());
102                }
103
104                CliCommand::Run { submit, example }
105            }
106            Some("download") => CliCommand::Download {},
107            Some(_) => {
108                print!("{HELP}");
109                return Err("".into());
110            }
111            None => {
112                print!("{HELP}");
113                return Err("".into());
114            }
115        };
116
117        Ok(Self { command })
118    }
119}
120
121impl CliCommand {
122    fn execute<F1, F2, T1, T2>(self, year: u16, day: u8, p1: F1, p2: F2) -> Result<(), String>
123    where
124        F1: Fn(&str) -> Option<T1>,
125        T1: Display,
126        F2: Fn(&str) -> Option<T2>,
127        T2: Display,
128    {
129        match self {
130            CliCommand::Run { submit, example } => {
131                let input = get_input(day, example)?;
132                let answers = Answers::solve(&input, &(p1, p2));
133                answers.print(year, day);
134
135                if submit {
136                    let (part, answer) = answers.highest().ok_or("nothing to submit")?;
137                    crate::submit(year, day, part, &answer)?;
138                }
139            }
140            CliCommand::Download {} => download(year, day)?,
141        }
142        Ok(())
143    }
144}
145
146fn download(year: u16, day: u8) -> Result<(), String> {
147    let output = run_aoc_cli_output(
148        Command::new("aoc")
149            .args(["download", "--quiet", "--overwrite"])
150            .args(["--year", &year.to_string()])
151            .args(["--day", &day.to_string()])
152            .args(["--input-only"])
153            .args(["--input-file", &input_path(day).display().to_string()]),
154    )?;
155
156    if output.stderr.is_empty() {
157        println!("Successfully downloaded input for day {day}");
158    } else {
159        return Err(format!(
160            "download failed: {}",
161            String::from_utf8_lossy(&output.stderr).trim()
162        ));
163    }
164
165    Ok(())
166}
167
168fn run_aoc_cli_output(cmd: &mut Command) -> Result<Output, String> {
169    let output = cmd.output().map_err(|e| {
170        format!(
171            "couldn't spawn aoc-cli (is it installed? \
172            try `cargo install aoc-cli --version 0.12.0`): {e}"
173        )
174    })?;
175
176    if !output.status.success() {
177        let stderr = String::from_utf8_lossy(&output.stderr);
178        return Err(format!("aoc-cli exited with {}: {}", output.status, stderr));
179    }
180
181    Ok(output)
182}
183
184fn root() -> PathBuf {
185    PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default())
186}
187
188fn input_path(day: u8) -> PathBuf {
189    root().join(format!("data/inputs/day{day:02}.txt"))
190}
191
192fn example_path(day: u8) -> PathBuf {
193    root().join(format!("data/examples/day{day:02}.txt"))
194}
195
196fn get_input(day: u8, example: bool) -> Result<String, String> {
197    std::fs::read_to_string(if !example {
198        input_path(day)
199    } else {
200        example_path(day)
201    })
202    .map_err(|e| format!("failed to read input from file: {e}"))
203}
204
205// ---------------------------------------------------------------------------
206// Submitting
207// ---------------------------------------------------------------------------
208
209#[derive(Debug)]
210enum SubmissionResult {
211    Correct,
212    Wrong(Option<String>),
213    TooSoon(Option<String>),
214    WrongLevel,
215    Unknown,
216}
217
218impl From<&String> for SubmissionResult {
219    fn from(html: &String) -> Self {
220        if html.contains("That's the right answer") {
221            SubmissionResult::Correct
222        } else if html.contains("That's not the right answer") {
223            let hint = if html.contains("too high") {
224                Some("Too high".to_string())
225            } else if html.contains("too low") {
226                Some("Too low".to_string())
227            } else {
228                None
229            };
230            SubmissionResult::Wrong(hint)
231        } else if html.contains("You gave an answer too recently") {
232            let wait = html
233                .split_once("You have")
234                .and_then(|(_, rest)| rest.split_once("left"))
235                .map(|(wait, _)| wait.trim().to_string());
236            SubmissionResult::TooSoon(wait)
237        } else if html.contains("You don't seem to be solving the right level") {
238            SubmissionResult::WrongLevel
239        } else {
240            SubmissionResult::Unknown
241        }
242    }
243}
244
245impl Display for SubmissionResult {
246    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247        write!(f, "\n  ")?;
248        match self {
249            SubmissionResult::Correct => {
250                write!(f, "\x1b[92m※ \\(^o^)/※ \x1b[m That's the correct answer!")?;
251            }
252            SubmissionResult::Wrong(hint) => {
253                write!(f, "\x1b[31m(>︿<)\x1b[m Wrong answer.",)?;
254                if let Some(hint) = hint {
255                    write!(f, " {hint}.")?;
256                }
257            }
258            SubmissionResult::TooSoon(wait) => {
259                write!(f, "(-.-) Too soon.",)?;
260                if let Some(wait) = wait {
261                    write!(f, " Please wait {wait}.")?;
262                }
263            }
264            SubmissionResult::WrongLevel => {
265                write!(f, "¯\\_(•_•)_/¯ You seem to be solving the wrong level.")?;
266            }
267            SubmissionResult::Unknown => {
268                write!(f, "Could not deduce submission response from html",)?;
269            }
270        }
271        writeln!(f, "")?;
272        Ok(())
273    }
274}
275
276fn submit(year: u16, day: u8, part: u8, answer: &str) -> Result<(), String> {
277    println!("\nSubmitting \"{answer}\" for part {part}:");
278    let _output = run_aoc_cli_output(
279        Command::new("aoc")
280            .args(["submit", "--quiet"])
281            .args(["--year", &year.to_string()])
282            .args(["--day", &day.to_string()])
283            .arg(part.to_string())
284            .arg(answer),
285    )?;
286    println!(
287        "{}",
288        SubmissionResult::from(&String::from_utf8_lossy(&_output.stdout).to_string())
289    );
290    Ok(())
291}
292
293// ---------------------------------------------------------------------------
294// Puzzle Solving
295// ---------------------------------------------------------------------------
296
297struct Answer {
298    value: String,
299    time: Duration,
300}
301
302struct Answers {
303    part_one: Option<Answer>,
304    part_two: Option<Answer>,
305}
306
307pub trait Solution {
308    fn part_one(&self, input: &str) -> Option<String>;
309    fn part_two(&self, input: &str) -> Option<String>;
310}
311
312impl Answers {
313    fn solve<S>(input: &str, solution: &S) -> Self
314    where
315        S: Solution,
316    {
317        Self {
318            part_one: timed(|| solution.part_one(input)),
319            part_two: timed(|| solution.part_two(input)),
320        }
321    }
322
323    fn highest(&self) -> Option<(u8, String)> {
324        match self {
325            Self {
326                part_two: Some(Answer { value, .. }),
327                ..
328            } => Some((2, value.to_owned())),
329            Self {
330                part_one: Some(Answer { value, .. }),
331                part_two: None,
332            } => Some((1, value.to_owned())),
333            Self {
334                part_one: None,
335                part_two: None,
336            } => None,
337        }
338    }
339
340    fn print(&self, year: u16, day: u8) {
341        println!("{year} Day {day}:");
342        match self.part_one {
343            Some(ref a) => {
344                println!("  Part 1: {:<20} {:?}", a.value, a.time);
345            }
346            None => {
347                println!("  Part 1: unsolved");
348            }
349        };
350        match self.part_two {
351            Some(ref a) => {
352                println!("  Part 2: {:<20} {:?}", a.value, a.time);
353            }
354            None => {
355                println!("  Part 2: unsolved");
356            }
357        };
358    }
359}
360
361impl<F1, F2, T1, T2> Solution for (F1, F2)
362where
363    F1: Fn(&str) -> Option<T1>,
364    F2: Fn(&str) -> Option<T2>,
365    T1: Display,
366    T2: Display,
367{
368    fn part_one(&self, input: &str) -> Option<String> {
369        self.0(input).map(|a| a.to_string())
370    }
371
372    fn part_two(&self, input: &str) -> Option<String> {
373        self.1(input).map(|a| a.to_string())
374    }
375}
376
377fn timed<F>(f: F) -> Option<Answer>
378where
379    F: FnOnce() -> Option<String>,
380{
381    let start = Instant::now();
382    let value = f()?;
383    let time = start.elapsed();
384    Some(Answer { value, time })
385}