Skip to content

Commit

Permalink
Merge pull request #37 from ephemient/rs/day4
Browse files Browse the repository at this point in the history
  • Loading branch information
ephemient authored Dec 4, 2024
2 parents a6ef04b + 53977ed commit d4f6cef
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 11 deletions.
16 changes: 16 additions & 0 deletions rs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ name = "aoc2024"
path = "src/main.rs"

[dependencies]
array-util = "1.0.2"
itertools = "0.13"

[dev-dependencies]
Expand Down
23 changes: 12 additions & 11 deletions rs/src/day4.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
use array_util::try_from_fn;
use itertools::izip;

pub fn part1(data: &str) -> usize {
const XMAS: [[u8; 4]; 2] = [*b"XMAS", *b"SAMX"];

let lines = &data.lines().collect::<Vec<_>>()[..];
lines
.iter()
.enumerate()
.flat_map(|(y, line)| {
(0..line.len()).flat_map(move |x| {
(-1..=1).flat_map(move |dy| {
(-1..=1).filter(move |dx| {
"XMAS".bytes().enumerate().all(|(i, b)| {
[(1, 0), (1, 1), (0, 1), (-1, 1)]
.iter()
.filter_map(move |(dx, dy)| {
try_from_fn(|i| {
y.checked_add_signed(i as isize * dy)
.and_then(|y| lines.get(y))
.zip(x.checked_add_signed(i as isize * dx))
.and_then(|(line, x)| line.as_bytes().get(x))
== Some(&b)
.and_then(|(line, x)| line.as_bytes().get(x).copied())
})
})
})
})
})
.filter(|s| XMAS.contains(s))
.count()
}

pub fn part2(data: &str) -> usize {
const XMAS: [[u8; 5]; 4] = [*b"MMASS", *b"MSAMS", *b"SMASM", *b"SSAMM"];

let lines = data.lines().collect::<Vec<_>>();
izip!(&lines[..], &lines[1..], &lines[2..])
.flat_map(|(above, line, below)| {
Expand All @@ -34,12 +39,8 @@ pub fn part2(data: &str) -> usize {
below.bytes(),
below.bytes().skip(2)
)
.filter(|&(nw, ne, b, sw, se)| {
b == b'A'
&& (nw == b'M' && se == b'S' || se == b'M' && nw == b'S')
&& (ne == b'M' && sw == b'S' || sw == b'M' && ne == b'S')
})
})
.filter(|&(nw, ne, b, sw, se)| XMAS.contains(&[nw, ne, b, sw, se]))
.count()
}

Expand Down

0 comments on commit d4f6cef

Please sign in to comment.