Skip to content

Commit

Permalink
Merge pull request #35 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 9a4f416 + 282e77c commit 77e7fb8
Showing 1 changed file with 36 additions and 40 deletions.
76 changes: 36 additions & 40 deletions rs/src/day4.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,46 @@
use itertools::izip;

pub fn part1(data: &str) -> usize {
let lines = data.lines().collect::<Vec<_>>();
let mut result = 0;
for (y, line) in lines.iter().enumerate() {
for x in 0..line.len() {
for dy in -1..=1 {
for dx in -1..=1 {
if "XMAS".bytes().enumerate().all(|(i, b)| {
y.checked_add_signed(i as isize * dy)
.and_then(|y| lines.get(y))
.and_then(|line| {
x.checked_add_signed(i as isize * dx)
.and_then(|x| line.as_bytes().get(x))
})
== Some(&b)
}) {
result += 1;
}
}
}
}
}
result
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)| {
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)
})
})
})
})
})
.count()
}

pub fn part2(data: &str) -> usize {
let lines = data.lines().collect::<Vec<_>>();
let mut result = 0;
for (above, line, below) in izip!(&lines[..], &lines[1..], &lines[2..]) {
for (nw, ne, b, sw, se) in izip!(
above.bytes(),
above.bytes().skip(2),
line.bytes().skip(1),
below.bytes(),
below.bytes().skip(2)
) {
if 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')
{
result += 1;
}
}
}
result
izip!(&lines[..], &lines[1..], &lines[2..])
.flat_map(|(above, line, below)| {
izip!(
above.bytes(),
above.bytes().skip(2),
line.bytes().skip(1),
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')
})
})
.count()
}

#[cfg(test)]
Expand Down

0 comments on commit 77e7fb8

Please sign in to comment.