AoC2020/src/bin/day2_part2.rs

44 lines
1.2 KiB
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 pos1: usize = line[0].parse().unwrap();
let pos2: usize = line[1].parse().unwrap();
let policy_char = line[2].chars().nth(0).unwrap();
let char1 = line[3].chars().nth(pos1 - 1);
let char2 = line[3].chars().nth(pos2 - 1);
match (char1, char2) {
(Some(c1), Some(c2)) => (c1 == policy_char) ^ (c2 == policy_char),
(Some(c), None) => (c == policy_char),
(None, Some(c)) => (c == policy_char),
(None, None) => false,
}
}
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(())
}