advent-of-code/2022/rust/src/day4.rs

41 lines
836 B
Rust
Raw Normal View History

2022-12-02 23:40:13 -06:00
mod common;
2022-12-04 01:44:06 -06:00
fn processed_input(input: &str) -> Vec<Vec<i32>> {
2022-12-04 00:00:56 -06:00
input
2022-12-04 01:44:06 -06:00
.lines()
.map(|l| l.split(&['-', ',']).map(|s| s.parse().unwrap()).collect())
2022-12-04 00:00:56 -06:00
.collect()
}
2022-12-03 23:18:55 -06:00
2022-12-04 01:44:06 -06:00
fn both_parts(input: &Vec<Vec<i32>>) -> (usize, usize) {
input.iter().fold((0, 0), |(a, b), n| {
(
(a + ((n[0] <= n[2] && n[1] >= n[3]) || (n[2] <= n[0] && n[3] >= n[1])) as usize),
b + ((n[0] <= n[3] && n[2] <= n[1]) as usize),
)
})
2022-12-02 23:40:13 -06:00
}
2022-12-04 01:44:06 -06:00
fn main() {
let input = processed_input(&common::day_input(4));
common::show_both_answers(&both_parts(&input))
2022-12-02 23:40:13 -06:00
}
#[cfg(test)]
mod tests {
use super::*;
2022-12-04 01:44:06 -06:00
#[test]
fn test() {
let input = processed_input(
"2-4,6-8
2022-12-03 23:18:55 -06:00
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2022-12-04 01:44:06 -06:00
2-6,4-8",
);
assert_eq!(both_parts(&input), (2, 4));
2022-12-02 23:40:13 -06:00
}
}