use std::env;
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() {
match $crate::run(
::std::path::Path::new(env!("CARGO_MANIFEST_DIR")),
$year,
$day,
|input: &str| part_one(input).map(|a| a.to_string()),
|input: &str| part_two(input).map(|a| a.to_string()),
) {
Err(e) => eprintln!("error: {e}"),
Ok(()) => {}
};
}
};
}
#[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 {
Run { submit: bool, example: bool },
}
const HELP: &str = "\
Usage: cargo run [--release] --bin <DAY> -- [OPTIONS]
Options:
--help (-h) Print help.
--submit (-s) Submit the answer of the highest solved part
--example (-e) Use the example input instead of your puzzle input";
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 mut args = env::args().skip(1);
let command = match args.next().as_deref() {
Some(arg) => {
let mut submit = false;
let mut example = false;
if arg == "--help" || arg == "-h" {
print!("{HELP}");
return Err("".into());
}
if arg == "--submit" || arg == "-s" {
submit = true;
}
if arg == "--example" || arg == "-e" {
example = true;
}
CliCommand::Run { submit, example }
}
None => CliCommand::Run {
submit: false,
example: false,
},
};
Ok(Self { command })
}
}
impl CliCommand {
fn execute(self, puzzle: &Puzzle) -> Result<(), String> {
let Puzzle {
ref root,
year,
day,
part_one,
part_two,
} = *puzzle;
match self {
CliCommand::Run { submit, example } => {
let input = get_input(root, year, day, example)?;
let answers = Answers::solve(&input, &(part_one, part_two));
answers.print(year, day);
if submit {
let (part, answer) = answers.highest().ok_or("nothing to submit")?;
crate::submit(year, day, part, &answer)?;
}
}
}
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 })
}