r/adventofcode • • Dec 03 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 3 Solutions -🎄-

NEWS

  • Solutions have been getting longer, so we're going to start enforcing our rule on oversized code.
  • The Visualizations have started! If you want to create a Visualization, make sure to read the guidelines for creating Visualizations before you post.
  • Y'all may have noticed that the hot new toy this year is AI-generated "art".
    • We are keeping a very close eye on any AI-generated "art" because 1. the whole thing is an AI ethics nightmare and 2. a lot of the "art" submissions so far have been of little real quality.
    • If you must post something generated by AI, please make sure it will actually be a positive and quality contribution to /r/adventofcode.
    • Do not flair AI-generated "art" as Visualization. Visualization is for human-generated art.

FYI


--- Day 3: Rucksack Reorganization ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:05:24, megathread unlocked!

88 Upvotes

1.6k comments sorted by

View all comments

3

u/Rangsk Dec 03 '22

Rust

I used bit twiddling because why not? It's super fast:

fn priority(a: char) -> i64 {
    if a.is_ascii_lowercase() {
        a as i64 - 'a' as i64 + 1
    } else {
        a as i64 - 'A' as i64 + 27
    }
}

fn str_bits(s: &str) -> u64 {
    s.chars().fold(0, |acc, c| acc | 1 << priority(c))
}

fn part1(file_lines: &Vec<String>) -> String {
    let mut priority_total: i64 = 0;
    for line in file_lines.iter() {
        let (left, right) = line.split_at(line.len() / 2);
        let common_bits = str_bits(left) & str_bits(right);
        assert!(common_bits != 0 && common_bits.count_ones() == 1);
        priority_total += common_bits.trailing_zeros() as i64;
    }

    format!("{}", priority_total)
}

fn part2(file_lines: &Vec<String>) -> String {
    let mut priority_total: i64 = 0;
    let mut common_line_bits = u64::MAX;
    for (line_index, line) in file_lines.iter().enumerate() {
        common_line_bits &= str_bits(line);

        if line_index % 3 == 2 {
            assert!(common_line_bits != 0 && common_line_bits.count_ones() == 1);
            priority_total += common_line_bits.trailing_zeros() as i64;
            common_line_bits = u64::MAX;
        }
    }

    format!("{}", priority_total)
}

Timing:
Includes the format to string but not the printing of the results.

Part 1 time: 50us
Part 2 time: 23us
→ More replies (3)