Add solutions macro

main
mat ess 2022-12-04 19:20:16 -05:00
parent 1b08937fec
commit b561e148e0
1 changed files with 27 additions and 18 deletions

View File

@ -6,26 +6,19 @@ use anyhow::Error;
use chrono::{Datelike, Local}; use chrono::{Datelike, Local};
use pico_args::Arguments; use pico_args::Arguments;
fn main() -> Result<(), Error> { macro_rules! solutions {
let mut args = Arguments::from_env(); ($($all:tt),*) => {
let small = args.contains("--small"); const DAYS: usize = 0 $( + solutions!(@expand $all 1) )*;
let part = args.opt_free_from_str()?.unwrap_or(1); const SOLUTIONS: [Day; DAYS] = [
let day = args $($all),*
.opt_free_from_str()? ];
.unwrap_or_else(|| Local::now().day()); };
let small = if small { ".small" } else { "" }; (@expand $ignore:tt $e:expr) => {$e};
let path = format!("inputs/{day}{small}.txt");
let input = fs::read_to_string(path)?;
println!("running day {day} part {part}");
let result = SOLNS[day as usize - 1][part as usize - 1](input);
println!("{result}");
Ok(())
} }
type Part = fn(String) -> u64; type Part = fn(String) -> u64;
type Day = [Part; 2]; type Day = [Part; 2];
const DAYS: usize = 4; solutions! {
const SOLNS: [Day; DAYS] = [
[ [
// day 1 part 1 // day 1 part 1
|input| { |input| {
@ -136,8 +129,24 @@ const SOLNS: [Day; DAYS] = [
.map(|b| if b { 1 } else { 0 }) .map(|b| if b { 1 } else { 0 })
.sum() .sum()
}, },
], ]
]; }
fn main() -> Result<(), Error> {
let mut args = Arguments::from_env();
let small = args.contains("--small");
let part = args.opt_free_from_str()?.unwrap_or(1);
let day = args
.opt_free_from_str()?
.unwrap_or_else(|| Local::now().day());
let small = if small { ".small" } else { "" };
let path = format!("inputs/{day}{small}.txt");
let input = fs::read_to_string(path)?;
println!("running day {day} part {part}");
let result = SOLUTIONS[day as usize - 1][part as usize - 1](input);
println!("{result}");
Ok(())
}
fn make_ranges(input: String) -> Vec<(Range<u64>, Range<u64>)> { fn make_ranges(input: String) -> Vec<(Range<u64>, Range<u64>)> {
input input