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

73 lines
1.7 KiB
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));
}
fn part1(input: &str) -> i32 {
2022-12-03 23:18:55 -06:00
let mut r = 0;
for l in input.lines() {
let mut c = l.split(",");
let p1 = c.next().unwrap();
let p2 = c.next().unwrap();
let mut p1c = p1.split("-");
let p1n1 = p1c.next().unwrap().parse::<i32>().unwrap();
let p1n2 = p1c.next().unwrap().parse::<i32>().unwrap();
let mut p2c = p2.split("-");
let p2n1 = p2c.next().unwrap().parse::<i32>().unwrap();
let p2n2 = p2c.next().unwrap().parse::<i32>().unwrap();
if (p1n1 <= p2n1 && p1n2 >= p2n2) || (p2n1 <= p1n1 && p2n2 >= p1n2) {
r += 1
}
}
r
2022-12-02 23:40:13 -06:00
}
fn part2(input: &str) -> i32 {
2022-12-03 23:18:55 -06:00
let mut r = 0;
for l in input.lines() {
println!("{}", l);
let mut c = l.split(",");
let p1 = c.next().unwrap();
let p2 = c.next().unwrap();
let mut p1c = p1.split("-");
let x1 = p1c.next().unwrap().parse::<i32>().unwrap();
let x2 = p1c.next().unwrap().parse::<i32>().unwrap();
let mut p2c = p2.split("-");
let y1 = p2c.next().unwrap().parse::<i32>().unwrap();
let y2 = p2c.next().unwrap().parse::<i32>().unwrap();
println!("{}-{} , {}-{}", x1, x2, y1, y2);
if x1 <= y2 && y1 <= x2 {
r += 1;
println!("overlap");
}
}
r
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
}
}