diff --git a/day1/rust/.gitignore b/day1/rust/.gitignore new file mode 100644 index 0000000..eb5a316 --- /dev/null +++ b/day1/rust/.gitignore @@ -0,0 +1 @@ +target diff --git a/day1/rust/Cargo.lock b/day1/rust/Cargo.lock new file mode 100644 index 0000000..b21cc6a --- /dev/null +++ b/day1/rust/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "rust" +version = "0.1.0" diff --git a/day1/rust/Cargo.toml b/day1/rust/Cargo.toml new file mode 100644 index 0000000..1ec6963 --- /dev/null +++ b/day1/rust/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rust" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/day1/rust/src/main.rs b/day1/rust/src/main.rs new file mode 100644 index 0000000..e171103 --- /dev/null +++ b/day1/rust/src/main.rs @@ -0,0 +1,44 @@ +fn main() { + let part2 = true; + let english_digit_names = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; + + + let stdin = std::io::stdin(); + let mut sum = 0; + + for line in stdin.lines() { + let line = line.unwrap(); + + let mut first: Option = None; + let mut last = 0; + for i in 0..line.chars().count() { + let slice = &line[i..]; + + let first_char = slice.chars().next().unwrap(); + if first_char.is_digit(10) { + if first == None { + first = first_char.to_digit(10); + } + + last = first_char.to_digit(10).unwrap(); + } + + if part2 { + for (i, name) in english_digit_names.iter().enumerate() { + if slice.starts_with(name) { + if first == None { + first = Some(i.try_into().unwrap()); + } + + last = i.try_into().unwrap(); + } + } + } + } + + sum += first.unwrap() * 10; + sum += last; + } + + println!("{}", sum); +}