Advent of Code — Day 1

Advent of Code is one of my favourite times of year. Partly for the puzzles, and partly because it's a sign the year is winding up. Like 24 ways to impress your friends and UXmas before it, Advent of Code is an advent calendar, where each day is a pair of code challenges. There's usually some kind of narrative that ties the puzzles together, which ends up adding a fun christmas-y spin to the whole thing.

Usually, I try and do it in a programming language I am not super familiar with, but this year I'm going to stick to Ruby (mainly because I am out of ideas for languages to try 😆).

Part 1

The first part was nice and simple. The challenge was to extract the first and last digits from each line, concatenate them in to a new number, and then sum the total.

E.g. given:

1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet

The first line would be 12, the second 38 and so on, with the solution being 12 + 38 + ...

My solution was as follows

input.map{ |line|   
  matches = line.scan(/\d/)   
  Integer("#{matches[0]}#{matches[-1]}")   
}.inject(:+)

⭐️ Success!

Part 2

The second part was sneaky! Building on from the previous part, we're now tasked with including numbers that have been spelled out.

So for example, given:

two1nine  
4nineeightseven2

The first line would be 29 and the second would be 42.

Which seemed simple at first:

NUMBERS = {one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9}.freeze

num_pattern = NUMBERS.keys.join("|")  

input.map {|line|  
  matches = line.scan(/#{num_pattern}|\d/)  
  first = NUMBERS[matches[0].to_sym] || matches[0]  
  last = NUMBERS[matches[-1].to_sym] || matches[-1]  

  Integer("#{first}#{last}")  
}.inject(:+)
  1. Search for either a digit, or the number-in-letters
  2. Grab the first and last match (and if either is a number-in-letters, replace it with the digit)
  3. Create a new integer and we're done!

I submitted my answer, and booo , too high!

My tests passed, what was I missing?

I threw in a bunch of puts in the above code and saw a line like the following:

pxxtd793frjfckbhstcdhsrx58mksktwoneqx

Which my code was resolving to 72, but should have been 71!

The issue was with the last section ktwoneqx, the regular expression I was using was was not looking ahead! So a quick change to use a positive lookahead and I was done!

The new pattern becomes: /(?=(#{num_pattern}|\d))/

⭐️ Success!

Day one: https://github.com/dNitza/advent-of-code/tree/main/2023/01

Published

by Daniel Nitsikopoulos

in posts

Tagged

© 2010 - 2024 Daniel Nitsikopoulos. All rights reserved.

🕸💍  →