Skip to content

Instantly share code, notes, and snippets.

@gre
Last active December 1, 2023 10:52
Show Gist options
  • Save gre/54071ebac9c3e2457be8db97a735c8e5 to your computer and use it in GitHub Desktop.
Save gre/54071ebac9c3e2457be8db97a735c8e5 to your computer and use it in GitHub Desktop.
advent of code 2023
fn day1(input: &str) -> usize {
let digits = vec!["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let digits_rev = vec!["eno", "owt", "eerht", "ruof", "evif", "xis", "neves", "thgie", "enin"];
let values = vec!['1','2','3','4','5','6','7','8','9'];
input.lines().map(|line| {
let regular = line.chars().collect::<Vec<char>>();
let reversed = line.chars().rev().collect::<Vec<char>>();
let mut s = String::new();
for (chars, digits) in vec![(regular, &digits), (reversed, &digits_rev)] {
let first_numeric =
chars.iter()
.enumerate()
.find_map(|c|
if c.1.is_numeric() {
Some((c.0, *c.1))
} else {
None
});
let mut first_literal: Option<(usize, char)> = None;
let str = String::from_iter(chars);
for (i, d) in digits.iter().enumerate() {
if let Some(index) = str.find(d) {
match first_literal {
Some(e) if index < e.0 => {
first_literal = Some((index, values[i]));
},
None => {
first_literal = Some((index, values[i]));
}
_ => {}
}
}
}
match (first_literal, first_numeric) {
(Some((i, a)), Some((j, b))) => if i < j {
s.push(a);
} else {
s.push(b);
},
(Some((_, c)), _) => {
s.push(c);
},
(_, Some((_, c))) => {
s.push(c);
},
_ => {}
}
}
s
}).fold(0, |acc, x| acc + x.parse::<usize>().unwrap_or_default())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment