- Notifications
You must be signed in to change notification settings - Fork0
🎄Starter template for solving Advent of Code in Rust.
License
PaulTreitel/advent-of-code-rust-template
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Solutions forAdvent of Code inRust.
This template supports all major OS (macOS, Linux, Windows).
- Openthe template repository on Github.
- ClickUse this template and create your repository.
- Clone your repository to your computer.
- Install theRust toolchain.
- (recommended) Install therust-analyzer extension for your code editor.
- (optional) Install a native debugger. If you are using VS Code,CodeLLDB is a good option.
✨ You can start solving puzzles now! Head to theUsage section to see how to use this template. If you like, you can configuresome optional features.
# example: `cargo new-year 2024`cargo new-year<year># output:# Created 2024 workspace project.# Set the repository's current working year to 2024.# ---# 🎄 Type `cargo scaffold <day>` to get started on the year.# 🎄 Or type `cargo set-year <year>` to switch to working on a different year.
A year has its own directory./<year>/ within the repository. This subdirectory behaves as its own crate with its own dependencies separate from the repository root. Its contents are copied from the directory./year_template/ so if you add dependencies or utility files there they will be copied into any new year project you create. You can run all of the following commands from within the./<year>/ directory. You can also run the Advent of Code custom commands from the project root directory so long as the repository year is set to<year> (see theset-year command).
# example: `cargo scaffold 1`cargo scaffold<day># output:# Created module file "src/bin/01.rs"# Created empty input file "data/inputs/01.txt"# Created empty example file "data/examples/01.txt"# ---# 🎄 Type `cargo solve 01` to run your solution.
Individual solutions live in the./src/bin/ directory as separate binaries.Inputs andexamples live in the the./data directory.
Everysolution hastests referencing itsexample file in./data/examples. Use these tests to develop and debug your solutions against the example input. In VS Code,rust-analyzer will display buttons for running / debugging these unit tests above the unit test blocks.
Tip
If a day has multiple example inputs, you can use theread_file_part() helper in your tests instead ofread_file(). If this e.g. applies to day 1, you can create a second example file01-2.txt and invoke the helper likelet result = part_two(&advent_of_code::template::read_file_part("examples", DAY, 2));. This supports an arbitrary number of example files.
Important
This requiresinstalling the aoc-cli crate.
You can automatically download puzzle input and description by either appending the--download flag toscaffold (e.g.cargo scaffold 4 --download) or with the separatedownload command:
# example: `cargo download 1`cargo download<day># output:# [INFO aoc] 🎄 aoc-cli - Advent of Code command-line tool# [INFO aoc_client] 🎅 Saved puzzle to 'data/puzzles/01.md'# [INFO aoc_client] 🎅 Saved input to 'data/inputs/01.txt'# ---# 🎄 Successfully wrote input to "data/inputs/01.txt".# 🎄 Successfully wrote puzzle to "data/puzzles/01.md".
# example: `cargo try 1`cargo try<day># Finished `test` profile [unoptimized + debuginfo] target(s) in 0.84s# Running unittests src/bin/01.rs (target/debug/deps/01-faca1023160cfe39)# running 2 tests# test tests::test_part_two ... ok# test tests::test_part_one ... ok## test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Thetry command runs the tests for your solution against the example puzzle inputs. You can narrow it down to a specific test or set of tests, e.g.cargo try 1 part_one to run just the part one test.
# example: `cargo solve 01`cargo solve<day># output:# Finished dev [unoptimized + debuginfo] target(s) in 0.13s# Running `target/debug/01`# Part 1: 42 (166.0ns)# Part 2: 42 (41.0ns)
Thesolve command runs your solution against real puzzle inputs. To run an optimized build of your code, append the--release flag as with any other rust program.
Important
This requiresinstalling the aoc-cli crate.
Append the--submit <part> option to thesolve command to submit your solution for checking.
cargo all# output:# Running `target/release/advent_of_code`# ----------# | Day 01 |# ----------# Part 1: 42 (19.0ns)# Part 2: 42 (19.0ns)# <...other days...># Total: 0.20ms
This runs all solutions for a year sequentially and prints output to the command-line. Same as for thesolve command, the--release flag runs an optimized build.
# example: `cargo time 8 --store`cargotime<day> [--all] [--store]# output:# Day 08# ------# Part 1: 1 (39.0ns @ 10000 samples)# Part 2: 2 (39.0ns @ 10000 samples)## Total (Run): 0.00ms## Stored updated benchmarks.
Thecargo time command allows you to benchmark your code and store timings in the readme. When benching, the runner will run your code between10 and10.000 times, depending on execution time of first execution, and print the average execution time.
cargo time has three modes of execution:
cargo timewithout arguments incrementally benches solutions that do not have been stored in the readme yet and skips the rest.cargo time <day>benches a single solution.cargo time --allbenches all solutions.
By default,cargo time does not write to the readme. In order to do so, append the--store flag:cargo time --store.
Please note that these are notscientific benchmarks, understand them as a fun approximation. 😉 Timings, especially in the microseconds range, might change a bit between invocations.
cargotestTo run tests for a specific day, append--bin <day>, e.g.cargo test --bin 01. You can further scope it down to a specific part, e.g.cargo test --bin 01 part_one. This command only works within a given year's subdirectory (such as running all the 2024 tests by runningcargo test in./2024/).
Important
This command requiresinstalling the aoc-cli crate.
# example: `cargo read 1`cargoread<day># output:# Loaded session cookie from "/Users/<snip>/.adventofcode.session".# Fetching puzzle for day 1, 2022...# ...the input...
Important
This command requiresinstalling the aoc-cli crate.
During december, thetoday shorthand command can be used to:
- scaffold a solution for the current day
- download its input
- and read the puzzle
in one go.
# example: `cargo today` on December 1stcargo today# output:# Created module file "src/bin/01.rs"# Created empty input file "data/inputs/01.txt"# Created empty example file "data/examples/01.txt"# ---# 🎄 Type `cargo solve 01` to run your solution.# [INFO aoc] 🎄 aoc-cli - Advent of Code command-line tool# [INFO aoc_client] 🎅 Saved puzzle to 'data/puzzles/01.md'# [INFO aoc_client] 🎅 Saved input to 'data/inputs/01.txt'# ---# 🎄 Successfully wrote input to "data/inputs/01.txt".# 🎄 Successfully wrote puzzle to "data/puzzles/01.md".## Loaded session cookie from "/Users/<snip>/.adventofcode.session".# Fetching puzzle for day 1, 2022...# ...the input...
# example: `cargo set-year 2024`cargo set-year 2024# output:# Set repository to year 2024.
This sets the repository's "configured year" which is tracked in./.cargo/config.toml. When running Advent of Code custom commands from the project's root directory, it will execute them for this year. Creating a new year subproject automatically sets the repository's year to that year.
# example: `cargo get-year` when you've been working on 2024cargo get-year# output:# The repository is currently set to 2024.
cargo fmt
Run this inside the./<year> directory.
cargo clippy
Run this inside the./<year> directory.
- Install
aoc-clivia cargo:cargo install aoc-cli --version 0.12.0 - Create the file
<home_directory>/.adventofcode.sessionand paste your session cookie into it. To retrieve the session cookie, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look inCookies under theApplication orStorage tab, and copy out thesessioncookie value.1
Once installed, you can use thedownload command, the read command, and automatically submit solutions via the--submit flag.
This template includesa Github action that automatically updates the readme with your advent of code progress.
To enable it, complete the following steps:
Go to the leaderboard page of the year you want to track and clickPrivate Leaderboard. If you have not created a leaderboard yet, create one by clickingCreate It. Your leaderboard should be accessible underhttps://adventofcode.com/{year}/leaderboard/private/view/{aoc_user_id}.
Go to theSecrets tab in your repository settings and create the following secrets:
AOC_USER_ID: Go tothis page 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 session2 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 thesessioncookie.
Go to theVariables tab in your repository settings and create the following variable:
AOC_ENABLED: This variable controls whether the workflow is enabled. Set it totrueto enable the progress tracker. After you complete AoC or no longer work on it, you can set this tofalseto disable the CI.
✨ You can now run this action manually via theRun workflow button on the workflow page. If you want the workflow to run automatically, uncomment theschedule section in thereadme-stars.yml workflow file or add apush trigger.
Uncomment the respective sections in theci.yml workflow.
If you are not only interested in the runtime of your solution, but also its memory allocation profile, you can use the template'sDHAT integration to analyze it. In order to activate DHAT, call thesolve command with the--dhat flag.
cargo solve 1 --dhat# output:# Running `target/dhat/1`# dhat: Total: 276 bytes in 3 blocks# dhat: At t-gmax: 232 bytes in 2 blocks# dhat: At t-end: 0 bytes in 0 blocks# dhat: The data has been saved to dhat-heap.json, and is viewable with dhat/dh_view.html# Part 1: 9001 (4.1ms)
The command will output some basic stats to the command-line and generate adhat-heap.json report in the repo root directory.
You can pass the report a tool likedh-view to view a detailed breakdown of heap allocations.
- Installrust-analyzer andCodeLLDB.
- Set breakpoints in your code.3
- ClickDebug next to the unit test or themain function.4
- The debugger will halt your program at the specific line and allow you to inspect the local stack.5
- itertools: Extends iterators with extra methods and adaptors. Frequently useful for aoc puzzles.
- regex: Official regular expressions implementation for Rust.
A curated list of popular crates can be found onblessed.rs.
Do you have aoc-specific crate recommendations?Share them!
Footnotes
The session cookie might expire after a while (~1 month) which causes the downloads to fail. To fix this issue, refresh the
.adventofcode.sessionfile.↩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.↩
↩
↩
↩
About
🎄Starter template for solving Advent of Code in Rust.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- Rust100.0%
