advent_of_code/src/aoc06/mod.rs

51 lines
1.2 KiB
Rust
Raw Normal View History

2020-12-07 09:12:08 +01:00
use std::error::Error;
use std::fs;
use std::collections::HashMap;
use std::str;
pub fn both(filename: &str) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(filename)?;
let mut answers: HashMap<u8, bool> = HashMap::new();
let mut sum = 0;
for line in contents.lines() {
if line.trim() == "" {
sum += answers.len();
answers = HashMap::new();
continue
}
for byte in line.as_bytes() {
answers.insert(*byte, true);
}
}
sum += answers.len();
println!("sum of group unique questions with yes: {}", sum);
answers = HashMap::new();
let mut first = true;
sum = 0;
for line in contents.lines() {
if line.trim() == "" {
sum += answers.len();
answers = HashMap::new();
first = true;
continue
}
if first {
for byte in line.as_bytes() {
answers.insert(*byte, true);
}
first = false;
} else {
answers.retain(|k, _| line.as_bytes().contains(k));
}
}
sum += answers.len();
println!("sum of group questions with all yes: {}", sum);
Ok(())
}