aoc/year2024/day25.rs
1//! # Code Chronicle
2//!
3//! Efficiently checks if locks and keys overlap using bitwise logic. The ASCII character
4//! `#` (35) is odd and `.` (46) is even so bitwise AND with 1 results in either 1 or 0.
5//! The newline character `\n` (10) is even so will result in 0 and not contribute to matches.
6//! There are 25 bits plus 4 newline bits so each lock or key can be stored in an `u32`.
7//! For example:
8//!
9//! ```none
10//! #####
11//! ##.## 11011
12//! .#.## 01011
13//! ...## => 00011 => 110110_010110_000110_000100_00010
14//! ...#. 00010
15//! ...#. 00010
16//! .....
17//! ```
18pub fn parse(input: &str) -> &str {
19 input
20}
21
22pub fn part1(input: &str) -> u32 {
23 let mut slice = input.as_bytes();
24 let mut locks = Vec::with_capacity(250);
25 let mut keys = Vec::with_capacity(250);
26 let mut result = 0;
27
28 while !slice.is_empty() {
29 let bits = slice[6..35].iter().fold(0, |bits, &n| (bits << 1) | (n & 1) as u32);
30
31 if slice[0] == b'#' {
32 locks.push(bits);
33 } else {
34 keys.push(bits);
35 }
36
37 slice = &slice[43.min(slice.len())..];
38 }
39
40 for lock in &locks {
41 for key in &keys {
42 result += (lock & key == 0) as u32;
43 }
44 }
45
46 result
47}
48
49pub fn part2(_input: &str) -> &'static str {
50 "n/a"
51}