Git Product home page Git Product logo

advent-of-code-rust's Introduction

πŸŽ„ Advent of Code {year}

Solutions for Advent of Code in Rust.


Template setup

This template supports all major OS (macOS, Linux, Windows).

πŸ“ Create your repository

  1. Open the template repository on Github.
  2. Click Use this template and create your repository.
  3. Clone your repository to your computer.
  4. If you are solving a previous year's advent of code, change the AOC_YEAR variable in .cargo/config.toml to reflect the year you are solving.

πŸ’» Setup rust

  1. Install the Rust toolchain.
  2. (recommended) Install the rust-analyzer extension for your code editor.
  3. (optional) Install a native debugger. If you are using VS Code, CodeLLDB is a good option.

✨ You can start solving puzzles now! Head to the Usage section to see how to use this template. If you like, you can configure some optional features.

Usage

➑️ Scaffold a day

# 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 and examples live in the the ./data directory.

Every solution has tests referencing its example 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 the read_file_part() helper in your tests instead of read_file(). If this e.g. applies to day 1, you can create a second example file 01-2.txt and invoke the helper like let result = part_two(&advent_of_code::template::read_file_part("examples", DAY, 2));. This supports an arbitrary number of example files.

➑️ Download input for a day

Important

This requires installing the aoc-cli crate.

You can automatically download puzzle input and description by either appending the --download flag to scaffold (e.g. cargo scaffold 4 --download) or with the separate download 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".

➑️ Run solutions for a day

# 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)

The solve 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.

Submitting solutions

Important

This requires installing the aoc-cli crate.

Append the --submit <part> option to the solve command to submit your solution for checking.

➑️ Run all solutions

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 sequentially and prints output to the command-line. Same as for the solve command, the --release flag runs an optimized build.

➑️ Benchmark your solutions

# example: `cargo time 8 --store`
cargo time <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.

The cargo time command allows you to benchmark your code and store timings in the readme. When benching, the runner will run your code between 10 and 10.000 times, depending on execution time of first execution, and print the average execution time.

cargo time has three modes of execution:

  1. cargo time without arguments incrementally benches solutions that do not have been stored in the readme yet and skips the rest.
  2. cargo time <day> benches a single solution.
  3. cargo time --all benches 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 not scientific benchmarks, understand them as a fun approximation. πŸ˜‰ Timings, especially in the microseconds range, might change a bit between invocations.

➑️ Run all tests

cargo test

To 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.

➑️ Read puzzle description

Important

This command requires installing the aoc-cli crate.

# example: `cargo read 1`
cargo read <day>

# output:
# Loaded session cookie from "/Users/<snip>/.adventofcode.session".
# Fetching puzzle for day 1, 2022...
# ...the input...

➑️ Scaffold, download & read the current aoc day

Important

This command requires installing the aoc-cli crate.

During december, the today 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 1st
cargo 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...

➑️ Format code

cargo fmt

➑️ Lint code

cargo clippy

Optional template features

Configure aoc-cli integration

  1. Install aoc-cli via cargo: cargo install aoc-cli --version 0.12.0
  2. Create the file <home_directory>/.adventofcode.session and 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 in Cookies under the Application or Storage tab, and copy out the session cookie value. 1

Once installed, you can use the download command, the read command, and automatically submit solutions via the --submit flag.

Automatically track ⭐️ progress in the readme

This template includes a Github action 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_USER_ID: Go to this 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 the session cookie.

Go to the Variables tab in your repository settings and create the following variable:

  • AOC_ENABLED: This variable controls whether the workflow is enabled. Set it to true to enable the progress tracker. After you complete AoC or no longer work on it, you can set this to false to disable the CI.

✨ 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.

Enable code formatting / clippy checks in the CI

Uncomment the respective sections in the ci.yml workflow.

Use DHAT to profile heap allocations

If you are not only interested in the runtime of your solution, but also its memory allocation profile, you can use the template's DHAT integration to analyze it. In order to activate DHAT, call the solve 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 a dhat-heap.json report in the repo root directory.

You can pass the report a tool like dh-view to view a detailed breakdown of heap allocations.

Use VS Code to debug your code

  1. Install rust-analyzer and CodeLLDB.
  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: 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 on blessred.rs.

Do you have aoc-specific crate recommendations? Share them!

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 in release mode, leading to wrong output when running your solution.

Footnotes

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 ↩

advent-of-code-rust's People

Contributors

andypymont avatar fspoettel avatar kcaffrey avatar mfornet avatar mjclarke94 avatar peteanning avatar pokeylope avatar tguichaoua avatar tomvaneyck avatar wasabi375 avatar wmmc88 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

advent-of-code-rust's Issues

CRLF vs LF issue for input str

If your IDE defaults to using CRLF instead of LF, which generally happens in Windows, the input str has an extra character at the end on all lines except the last one.

image

Like in the image, line 1 shows a length of 22 while it's 21, and line 2 shows the correct length as it is the last. It would be nice to see this template handle that issue as it causes regex expressions using \n to not work properly.

