NickyMeulemanNime
Metadata
  • Date

  • By

    • Nicky Meuleman
  • Tagged

  • Part of series

  • Older post

    Advent of Code 2015 Day 4

  • Newer post

    Advent of Code 2023 Day 2

Table of contents
  1. Day 1: Trebuchet?!
  2. Part 1
    1. Option 1: A for loop
    2. Option 2: An iterator chain
    3. Code
  3. Part 2
    1. Code
  4. Final code

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:

input.txt
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet

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 line
let last = // last digit in line;
let num = first * 10 + last; // smoosh the two digits together really close
sum += 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

day_01.rs
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:

two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

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 line
let last = // last digit in line;
let num = first * 10 + last; // smoosh the two digits together really close
sum += 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:

  1. I check if the temporary line ends with a valid suffix.
  2. 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 'first
break 'first;
}
}
// all valid digits were checked an none matched, shorten the temporary line by removing one character from the front
temporary = &temporary[1..];
}
// the same logic for the last digit
// the summing logic
}

Code

day_01.rs
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

day_01.rs
1use std::collections::HashMap;
2
3fn main() {
4 let input = include_str!("day_01.txt");
5 println!("{}", part_1(input));
6 println!("{}", part_2(input));
7}
8
9
10fn part_1(input: &str) -> u32 {
11 input
12 .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 + last
17 })
18 .sum()
19}
20
21fn 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 ]);
42
43 let mut sum = 0;
44 for line in input.lines() {
45 let mut forwards = line;
46 let mut backwards = line;
47
48 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 };
56
57 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 };
65
66 let num = first * 10 + last;
67 sum += num;
68 }
69
70 sum
71}

Series navigation for: Advent of Code 2023

2. Advent of Code 2023 Day 2

Designed and developed by Nicky Meuleman

Built with Gatsby. Hosted on Netlify.