diff --git a/2022/.assets/banner.png b/2022/.assets/banner.png
new file mode 100644
index 0000000..36ca006
Binary files /dev/null and b/2022/.assets/banner.png differ
diff --git a/2022/.assets/christmas_ferris.png b/2022/.assets/christmas_ferris.png
new file mode 100644
index 0000000..365527a
Binary files /dev/null and b/2022/.assets/christmas_ferris.png differ
diff --git a/2022/.cargo/config b/2022/.cargo/config
new file mode 100644
index 0000000..6731f8f
--- /dev/null
+++ b/2022/.cargo/config
@@ -0,0 +1,6 @@
+[alias]
+scaffold = "run --bin scaffold -- "
+download = "run --bin download -- "
+
+solve = "run --bin"
+all = "run"
diff --git a/2022/.devcontainer/devcontainer.json b/2022/.devcontainer/devcontainer.json
new file mode 100644
index 0000000..6043626
--- /dev/null
+++ b/2022/.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/2022/.editorconfig b/2022/.editorconfig
new file mode 100644
index 0000000..c075e7e
--- /dev/null
+++ b/2022/.editorconfig
@@ -0,0 +1,16 @@
+# 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
+
+[*.md]
+trim_trailing_whitespace = false
diff --git a/2022/.github/workflows/ci.yml b/2022/.github/workflows/ci.yml
new file mode 100644
index 0000000..dadca12
--- /dev/null
+++ b/2022/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: Continuous Integration
+
+on: push
+
+env:
+ CARGO_TERM_COLOR: always
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ name: Check
+ steps:
+ - uses: actions/checkout@v2
+ - name: cargo check
+ run: cargo check
+ test:
+ runs-on: ubuntu-latest
+ name: Test
+ steps:
+ - uses: actions/checkout@v2
+ - name: cargo test
+ run: cargo test
+ # uncomment to enable clippy lints
+ # clippy:
+ # runs-on: ubuntu-latest
+ # name: Lint (clippy)
+ # steps:
+ # - uses: actions/checkout@v2
+ # - name: cargo clippy
+ # run: cargo clippy -- -D warnings
diff --git a/2022/.github/workflows/readme-stars.yml b/2022/.github/workflows/readme-stars.yml
new file mode 100644
index 0000000..e1b2b1e
--- /dev/null
+++ b/2022/.github/workflows/readme-stars.yml
@@ -0,0 +1,29 @@
+name: Update readme βοΈ progress
+
+on:
+ schedule:
+ - cron: "51 */4 * * *" # Every 4 hours
+ workflow_dispatch:
+
+jobs:
+ update-readme:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ 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/2022/.gitignore b/2022/.gitignore
new file mode 100644
index 0000000..f2fd7aa
--- /dev/null
+++ b/2022/.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/2022/Cargo.lock b/2022/Cargo.lock
new file mode 100644
index 0000000..a53d473
--- /dev/null
+++ b/2022/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/2022/Cargo.toml b/2022/Cargo.toml
new file mode 100644
index 0000000..3ec21e9
--- /dev/null
+++ b/2022/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/2022/LICENSE b/2022/LICENSE
new file mode 100644
index 0000000..b97fd05
--- /dev/null
+++ b/2022/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/2022/README.md b/2022/README.md
new file mode 100644
index 0000000..216bb10
--- /dev/null
+++ b/2022/README.md
@@ -0,0 +1,203 @@
+
+
+# π 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 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:
+# Downloading input with aoc-cli...
+# Loaded session cookie from "/home/felix/.adventofcode.session".
+# Downloading input for day 1, 2021...
+# Saving puzzle input to "/tmp/tmp.MBdcAdL9Iw/input"...
+# Done!
+# ---
+# π Successfully wrote input to "src/inputs/01.txt"!
+```
+
+To download inputs for previous years, append the `--year/-y` flag. _(example: `cargo download 1 --year 2020`)_
+
+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
+```
+
+### Format code
+
+```sh
+cargo fmt
+```
+
+### Lint code
+
+```sh
+cargo clippy
+```
+
+## 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.5.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-for-a-day).
+
+### 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.
+
+### 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]:
+
+
+[^4]:
+
+
+[^5]:
+
diff --git a/2022/src/bin/download.rs b/2022/src/bin/download.rs
new file mode 100644
index 0000000..edb567d
--- /dev/null
+++ b/2022/src/bin/download.rs
@@ -0,0 +1,105 @@
+/*
+ * This file contains template code.
+ * There is no need to edit this file unless you want to change template functionality.
+ */
+use std::io::Write;
+use std::path::PathBuf;
+use std::{env::temp_dir, io, process::Command};
+use std::{fs, 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 remove_file(path: &PathBuf) {
+ #[allow(unused_must_use)]
+ {
+ fs::remove_file(path);
+ }
+}
+
+fn exit_with_status(status: i32, path: &PathBuf) -> ! {
+ remove_file(path);
+ process::exit(status);
+}
+
+fn main() {
+ // acquire a temp file path to write aoc-cli output to.
+ // aoc-cli expects this file not to be present - delete just in case.
+ let mut tmp_file_path = temp_dir();
+ tmp_file_path.push("aoc_input_tmp");
+ remove_file(&tmp_file_path);
+
+ let args = match parse_args() {
+ Ok(args) => args,
+ Err(e) => {
+ eprintln!("Failed to process arguments: {}", e);
+ exit_with_status(1, &tmp_file_path);
+ }
+ };
+
+ let day_padded = format!("{:02}", args.day);
+ let input_path = format!("src/inputs/{}.txt", day_padded);
+
+ // check if aoc binary exists and is callable.
+ if Command::new("aoc").arg("-V").output().is_err() {
+ eprintln!("command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it.");
+ exit_with_status(1, &tmp_file_path);
+ }
+
+ let mut cmd_args = vec![];
+
+ if let Some(year) = args.year {
+ cmd_args.push("--year".into());
+ cmd_args.push(year.to_string());
+ }
+
+ cmd_args.append(&mut vec![
+ "--input-file".into(),
+ tmp_file_path.to_string_lossy().to_string(),
+ "--day".into(),
+ args.day.to_string(),
+ "download".into(),
+ ]);
+
+ println!("Downloading input with >aoc {}", cmd_args.join(" "));
+
+ match Command::new("aoc").args(cmd_args).output() {
+ Ok(cmd_output) => {
+ io::stdout()
+ .write_all(&cmd_output.stdout)
+ .expect("could not write cmd stdout to pipe.");
+ io::stderr()
+ .write_all(&cmd_output.stderr)
+ .expect("could not write cmd stderr to pipe.");
+ if !cmd_output.status.success() {
+ exit_with_status(1, &tmp_file_path);
+ }
+ }
+ Err(e) => {
+ eprintln!("failed to spawn aoc-cli: {}", e);
+ exit_with_status(1, &tmp_file_path);
+ }
+ }
+
+ match fs::copy(&tmp_file_path, &input_path) {
+ Ok(_) => {
+ println!("---");
+ println!("π Successfully wrote input to \"{}\".", &input_path);
+ exit_with_status(0, &tmp_file_path);
+ }
+ Err(e) => {
+ eprintln!("could not copy downloaded input to input file: {}", e);
+ exit_with_status(1, &tmp_file_path);
+ }
+ }
+}
diff --git a/2022/src/bin/scaffold.rs b/2022/src/bin/scaffold.rs
new file mode 100644
index 0000000..0c77b4d
--- /dev/null
+++ b/2022/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!("{:02}", day);
+
+ let input_path = format!("src/inputs/{}.txt", day_padded);
+ let example_path = format!("src/examples/{}.txt", day_padded);
+ let module_path = format!("src/bin/{}.rs", day_padded);
+
+ 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/2022/src/examples/.keep b/2022/src/examples/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/2022/src/helpers.rs b/2022/src/helpers.rs
new file mode 100644
index 0000000..079071f
--- /dev/null
+++ b/2022/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/2022/src/lib.rs b/2022/src/lib.rs
new file mode 100644
index 0000000..23acd28
--- /dev/null
+++ b/2022/src/lib.rs
@@ -0,0 +1,125 @@
+/*
+ * 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!("{:02}.txt", day));
+
+ 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
+ );
+ }
+}
diff --git a/2022/src/main.rs b/2022/src/main.rs
new file mode 100644
index 0000000..45701ab
--- /dev/null
+++ b/2022/src/main.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::{ANSI_BOLD, ANSI_ITALIC, ANSI_RESET};
+use std::process::Command;
+
+fn main() {
+ let total: f64 = (1..=25)
+ .map(|day| {
+ let day = format!("{:02}", day);
+
+ let cmd = Command::new("cargo")
+ .args(["run", "--release", "--bin", &day])
+ .output()
+ .unwrap();
+
+ println!("----------");
+ println!("{}| Day {} |{}", ANSI_BOLD, 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!(
+ "{}Total:{} {}{:.2}ms{}",
+ ANSI_BOLD, ANSI_RESET, ANSI_ITALIC, total, ANSI_RESET
+ );
+}