Advent of Code 2017, Day 2: Corruption Checksum

#ruby #advent of code 2017

Part A

On Day 2 we have another warming exercise. We have a spreadsheet given as input. We need to calculate the difference between lowest and highest number in each row and then add them together.

data = File.readlines("2.txt", chomp: true).map { |row| row.split("\t").map(&:to_i) }

sum = data.map do |row|
  row.minmax.reduce(:-).abs
end.sum

puts sum

minmax is a nice method that returns min and max value.

Part B

Second part is more complicated. In each row we need to find numbers that divide into a whole number. Then we need to sum the results of such divisions.

Here is Ruby code:

data = File.readlines("2.txt", chomp: true).map { |row| row.split("\t").map(&:to_i) }

def fetch(row)
  row.size.times do |i|
    (i + 1).upto(row.size - 1) do |j|
      a = row[i]
      b = row[j]

      if b % a == 0
        return b / a
      end
    end
  end
end

values = data.map do |row|
  fetch(row.sort)
end

puts values.sum

For each row we basically check every number with every other number. Values in row are first sorted, so we should actually get correct results.