Day1 Rust

This commit is contained in:
dobiadi
2023-12-02 16:26:30 +01:00
parent 7850c50a55
commit 7e9d5e3fdd
4 changed files with 60 additions and 0 deletions

1
day1/rust/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target

7
day1/rust/Cargo.lock generated Normal file
View File

@@ -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"

8
day1/rust/Cargo.toml Normal file
View File

@@ -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]

44
day1/rust/src/main.rs Normal file
View File

@@ -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<u32> = 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);
}