Advent of Code 2023 Day 1
Day 1: Trebuchet?!
https://adventofcode.com/2023/day/1
Something is wrong with the global snow production and you are the lucky fixer! (yay?)
Snow comes from the sky, and the sky is where you are going. The vehicle of choice to get to the destination is a trebuchet.
Today’s input is a list of calibration instructions for that trebuchet.
An example input looks like this:
1abc2pqr3stu8vwxa1b2c3d4e5ftreb7uchet
Part 1
Each line of input holds a calibration value. A calibration value is a two-digit number.
It can be constructed by concatenating the first digit in a line with the last digit in that line. The question asks for sum of all calibration values in the input.
Option 1: A for loop
Some skeleton/pseudo-code to start with:
let mut sum = 0;for line in input.lines() {let first = // first digit in linelet last = // last digit in line;let num = first * 10 + last; // smoosh the two digits together really closesum += num; // add the combined two-digit number to the sum}sum
I chose to not overthink this one and to be very verbose on purpose.
Starting to search from the front of the line, I look for the first character that is a digit. Then I turn that into an integer so I can do math on it.
To find the last digit, I do the same thing starting from the back of the line.
When I found both digits, I merge them into a two-digit number and add that number to the final sum.
let mut sum = 0;for line in input.lines() {let first = line.chars().find(|c| c.is_ascii_digit()).unwrap();let first: u32 = first.to_digit(10).unwrap();let last = line.chars().rfind(|c| c.is_ascii_digit()).unwrap();let last: u32 = last.to_digit(10).unwrap();let num = first * 10 + last;sum += num;}sum
Option 2: An iterator chain
The exact same idea, but implemented a bit differently.
Split the input into lines. Turn each line into a number. Sum those numbers.
input.lines().map(|line| {let first = line.chars().find_map(|c| c.to_digit(10)).unwrap();let last = line.chars().rev().find_map(|c| c.to_digit(10)).unwrap();10 * first + last}).sum()
Code
fn part_1(input: &str) -> u32 {input.lines().map(|line| {let first = line.chars().find_map(|c| c.to_digit(10)).unwrap();let last = line.chars().rev().find_map(|c| c.to_digit(10)).unwrap();10 * first + last}).sum()}
Part 2
It turns out spelled out digits are also valid.
So “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, and “nine” also count as valid “digits”,
with values from 1 to 9 respectively.
Input lines can look like this:
two1nineeightwothreeabcone2threexyzxtwone3four4nineeightseven2zoneight2347pqrstsixteen
For example, the first digit on the first line would be "two"
, with a numeric value of 2
.
The last digit on that line is "nine"
, with a value of 9
.
That means the calibration value for that line is 29
.
This complicates things, because you can’t look at a line 1 character at a time like in part 1.
The skeleton code remains unchanged from part 1.
let mut sum = 0;for line in input.lines() {let first = // first digit in linelet last = // last digit in line;let num = first * 10 + last; // smoosh the two digits together really closesum += num; // add the combined two-digit number to the sum}sum
To find the first digit, I create a temporary line that starts off as the entire line. If it starts with a valid prefix, the digit was found. If it does not, I shorten that temporary variable so it starts one character later and do the check again.
To find the last digit, I apply the same logic with 2 changes:
- I check if the temporary line ends with a valid suffix.
- I shorten that temporary line by removing one character from the end.
In pseudocode that looks like:
let nums = // a map with all possible valid strings as key, and their number as value. (ie. key: "nine", value: 9)for line in lines {let mut first = 0;'first: loop {let mut temporary = line;for (prefix, digit) in nums {if line.starts_with(prefix) {first = digit;// break out of the outer loop marked as 'firstbreak 'first;}}// all valid digits were checked an none matched, shorten the temporary line by removing one character from the fronttemporary = &temporary[1..];}// the same logic for the last digit// the summing logic}
Code
use std::collections::HashMap;fn part_2(input: &str) -> u32 {let nums = HashMap::from([("1", 1),("2", 2),("3", 3),("4", 4),("5", 5),("6", 6),("7", 7),("8", 8),("9", 9),("one", 1),("two", 2),("three", 3),("four", 4),("five", 5),("six", 6),("seven", 7),("eight", 8),("nine", 9),]);let mut sum = 0;for line in input.lines() {let mut forwards = line;let mut backwards = line;let first = 'outer: loop {for (prefix, num) in nums.iter() {if forwards.starts_with(prefix) {break 'outer num;}}forwards = &forwards[1..];};let last = 'outer: loop {for (suffix, num) in nums.iter() {if backwards.ends_with(suffix) {break 'outer num;}}backwards = &backwards[..backwards.len() - 1];};let num = first * 10 + last;sum += num;}sum}
Final code
1use std::collections::HashMap;23fn main() {4 let input = include_str!("day_01.txt");5 println!("{}", part_1(input));6 println!("{}", part_2(input));7}8910fn part_1(input: &str) -> u32 {11 input12 .lines()13 .map(|line| {14 let first = line.chars().find_map(|c| c.to_digit(10)).unwrap();15 let last = line.chars().rev().find_map(|c| c.to_digit(10)).unwrap();16 10 * first + last17 })18 .sum()19}2021fn part_2(input: &str) -> u32 {22 let nums = HashMap::from([23 ("1", 1),24 ("2", 2),25 ("3", 3),26 ("4", 4),27 ("5", 5),28 ("6", 6),29 ("7", 7),30 ("8", 8),31 ("9", 9),32 ("one", 1),33 ("two", 2),34 ("three", 3),35 ("four", 4),36 ("five", 5),37 ("six", 6),38 ("seven", 7),39 ("eight", 8),40 ("nine", 9),41 ]);4243 let mut sum = 0;44 for line in input.lines() {45 let mut forwards = line;46 let mut backwards = line;4748 let first = 'outer: loop {49 for (prefix, num) in nums.iter() {50 if forwards.starts_with(prefix) {51 break 'outer num;52 }53 }54 forwards = &forwards[1..];55 };5657 let last = 'outer: loop {58 for (suffix, num) in nums.iter() {59 if backwards.ends_with(suffix) {60 break 'outer num;61 }62 }63 backwards = &backwards[..backwards.len() - 1];64 };6566 let num = first * 10 + last;67 sum += num;68 }6970 sum71}
Series navigation for: Advent of Code 2023