~janbaudisch/aoc-2020

ref: 6e5cbaeadad46c790ecccfee2c1dd3e14e7356c9 aoc-2020/day_07/src/rule.rs -rw-r--r-- 1.0 KiB
6e5cbaeaJan Baudisch add day 7 7 months ago
                                                                                
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
41
42
43
44
45
46
use std::collections::HashMap;

#[derive(Clone)]
pub struct Rule {
    pub color: String,
    pub contents: HashMap<String, u32>,
}

impl From<&str> for Rule {
    fn from(input: &str) -> Self {
        let mut words = input.split_whitespace();

        let mut color = words.next().unwrap().to_string();
        color.push(' ');
        color.push_str(words.next().unwrap());

        let _ = words.next();
        let _ = words.next();

        let mut contents = HashMap::new();

        while let Some(count) = words.next() {
            if count == "no" {
                break;
            }

            let count = u32::from_str_radix(count, 10).unwrap();

            let mut color = words.next().unwrap().to_string();
            color.push(' ');
            color.push_str(words.next().unwrap());

            contents.insert(color, count);

            let _ = words.next();
        }

        Self { color, contents }
    }
}

impl From<&String> for Rule {
    fn from(input: &String) -> Self {
        Rule::from(input.as_str())
    }
}