2022-12-02 — 2 min read

Advent of Code 2015, Day 10 – In Ruby

Let’s see the puzzle for the 10th day of 2015!

The first half of the puzzle

Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as “one two, two ones”, which becomes 1221 (1 2, 2 1s).

Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by the digit itself (1).

For example:

  • 1 becomes 11 (1 copy of digit 1).
  • 11 becomes 21 (2 copies of digit 1).
  • 21 becomes 1211 (one 2 followed by one 1).
  • 1211 becomes 111221 (one 1, one 2, and two 1s).
  • 111221 becomes 312211 (three 1s, two 2s, and one 1).

Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?

The solution:

#!/usr/bin/env ruby

input = ARGV.first

def generate(input)
  input.scan(/((\w)\2*)/).map(&:first).map{|x| "#{x.length}#{x[0]}"}.join
end

40.times do
  input = generate(input)
end

puts input.length

We split the input into parts with identical digits first. The regexp ((\w)\2*) means: take any word character, capture it (this will be group #2), if it is repeated, capture the whole run as well (it will be group #1 because it’s captured with the outer parentheses). If it’s not repeated, groups #1 and #2 will be identical. We’ll only keep the first groups of the results (the .map(&:first) part), then transform them to the required format: the number of digits, followed by the digit itself. At the end, we join them into a single string.

The second half of the puzzle

Neat, right? You might also enjoy hearing John Conway talking about this sequence (that’s Conway of Conway’s Game of Life fame).

Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the new result?

The solution:

#!/usr/bin/env ruby

input = ARGV.first

def generate(input)
  input.scan(/((\w)\2*)/).map(&:first).map{|x| "#{x.length}#{x[0]}"}.join
end

50.times do
  input = generate(input)
end

puts input.length

The only change needed is to run the loop 50 times instead of 40.

The code with my input text is available in the GitHub repo.

Thanks for reading! If you have any comments, additions, or corrections, feel free to reach me via e-mail.

Copyright © 2023 csm.hu
Contact