solved part 2

master
Jeff Yates 2020-12-09 12:20:47 -05:00
parent 1cd2b62ba0
commit dc84f2c151
1 changed files with 41 additions and 0 deletions

41
day09/solution2.rb Executable file
View File

@ -0,0 +1,41 @@
#!/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