AoC2020/src/bin/day2.rs

38 lines
980 B
Rust

use std::error::Error;
use std::fs::File;
use std::io::{self, BufRead};
use std::vec::Vec;
fn is_valid(line: &Vec<String>) -> bool {
let min: usize = line[0].parse().unwrap();
let max: usize = line[1].parse().unwrap();
let policy_char = line[2].chars().nth(0).unwrap();
let count = line[3].matches(policy_char).count();
count >= min && count <= max
}
fn main() -> Result<(), Box<dyn Error>> {
let file = File::open("inputs/day2.txt")?;
let lines = io::BufReader::new(file).lines().map(|l| l.unwrap());
let parts: Vec<Vec<String>> = lines
.map(|l| {
l.split(|c| c == ' ' || c == ':' || c == '-')
.filter(|s| *s != "")
.map(|s| s.to_string())
.collect()
})
.collect();
let valid_count = parts
.iter()
.map(|p| if is_valid(p) { 1 } else { 0 })
.fold(0, |acc, x| acc + x);
println!("Total valid: {}", valid_count);
Ok(())
}