def range(s) n1, n2 = s.split('-') return n1.to_i .. n2.to_i end def read_pairs(filename) retval = [] File.open(filename) do |file| file.readlines.each do |line| elf1, elf2 = line.split(',') retval << [range(elf1), range(elf2)] end end return retval end def range_included(r1, r2) return (r2.include?(r1.first) && r2.include?(r1.last)) || (r1.include?(r2.first) && r1.include?(r2.last)) end def range_overlaps(r1, r2) return (r2.include?(r1.first) || r2.include?(r1.last)) || (r1.include?(r2.first) || r1.include?(r2.last)) end def part1(filename) read_pairs(filename).map { |pairs| range_included(pairs[0], pairs[1]) }.select { |x| x }.count end def part2(filename) read_pairs(filename).map { |pairs| range_overlaps(pairs[0], pairs[1]) }.select { |x| x }.count end