Skip to content

Commit

Permalink
puzzles/day_7: Implement part 2
Browse files Browse the repository at this point in the history
Signed-off-by: Jim Gerth <[email protected]>
  • Loading branch information
jimgerth committed Jan 3, 2021
1 parent 31eb74c commit ec684b2
Showing 1 changed file with 66 additions and 5 deletions.
71 changes: 66 additions & 5 deletions src/puzzles/day_7.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;

use regex::Regex;

Expand Down Expand Up @@ -49,7 +48,7 @@ pub fn part_1() -> i32 {
contained_in_rules.insert(bag_color, HashSet::new());
}

println!("{:#?}", can_contain_rules);
// println!("{:#?}", can_contain_rules);

// Invert rules.
for (color, contained_colors) in can_contain_rules.iter() {
Expand All @@ -61,11 +60,11 @@ pub fn part_1() -> i32 {
}
}

println!("{:#?}", contained_in_rules);
// println!("{:#?}", contained_in_rules);

let containers = get_containers("shiny gold", &contained_in_rules);

println!("{:#?}", containers);
// println!("{:#?}", containers);

containers.len() as i32
}
Expand All @@ -88,5 +87,67 @@ fn get_containers<'a>(
}

pub fn part_2() -> i32 {
5
let input = input::read_lines(7);
let mut rules: HashMap<&str, HashMap<&str, i32>> = HashMap::new();

let bag_color_regex = Regex::new(r"^\w* \w*").unwrap();
let bag_rules_regex = Regex::new(r"bags contain (.*).").unwrap();
let bag_rule_regex = Regex::new(r"(\d+) (\w+ \w+) \w+").unwrap();

// Parse rules.
for line in &input {
let bag_color = bag_color_regex
.captures(line)
.unwrap()
.get(0)
.unwrap()
.as_str();
let bag_rules = bag_rules_regex
.captures(line)
.unwrap()
.get(1)
.unwrap()
.as_str();

let bag_rules: HashMap<&str, i32> = if bag_rules != "no other bags" {
bag_rules
.split(", ")
.map(|rule| {
(
bag_rule_regex
.captures(rule)
.unwrap()
.get(2)
.unwrap()
.as_str(),
bag_rule_regex
.captures(rule)
.unwrap()
.get(1)
.unwrap()
.as_str()
.parse()
.unwrap(),
)
})
.collect()
} else {
HashMap::new()
};

rules.insert(bag_color, bag_rules);
}

// println!("{:#?}", rules);

get_content_count("shiny gold", &rules)
}

fn get_content_count(color: &str, rules: &HashMap<&str, HashMap<&str, i32>>) -> i32 {
let rule = rules.get(color).expect("Color not listed in rules.");
let mut total = 0;
for (color, count) in rule {
total += count + count * get_content_count(color, &rules);
}
total
}

0 comments on commit ec684b2

Please sign in to comment.