-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathday14.rb
More file actions
84 lines (72 loc) · 1.47 KB
/
day14.rb
File metadata and controls
84 lines (72 loc) · 1.47 KB
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
80
81
82
83
84
class Computer
def initialize (filename)
@data = File.readlines(filename, chomp: true)
@mem = Hash.new(0)
end
def simulate
@data.each do |line|
case line
when /mask = (\w+)/
mask($1)
else
mem_access(line)
end
end
end
def answer
@mem.values.sum
end
end
class Computer1 < Computer
def initialize (filename)
super(filename)
@on = nil
@off = nil
end
def mask (bits)
@on = bits.gsub('X', '0').to_i(2)
@off = bits.gsub('X', '1').to_i(2)
end
def mem_access (line)
addr, val = line.scan(/\d+/).map(&:to_i)
@mem[addr] = (val | @on) & @off
end
end
class Computer2 < Computer
def initialize (filename)
super(filename)
@mask = nil
end
def mask(bits)
@mask = bits
end
def update(addr, val, index)
if index == addr.length
@mem[addr] = val
return
end
case @mask[index]
when '0' # leave address alone
update(addr, val, index + 1)
when '1' # set bit to one
addr[index] = '1'
update(addr, val, index + 1)
when 'X' # try both!
addr[index] = '0'
update(addr, val, index + 1)
addr[index] = '1'
update(addr, val, index + 1)
end
end
def mem_access (line)
addr, val = line.scan(/\d+/).map(&:to_i)
addr = addr.to_s(2).rjust(36, '0')
update(addr, val, 0)
end
end
c1 = Computer1.new (ARGF.filename)
c1.simulate
p c1.answer
c2 = Computer2.new (ARGF.filename)
c2.simulate
p c2.answer