diff --git a/rs/src/day4.rs b/rs/src/day4.rs index e32620cf..ce595f2f 100644 --- a/rs/src/day4.rs +++ b/rs/src/day4.rs @@ -1,50 +1,46 @@ use itertools::izip; pub fn part1(data: &str) -> usize { - let lines = data.lines().collect::>(); - 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::>()[..]; + 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::>(); - 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)]