-
Notifications
You must be signed in to change notification settings - Fork 1
/
day20.rb
63 lines (45 loc) · 1 KB
/
day20.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
52
53
54
55
56
57
58
59
60
61
62
63
def calculate_divisors(n)
divisors = []
# When calculaing divisors, only need to consider up to square root of number
1.upto((n**0.5).floor) do |i|
q, r = n.divmod(i)
divisors << q << i if r.zero?
end
divisors.uniq
end
target = 33100000
houses = {}
house = 1
# Part 1
loop do
puts "@ House ##{house}..."
houses[house] ||= 0
houses[house] = calculate_divisors(house).map { |d| d*10 }.inject(:+)
if houses[house] >= target
puts "House ##{house} has at least #{target}!"
break
else
puts "It has #{houses[house]} presents! "
end
house += 1
end
counts = Hash.new { |h, k| h[k] = 0 }
# Part 2
loop do
puts "@ House ##{house}..."
presents = 0
calculate_divisors(house).each do |elf|
if counts[elf] < 50
presents += 11*elf
counts[elf] += 1
end
end
houses[house] = presents
if houses[house] >= target
puts "House ##{house} has at least #{target}!"
break
else
puts "It has #{houses[house]} presents! "
end
house += 1
end