mirror of
https://gitlab.com/MisterBiggs/aoc-2023-rust.git
synced 2025-06-15 14:36:50 +00:00
85 lines
1.7 KiB
Rust
85 lines
1.7 KiB
Rust
use std::collections::HashSet;
|
|
use std::fs;
|
|
|
|
pub fn run() {
|
|
println!("Day 4:");
|
|
let input = fs::read_to_string("./inputs/day4.txt").expect("Could not read file");
|
|
|
|
println!("\tPart 1: {}", part1(&input));
|
|
println!("\tPart 2: {}", part2(&input));
|
|
}
|
|
|
|
struct SectionAssignment {
|
|
left: HashSet<usize>,
|
|
right: HashSet<usize>,
|
|
}
|
|
|
|
fn deserialize(line: &str) -> SectionAssignment {
|
|
let (left, right) = line.split_once(',').unwrap();
|
|
let left = left
|
|
.split_once('-')
|
|
.map(|(l, r)| l.parse().unwrap()..=r.parse().unwrap())
|
|
.unwrap()
|
|
.collect();
|
|
let right = right
|
|
.split_once('-')
|
|
.map(|(l, r)| l.parse().unwrap()..=r.parse().unwrap())
|
|
.unwrap()
|
|
.collect();
|
|
|
|
SectionAssignment { left, right }
|
|
}
|
|
|
|
fn part1(input: &str) -> usize {
|
|
let assignments = input.split_whitespace().map(deserialize);
|
|
let mut sum = 0;
|
|
for assignment in assignments {
|
|
if assignment.left.is_subset(&assignment.right)
|
|
|| assignment.right.is_subset(&assignment.left)
|
|
{
|
|
sum += 1;
|
|
}
|
|
}
|
|
sum
|
|
}
|
|
|
|
fn part2(input: &str) -> usize {
|
|
let assignments = input.split_whitespace().map(deserialize);
|
|
let mut sum = 0;
|
|
for assignment in assignments {
|
|
if assignment.left.intersection(&assignment.right).count() >= 1 {
|
|
sum += 1;
|
|
}
|
|
}
|
|
sum
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_1() {
|
|
let input = "2-4,6-8
|
|
2-3,4-5
|
|
5-7,7-9
|
|
2-8,3-7
|
|
6-6,4-6
|
|
2-6,4-8";
|
|
|
|
assert_eq!(part1(input), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn test_2() {
|
|
let input = "2-4,6-8
|
|
2-3,4-5
|
|
5-7,7-9
|
|
2-8,3-7
|
|
6-6,4-6
|
|
2-6,4-8";
|
|
|
|
assert_eq!(part2(input), 4);
|
|
}
|
|
}
|