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

57 lines
987 B
Rust
Raw Normal View History

2022-12-02 23:40:13 -06:00
mod common;
fn main() {
let input = common::day_input(4);
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}
2022-12-04 00:00:56 -06:00
fn nums(input: &str) -> Vec<i32> {
input
2022-12-04 01:26:00 -06:00
.split(&['-', ','])
2022-12-04 00:00:56 -06:00
.map(|s| s.parse::<i32>().unwrap())
.collect()
}
2022-12-03 23:18:55 -06:00
2022-12-04 00:00:56 -06:00
fn part1(input: &str) -> i32 {
input
.lines()
.map(|l| {
let n = nums(l);
((n[0] <= n[2] && n[1] >= n[3]) || (n[2] <= n[0] && n[3] >= n[1])) as i32
})
.sum()
2022-12-02 23:40:13 -06:00
}
fn part2(input: &str) -> i32 {
2022-12-04 00:00:56 -06:00
input
.lines()
.map(|l| {
let n = nums(l);
(n[0] <= n[3] && n[2] <= n[1]) as i32
})
.sum()
2022-12-02 23:40:13 -06:00
}
#[cfg(test)]
mod tests {
use super::*;
2022-12-03 23:18:55 -06:00
const TEST_INPUT: &str = "2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8";
2022-12-02 23:40:13 -06:00
#[test]
fn test_part1() {
2022-12-03 23:18:55 -06:00
assert_eq!(part1(TEST_INPUT), 2)
2022-12-02 23:40:13 -06:00
}
#[test]
fn test_part2() {
2022-12-03 23:18:55 -06:00
assert_eq!(part2(TEST_INPUT), 4)
2022-12-02 23:40:13 -06:00
}
}