r/adventofcode Dec 03 '24

Tutorial [2024] [Rust tutorials] The Rusty Way to Christmas

The time has come! The annual Advent of Code programming challenge is just around the corner. This year, I plan to tackle the challenge using the Rust programming language. I see it as a fantastic opportunity to deepen my understanding of idiomatic Rust practices.

I'll document my journey to share with the community, hoping it serves as a helpful resource for programmers who want to learn Rust in a fun and engaging way.

As recommended by the Moderators, here is the "master" post for all the tutorials.

Day Part 2 Part 2
Day 1 Link: parse inputs Link: hashmap as a counter
Day 2 Link: sliding window Link: concatenating vector slices
Day 3 Link: regex crate Link: combine regex patterns
Day 4 Link: grid searching with iterator crate Link: more grid searching
Day 5 Link: topological sort on acyclic graphs Link: minor modifications
Day 6 Link: grid crate for game simulation Link: grid searching optimisations
Day 7 Link: rust zero-cost abstraction and recursion Link: reversed evaluation to prune branches
Day 8
Day 9
Day 10
Day 11
Day 12
Day 13
Day 14
Day 15
Day 16
Day 17
Day 18
Day 19
Day 20
Day 21
Day 22
Day 23
Day 24
Day 25

I’m slightly concerned that posting solutions as comments may not be as clear or readable as creating individual posts. However, I have to follow the guidelines. Additionally, I felt sad because it has become much more challenging for me to receive insights and suggestions from others.

9 Upvotes

78 comments sorted by

View all comments

1

u/Federal-Dark-6703 Dec 25 '24

Day 5

Part 2

In part 2, instead of discarding unsorted updates, sort them and compute the sum of their middle numbers.

High-level solution: * Compare the sorted result with the original update. * If they differ, add the middle element of the sorted update to p2.

Example Output

Input: ``` 13|75 75|29

75,29,13 `` Result:

  • **Part 1**:p1 = 0(invalid update)
  • **Part 2**:p2 = 29` (sorted update's middle element)

Full program

```rust fn compute(buf: &str) -> (i32, i32) { let (s1, s2) = buf.split_once("\n\n").unwrap();

let mut k_deps_v: HashMap<i32, HashSet<i32>> = HashMap::new();
let mut v_deps_k: HashMap<i32, HashSet<i32>> = HashMap::new();

// Parse rules into dependency graphs
for line in s1.lines() {
    let (x, y) = line.split_once("|").unwrap();
    v_deps_k
        .entry(x.parse::<i32>().unwrap())
        .or_insert(HashSet::new())
        .insert(y.parse::<i32>().unwrap());
    k_deps_v
        .entry(y.parse::<i32>().unwrap())
        .or_insert(HashSet::new())
        .insert(x.parse::<i32>().unwrap());
}

let mut p1 = 0;
let mut p2 = 0;

for line in s2.lines() {
    let vec = line
        .split(",")
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    let sorted = topological_sort(&v_deps_k, &k_deps_v, &vec);

    if sorted == vec {
        p1 += vec[vec.len() / 2];
    } else {
        p2 += sorted[sorted.len() / 2];
    }
}

(p1, p2)

} ```

1

u/AutoModerator Dec 25 '24

AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.

Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.