DEV Community

Discussion on: AoC Day 2: Inventory Management System

Collapse
 
pabloxcl profile image
Pablo Olmos de Aguilera Corradini

A bit late to the party, here are my solutions on Ruby:

Part 1:

twos = 0
threes = 0

File.open('day-02_input.txt').each_line do |line|
  counter = {}

  line.each_char do |char|
    next if line.count(char) <= 1

    counter[char] = line.count(char)
  end

  twos += 1 if counter.value? 2
  threes += 1 if counter.value? 3
end

puts twos * threes

Part 2:

boxes = []

File.open('day-02_input.txt').each_line { |box| boxes << box.chomp! }

def find_distance pair, distance = 0
  pair[0].each_char.with_index do |char, index|
    distance += 1 if char != pair[1][index]
  end
  distance
end

boxes.combination(2).each do |pair|
  next unless find_distance(pair) == 1

  str = ''

  pair[0].chars.each_with_index do |_, i|
    str << pair[0][i] if pair[0][i] == pair[1][i]
  end
  puts str
end

I learnt about the combination method :)