add day 4 (it was easy)

This commit is contained in:
Nico 2022-12-04 18:30:12 +00:00
parent 7595d1de37
commit 6a082267e4
2 changed files with 62 additions and 0 deletions

56
src/bin/04.rs Normal file
View File

@ -0,0 +1,56 @@
use regex::Regex;
pub fn part_one(input: &str) -> Option<u32> {
let linere = Regex::new(r"(\d+)-(\d+),(\d+)-(\d+)").unwrap();
let mut result = 0;
for l in input.lines() {
let caps = linere.captures(l).unwrap();
let s1 = &caps[1].parse::<i32>().unwrap();
let e1 = &caps[2].parse::<i32>().unwrap();
let s2 = &caps[3].parse::<i32>().unwrap();
let e2 = &caps[4].parse::<i32>().unwrap();
if (s2 >= s1 && e2 <= e1) || (s1 >= s2 && e1 <= e2) {
result += 1;
}
}
Some(result)
}
pub fn part_two(input: &str) -> Option<u32> {
let linere = Regex::new(r"(\d+)-(\d+),(\d+)-(\d+)").unwrap();
let mut result = 0;
for l in input.lines() {
let caps = linere.captures(l).unwrap();
let s1 = &caps[1].parse::<i32>().unwrap();
let e1 = &caps[2].parse::<i32>().unwrap();
let s2 = &caps[3].parse::<i32>().unwrap();
let e2 = &caps[4].parse::<i32>().unwrap();
if !((s2 > e1 && e2 > e1) || (s1 > e2 && e1 > e2)) {
result += 1;
}
}
Some(result)
}
fn main() {
let input = &advent_of_code::read_file("inputs", 4);
advent_of_code::solve!(1, part_one, input);
advent_of_code::solve!(2, part_two, input);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let input = advent_of_code::read_file("examples", 4);
assert_eq!(part_one(&input), Some(2));
}
#[test]
fn test_part_two() {
let input = advent_of_code::read_file("examples", 4);
assert_eq!(part_two(&input), Some(4));
}
}

6
src/examples/04.txt Normal file
View File

@ -0,0 +1,6 @@
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8