Advent of Code (Day 9)


Check out out day 9 here.

Quick run down

You have a bunch of characters coming at you and you want to see how many curly parens {} groups there are. The thing is, there are also garbage groups in angle brackets <> and if there are curly parens { in the garbage group, then they don’t count.

I was thinking about regex, but then thought it would be easier to just iterate through the chars.

The different possible states


Modes
  Garbage On
    < symbol with out a closing
  Garbage Off
    > symbol closing
  Cancel mode
    ! skip the next char
  Score up
    {
  Score down
    }

Challenge One


garbage_mode = false
cancel_mode = false
current_score = 0

total_score = 0

stream.each do |char|
  if garbage_mode
    if cancel_mode
      cancel_mode = false
      next
    end

    if char == '!'
      cancel_mode = true
      next
    end

    if char == '>'
      garbage_mode = false
      next
    end
  end

  if char == '<'
    garbage_mode = true
  end

  if char == '{'
    current_score += 1
    total_score += current_score
  end

  if char == '}'
    current_score -= 1
  end
end

puts total_score

Challenge Two

Here you just had to count how many garbage characters there were, not counting valid state changing charaters: <, !, >


removed = ''

# ...

stream.each do |char|
  if garbage_mode
    # ...

    removed += char
    next
  end

  # ...
end

puts removed.size