Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More iterators! #35

Merged
merged 1 commit into from
Dec 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading