-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday14.rb
executable file
·79 lines (62 loc) · 1.77 KB
/
day14.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env ruby
# frozen_string_literal: true
input = File.read('day14.txt').lines.map(&:strip)
class Nanofactory
attr_accessor :reactions, :unused
def initialize(reactions)
@reactions = reactions
@unused = {}
end
def self.from_lines(lines)
new(lines.map do |line|
inp, outp = line.split(' => ')
inp = inp.split(', ').map { |i| i.split(' ') }.map { |qty, chemical| [chemical, qty.to_i] }
outp = outp.split(' ')
[outp[1], [outp[0].to_i, inp]]
end.to_h)
end
def get_ore_qty(req_chemical, req_qty)
if @unused.key?(req_chemical)
remaining_qty = @unused[req_chemical]
if remaining_qty >= req_qty
@unused[req_chemical] -= req_qty
return 0
else
@unused.delete(req_chemical)
return get_ore_qty(req_chemical, req_qty - remaining_qty)
end
end
return req_qty if req_chemical == 'ORE'
output_qty, input_chemicals = @reactions[req_chemical]
factor = (req_qty * 1.0 / output_qty).ceil
remaining_qty = (output_qty * factor) - req_qty
if remaining_qty > 0
@unused[req_chemical] = 0 unless @unused.key?(req_chemical)
@unused[req_chemical] += remaining_qty
end
input_chemicals.map do |input_chemical, input_quantity|
get_ore_qty(input_chemical, input_quantity * factor)
end.sum
end
end
# Part 1
factory = Nanofactory.from_lines(input)
ore_per_fuel = factory.get_ore_qty('FUEL', 1)
puts ore_per_fuel
# Part 2
factory = Nanofactory.from_lines(input)
factory.unused = { 'ORE' => 1_000_000_000_000 }
inc = 1_000
n = 0
while factory.unused.key?('ORE')
unused = factory.unused.dup
factory.get_ore_qty('FUEL', inc)
if factory.unused.key?('ORE')
n += inc
else
break if inc == 1
inc /= 10
factory.unused = unused
end
end
p n