Skip to main content

aoc_rust/
lib.rs

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