Feature Request: cargo scaffold + cargo download

Thank you for creating this template!

I have a very small request for a nice-to-have feature. After setting up my local copy of the template, l find myself running cargo scaffold <day> and, right after, I am running cargo download <day>.. I think a new flag to cargo scaffold like --download or even a separate command like cargo generate <day> that combines both steps would be nice.

What do you think?

RFC: Higher sample count for benching?

Implementation

Currently experimenting with a higher sample count for benching on my solution repo, might add to template after this year concludes. Unfortunately, using criterion with binary crates is not possible yet, would make this a bit simpler.

Advantages:

  • more accurate timings

Disadvantages:

  • Solutions take (at least) 2 seconds to execute (min. 1 sec or 5 iterations per part)
  • Input to benched functions required to be Copy (not an issue so far).

Example output:

πŸŽ„ Parser πŸŽ„
βœ“ (avg. time: 34.30Β΅s / 34507 samples)
πŸŽ„ Part 1 πŸŽ„
71506 (avg. time: 5.00ns / 3430531 samples)
πŸŽ„ Part 2 πŸŽ„
209603 (avg. time: 5.22Β΅s / 125659 samples)

cargo day 01 does not work

Tried cargo day 01 having created day 01 with cargo scaffold 1

Also tried adding the missing alias

[aliase]
day = "run --bin --"

But no joy I get

cargo day 01
error: "--bin" takes one argument.
Available binaries:
    01
    aoc
    download
    scaffold

Support different example inputs for part 1 and part 2 in tests

First of all, thank you for an amazing starter template. This repo makes it so easy to try out Rust for advent of code!

In AOC 2023 the first day puzzle has two example inputs, one for each part. The default read_file function only accepts a day which is strongly typed so you can only ever read 01.txt, etc.

In my project I just added a new function that takes a part number too:

pub fn read_file_part(folder: &str, day: Day, part: u8) -> String {
    let cwd = env::current_dir().unwrap();
    let filepath = cwd.join("data").join(folder).join(format!("{day}-{part}.txt"));
    let f = fs::read_to_string(filepath);
    f.expect("could not open input file")
}

Cross-platform support

This template uses bash scripts for automation which does not work on windows. Add equivalent powershell or implement scripts in rust to work around.

Automatically fetch example inputs

@NangiDev mentioned:

PS: I saw this Youtuber fetching the example input somehow πŸ€” so that should be possible

Edit: I did quick test on one way of fetching example input. Gist
It's not perfect because it highly depends on the text in puzzle description being typed in a particular way. It works for all (1-7) puzzles release so far this year (2022)

If it turns out that this is consistent, it would be neat to support this. We already download the puzzle by default now, maybe we can parse it from the markdown.

Cache crates.io index for CI

I decided personally it was a good idea to cache the crates.io index.

Do you think it's a good idea to do this for the template?

  • A disadvantage is that the index (which is about 300MB) is now stored on Github's servers.
  • An advantage is now the action doesn't have to fetch the entire crates.io index every time, which takes too long for my impatient self.

Example:

            - uses: actions/cache@v3
              with:
                path: |
                    ~/.cargo/registry/index/
                key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock')

Being able to store benchmarking metrics

I had this idea of trying to store benchmarks in a file when running them with a specific command.

example on command: cargo bm 02
My cargo .config

That would call on a rust binary that runs the benchmarking command with --release flag and stores it into a txt-file.

I started on the feature here
My attempt

But could not really finish it in a smart and reliable way.

The idea is that inside /src/benchmarks/table.txt should contain a line per day.
Containing Day, latest and best score for both parts.

Ex: 01 L1:85.40Β΅s B185.40Β΅s L2:74.10Β΅s B2:74.10Β΅s
first being the day (01). L1 being latest part 1 and B1 being best part 1 and so on.
My table so far

I'm pretty new at Rust so I think I sort of tangled myself into a weird mess.
My biggest problem is how to replace and update the correct line of the file.

What do you think? Anyone have a better and simpler way of doing this? Is it even valuable?

RFC: Separate parsing from solutions?

Implementation

Currently experimenting with a separately timed parser util on my solution repo, might add to template after this year concludes.

Advantages:

  • parser code is not timed twice.
  • parsing set up in template.
  • can use macro to generate main().

Disadvantages:

  • input has to be Clone.
  • replacing the macro (if needed for some reason) might not be clear for rust beginners (which this is aimed at).
type Input<'a> = Vec<&'a str>;

fn parse(input: &str) -> Input {
    input.lines().collect()
}

pub fn part_one(input: Input) -> Option<u32> {
    None
}

pub fn part_two(input: Input) -> Option<u32> {
    None
}

advent_of_code::main!(4);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_part_one() {
        let input = advent_of_code::read_file("examples", 4);
        assert_eq!(part_one(parse(&input)), None);
    }

    #[test]
    fn test_part_two() {
        let input = advent_of_code::read_file("examples", 4);
        assert_eq!(part_two(parse(&input)), None);
    }
}

