class String def to_ip IP.new self end end class IP < String def initialize(s) super s end def supports_tls? !has_abba_in_hypernet_sequences? && has_abba? end def abba? self[0] == self[3] && self[2] == self[1] && self[0] != self[1] end def has_abba? chars.each_cons(4).map(&:join).map(&:to_ip).any?(&:abba?) end def has_abba_in_hypernet_sequences? hypernet_sequences.any? &:has_abba? end def hypernet_sequences supernet_and_hypernet_sequences.each_with_index.select do |seq, i| i % 2 == 1 end.map(&:first) end def supernet_sequences supernet_and_hypernet_sequences.each_with_index.select do |seq, i| i % 2 == 0 end.map(&:first) end def supernet_and_hypernet_sequences split("[").map{ |chunk| chunk.split("]") }.flatten.map(&:to_ip) end def abas @abas ||= chars.each_cons(3).select { |triple| triple[0] == triple[2] && triple[0] != triple[1] }.map(&:join).map(&:to_ip) end def bab?(abas_to_match) abas_to_match.any? { |aba| aba[0] == self[1] && self[0] == aba[1] } end def babs(abas_to_match) abas.select { |aba| aba.bab?(abas_to_match) } end def supports_ssl? supernet_abas = supernet_sequences.map(&:abas).flatten hypernet_sequences.any? { |seq| seq.babs(supernet_abas).length > 0 } end end input = STDIN.read.chomp lines = input.split("\n").map(&:to_ip) part_1 = lines.count(&:supports_tls?) puts "Part 1: #{part_1}" part_2 = lines.count(&:supports_ssl?) puts "Part 2: #{part_2}"