Advent of Code 2017, Day 1: Inverse Captcha

#ruby #advent of code 2017

Part A

On Day 1 we have a warming exercise. We need to sum numbers in array, but only if two consecutive numbers are equal.

For example:

We can do simple loop:

data = File.read("1.txt").strip.split("").map(&:to_i)
size = data.size
sum = 0

0.upto(size - 1) do |index|
  if data[index] == data[(index + 1) % size]
    sum += data[index]
  end
end

puts sum

Part B

In second part instead of comparing consecutive items we need to compare number that is halfway around the circular list. If the list has 10 elements we need to compare number with one 5 items away.

Here is the code:

data = File.read("1.txt").strip.split("").map(&:to_i)
size = data.size
sum = 0
forward = size / 2

0.upto(size - 1) do |index|
  if data[index] == data[(index + forward) % size]
    sum += data[index]
  end
end

puts sum

Bonus

In the newer versions of Ruby there is nice each_cons method that allows to iterate over consecutive items.

We can implement Part A like this:

data = File.read("1.txt").strip.split("").map(&:to_i)
data.push(data[0])

sum = data.
  each_cons(2).
  select { |(first, second)| first == second }.
  map { |(first, second)| first }.
  sum

puts sum

We need to add first element to the end so comparing last element with the first one on circular list still works. each_cons returns arrays of 2 consecutive elements, we select only those with same numbers, then we map to just one number and sum them together.