Skip to main content

aoc_rust/
lib.rs

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