#!/bin/env ruby def valid_nums (nums) nums.map { |num| nums .map { |sub| sub + num if sub != num }}.flatten.uniq.compact end def find_invalid (numbers, preamble) numbers.each.with_index do |number, i| next if i < preamble if !valid_nums(numbers[(i-preamble)..(i-1)]).include?(number) return i, number break end end end numbers = File.readlines('./input').to_ary.map(&:strip!).map(&:to_i) preamble = 25 index, wrong_number = find_invalid(numbers, preamble) pp index, wrong_number numbers.slice!(index..) numbers.delete_if { |number| number > wrong_number } max = numbers.length step = 1 solution = nil while step < max do range_sums = numbers.map.with_index { |num, i| {"#{i..i+step}" => numbers[i..i+step].sum}} range_sums.each do |set| if set.values.include?(wrong_number) solution = set break end end step += 1 end first, last = solution.keys[0].split('..').map(&:to_i) pp solution p numbers[first..last].min + numbers[first..last].max