From 6a3b945f0a4cdf2a27adf915e8a237077fef9f30 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Sat, 5 Dec 2020 21:33:29 -0800 Subject: 06 --- 06/Cargo.toml | 8 +++++ 06/src/main.rs | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 06/Cargo.toml create mode 100644 06/src/main.rs (limited to '06') diff --git a/06/Cargo.toml b/06/Cargo.toml new file mode 100644 index 0000000..e415fff --- /dev/null +++ b/06/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "advent_06" +version = "0.1.0" +authors = ["Irene Knapp "] +edition = "2018" + +[dependencies] +advent_lib = { path = "../lib" } diff --git a/06/src/main.rs b/06/src/main.rs new file mode 100644 index 0000000..4cc94f6 --- /dev/null +++ b/06/src/main.rs @@ -0,0 +1,93 @@ +use advent_lib::prelude::*; + +use std::collections::BTreeSet; + + +fn main() -> Result<()> { + let mut args = std::env::args(); + if args.len() != 2 { + eprintln!("Usage: advent input"); + } + let _ = args.next(); + let filename = args.next().unwrap(); + + let input = advent_lib::read_lines_file(&filename)?; + + let mut yes_counts = Vec::new(); + let mut yes_answers = BTreeSet::new(); + + for line in &input { + if line.trim().len() == 0 { + let count = yes_answers.len(); + yes_counts.push(count); + + yes_answers = BTreeSet::new(); + } + + for c in line.trim().chars() { + yes_answers.insert(c); + } + } + + let count = yes_answers.len(); + yes_counts.push(count); + + let mut sum = 0; + for count in yes_counts { + sum += count; + } + + println!("{}", sum); + + let mut everyone_yes_counts = Vec::new(); + let mut everyone_yes_answers = BTreeSet::new(); + let mut is_within_group = false; + + for line in &input { + let this_line_is_blank = line.trim().len() == 0; + + if this_line_is_blank { + let count = everyone_yes_answers.len(); + everyone_yes_counts.push(count); + //println!("{}", count); + + everyone_yes_answers = BTreeSet::new(); + is_within_group = false; + } + + let mut this_person_yes_answers = BTreeSet::new(); + + for c in line.trim().chars() { + this_person_yes_answers.insert(c); + } + + //println!("{} {}", everyone_yes_answers.len(), this_person_yes_answers.len()); + if is_within_group { + let intersection = + everyone_yes_answers.intersection(&this_person_yes_answers); + + let mut copied = BTreeSet::new(); + for c in intersection { + copied.insert(c.clone()); + } + + everyone_yes_answers = copied; + } else { + everyone_yes_answers = this_person_yes_answers; + } + + is_within_group = !this_line_is_blank; + } + + let count = everyone_yes_answers.len(); + everyone_yes_counts.push(count); + + let mut everyone_sum = 0; + for count in everyone_yes_counts { + everyone_sum += count; + } + + println!("{}", everyone_sum); + + Ok(()) +} -- cgit 1.4.1