This commit is contained in:
Daniel S. 2020-12-07 14:04:31 +01:00
parent 8b702bca9f
commit d1c0ec56de
2 changed files with 80 additions and 0 deletions

79
src/day7.rs Normal file
View file

@ -0,0 +1,79 @@
use aoc_runner_derive::{aoc, aoc_generator};
use std::collections::{HashMap, HashSet, VecDeque};
pub struct Data {
fwd: HashMap<String, Vec<(usize, String)>>,
rev: HashMap<String, Vec<(usize, String)>>,
}
impl Data {
pub fn new() -> Data {
Data {
fwd: HashMap::new(),
rev: HashMap::new(),
}
}
}
#[aoc_generator(day7)]
pub fn input_generator(input: &str) -> Data {
let mut ret = Data::new();
for line in input.lines() {
let mut line = line.to_owned();
line = line.replace("contain", "");
line = line.replace("bags", "");
line = line.replace("bag", "");
line = line.replace(",", "");
line = line.replace(".", "");
while line.contains(" ") {
line = line.replace(" ", " ");
}
line = line.trim().to_owned();
let mut l: VecDeque<String> = line
.split_ascii_whitespace()
.map(|s| s.to_owned())
.collect();
let outer_color: String = [l.pop_front().unwrap(), l.pop_front().unwrap()].join(" ");
while let (Some(n), Some(c1), Some(c2)) = (l.pop_front(), l.pop_front(), l.pop_front()) {
let n: usize = n.parse().unwrap();
let inner_color = vec![c1.to_owned(), c2.to_owned()].join(" ");
ret.fwd
.entry(outer_color.clone())
.or_default()
.push((n, inner_color.clone()));
ret.rev
.entry(inner_color.clone())
.or_default()
.push((n, outer_color.clone()));
}
}
ret
}
#[aoc(day7, part1)]
pub fn solve_part1(input: &Data) -> usize {
let mut cnt = 0;
let mut q = VecDeque::new();
q.push_back("shiny gold".to_owned());
while let Some(c) = q.pop_front() {
for (_, nc) in input.rev.get(&c).iter().map(|v| v.iter()).flatten() {
cnt += 1;
q.push_back(nc.clone());
}
}
return cnt;
}
#[aoc(day7, part2)]
pub fn solve_part2(input: &Data) -> usize {
let mut cnt = 0;
let mut q = VecDeque::new();
q.push_back((1, "shiny gold".to_owned()));
while let Some((o_n, c)) = q.pop_front() {
for (n, nc) in input.fwd.get(&c).iter().map(|v| v.iter()).flatten() {
cnt += n * o_n;
q.push_back((n * o_n, nc.clone()));
}
}
return cnt;
}

View file

@ -5,4 +5,5 @@ pub mod day3;
pub mod day4;
pub mod day5;
pub mod day6;
pub mod day7;
aoc_lib! { year = 2020 }