summaryrefslogtreecommitdiff
path: root/aoc01/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'aoc01/src/main.rs')
-rw-r--r--aoc01/src/main.rs58
1 files changed, 58 insertions, 0 deletions
diff --git a/aoc01/src/main.rs b/aoc01/src/main.rs
new file mode 100644
index 0000000..62db893
--- /dev/null
+++ b/aoc01/src/main.rs
@@ -0,0 +1,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}");
+}