diff --git a/.assets/banner.png b/.assets/banner.png new file mode 100644 index 0000000..36ca006 Binary files /dev/null and b/.assets/banner.png differ diff --git a/.assets/christmas_ferris.png b/.assets/christmas_ferris.png new file mode 100644 index 0000000..365527a Binary files /dev/null and b/.assets/christmas_ferris.png differ diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 0000000..03ad300 --- /dev/null +++ b/.cargo/config @@ -0,0 +1,7 @@ +[alias] +scaffold = "run --bin scaffold --quiet --release -- " +download = "run --bin download --quiet --release -- " +read = "run --bin read --quiet --release -- " + +solve = "run --bin" +all = "run" diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..6043626 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,6 @@ +{ + "name": "rust-devcontainer", + "image": "mcr.microsoft.com/devcontainers/rust:latest", + "postCreateCommand": "rustc --version", + "remoteUser": "vscode" +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..560e94b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +# EditorConfig is awesome: http://EditorConfig.org +root = true + +[*] +indent_size = 4 +indent_style = space +end_of_line = lf +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.txt] +insert_final_newline = false +trim_trailing_whitespace = false + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7cfbf87 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,38 @@ +name: Continuous Integration + +on: push + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + runs-on: ubuntu-latest + name: Check + steps: + - uses: actions/checkout@v3 + - name: cargo check + run: cargo check + test: + runs-on: ubuntu-latest + name: Test + steps: + - uses: actions/checkout@v3 + - name: cargo test + run: cargo test + # uncomment to enable clippy lints + # clippy: + # runs-on: ubuntu-latest + # name: Lint (clippy) + # steps: + # - uses: actions/checkout@v3 + # - name: cargo clippy + # run: cargo clippy -- -D warnings + # uncoment to enable format checking + # fmt: + # runs-on: ubuntu-latest + # name: Format + # steps: + # - uses: actions/checkout@v3 + # - name: cargo fmt + # run: cargo fmt --check diff --git a/.github/workflows/readme-stars.yml b/.github/workflows/readme-stars.yml new file mode 100644 index 0000000..4b943fa --- /dev/null +++ b/.github/workflows/readme-stars.yml @@ -0,0 +1,30 @@ +name: Update readme ⭐️ progress + +on: + # !Please set a different minute than 51 if you enable this! + # schedule: + # - cron: "51 */6 * * *" # Every 6 hours + workflow_dispatch: + +jobs: + update-readme: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + if: ${{ env.AOC_ENABLED }} + env: + AOC_ENABLED: ${{ secrets.AOC_ENABLED }} + - uses: k2bd/advent-readme-stars@v1 + if: ${{ env.AOC_ENABLED }} + env: + AOC_ENABLED: ${{ secrets.AOC_ENABLED }} + with: + userId: ${{ secrets.AOC_USER_ID }} + sessionCookie: ${{ secrets.AOC_SESSION }} + year: ${{ secrets.AOC_YEAR }} + - uses: stefanzweifel/git-auto-commit-action@v4 + if: ${{ env.AOC_ENABLED }} + env: + AOC_ENABLED: ${{ secrets.AOC_ENABLED }} + with: + commit_message: "update readme progess" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2fd7aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + + +# Added by cargo + +/target + +# Advent of Code +# @see https://old.reddit.com/r/adventofcode/comments/k99rod/sharing_input_data_were_we_requested_not_to/gf2ukkf/?context=3 +/src/inputs +!/src/inputs/.keep diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..2475a54 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "vadimcn.vscode-lldb", + "rust-lang.rust-analyzer", + "serayuzgur.crates" + ] +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..0a9370e --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,50 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug unit tests in executable 'advent_of_code'", + "cargo": { + "args": ["test", "--no-run", "--bin=advent_of_code", "--package=advent_of_code"], + "filter": { + "name": "advent_of_code", + "kind": "bin" + } + }, + "args": [], + "cwd": "${workspaceFolder}" + }, + { + "type": "lldb", + "request": "launch", + "name": "Debug executable 'advent_of_code'", + "cargo": { + "args": ["build", "--bin=advent_of_code", "--package=advent_of_code"], + "filter": { + "name": "advent_of_code", + "kind": "bin" + } + }, + "args": ["1"], + "cwd": "${workspaceFolder}" + }, + { + "type": "lldb", + "request": "launch", + "name": "Debug unit tests in library 'advent_of_code'", + "cargo": { + "args": ["test", "--no-run", "--lib", "--package=advent_of_code"], + "filter": { + "name": "advent_of_code", + "kind": "lib" + } + }, + "args": [], + "cwd": "${workspaceFolder}" + } + ] +} diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a53d473 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,16 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "advent_of_code" +version = "0.8.0" +dependencies = [ + "pico-args", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3ec21e9 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "advent_of_code" +version = "0.8.0" +authors = ["Felix SpΓΆttel <1682504+fspoettel@users.noreply.github.com>"] +edition = "2021" +default-run = "advent_of_code" +publish = false +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +pico-args = "0.5.0" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b97fd05 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Felix Spoettel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..26851a4 --- /dev/null +++ b/README.md @@ -0,0 +1,230 @@ + + +# πŸŽ„ Advent of Code {year} + +Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.rust-lang.org/). + + + +--- + +## Template setup + +This template supports all major OS (macOS, Linux, Windows). + +### Create your repository πŸ“ + +1. Open [the template repository](https://github.com/fspoettel/advent-of-code-rust) on Github. +2. Click [Use this template](https://github.com/fspoettel/advent-of-code-rust/generate) and create your repository. +3. Clone your repository to your computer. + +### Setup rust πŸ’» + +1. Install the [Rust toolchain](https://www.rust-lang.org/tools/install). +2. (recommended) Install the [rust-analyzer](https://rust-analyzer.github.io/manual.html) extension for your code editor. +3. (optional) Install a native debugger. If you are using VS Code, [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb) is a good option. + +--- + +✨ You can start solving puzzles now! Head to the [Usage section](#usage) to see how to use this template. If you like, you can configure [some optional features](#optional-template-features). + +## Usage + +### Scaffold a day + +```sh +# example: `cargo scaffold 1` +cargo scaffold + +# output: +# Created module "src/bin/01.rs" +# Created empty input file "src/inputs/01.txt" +# Created empty example file "src/examples/01.txt" +# --- +# πŸŽ„ Type `cargo solve 01` to run your solution. +``` + +Individual solutions live in the `./src/bin/` directory as separate binaries. + +Every [solution](https://github.com/fspoettel/advent-of-code-rust/blob/main/src/bin/scaffold.rs#L11-L41) has _unit tests_ referencing its _example_ file. Use these unit tests to develop and debug your solution against the example input. For some puzzles, it might be easier to forgo the example file and hardcode inputs into the tests. + +When editing a solution, `rust-analyzer` will display buttons for running / debugging unit tests above the unit test blocks. + +### Download input & description for a day + +> **Note** +> This command requires [installing the aoc-cli crate](#download-puzzle-inputs-via-aoc-cli). + +```sh +# example: `cargo download 1` +cargo download + +# output: +# Loaded session cookie from "/Users//.adventofcode.session". +# Fetching puzzle for day 1, 2022... +# Saving puzzle description to "src/puzzles/01.md"... +# Downloading input for day 1, 2022... +# Saving puzzle input to "src/inputs/01.txt"... +# Done! +# --- +# πŸŽ„ Successfully wrote input to "src/inputs/01.txt". +# πŸŽ„ Successfully wrote puzzle to "src/puzzles/01.md". +``` + +To download inputs for previous years, append the `--year/-y` flag. _(example: `cargo download 1 --year 2020`)_ + +Puzzle descriptions are stored in `src/puzzles` as markdown files. Puzzle inputs are not checked into git. [Reasoning](https://old.reddit.com/r/adventofcode/comments/k99rod/sharing_input_data_were_we_requested_not_to/gf2ukkf/?context=3). + +### Run solutions for a day + +```sh +# example: `cargo solve 01` +cargo solve + +# output: +# Running `target/debug/01` +# πŸŽ„ Part 1 πŸŽ„ +# +# 6 (elapsed: 37.03Β΅s) +# +# πŸŽ„ Part 2 πŸŽ„ +# +# 9 (elapsed: 33.18Β΅s) +``` + +`solve` is an alias for `cargo run --bin`. To run an optimized version for benchmarking, append the `--release` flag. + +Displayed _timings_ show the raw execution time of your solution without overhead (e.g. file reads). + +### Run all solutions + +```sh +cargo all + +# output: +# Running `target/release/advent_of_code` +# ---------- +# | Day 01 | +# ---------- +# πŸŽ„ Part 1 πŸŽ„ +# +# 0 (elapsed: 170.00Β΅s) +# +# πŸŽ„ Part 2 πŸŽ„ +# +# 0 (elapsed: 30.00Β΅s) +# <...other days...> +# Total: 0.20ms +``` + +`all` is an alias for `cargo run`. To run an optimized version for benchmarking, use the `--release` flag. + +_Total timing_ is computed from individual solution _timings_ and excludes as much overhead as possible. + +### Run all solutions against the example input + +```sh +cargo test +``` + +To run tests for a specific day, append `--bin `, e.g. `cargo test --bin 01`. You can further scope it down to a specific part, e.g. `cargo test --bin 01 part_one`. + +### Format code + +```sh +cargo fmt +``` + +### Lint code + +```sh +cargo clippy +``` + +### Read puzzle description in terminal + +> **Note** +> This command requires [installing the aoc-cli crate](#download-puzzle-inputs-via-aoc-cli). + +```sh +# example: `cargo read 1` +cargo read + +# output: +# Loaded session cookie from "/Users//.adventofcode.session". +# Fetching puzzle for day 1, 2022... +# ...the input... +``` + +To read inputs for previous years, append the `--year/-y` flag. _(example: `cargo read 1 --year 2020`)_ + +## Optional template features + +### Download puzzle inputs via aoc-cli + +1. Install [`aoc-cli`](https://github.com/scarvalhojr/aoc-cli/) via cargo: `cargo install aoc-cli --version 0.7.0` +2. Create an `.adventofcode.session` file in your home directory and paste your session cookie[^1] into it. To get this, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in your Cookies under the Application or Storage tab, and copy out the `session` cookie value. + +Once installed, you can use the [download command](#download-input--description-for-a-day). + +### Check code formatting in CI + +Uncomment the `format` job in the `ci.yml` workflow to enable fmt checks in CI. + +### Enable clippy lints in CI + +Uncomment the `clippy` job in the `ci.yml` workflow to enable clippy checks in CI. + +### Automatically track ⭐️ progress in the readme + +This template includes [a Github action](https://github.com/k2bd/advent-readme-stars) that automatically updates the readme with your advent of code progress. + +To enable it, complete the following steps: + +#### 1. Create a private leaderboard + +Go to the leaderboard page of the year you want to track and click _Private Leaderboard_. If you have not created a leaderboard yet, create one by clicking _Create It_. Your leaderboard should be accessible under `https://adventofcode.com/{year}/leaderboard/private/view/{aoc_user_id}`. + +#### 2. Set repository secrets + +Go to the _Secrets_ tab in your repository settings and create the following secrets: + +- `AOC_ENABLED`: This variable controls whether the workflow is enabled. Set it to `true` to enable the progress tracker. +- `AOC_USER_ID`: Go to [this page](https://adventofcode.com/settings) and copy your user id. It's the number behind the `#` symbol in the first name option. Example: `3031` +- `AOC_YEAR`: the year you want to track. Example: `2021` +- `AOC_SESSION`: an active session[^2] for the advent of code website. To get this, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in your Cookies under the Application or Storage tab, and copy out the `session` cookie. + +✨ You can now run this action manually via the _Run workflow_ button on the workflow page. If you want the workflow to run automatically, uncomment the `schedule` section in the `readme-stars.yml` workflow file or add a `push` trigger. + +### Use VS Code to debug your code + +1. Install [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) and [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb). +2. Set breakpoints in your code. [^3] +3. Click _Debug_ next to the unit test or the _main_ function. [^4] +4. The debugger will halt your program at the specific line and allow you to inspect the local stack. [^5] + +## Useful crates + +- [itertools](https://crates.io/crates/itertools): Extends iterators with extra methods and adaptors. Frequently useful for aoc puzzles. +- [regex](https://crates.io/crates/regex): Official regular expressions implementation for Rust. + +A curated list of popular crates can be found on [blessred.rs](https://blessed.rs/crates). + +Do you have aoc-specific crate recommendations? [Share them!](https://github.com/fspoettel/advent-of-code-rust/edit/main/README.md) + +## Common pitfalls + +- **Integer overflows:** This template uses 32-bit integers by default because it is generally faster - for example when packed in large arrays or structs - than using 64-bit integers everywhere. For some problems, solutions for real input might exceed 32-bit integer space. While this is checked and panics in `debug` mode, integers [wrap](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-overflow) in `release` mode, leading to wrong output when running your solution. + +## Footnotes + +[^1]: The session cookie might expire after a while (~1 month) which causes the downloads to fail. To fix this issue, refresh the `.adventofcode.session` file. +[^2]: The session cookie might expire after a while (~1 month) which causes the automated workflow to fail. To fix this issue, refresh the AOC_SESSION secret. +[^3]: + Set a breakpoint + +[^4]: + Run debugger + +[^5]: + Inspect debugger state diff --git a/src/bin/download.rs b/src/bin/download.rs new file mode 100644 index 0000000..545eacd --- /dev/null +++ b/src/bin/download.rs @@ -0,0 +1,46 @@ +/* + * This file contains template code. + * There is no need to edit this file unless you want to change template functionality. + */ +use advent_of_code::aoc_cli; +use std::process; + +struct Args { + day: u8, + year: Option, +} + +fn parse_args() -> Result { + let mut args = pico_args::Arguments::from_env(); + Ok(Args { + day: args.free_from_str()?, + year: args.opt_value_from_str(["-y", "--year"])?, + }) +} + +fn main() { + let args = match parse_args() { + Ok(args) => args, + Err(e) => { + eprintln!("Failed to process arguments: {e}"); + process::exit(1); + } + }; + + if aoc_cli::check().is_err() { + eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."); + process::exit(1); + } + + match aoc_cli::download(args.day, args.year) { + Ok(cmd_output) => { + if !cmd_output.status.success() { + process::exit(1); + } + } + Err(e) => { + eprintln!("failed to spawn aoc-cli: {e}"); + process::exit(1); + } + } +} diff --git a/src/bin/read.rs b/src/bin/read.rs new file mode 100644 index 0000000..7fe21c4 --- /dev/null +++ b/src/bin/read.rs @@ -0,0 +1,46 @@ +/* + * This file contains template code. + * There is no need to edit this file unless you want to change template functionality. + */ +use advent_of_code::aoc_cli; +use std::process; + +struct Args { + day: u8, + year: Option, +} + +fn parse_args() -> Result { + let mut args = pico_args::Arguments::from_env(); + Ok(Args { + day: args.free_from_str()?, + year: args.opt_value_from_str(["-y", "--year"])?, + }) +} + +fn main() { + let args = match parse_args() { + Ok(args) => args, + Err(e) => { + eprintln!("Failed to process arguments: {e}"); + process::exit(1); + } + }; + + if aoc_cli::check().is_err() { + eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."); + process::exit(1); + } + + match aoc_cli::read(args.day, args.year) { + Ok(cmd_output) => { + if !cmd_output.status.success() { + process::exit(1); + } + } + Err(e) => { + eprintln!("failed to spawn aoc-cli: {e}"); + process::exit(1); + } + } +} diff --git a/src/bin/scaffold.rs b/src/bin/scaffold.rs new file mode 100644 index 0000000..2d04737 --- /dev/null +++ b/src/bin/scaffold.rs @@ -0,0 +1,114 @@ +/* + * This file contains template code. + * There is no need to edit this file unless you want to change template functionality. + */ +use std::{ + fs::{File, OpenOptions}, + io::Write, + process, +}; + +const MODULE_TEMPLATE: &str = r###"pub fn part_one(input: &str) -> Option { + None +} + +pub fn part_two(input: &str) -> Option { + None +} + +fn main() { + let input = &advent_of_code::read_file("inputs", DAY); + advent_of_code::solve!(1, part_one, input); + advent_of_code::solve!(2, part_two, input); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let input = advent_of_code::read_file("examples", DAY); + assert_eq!(part_one(&input), None); + } + + #[test] + fn test_part_two() { + let input = advent_of_code::read_file("examples", DAY); + assert_eq!(part_two(&input), None); + } +} +"###; + +fn parse_args() -> Result { + let mut args = pico_args::Arguments::from_env(); + args.free_from_str() +} + +fn safe_create_file(path: &str) -> Result { + OpenOptions::new().write(true).create_new(true).open(path) +} + +fn create_file(path: &str) -> Result { + OpenOptions::new().write(true).create(true).open(path) +} + +fn main() { + let day = match parse_args() { + Ok(day) => day, + Err(_) => { + eprintln!("Need to specify a day (as integer). example: `cargo scaffold 7`"); + process::exit(1); + } + }; + + let day_padded = format!("{day:02}"); + + let input_path = format!("src/inputs/{day_padded}.txt"); + let example_path = format!("src/examples/{day_padded}.txt"); + let module_path = format!("src/bin/{day_padded}.rs"); + + let mut file = match safe_create_file(&module_path) { + Ok(file) => file, + Err(e) => { + eprintln!("Failed to create module file: {e}"); + process::exit(1); + } + }; + + match file.write_all(MODULE_TEMPLATE.replace("DAY", &day.to_string()).as_bytes()) { + Ok(_) => { + println!("Created module file \"{}\"", &module_path); + } + Err(e) => { + eprintln!("Failed to write module contents: {e}"); + process::exit(1); + } + } + + match create_file(&input_path) { + Ok(_) => { + println!("Created empty input file \"{}\"", &input_path); + } + Err(e) => { + eprintln!("Failed to create input file: {e}"); + process::exit(1); + } + } + + match create_file(&example_path) { + Ok(_) => { + println!("Created empty example file \"{}\"", &example_path); + } + Err(e) => { + eprintln!("Failed to create example file: {e}"); + process::exit(1); + } + } + + println!("---"); + println!( + "πŸŽ„ Type `cargo solve {}` to run your solution.", + &day_padded + ); +} diff --git a/src/examples/.keep b/src/examples/.keep new file mode 100644 index 0000000..e69de29 diff --git a/src/helpers.rs b/src/helpers.rs new file mode 100644 index 0000000..079071f --- /dev/null +++ b/src/helpers.rs @@ -0,0 +1,4 @@ +/* + * Use this file if you want to extract helpers from your solutions. + * Example import from this file: `use advent_of_code::helpers::example_fn;`. + */ diff --git a/src/inputs/.keep b/src/inputs/.keep new file mode 100644 index 0000000..e69de29 diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6831a1e --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,234 @@ +/* + * This file contains template code. + * There is no need to edit this file unless you want to change template functionality. + * Prefer `./helpers.rs` if you want to extract code from your solutions. + */ +use std::env; +use std::fs; + +pub mod helpers; + +pub const ANSI_ITALIC: &str = "\x1b[3m"; +pub const ANSI_BOLD: &str = "\x1b[1m"; +pub const ANSI_RESET: &str = "\x1b[0m"; + +#[macro_export] +macro_rules! solve { + ($part:expr, $solver:ident, $input:expr) => {{ + use advent_of_code::{ANSI_BOLD, ANSI_ITALIC, ANSI_RESET}; + use std::fmt::Display; + use std::time::Instant; + + fn print_result(func: impl FnOnce(&str) -> Option, input: &str) { + let timer = Instant::now(); + let result = func(input); + let elapsed = timer.elapsed(); + match result { + Some(result) => { + println!( + "{} {}(elapsed: {:.2?}){}", + result, ANSI_ITALIC, elapsed, ANSI_RESET + ); + } + None => { + println!("not solved.") + } + } + } + + println!("πŸŽ„ {}Part {}{} πŸŽ„", ANSI_BOLD, $part, ANSI_RESET); + print_result($solver, $input); + }}; +} + +pub fn read_file(folder: &str, day: u8) -> String { + let cwd = env::current_dir().unwrap(); + + let filepath = cwd.join("src").join(folder).join(format!("{day:02}.txt")); + + let f = fs::read_to_string(filepath); + f.expect("could not open input file") +} + +fn parse_time(val: &str, postfix: &str) -> f64 { + val.split(postfix).next().unwrap().parse().unwrap() +} + +pub fn parse_exec_time(output: &str) -> f64 { + output.lines().fold(0_f64, |acc, l| { + if !l.contains("elapsed:") { + acc + } else { + let timing = l.split("(elapsed: ").last().unwrap(); + // use `contains` istd. of `ends_with`: string may contain ANSI escape sequences. + // for possible time formats, see: https://github.com/rust-lang/rust/blob/1.64.0/library/core/src/time.rs#L1176-L1200 + if timing.contains("ns)") { + acc // range below rounding precision. + } else if timing.contains("Β΅s)") { + acc + parse_time(timing, "Β΅s") / 1000_f64 + } else if timing.contains("ms)") { + acc + parse_time(timing, "ms") + } else if timing.contains("s)") { + acc + parse_time(timing, "s") * 1000_f64 + } else { + acc + } + } + }) +} + +/// copied from: https://github.com/rust-lang/rust/blob/1.64.0/library/std/src/macros.rs#L328-L333 +#[cfg(test)] +macro_rules! assert_approx_eq { + ($a:expr, $b:expr) => {{ + let (a, b) = (&$a, &$b); + assert!( + (*a - *b).abs() < 1.0e-6, + "{} is not approximately equal to {}", + *a, + *b + ); + }}; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_exec_time() { + assert_approx_eq!( + parse_exec_time(&format!( + "πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 74.13ns){}\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 50.00ns){}", + ANSI_RESET, ANSI_RESET + )), + 0_f64 + ); + + assert_approx_eq!( + parse_exec_time("πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 755Β΅s)\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 700Β΅s)"), + 1.455_f64 + ); + + assert_approx_eq!( + parse_exec_time("πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 70Β΅s)\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 1.45ms)"), + 1.52_f64 + ); + + assert_approx_eq!( + parse_exec_time( + "πŸŽ„ Part 1 πŸŽ„\n0 (elapsed: 10.3s)\nπŸŽ„ Part 2 πŸŽ„\n0 (elapsed: 100.50ms)" + ), + 10400.50_f64 + ); + } +} + +pub mod aoc_cli { + use std::{ + fmt::Display, + fs::create_dir_all, + process::{Command, Output, Stdio}, + }; + + pub enum AocCliError { + CommandNotFound, + CommandNotCallable, + BadExitStatus(Output), + IoError, + } + + impl Display for AocCliError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AocCliError::CommandNotFound => write!(f, "aoc-cli is not present in environment."), + AocCliError::CommandNotCallable => write!(f, "aoc-cli could not be called."), + AocCliError::BadExitStatus(_) => { + write!(f, "aoc-cli exited with a non-zero status.") + } + AocCliError::IoError => write!(f, "could not write output files to file system."), + } + } + } + + pub fn check() -> Result<(), AocCliError> { + Command::new("aoc") + .arg("-V") + .output() + .map_err(|_| AocCliError::CommandNotFound)?; + Ok(()) + } + + pub fn read(day: u8, year: Option) -> Result { + // TODO: output local puzzle if present. + let args = build_args("read", &[], day, year); + call_aoc_cli(&args) + } + + pub fn download(day: u8, year: Option) -> Result { + let input_path = get_input_path(day); + + let puzzle_path = get_puzzle_path(day); + create_dir_all("src/puzzles").map_err(|_| AocCliError::IoError)?; + + let args = build_args( + "download", + &[ + "--overwrite".into(), + "--input-file".into(), + input_path.to_string(), + "--puzzle-file".into(), + puzzle_path.to_string(), + ], + day, + year, + ); + + let output = call_aoc_cli(&args)?; + + if output.status.success() { + println!("---"); + println!("πŸŽ„ Successfully wrote input to \"{}\".", &input_path); + println!("πŸŽ„ Successfully wrote puzzle to \"{}\".", &puzzle_path); + Ok(output) + } else { + Err(AocCliError::BadExitStatus(output)) + } + } + + fn get_input_path(day: u8) -> String { + let day_padded = format!("{day:02}"); + format!("src/inputs/{day_padded}.txt") + } + + fn get_puzzle_path(day: u8) -> String { + let day_padded = format!("{day:02}"); + format!("src/puzzles/{day_padded}.md") + } + + fn build_args(command: &str, args: &[String], day: u8, year: Option) -> Vec { + let mut cmd_args = args.to_vec(); + + if let Some(year) = year { + cmd_args.push("--year".into()); + cmd_args.push(year.to_string()); + } + + cmd_args.append(&mut vec!["--day".into(), day.to_string(), command.into()]); + + cmd_args + } + + fn call_aoc_cli(args: &[String]) -> Result { + if cfg!(debug_assertions) { + println!("Calling >aoc with: {}", args.join(" ")); + } + + Command::new("aoc") + .args(args) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .output() + .map_err(|_| AocCliError::CommandNotCallable) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..1b6c855 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,45 @@ +/* + * This file contains template code. + * There is no need to edit this file unless you want to change template functionality. + */ +use advent_of_code::{ANSI_BOLD, ANSI_ITALIC, ANSI_RESET}; +use std::process::Command; + +fn main() { + let total: f64 = (1..=25) + .map(|day| { + let day = format!("{day:02}"); + + let mut args = vec!["run", "--bin", &day]; + if cfg!(not(debug_assertions)) { + args.push("--release"); + } + + let cmd = Command::new("cargo").args(&args).output().unwrap(); + + println!("----------"); + println!("{ANSI_BOLD}| Day {day} |{ANSI_RESET}"); + println!("----------"); + + let output = String::from_utf8(cmd.stdout).unwrap(); + let is_empty = output.is_empty(); + + println!( + "{}", + if is_empty { + "Not solved." + } else { + output.trim() + } + ); + + if is_empty { + 0_f64 + } else { + advent_of_code::parse_exec_time(&output) + } + }) + .sum(); + + println!("{ANSI_BOLD}Total:{ANSI_RESET} {ANSI_ITALIC}{total:.2}ms{ANSI_RESET}"); +}