aboutsummaryrefslogtreecommitdiff
path: root/day05/part2
blob: d09ff869cf27631d99404255bf6baaa5c4a2792f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env ruby

input = gets.chomp.chars

units = input.map(&:downcase).uniq
lengths = {}

units.each do |unit|
  polymer = input.dup
  polymer.delete_if {|u| u == unit || u == unit.upcase}
  nextpolymer = Array.new(polymer.length)
  nextpolymer[0] = polymer[0]
  index = 1
  nextindex = 0

  while index < polymer.length do
    if polymer[index].swapcase != nextpolymer[nextindex]
      nextindex += 1
      nextpolymer[nextindex] = polymer[index]
    else
      nextpolymer[nextindex] = nil
      nextindex -= 1
    end
    index += 1
  end

  lengths[unit] = nextpolymer.compact.length
end

puts lengths.values.min