-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.rs
40 lines (34 loc) · 1.1 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use regex::Regex;
lazy_static::lazy_static! {
static ref RE_RULE: Regex = Regex::new(r#"^([a-z ]+) bags contain (.*)$"#).unwrap();
static ref RE_CONT: Regex = Regex::new(r#"\d ([a-z ]+) b"#).unwrap();
}
pub fn main() {
let rules: Vec<_> = include_str!("../input.txt")
.lines()
.map(parse_bag)
.collect();
let (mut bags, mut cursor) = (vec!["shiny gold"], 0);
while let Some(target) = bags.get(cursor) {
let extra = rules
.iter()
.filter(|(color, cont)| cont.contains(target) && !bags.contains(color))
.map(|(color, _)| *color)
.collect::<Vec<_>>();
bags.extend_from_slice(&extra);
cursor += 1;
}
println!("{}", bags.len() - 1);
}
/// Parse bag ruleset.
#[inline(always)]
fn parse_bag<'a>(rule: &'a str) -> (&'a str, Vec<&str>) {
let captures = RE_RULE.captures(rule).unwrap();
(
captures.get(1).unwrap().as_str(),
RE_CONT
.captures_iter(captures.get(2).unwrap().as_str())
.map(|cond| cond.get(1).unwrap().as_str())
.collect(),
)
}