summaryrefslogtreecommitdiff
path: root/aoc01/src/main.rs
blob: 62db893c08f0d5a036f28529cdc8ec83c294af9f (plain) (blame)
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
47
48
49
50
51
52
53
54
55
56
57
58
use std::{env::args, io::stdin};

const NUM_WORDS: [(&str, &str); 9] = [
    ("one", "1"),
    ("two", "2"),
    ("three", "3"),
    ("four", "4"),
    ("five", "5"),
    ("six", "6"),
    ("seven", "7"),
    ("eight", "8"),
    ("nine", "9"),
];

fn word_to_digit(word: &str) -> &str {
    match word {
        "one" => "1",
        "two" => "2",
        "three" => "3",
        "four" => "4",
        "five" => "5",
        "six" => "6",
        "seven" => "7",
        "eight" => "8",
        "nine" => "9",
        num => num,
    }
}

fn get_digits(line: &str) -> u32 {
    let mut found = Vec::new();
    let find_words = args().any(|b| b == "-b");

    for (word, num) in NUM_WORDS {
        found.extend(line.match_indices(num));

        if find_words {
            found.extend(line.match_indices(word));
        }
    }

    found.sort();

    let first = word_to_digit(found.first().unwrap().1);
    let last = word_to_digit(found.last().unwrap().1);

    let combined = format!("{first}{last}");
    combined.parse().unwrap()
}

fn main() {
    let i: u32 = stdin()
        .lines()
        .filter_map(|l| Some(get_digits(&l.ok()?)))
        .sum();

    println!("{i}");
}