use std::fmt::Display;
use std::path::Path;
use std::path::PathBuf;
use std::process::{Command, Output};
use std::time::{Duration, Instant};
pub type Solver = fn(&str) -> Option<String>;
#[macro_export]
macro_rules! solution {
($year:expr, $day:expr) => {
#[allow(unused_imports)]
use $crate::debug;
fn main() {
if let ::core::result::Result::Err(e) = $crate::run(
match ::core::option_env!("CARGO_MANIFEST_DIR") {
::core::option::Option::Some(dir) => ::std::path::Path::new(dir),
::core::option::Option::None => ::std::path::Path::new("."),
},
$year,
$day,
|input: &str| part_one(input).map(|a| ::std::string::ToString::to_string(&a)),
|input: &str| part_two(input).map(|a| ::std::string::ToString::to_string(&a)),
) {
::std::eprintln!("error: {e}");
::std::process::exit(1);
}
}
};
}
#[macro_export]
macro_rules! debug {
($($t:tt)*) => {{
#[cfg(debug_assertions)]
{
eprintln!($($t)*);
}
}};
}
struct Puzzle {
root: PathBuf,
year: u16,
day: u8,
part_one: Solver,
part_two: Solver,
}
pub fn run(
root: &Path,
year: u16,
day: u8,
part_one: Solver,
part_two: Solver,
) -> Result<(), String> {
let puzzle = Puzzle {
root: root.to_path_buf(),
year,
day,
part_one,
part_two,
};
Cli::parse().command.execute(&puzzle)
}
struct Cli {
command: CliCommand,
}
enum CliCommand {
Help,
Run(Options),
}
#[derive(Debug, Default)]
enum Input {
#[default]
Puzzle,
Example,
File(PathBuf),
}
#[derive(Debug, Default)]
struct Options {
input: Input,
submit: bool,
}
const HELP: &str = "\
Usage: <DAY> [OPTIONS]
cargo run [--release] --bin <DAY> -- [OPTIONS]
Options:
-s, --submit Submit the answer of the highest solved part
-e, --example Use the example input instead of your puzzle input
-f, --file <PATH> Use the input file at <PATH>
-h, --help Print help
By default, the puzzle input is read from data/inputs/<DAY>.txt.";
impl Cli {
fn parse() -> Self {
match Self::try_parse() {
Ok(cli) => cli,
Err(e) => {
println!("{e}");
std::process::exit(2);
}
}
}
fn try_parse() -> Result<Self, String> {
let args: Vec<String> = std::env::args().skip(1).collect();
let args: Vec<&str> = args.iter().map(String::as_str).collect();
Ok(Cli {
command: parse(&args, Options::default())?,
})
}
}
fn parse(args: &[&str], opts: Options) -> Result<CliCommand, String> {
match args {
[] => Ok(CliCommand::Run(opts)),
["-h" | "--help", ..] => Ok(CliCommand::Help),
["-s" | "--submit", rest @ ..] => parse(
rest,
Options {
submit: true,
..opts
},
),
["-e" | "--example", rest @ ..] => parse(
rest,
Options {
input: Input::Example,
..opts
},
),
["f" | "--file", path, rest @ ..] => parse(
rest,
Options {
input: Input::File(PathBuf::from(path)),
..opts
},
),
["-f" | "--file"] => Err("--file needs path".into()),
[other, ..] => Err(format!("unknown option {other}")),
}
}
impl CliCommand {
fn execute(self, puzzle: &Puzzle) -> Result<(), String> {
let Puzzle {
ref root,
year,
day,
part_one,
part_two,
} = *puzzle;
match self {
CliCommand::Run(opts) => {
let input = match opts.input {
Input::Puzzle => get_input(root, year, day, false)?,
Input::Example => get_input(root, year, day, true)?,
Input::File(path) => std::fs::read_to_string(&path)
.map_err(|e| format!("failed to read from {}: {e}", path.display()))?,
};
let answers = Answers::solve(&input, &(part_one, part_two));
answers.print(year, day);
if opts.submit {
let (part, answer) = answers.highest().ok_or("nothing to submit")?;
crate::submit(year, day, part, &answer)?;
}
}
CliCommand::Help => {
println!("{HELP}");
}
}
Ok(())
}
}
fn run_aoc_cli_output(cmd: &mut Command) -> Result<Output, String> {
let output = cmd.output().map_err(|e| {
format!(
"couldn't spawn aoc-cli (is it installed? \
try `cargo install aoc-cli --version 0.12.0`): {e}"
)
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("aoc-cli exited with {}: {}", output.status, stderr));
}
Ok(output)
}
fn get_input(root: &Path, _year: u16, day: u8, example: bool) -> Result<String, String> {
let path = if example {
root.join(format!("data/examples/day{day:02}.txt"))
} else {
root.join(format!("data/inputs/day{day:02}.txt"))
};
std::fs::read_to_string(&path)
.map_err(|e| format!("failed to read from {}: {e}", path.display()))
}
#[derive(Debug)]
enum SubmissionResult {
Correct,
Wrong(Option<String>),
TooSoon(Option<String>),
WrongLevel,
Unknown,
}
impl From<&String> for SubmissionResult {
fn from(html: &String) -> Self {
if html.contains("That's the right answer") {
SubmissionResult::Correct
} else if html.contains("That's not the right answer") {
let hint = if html.contains("too high") {
Some("Too high".to_string())
} else if html.contains("too low") {
Some("Too low".to_string())
} else {
None
};
SubmissionResult::Wrong(hint)
} else if html.contains("You gave an answer too recently") {
let wait = html
.split_once("You have")
.and_then(|(_, rest)| rest.split_once("left"))
.map(|(wait, _)| wait.trim().to_string());
SubmissionResult::TooSoon(wait)
} else if html.contains("You don't seem to be solving the right level") {
SubmissionResult::WrongLevel
} else {
SubmissionResult::Unknown
}
}
}
impl Display for SubmissionResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "\n ")?;
match self {
SubmissionResult::Correct => {
write!(f, "\x1b[92m*\\(^o^)/*\x1b[m That's the correct answer!")?;
}
SubmissionResult::Wrong(hint) => {
write!(f, "\x1b[31m(>︿<)\x1b[m Wrong answer.",)?;
if let Some(hint) = hint {
write!(f, " {hint}.")?;
}
}
SubmissionResult::TooSoon(wait) => {
write!(f, "(-.-) Too soon.",)?;
if let Some(wait) = wait {
write!(f, " Please wait {wait}.")?;
}
}
SubmissionResult::WrongLevel => {
write!(f, "¯\\_(•_•)_/¯ You seem to be solving the wrong level.")?;
}
SubmissionResult::Unknown => {
write!(f, "Could not deduce submission response from html",)?;
}
}
writeln!(f, "")?;
Ok(())
}
}
fn submit(year: u16, day: u8, part: u8, answer: &str) -> Result<(), String> {
println!("\nSubmitting \"{answer}\" for part {part}:");
let _output = run_aoc_cli_output(
Command::new("aoc")
.args(["submit", "--quiet"])
.args(["--year", &year.to_string()])
.args(["--day", &day.to_string()])
.arg(part.to_string())
.arg(answer),
)?;
println!(
"{}",
SubmissionResult::from(&String::from_utf8_lossy(&_output.stdout).to_string())
);
Ok(())
}
struct Answer {
value: String,
time: Duration,
}
struct Answers {
part_one: Option<Answer>,
part_two: Option<Answer>,
}
pub trait Solution {
fn part_one(&self, input: &str) -> Option<String>;
fn part_two(&self, input: &str) -> Option<String>;
}
impl Answers {
fn solve<S>(input: &str, solution: &S) -> Self
where
S: Solution,
{
Self {
part_one: timed(|| solution.part_one(input)),
part_two: timed(|| solution.part_two(input)),
}
}
fn highest(&self) -> Option<(u8, String)> {
match self {
Self {
part_two: Some(Answer { value, .. }),
..
} => Some((2, value.to_owned())),
Self {
part_one: Some(Answer { value, .. }),
part_two: None,
} => Some((1, value.to_owned())),
Self {
part_one: None,
part_two: None,
} => None,
}
}
fn print(&self, year: u16, day: u8) {
println!("{year} Day {day}:");
match self.part_one {
Some(ref a) => {
println!(" Part 1: {:<20} {:.2?}", a.value, a.time);
}
None => {
println!(" Part 1: unsolved");
}
};
match self.part_two {
Some(ref a) => {
println!(" Part 2: {:<20} {:.2?}", a.value, a.time);
}
None => {
println!(" Part 2: unsolved");
}
};
}
}
impl<F1, F2, T1, T2> Solution for (F1, F2)
where
F1: Fn(&str) -> Option<T1>,
F2: Fn(&str) -> Option<T2>,
T1: Display,
T2: Display,
{
fn part_one(&self, input: &str) -> Option<String> {
self.0(input).map(|a| a.to_string())
}
fn part_two(&self, input: &str) -> Option<String> {
self.1(input).map(|a| a.to_string())
}
}
fn timed<F>(f: F) -> Option<Answer>
where
F: FnOnce() -> Option<String>,
{
let start = Instant::now();
let value = f()?;
let time = start.elapsed();
Some(Answer { value, time })
}