2023(1): Treat written digits as digits

This is wrong, though, as cases like `oneight` should return `83` whereas
I replace the `one`s first, so that `1ight` will remain that way.

See <https://www.reddit.com/r/adventofcode/comments/1884fpl/2023_day_1for_those_who_stuck_on_part_2/>.
This commit is contained in:
2023-12-02 22:03:52 +01:00
parent ce39b976ab
commit 1c17fcede7
2 changed files with 51 additions and 2 deletions

View File

@ -27,3 +27,28 @@ In this example, the calibration values of these four lines are `12`, `38`, `15`
Consider your entire calibration document. _What is the sum of all of the calibration values?_ Consider your entire calibration document. _What is the sum of all of the calibration values?_
To begin, [get your puzzle input](https://adventofcode.com/2023/day/1/input). To begin, [get your puzzle input](https://adventofcode.com/2023/day/1/input).
Your puzzle answer was `54990`.
The first half of this puzzle is complete! It provides one gold star: *
## --- Part Two ---
Your calculation isn't quite right. It looks like some of the digits are actually _spelled out with letters_: `one`, `two`, `three`, `four`, `five`, `six`, `seven`, `eight`, and `nine` _also_ count as valid "digits".
Equipped with this new information, you now need to find the real first and last digit on each line. For example:
```
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
```
In this example, the calibration values are `29`, `83`, `13`, `24`, `42`, `14`, and `76`. Adding these together produces `_281_`.
_What is the sum of all of the calibration values?_

View File

@ -9,8 +9,32 @@ fn main() {
if let Ok(lines) = read_lines("./input") { if let Ok(lines) = read_lines("./input") {
for line in lines { for line in lines {
if let Ok(text) = line { if let Ok(text) = line {
sum = sum + first_digit(&text); // TODO: Please us something like a collection instead of
mus = mus + last_digit(&text); // hardcoding every replacement.
let sanitext = text
.replace("one", "1")
.replace("two", "2")
.replace("three", "3")
.replace("four", "4")
.replace("five", "5")
.replace("six", "6")
.replace("seven", "7")
.replace("eight", "8")
.replace("nine", "9")
;
// DEBUG:
println!(
"{} => {} yields {} + {} = {}",
text,
sanitext,
first_digit(&sanitext),
last_digit(&sanitext),
first_digit(&sanitext) + last_digit(&sanitext)
);
sum = sum + first_digit(&sanitext);
mus = mus + last_digit(&sanitext);
} else {
println!("Error on line \"{:?}\"", line);
} }
} }
} }