Example output:

πŸŽ„ Parser πŸŽ„
(elapsed: 24.96Β΅s)
πŸŽ„ Part 1 πŸŽ„
13005 (elapsed: 6.00ns)
πŸŽ„ Part 2 πŸŽ„
11373 (elapsed: 831.00ns)

Cargo configuration doesn't find the target

Hello! I was trying to solve the first exercise with your template, but if I run cargo build or cargo scaffold 01, the output is always the same:

error: failed to parse manifest at `/home/herz/Cargo.toml`

Caused by:
  no targets specified in the manifest
  either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present

Thank you :)

Read only part 2

It would be nice to have a flag for reading only part 2 of a puzzle.

Overwrite existing day.rs file

If you accidentally run the cargo scaffold command without the --download argument or want to redo an entire problem, a manual deletion of the file is required before running the cargo scaffold <day> --download command again. It would be nice to have sort of a --overwrite argument that can overwrite the existing solution file

Multi-year support?

I see that year can be specified at the command line, but it doesn't seem like the code/inputs themselves are organized in any particular way to support different years.

Is there a way to accomplish catching up over a few years of missed AoC?

File for helper functions

Hi, I am a beginner in rust and I have problems extracting common helper functions to a file.

For example let's say that I wanted to factor out a common transpose function that I repeatedly used in days 7, 11 and 13. With the template it seems I can't do that in the bin folder, right? πŸ˜•

If possible, it would be really nice if there was an empty file in the template already for this purpose.

How to use modules?

Thanks for the great template! It helps a lot to get started quickly with using Rust for AoC.

I was wondering how to go about introducing modules to split out some of the code for a specific puzzle. E.g. for a puzzle where there is a lot of code for parsing the input into structs I would like to have a dedicated file for that day that handles this.

I tried to add a 03 folder with a input.rs but I wasn't able to include anything from it in my 03.rs. I guess it might be that modules may not have a numeric name. But it feels like a more general issue with the structure of the template.

Another case I could imagine is if I wanted to add some more generic functionality that could be reused by multiple puzzles. That I would like to put into a separate module as well. How would that work?

Incorrect documentation for --release flag

The docs say setting the --release flag should run the real puzzle inputs, and omitting the flag should run the examples.

The solve command runs your solution. If you set the --release flag, real puzzle inputs will be passed to your solution, otherwise the example inputs will be used.

As far as I can tell this is not the case. Running tests uses the example file, but any configuration of solve, with or without the release flag, will run the real puzzle inputs. I think one of these things would need to be updated, but first I would want to check which behavior is correct.

Is the expectation that solve should run the example or puzzle based on its input? Or does the documentation need to be updated that "solve" will always run puzzle input and "test" should be used for running examples?

Add dhat?

I added dhat to my repo (which was generated from the template), so that I can run and get output like the following:

$ cargo solve 5 --dhat
    Finished dhat [optimized + debuginfo] target(s) in 0.01s
     Running `target/dhat/05`
dhat: Total:     23,920 bytes in 244 blocks
dhat: At t-gmax: 8,176 bytes in 12 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: 382895070 (6.2ms)
dhat: Total:     32,528 bytes in 307 blocks
dhat: At t-gmax: 8,384 bytes in 11 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 2: 17729182 (4.2ms)

Do you have any interest in getting this upstream? I'm not sure how many people would care to use it. I was mainly curious about optimizing allocations in various computations (e.g. using custom iterators instead of allocating vectors for temporary results) as a learning experience, so I found it useful to be able to see what's going on in the memory allocator.

Time individual puzzles

In the light of solutions that may take a long time to run it would be great to have the option to time only one puzzle.
I.e.: allow cargo time 5 to only time day 5.

I guess the hardest bit would be to include the result in the benchmark table. Though it should be manageable.

Separate example file for each part

Hey, thanks for this amazing template. It makes AoC even more fun!

As some kind of enhancement I would suggest to allow to have 2 separate files with example input for each part of the day’s problem. I encountered this problem in last year’s AoC a few times and in the very first puzzle of this year’s. Currently there can be only one set of example input data, which doesn’t necessarily work with both solutions and therefore Github CI throws error because not all tests are green.

aoc-cli 0.5

aoc-cli release v0.5.0 4 days ago and rename the --file command flag by --input-file.

It can be solved by either :

  • install aoc-cli v0.4 with cargo install aoc-cli --version 0.4
  • patch src/bin/download.rs with
    cmd_args.append(&mut vec![
    "--file".into(),
    tmp_file_path.to_string_lossy().to_string(),
    "--day".into(),
    args.day.to_string(),
    "download".into(),
    ]);
    cmd_args.append(&mut vec![
-      "--file".into(),
+      "--input-file".into(),
        tmp_file_path.to_string_lossy().to_string(),
        "--day".into(),
        args.day.to_string(),
        "download".into(),
    ]);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.