-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.rb
51 lines (41 loc) · 1.2 KB
/
solution.rb
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true
require_relative '../solution'
module Day09
class Solution < Solution
def solve_part01
Xmas.first_invalid_number(25, input)
end
def solve_part02
Xmas.find_encryption_weakness(25, input)
end
end
class Xmas
def self.first_invalid_number(preamble_size, input)
input.map(&:to_i).each_with_index do |num, index|
next if index + 1 <= preamble_size
numbers = input[(index - preamble_size)..index]
sums = numbers.map(&:to_i).combination(2).map { |a, b| a + b }
return num unless sums.include?(num)
end
end
def self.find_encryption_weakness(preamble_size, input)
invalid_num = first_invalid_number(preamble_size, input)
sum = 0
numbers = []
input.map(&:to_i).each_with_index do |_num, index|
input[index..-1].map(&:to_i).each do |n|
sum += n
numbers.push(n)
break if sum == invalid_num && numbers.size > 1
if sum > invalid_num
sum = 0
numbers = []
break
end
end
break if sum == invalid_num && numbers.size > 1
end
numbers.min + numbers.max
end
end
end